From 881fec6a02588e032c1d85a99f50261efec5271e Mon Sep 17 00:00:00 2001 From: fork Date: Sun, 22 Nov 2026 19:26:49 +0100 Subject: [PATCH 1/2] Pick BOM components by search in web and desktop (#419) The web *Add component* field lists matching items while typing part of their number, name or file name (thumbnail, revision, state, group, matched file; keyboard and ARIA combobox), progressive enhancement over the exact number field. New GET /items/suggest (session) and GET /api/v1/items/suggest over items::suggest, i.e. the item search with the caller's read rights. Desktop Structure tab: Add line... with the same picker, editable quantity and Remove on first-level lines of an own check-out. Tests for name and file-name matches, restricted groups, sign-in and the check-out rule; docs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++ README.md | 3 +- desktop/README.md | 3 +- desktop/ui/app.css | 11 ++ desktop/ui/js/bom-lines.js | 172 ++++++++++++++++++ desktop/ui/js/main.js | 2 +- desktop/ui/js/revision.js | 19 +- docs/OPEN_WORK.md | 6 +- docs/src/dev/threat-model.md | 1 + docs/src/guide/desktop.md | 13 ++ docs/src/guide/structure.md | 20 +++ docs/src/reference/api.md | 2 +- src/api/items_api.rs | 19 ++ src/api/mod.rs | 2 + src/services/items.rs | 69 ++++++++ src/services/similar.rs | 5 +- src/web/items.rs | 35 ++++ src/web/mod.rs | 2 + static/app.js | 137 ++++++++++++++ static/style.css | 19 +- templates/revisions/show.html | 7 +- tests/component_picker.rs | 325 ++++++++++++++++++++++++++++++++++ 22 files changed, 873 insertions(+), 13 deletions(-) create mode 100644 desktop/ui/js/bom-lines.js create mode 100644 tests/component_picker.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bb48d14..3ce0897a 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,20 @@ see the notices in the README. ## [Unreleased] +### Added + +- **BOM components picked by search** (#419, UX B5 of #408): *Add component* + on the web BOM card lists matching items as you type part of their number, + name or file name – with the preview image from the CAD file, latest + revision, state, project group and the file name that matched; ↑/↓, Enter + and Esc work, and without JavaScript the field still takes the exact item + number. The desktop app's *Structure* tab gets *Add line…* with the same + picker, an editable quantity and *Remove* on every first-level line of an + own check-out. New routes: `GET /items/suggest` (web session) and + `GET /api/v1/items/suggest`; both use the item search with the user's read + rights, so items of restricted groups the user is not in never appear (at + most 10 rows, nothing for fewer than 2 characters). + ## [0.2.12] - 2026-11-22 ### Security diff --git a/README.md b/README.md index 6b9bde78..cc2518e5 100755 --- a/README.md +++ b/README.md @@ -230,7 +230,8 @@ end-to-end tests against a real PostgreSQL. **Structure** - **Multi-level BOM** – mass and cost roll-up, revision rules, comparison of - two revisions, CSV/Excel export. + two revisions, CSV/Excel export; components are picked by searching their + number, name or file name (web and desktop). - **Mass properties** – mass, centre of gravity and inertia tensor of a whole assembly or vehicle from the exported meshes of its parts, a material library of densities and measured masses of bought parts; CSV/JSON export. diff --git a/desktop/README.md b/desktop/README.md index 3491c674..66084aef 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -27,7 +27,7 @@ TeamCraft server – it is a client, not an offline copy. | Right-click menu | On items and files in the navigator, Home *Files* / *All items* / *Structure*, the worklist's check-outs and the Graph cards (rows with `data-item` + `data-rev`, one listener in `js/item-menu.js`): *Check out and open* / *Open in CAD*, *Check out*, *Check in…*, *Get…*, *Show in folder*, *Copy number*, *Where used*, *Request change…*, *Open in browser*; the entries and the tooltip of a disabled one come from the toolbar's rules (`js/item-menu-rules.js`, tested by `scripts/desktop-item-menu.test.mjs`); Shift+F10 / context-menu key, arrows, `Esc` – #417 | | Toolbar | Below the tab strip, acting on the active tab: grouped buttons that keep their place (revision: Lock · Work · Lifecycle · Collaborate; change: Review · Lifecycle · Collaborate; request: Triage · Requester · Collaborate), the **next step highlighted** (*Check out*, *Check in…* with local changes, *Release…* on a clean check-out, *Revise* when released, *Submit for review* / *Approve change* on a change), greyed-out buttons with a tooltip saying why (*Check in…* has an upload arrow, never the download arrow of *Get…*, #409; *Edit attributes* as in the web UI, #410), rare actions (*Pack and Go…*, *Open in browser*, *Refresh*, *Mark obsolete…*) in **More ▾** – keyboard: `Enter`/`Space`/`↓` open, arrows move, `Esc` closes | | Tab order | Drag a tab to move it (pointer events, an insertion bar shows the landing place, the strip scrolls at its edges, `Esc` cancels; a plain click still activates, a dragged tab keeps its state and is not activated). Keyboard: arrow keys, `Home`, `End` move the focus between the tabs (WAI-ARIA tabs, roving tabindex, `Enter`/`Space` activates), `Ctrl+Shift+PageUp/PageDown` move the active tab. Right click (or the menu key): *Move to start*, *Move to end*, *Close*, *Close others*, *Close tabs to the right*. The order is kept while the app runs (open tabs are not restored on start). Rules in `ui/js/tab-order.js`, tested by `scripts/desktop-tab-order.test.mjs` (`node`); the dragging itself is checked by hand | -| Revision tabs | Overview (with *At a glance*: the preview image from the CAD file, files, BOM lines, where used, references, change orders, open requests – and a link to the similar parts in the browser), Files (versions, restore, open), Structure (multi-level BOM, revision rules, roll-up), Where used, References, **Graph** (see below), Changes, History, **3D viewer** (STEP, meshes, point clouds – converted by the server), Workspace | +| Revision tabs | Overview (with *At a glance*: the preview image from the CAD file, files, BOM lines, where used, references, change orders, open requests – and a link to the similar parts in the browser), Files (versions, restore, open), Structure (multi-level BOM, revision rules, roll-up; under your check-out *Add line…*, quantities and *Remove*), Where used, References, **Graph** (see below), Changes, History, **3D viewer** (STEP, meshes, point clouds – converted by the server), Workspace | | Graph | A navigable reference/BOM graph around the revision: the focused item in the middle, its BOM children and references below, the assemblies that use it above. Node **colour** = lifecycle state, **size** and the ⚙ badge = the item's own BOM complexity, **×n in the top-left corner** = how many instances of that part or sub-assembly the assembly contains (summed over its BOM lines, ×1 included). Every node is clickable and takes the tab to that item – a sub-assembly shows its own graph, anything else its overview, the item in the middle its own overview – with a **back control that stays in the same place** (the left of the sub-tab row) and leads back the way you came, one step per click; `Ctrl`/`⌘`+click opens a node in a tab of its own. Mouse-wheel zooms on the cursor; drag to pan; the view fits itself while details load until you zoom or pan, a double-click on the background fits it again. More than 8 neighbours on one side are laid out in rows; above 48 only the first 48 are fetched for preview and complexity (one request each), the rest keep a basic card. Preview images and filenames on the nodes; pure SVG, no external engine | | Working folder | One folder per project group that **mirrors the folder structure of the files** (`///`, the folder is stored with every file on the server), one copy of each file – the revision is metadata in `/.teamcraft/state.json` (item, revision, file id, version, SHA-256, checked out). Files you have not checked out are **read-only** on disk; *Check out* takes the lock and makes them writable; *Check in…* uploads the chosen files as new versions, releases the lock in one step and makes them read-only again (files above 32 MiB go first as chunked, resumable uploads, then join the same check-in transaction). The check-in dialog shows the progress, and **Cancel** stops the check-in until its last byte is sent – before the next STEP export, between two chunks (the upload sessions are discarded, `DELETE /uploads/{id}`) or half-way through the streamed request with the small files: nothing is stored, the revision stays checked out (`src/abortable.rs`). Every check-in names the version each file is based on, so the server refuses (409) to overwrite a version somebody else checked in meanwhile. The Workspace tab shows *up to date* / *modified* / *outdated* / *conflict* / *new* / *missing* / *name clash* per file (from the server's file status) with its path, read-only flag and the lock owner. Two items with the same folder and file name are reported, never overwritten. Lock and backup files of the CAD programs are skipped; a SolidCraft design that is open in SolidCraft (a fresh `.~.lock` beside it, `src/cadlock.rs`) is marked *Open in SolidCraft* with the computer and user, and the check-in dialog warns that unsaved changes there are not checked in; Creo iterations count as one file. A tracked revision the server no longer shows (you left a restricted project group) is listed as *No longer accessible*: its local copies stay untouched and are never synced again – delete them yourself if you must In *Check in…*, a new part or assembly file next to a revision that has a model already is offered unticked, with *New item from this file* (#359) | | Get | *Get…* on a revision: the item with its BOM (revision rule *latest* or *released*) and the parts its CAD files reference, resolved by the server (`…/workset`); only missing and outdated files are downloaded (SHA-256, checked after the download), recorded one by one so an interrupted Get continues where it stopped – also inside a large file: the bytes received stay in `..teamcraft-download` and the next Get asks only for the rest (`Range` / `If-Range`, `src/resume.rs`), checks the SHA-256 of the whole file and renames it into place; progress and *Cancel* in the status bar. No browser downloads | @@ -46,6 +46,7 @@ TeamCraft server – it is a client, not an offline copy. | New on this computer | Worklist section (#359, editors): the parts and assemblies in the working folder that belong to no item yet, one suggestion per model file with its drawing and exports of the same name in the same folder, newest first, counted on the rail. A click opens *New* prefilled, *Create items…* creates the ticked ones after a summary of what is created and what is refused, *×* ignores a file (`.teamcraft/ignored.json`, *Show ignored*; entries of files that are gone are dropped after a complete scan). The scan (`desktop/src/newfiles.rs`, `new_files_scan`) skips tracked and added files, companions of tracked files, lock/backup/temporary files, `OldVersions` and hidden folders; at most 50 000 entries and 2 000 files per scan, run when the worklist opens or the window gets the focus back (at most every 15 s). Nothing is uploaded without the dialog or the summary | | App version | The version of the app above the logo at the bottom of the rail, always visible (#357) | | Import BOM | *Import BOM…* in the *Structure* tab (and the *More* menu) of a revision you have checked out, *Tools → Import BOM as New Assembly…* for a new one: a BOM exported by the CAD program (CSV, TSV, Excel, ODS or a STEP assembly, chosen in the native dialog) goes to the server's BOM import as a dry run first – the dialog shows the counts of lines, new and existing items, the notes and the first lines – and *Import* creates the lines and missing items in one transaction (numbers from the file or the group's numbering scheme, reuse of existing items optional) | +| BOM lines | *Add line…* in the *Structure* tab of a revision you have checked out (`js/bom-lines.js`, #419): a component picker searches number, name and file name (`GET /items/suggest`, older servers `GET /items?q=`; preview image, revision, state, group; ↑/↓ + Enter), then quantity, find number and notes (`POST /items/{n}/revisions/{c}/bom`); under the own check-out every first-level line has an editable quantity (`PATCH /bom-lines/{id}`) and *Remove* (`DELETE /bom-lines/{id}`, confirmed); the tab reloads after each change | | Release and changes | *Release…* creates and submits a change order – with the unreleased dependencies (BOM children, drawings) by default; the own user name is refused as reviewer, with nobody else in the group it creates a draft, and a refused revision or reviewer cancels the half-made draft again (#291); *Release readiness* panel with *Add all*; on a draft *Add reviewer* by user name, *Remove* and *Cancel change*, *Submit for review* disabled with the reason while a revision or reviewer is missing; approve/reject from the worklist | | Change requests | *Request change…* on a revision tab and *Request…* on a file (Files and Workspace tabs) raise a change request prefilled with item, revision and file name, with an optional screenshot or PDF (native file dialog, uploaded by the Rust side); request tabs with discussion, decision (accept / defer / reject), *Create change order*, attachments; *Requests assigned to me* and *My open requests* in the worklist | | Change propagation | *Dependents to check* grouped by dependent revision (one worklist line with a count, expandable; on the home page **Open**, **Revise**, **Acknowledge all…** per dependent and **Acknowledge…** per change), *Check needed* on the revision tab, references, *As released* rule, impact analysis | diff --git a/desktop/ui/app.css b/desktop/ui/app.css index 2ceede43..ad34df36 100755 --- a/desktop/ui/app.css +++ b/desktop/ui/app.css @@ -1328,3 +1328,14 @@ pre.release-notes { /* right-click menu of an item (#417, item-menu.js): busy while its revision loads */ body.menu-loading, body.menu-loading * { cursor: progress; } + +/* Structure tab: Add line… component picker and editable BOM lines (#419, js/bom-lines.js) */ +.picker-list { list-style: none; margin: 4px 0 0; padding: 4px 0; max-height: 18rem; overflow-y: auto; + border: 1px solid var(--border); border-radius: var(--radius-xs); background: var(--surface); } +.picker-list:empty { display: none; } +.picker-option { display: flex; gap: 8px; align-items: center; padding: 4px 8px; cursor: pointer; } +.picker-option:hover, .picker-option[aria-selected="true"] { background: var(--selected); } +.picker-thumb { flex: none; width: 36px; height: 36px; object-fit: contain; border-radius: var(--radius-xs); background: var(--surface-sunken); } +.picker-main { display: flex; flex-direction: column; min-width: 0; } +.picker-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +td input.qty { width: 6.5em; text-align: right; } diff --git a/desktop/ui/js/bom-lines.js b/desktop/ui/js/bom-lines.js new file mode 100644 index 00000000..56ee8551 --- /dev/null +++ b/desktop/ui/js/bom-lines.js @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MPL-2.0 +// TeamCraft Desktop – BOM lines in the Structure tab (#419): Add line… with +// a component picker, quantity editing and removing lines of an own check-out. +// Part of the desktop UI (ES modules, no build step; js/main.js starts it). + +import { api, badge, confirmDialog, dialog, enc, errorText, field, h, invoke, run, toast } from "./core.js"; +import { fmtNum } from "/static/shared/js/format.js"; +import { reloadActive } from "./tabs.js"; + +/** Most suggestions the picker shows (the server caps them the same way). */ +export var PICKER_LIMIT = 10; + +/** A quantity as typed: decimal comma or point; null when it is not a positive number. */ +export function parseQuantity(text) { + var t = String(text || "").trim().replace(",", "."); + if (!/^\d*\.?\d+$|^\d+\.$/.test(t)) return null; + var n = Number(t); + return n > 0 && isFinite(n) ? n : null; +} + +/** Items matching `q` (number, name, file name) the user may read. Older + * servers without `GET /items/suggest` answer through the item search. */ +export function suggestItems(q) { + var query = "?limit=" + PICKER_LIMIT + "&q=" + enc(q); + return api("GET", "/items/suggest" + query).catch(function (err) { + if (!err || err.status !== 404) throw err; + return api("GET", "/items" + query); + }).then(function (r) { return (r && r.items) || []; }); +} + +var pickerThumbUrls = {}; +function pickerThumb(fileId) { + if (!fileId) return h("span.picker-thumb.picker-thumb-none"); + var img = h("img.picker-thumb.hidden", { alt: "" }); + var url = pickerThumbUrls[fileId] || (pickerThumbUrls[fileId] = invoke("file_bytes", { kind: "thumbnail", id: fileId }) + .then(function (bytes) { return URL.createObjectURL(new Blob([bytes])); })); + url.then(function (u) { img.src = u; img.classList.remove("hidden"); }, function () { /* none */ }); + return img; +} + +/** + * Add line…: picks a component by typing part of its number, name or file + * name and adds it with quantity, find number and notes to the BOM of `rev` + * (my check-out) – `POST /items/{n}/revisions/{c}/bom`, the route of the web + * UI's *Add component*. A typed exact item number works without choosing. + */ +export function addLineDialog(rev) { + var chosen = null, rows = [], active = -1, timer = null, asked = ""; + var search = h("input", { type: "text", autocomplete: "off", placeholder: "Number, name or file name", role: "combobox", + "aria-autocomplete": "list", "aria-expanded": "false", "aria-controls": "add-line-suggestions" }); + var list = h("ul.picker-list.static", { id: "add-line-suggestions", role: "listbox", "aria-label": "Matching items" }); + var info = h("p.hint", { text: "Type at least 2 characters." }); + var qty = h("input.qty", { type: "text", value: "1", inputmode: "decimal" }); + var find = h("input.find", { type: "text", placeholder: "auto", inputmode: "numeric" }); + var notes = h("input", { type: "text", placeholder: "optional", maxlength: "500" }); + + function highlight(i) { + active = i; + rows.forEach(function (r, k) { r.el.setAttribute("aria-selected", k === i || (i < 0 && chosen === r.item) ? "true" : "false"); }); + if (i >= 0 && rows[i]) rows[i].el.scrollIntoView({ block: "nearest" }); + } + function choose(i) { + var r = rows[i]; + if (!r) return; + chosen = r.item; + search.value = r.item.number; + asked = r.item.number; + info.textContent = "Chosen: " + r.item.number + " – " + r.item.name; + highlight(-1); + qty.focus(); + qty.select(); + } + function render(items) { + list.replaceChildren(); + rows = []; + active = -1; + items.forEach(function (item, i) { + var li = h("li.picker-option", { id: "add-line-option-" + i, role: "option", "aria-selected": "false", + on: { mousedown: function (e) { e.preventDefault(); choose(i); } } }, [ + pickerThumb(item.thumbnail_file_id), + h("span.picker-main", null, [ + h("span", null, [h("span.mono", { text: item.number + "/" + item.latest_code }), " ", badge(item.latest_state), + item.project_code ? h("span.hint", { text: " " + item.project_code }) : null]), + h("span.picker-name", { text: item.name }), + item.matched_file ? h("span.hint.mono", { text: item.matched_file }) : null + ]) + ]); + list.appendChild(li); + rows.push({ el: li, item: item }); + }); + search.setAttribute("aria-expanded", items.length ? "true" : "false"); + info.textContent = items.length ? items.length + " match" + (items.length === 1 ? "" : "es") + " – click one or use ↑/↓ and Enter" + : "No readable item matches – an exact item number still works."; + } + function lookup() { + var q = search.value.trim(); + if (q === asked) return; + asked = q; + chosen = null; + if (q.length < 2) { render([]); info.textContent = "Type at least 2 characters."; return; } + suggestItems(q).then(function (items) { if (search.value.trim() === q) render(items); }, + function (err) { info.textContent = errorText(err); }); + } + search.addEventListener("input", function () { clearTimeout(timer); timer = setTimeout(lookup, 200); }); + search.addEventListener("keydown", function (e) { + if (!rows.length) return; + if (e.key === "ArrowDown") { e.preventDefault(); highlight(active < rows.length - 1 ? active + 1 : 0); } + else if (e.key === "ArrowUp") { e.preventDefault(); highlight(active > 0 ? active - 1 : rows.length - 1); } + else if (e.key === "Enter" && active >= 0) { e.preventDefault(); e.stopPropagation(); choose(active); } + }); + + var body = h("div.stack", null, [ + field("Item", search), list, info, + h("div.row", null, [field("Qty", qty), field("Find no.", find), field("Notes", notes)]) + ]); + dialog("Add line to " + rev.item_number + "/" + rev.code, body, [ + { label: "Cancel", onClick: function (d) { d.close(); } }, + { label: "Add", primary: true, submit: true, onClick: function (d) { + var child = chosen ? chosen.number : search.value.trim(); + if (!child) { d.fail("Choose an item."); return; } + var quantity = parseQuantity(qty.value); + if (quantity === null) { d.fail("The quantity must be a number above 0."); return; } + var payload = { child: child, quantity: quantity }; + var f = find.value.trim(); + if (f) { + if (!/^\d+$/.test(f)) { d.fail("The find number must be a whole number."); return; } + payload.find_number = parseInt(f, 10); + } + if (notes.value.trim()) payload.notes = notes.value.trim(); + api("POST", "/items/" + enc(rev.item_number) + "/revisions/" + enc(rev.code) + "/bom", payload).then(function (line) { + d.close(); + toast("Added " + child + " × " + fmtNum(quantity, 6) + (line && line.find_number ? " as find no. " + line.find_number : "")); + reloadActive(); + }, d.fail); + } } + ], { wide: true }); +} + +/** The quantity of a BOM line of my check-out as an input; a change is saved + * at once (`PATCH /bom-lines/{id}`). */ +export function quantityInput(line) { + var old = String(line.quantity); + var input = h("input.qty", { type: "text", value: old, inputmode: "decimal", "aria-label": "Quantity of " + line.item_number, + on: { + click: function (e) { e.stopPropagation(); }, + dblclick: function (e) { e.stopPropagation(); }, + keydown: function (e) { if (e.key === "Enter") input.blur(); else if (e.key === "Escape") { input.value = old; input.blur(); } }, + change: function () { + var quantity = parseQuantity(input.value); + if (quantity === null) { toast("The quantity must be a number above 0.", "error", "Change quantity"); input.value = old; return; } + run("Saving the quantity of " + line.item_number, function () { + return api("PATCH", "/bom-lines/" + line.line_id, { quantity: quantity }); + }).then(reloadActive, function () { input.value = old; }); + } + } }); + return input; +} + +/** Remove button of a BOM line of my check-out (`DELETE /bom-lines/{id}`). */ +export function removeLineButton(line) { + return h("button.small.danger", { type: "button", title: "Remove " + line.item_number + " from the BOM", on: { + dblclick: function (e) { e.stopPropagation(); }, + click: function (e) { + e.stopPropagation(); + confirmDialog("Remove line", "Remove " + line.item_number + " from the BOM?", "Remove", true).then(function (ok) { + if (!ok) return; + run("Removing " + line.item_number, function () { return api("DELETE", "/bom-lines/" + line.line_id); }) + .then(reloadActive, function () {}); + }); + } + } }, "Remove"); +} diff --git a/desktop/ui/js/main.js b/desktop/ui/js/main.js index 4a06e0d7..d52652df 100755 --- a/desktop/ui/js/main.js +++ b/desktop/ui/js/main.js @@ -9,7 +9,7 @@ // Every server call goes through the Rust commands (src/commands.rs); data // from the server is only ever inserted as text, never as HTML. // -// Modules: core.js, skins.js, connect.js, shell.js, navigator.js, tabs.js, assistant.js, agent.js, revision.js, references.js, workspace.js, change.js, requests.js, dialogs.js, bom-import.js, group-sync.js, folder-import.js, settings.js, crash.js, main.js. +// Modules: core.js, skins.js, connect.js, shell.js, navigator.js, tabs.js, assistant.js, agent.js, revision.js, references.js, workspace.js, change.js, requests.js, dialogs.js, bom-import.js, bom-lines.js, group-sync.js, folder-import.js, settings.js, crash.js, main.js. import { $, TAURI, call, errorText, h, invoke, setStatus, state, toast } from "./core.js"; import { applySkin } from "./skins.js"; diff --git a/desktop/ui/js/revision.js b/desktop/ui/js/revision.js index 1659dfaa..55f5d0bf 100755 --- a/desktop/ui/js/revision.js +++ b/desktop/ui/js/revision.js @@ -14,6 +14,7 @@ import { addFilesDialog, checkinDialog, doCancelCheckout, doCheckout, doObsolete import { openChange } from "./change.js"; import { openRequest, requestChangeDialog } from "./requests.js"; import { bomFromCadDialog, importBomDialog } from "./bom-import.js"; +import { addLineDialog, quantityInput, removeLineButton } from "./bom-lines.js"; import { cadTargetChip, groupDefault, mainCadFile, openWithCad } from "./cad-open.js"; import { incompleteGet, notOpenedText } from "./get-rules.js"; @@ -577,6 +578,8 @@ export function showVersions(tab, f, canRestore) { export function revStructure(tab, el) { var rule = tab.bomRule || "latest"; var d = tab.data, rev = d.rev; + // my check-out: the lines of this revision can be added, edited and removed (#419) + var mine = rev.checked_out_by === state.me.id; var head = h("div.panel-head", null, [ h("h2", { text: "Product structure" }), h("div.row", null, [ @@ -591,6 +594,12 @@ export function revStructure(tab, el) { type: "button", title: "Save the structure with this revision rule and all its files as ZIP", on: { click: function () { savePackage(rev, rule); } } }, "Pack and Go…"), + canEdit() ? h("button.small", { + type: "button", disabled: !mine, + title: mine ? "Add a component – search by number, name or file name" + : rev.checked_out_by ? "Checked out by " + rev.checked_out_by_name : "Check out first – BOM lines are added under your check-out", + on: { click: function () { addLineDialog(rev); } } + }, "Add line…") : null, canEdit() ? h("button.small", { type: "button", disabled: rev.checked_out_by !== state.me.id, title: rev.checked_out_by === state.me.id ? "Add the lines of a BOM exported by the CAD program (CSV, Excel, STEP assembly)" @@ -619,7 +628,7 @@ export function revStructure(tab, el) { tree.root.name, badge(tree.root.state), "", "", fmtNum(tree.total_mass_kg, 3) + " kg" + (tree.mass_complete ? "" : " ⚠"), fmtNum(tree.total_cost, 2) + " €" + (tree.cost_complete ? "" : " ⚠") - ], + ].concat(mine ? [""] : []), cls: "selected" }]; function walk(nodes, depth) { @@ -633,24 +642,26 @@ export function revStructure(tab, el) { var indent = h("span.indent"); indent.style.width = (depth * 1.2) + "rem"; var r = n.revision; + // the lines of this revision itself (first level) under my check-out + var editable = mine && depth === 1 && !n.restricted; rows.push({ cells: [ h("span", null, [indent, twisty, h("span.mono", { text: String(n.find_number) + " " }), h("span.mono", { text: n.item_number + (r ? "/" + r.code : "") })]), n.restricted ? h("span.muted", { text: "Restricted item – in a project group you are not a member of" }) : r ? r.name : h("span.warn-text", { text: "no " + (rule === "released" ? "released " : "") + "revision" }), r ? badge(r.state) : "", - fmtNum(n.quantity, 6) + " " + n.unit, + editable ? h("span.nowrap", null, [quantityInput(n), " " + n.unit]) : fmtNum(n.quantity, 6) + " " + n.unit, n.notes || "", fmtNum(n.total_mass_kg, 3) + " kg" + (n.mass_complete ? "" : " ⚠"), fmtNum(n.total_cost, 2) + " €" + (n.cost_complete ? "" : " ⚠") - ], + ].concat(mine ? [editable ? removeLineButton(n) : ""] : []), open: r ? function () { openRevision(n.item_number, r.code); } : null }); if (hasChildren && !collapsed) walk(n.children, depth + 1); }); } walk(tree.children, 1); - panel.appendChild(table(["Find no. / item", "Name", "State", "Qty", "Notes", "Mass", "Cost"], rows, { numeric: [3, 5, 6] })); + panel.appendChild(table(["Find no. / item", "Name", "State", "Qty", "Notes", "Mass", "Cost"].concat(mine ? [""] : []), rows, { numeric: [3, 5, 6] })); panel.appendChild(h("p.hint", { text: tree.line_count + " lines" + (tree.unresolved_count ? " · " + tree.unresolved_count + " without a matching revision" : "") + (tree.restricted_lines ? " · mass and cost exclude " + tree.restricted_lines + " restricted line" + (tree.restricted_lines === 1 ? "" : "s") : "") + " · double-click a line to open it · ⚠ = incomplete mass or cost" })); diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index df153896..5b1ba6f9 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -755,8 +755,10 @@ needs an issue with a reason first (see *Direction*). - [ ] Modern, quieter UI: fewer clicks, modal dialogs and legacy patterns on the common paths – the CAD-user review is #408: quick wins done (#409 check-in icon, #410 one vocabulary + glossary, #411 web check-out wording and *Get TeamCraft Desktop*, #412 preview at the top of the revision page, #413 no hash column, #414 revision vs - version explained), #421 section nav of the revision page, #417 right-click menus in the desktop app; left: the - daily CAD loop (#415, #416, #418–#420) and onboarding (#422–#424) + version explained), #421 section nav of the revision page, #417 right-click menus in the desktop app, #419 (B5) + BOM components picked by search (number, name, file name) in web and desktop, with Add line / quantity / remove in + the desktop *Structure* tab; left: the + daily CAD loop (#415, #416, #418, #420) and onboarding (#422–#424) - [ ] Responsive pages on large data (1M files, 100k items, 10k-line BOMs – see the scale targets) - [ ] Faster opening of large CAD files and assemblies - [ ] Configurable lifecycle states and site-specific allowed transitions instead of one built-in state machine diff --git a/docs/src/dev/threat-model.md b/docs/src/dev/threat-model.md index 5464769a..b27c8d0a 100755 --- a/docs/src/dev/threat-model.md +++ b/docs/src/dev/threat-model.md @@ -102,6 +102,7 @@ enial of service, **E**levation of privilege. | A mutation leaves no trace | R | `audit::record` in the transaction of every service mutation; exceptions listed with a reason | `tests/architecture_guards.rs` `every_service_mutation_writes_an_audit_entry` (#96) | mitigated | | One request makes the server resolve an unbounded list (A2) | D | list lengths are checked before the list is resolved: the affected items of a change request at most `requests::MAX_ITEMS` (100) in the REST API, the MCP tool and again in `requests::create` (distinct items; repeated references are dropped before any lookup – before the CodeQL triage each repeat was looked up and inserted, ~150 000 times for a 2 MB body of one item); simulation results at most `MAX_RESULTS` (2000) per import; JSON bodies are capped by axum's default limit (2 MB) | `tests/change_requests.rs` `too_many_items_are_rejected_before_any_is_resolved` | mitigated for the lists found by CodeQL; no general audit of list fields | | The duplicate check of new files tells what a group holds (#359) | I, D | `POST /projects/{code}/file-check` reads only the requested group, after `projects::get_by_code` and `access::ensure_visible` (a hidden group answers like an unknown code, before the entries are validated); it compares only that group's current files under `access::item_visible`, so a caller learns nothing the file browser of that group would not show; at most 200 files per request and 20 matches per file and kind. The upload guard (`refuse_clash`, `refuse_same_name`) only refuses, inside the group of a revision the caller has checked out (`services::file_check`) | `tests/file_check.rs` `a_restricted_group_is_not_found_and_viewers_may_check`, `bad_requests_are_refused`; `tests/read_permissions.rs` `outsiders_see_nothing_of_a_restricted_group` (every route) | mitigated | +| The component picker suggests items of a restricted group (#419) | I | `GET /items/suggest` (web session only, no bearer token) and `GET /api/v1/items/suggest` call `items::suggest`, which is the item search (`items::search`) with the caller's actor and `access::item_visible`, so a name, file name or number of a hidden item never matches; at most 10 rows, nothing below 2 characters, the text cut at 200; preview images come from files of the readable latest revision (`/files/{id}/thumbnail` checks again). Adding the chosen line still needs the caller's own check-out (`bom::add`) | `tests/component_picker.rs` `items_of_a_restricted_group_never_appear_for_outsiders`, `suggestions_need_a_signed_in_user`, `a_line_needs_my_check_out_through_the_web_form_and_the_api` | mitigated | ## Single sign-on (OIDC) diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index 6118bbfb..81ea83cd 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -86,6 +86,19 @@ check-outs and reviews, and a **local working folder**: the counts existed – are ticked; *Apply* adds and corrects them in one step (the same plan as *Create BOM from CAD references…* in the web UI). A quantity the CAD file does not tell never replaces an existing one; +* *Add line…* (also in the *Structure* tab of a revision you have checked + out) adds a single component: type part of its number, name or file name + and choose one of the matching items – shown with the preview image from + the CAD file, revision, state and project group (↑/↓ and Enter work too); + enter quantity, find number (empty = next free one) and notes, *Add*. An + exact item number works without choosing. Only items you may read are + offered (restricted groups you are not in stay hidden). Under your + check-out the quantity of every first-level line is an input – a change is + saved when you leave it or press Enter (Esc restores it) – and *Remove* + deletes a line after a confirmation; the tab reloads after each change. + These use the same REST routes as the web UI (`GET /items/suggest`, + `POST …/bom`, `PATCH`/`DELETE /bom-lines/{id}`); an older server without + the suggest route is searched through `GET /items?q=`; * the *Graph* tab draws a navigable reference and BOM graph around the revision: the focused item in the middle, its BOM children and references below (*ref*), the assemblies that use it above (*uses*). Every node is a diff --git a/docs/src/guide/structure.md b/docs/src/guide/structure.md index 27d5824f..03b688b9 100755 --- a/docs/src/guide/structure.md +++ b/docs/src/guide/structure.md @@ -55,6 +55,26 @@ that released it and who approved it when (`released_by`: change, title, release time, approvals); a change order the downloader may not see is only marked `restricted`. +### Adding components by search + +*Add component* on the BOM card of a revision you have checked out picks the +child item by search: type at least two characters of its **number, name or +file name** and a list of matching items opens under the field – with the +preview image stored in the CAD file (when there is one), number and latest +revision, state, project group and the file name that matched. Choose a row +with the mouse or with ↑/↓ and Enter (Esc closes the list); the field then +holds the item number, and *Add* adds the line with quantity, find number and +notes as before. At most 10 items are listed, best matches first. + +The list only offers items you may read: items of a restricted project group +you are not a member of never appear, by name, file name or number. Without +JavaScript the field takes the exact item number, as it always did. The list +comes from `GET /items/suggest?q=&limit=` (signed-in session; the REST twin +for scripts and the desktop app is `GET /api/v1/items/suggest`). + +The desktop app offers the same in its *Structure* tab – see +[Desktop app](desktop.md). + ## Creating a BOM from the CAD references An assembly uploaded as a file has no BOM, although the server already knows diff --git a/docs/src/reference/api.md b/docs/src/reference/api.md index f9e87045..53aa666f 100755 --- a/docs/src/reference/api.md +++ b/docs/src/reference/api.md @@ -466,7 +466,7 @@ the caller cannot read are left out; a successor there is a placeholder with | Resource | Endpoints | |-------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Items | `GET/POST /items` (`class=`, `attr=` + `value=`, `result=` + `result_name=` filters), `GET /items/duplicates?name=&type=` (likely duplicates by name, before creating), `POST /items/bulk` (`{"action": "revise"\|"obsolete", "items": [number]}`: the latest revision of up to 200 items, each in its own transaction, outcome per item), `GET/PATCH /items/{number}` (classification, unit, project, folder), `where-used` (`levels=1…25` for parents of parents), `interchange`, `alternates`, `supersession`, `replace`, history, impacts, watch | +| Items | `GET/POST /items` (`class=`, `attr=` + `value=`, `result=` + `result_name=` filters), `GET /items/duplicates?name=&type=` (likely duplicates by name, before creating), `GET /items/suggest?q=&limit=` (component picker of the BOM, #419: readable items whose number, name, description, attributes or file name match – at most 10, nothing for fewer than 2 characters – as `{"items": [{id, number, item_type, unit, name, latest_code, latest_state, project_code, matched_file, thumbnail_file_id}]}`; `thumbnail_file_id` is a file for `GET /files/{id}/thumbnail`; the web UI has the same list at `/items/suggest` for its session), `POST /items/bulk` (`{"action": "revise"\|"obsolete", "items": [number]}`: the latest revision of up to 200 items, each in its own transaction, outcome per item), `GET/PATCH /items/{number}` (classification, unit, project, folder), `where-used` (`levels=1…25` for parents of parents), `interchange`, `alternates`, `supersession`, `replace`, history, impacts, watch | | Attributes | `GET /attributes` (`all=true`: also inactive), `POST /attributes`, `PATCH /attributes/{key}` (admins); values in `attributes` of a revision | | Revisions | `GET/PATCH /items/{number}/revisions/{code\|latest}`, `checkout`, `checkin`, `cancel-checkout`, `file-status`, `revise`, `obsolete` | | Worklist | `GET /worklist` (check-outs, reviews, impacts and `impact_groups`, statistics), `POST /worklist/checkin-all` | diff --git a/src/api/items_api.rs b/src/api/items_api.rs index 710fa388..031ea832 100755 --- a/src/api/items_api.rs +++ b/src/api/items_api.rs @@ -462,6 +462,25 @@ pub(super) async fn item_duplicates( Ok(Json(json!(found))) } +#[derive(Deserialize)] +pub(super) struct SuggestQuery { + #[serde(default)] + q: String, + limit: Option, +} + +/// `GET /api/v1/items/suggest?q=&limit=`: the component picker of the BOM +/// (desktop *Add line*, #419) – readable items matching number, name or file +/// name, with the latest revision and a file with a preview image. +pub(super) async fn item_suggest( + State(st): State, + ApiUser(me): ApiUser, + Query(q): Query, +) -> AppResult> { + let found = items::suggest(&st.db, &me, &q.q, q.limit).await?; + Ok(Json(json!({ "items": found }))) +} + pub(super) async fn get_item( State(st): State, ApiUser(me): ApiUser, diff --git a/src/api/mod.rs b/src/api/mod.rs index 76cafef8..0e6dea20 100755 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -129,6 +129,7 @@ pub fn router(state: &AppState) -> Router { .route("/projects/{code}/default-cad", put(set_project_default_cad)) .route("/items", get(list_items).post(create_item)) .route("/items/duplicates", get(item_duplicates)) + .route("/items/suggest", get(item_suggest)) .route("/items/bulk", post(items_bulk)) .route("/items/{number}", get(get_item).patch(update_item)) .route("/attributes", get(list_attributes).post(create_attribute)) @@ -552,6 +553,7 @@ async fn index() -> Json { "GET /api/v1/items?q=&type=&project=&state=&system=&class=&attr=&value=&limit=&offset= system = CAD program, e.g. solidworks, nx, creo; class = make|purchased|standard; attr + value = custom attribute (value: text contains, yes/no, 12, >=10, <=20, 10..20, empty = has a value)", "POST /api/v1/items {item_type, name, number?, unit?, project?, description?, material?, mass_kg?, unit_cost?, classification?, attributes?, folder?}", "GET /api/v1/items/duplicates?name=&type=&limit= readable items with a similar name (check before creating one)", + "GET /api/v1/items/suggest?q=&limit= component picker: readable items matching number, name or file name (at most 10, q of 2+ characters), latest revision, group, thumbnail_file_id", "POST /api/v1/items/bulk {action: revise|obsolete, items: [number]} – the latest revision of each item, one by one (at most 200)", "GET /api/v1/items/{number}", "PATCH /api/v1/items/{number} {project?, unit?, classification?: make|purchased|standard, folder?} – master data", diff --git a/src/services/items.rs b/src/services/items.rs index 428e8d59..b881ab5f 100755 --- a/src/services/items.rs +++ b/src/services/items.rs @@ -349,6 +349,75 @@ pub async fn search( Ok((rows.into_iter().map(|r| r.item).collect(), total)) } +/// Most suggestions the component picker shows (#419). +pub const SUGGEST_MAX: i64 = 10; +/// Shortest search text the component picker answers (shorter: nothing). +pub const SUGGEST_MIN_CHARS: usize = 2; +/// Longest search text the component picker takes (longer: cut). +const SUGGEST_MAX_CHARS: usize = 200; + +/// One suggestion of the component picker: an item the actor may read whose +/// number, name, description, attributes or file name matched (#419). +#[derive(Clone, Debug, serde::Serialize)] +pub struct Suggestion { + pub id: Uuid, + pub number: String, + pub item_type: String, + pub unit: String, + pub name: String, + pub latest_code: String, + pub latest_state: String, + pub project_code: Option, + /// The file whose name or content matched, if that was the match. + pub matched_file: Option, + /// A file of the latest revision with an embedded preview image + /// (`/files/{id}/thumbnail`), if there is one. + pub thumbnail_file_id: Option, +} + +/// Suggestions of the component picker of the BOM (web *Add component*, +/// desktop *Add line*): the item search ([`search`]) with the actor's read +/// rights – restricted groups the actor does not belong to stay invisible – +/// at most [`SUGGEST_MAX`] rows, nothing for a text shorter than +/// [`SUGGEST_MIN_CHARS`] characters. +pub async fn suggest( + pool: &PgPool, + actor: &Actor, + query: &str, + limit: Option, +) -> AppResult> { + let query: String = query.trim().chars().take(SUGGEST_MAX_CHARS).collect(); + if query.chars().count() < SUGGEST_MIN_CHARS { + return Ok(Vec::new()); + } + let filter = ItemFilter { + query: Some(query), + ..ItemFilter::default() + }; + let page = Page { + limit: limit.unwrap_or(SUGGEST_MAX).clamp(1, SUGGEST_MAX), + offset: 0, + }; + let (rows, _) = search(pool, actor, &filter, page).await?; + let revision_ids: Vec = rows.iter().map(|r| r.latest_revision_id).collect(); + let thumbs = crate::services::similar::thumbnails(pool, &revision_ids).await?; + Ok(rows + .into_iter() + .map(|r| Suggestion { + thumbnail_file_id: thumbs.get(&r.latest_revision_id).copied(), + id: r.id, + number: r.number, + item_type: r.item_type, + unit: r.unit, + name: r.name, + latest_code: r.latest_code, + latest_state: r.latest_state, + project_code: r.project_code, + matched_file: r.matched_file, + }) + .collect()) +} + pub(crate) async fn get_unchecked(pool: impl sqlx::PgExecutor<'_>, id: Uuid) -> AppResult { sqlx::query_as::<_, Item>(&format!("{ITEM_SELECT} WHERE i.id = $1")) .bind(id) diff --git a/src/services/similar.rs b/src/services/similar.rs index 4bdefa2e..b7e8e519 100755 --- a/src/services/similar.rs +++ b/src/services/similar.rs @@ -470,7 +470,10 @@ pub async fn find( } /// Per revision the first file with an embedded preview image. -async fn thumbnails(pool: &PgPool, revision_ids: &[Uuid]) -> AppResult> { +pub(crate) async fn thumbnails( + pool: &PgPool, + revision_ids: &[Uuid], +) -> AppResult> { if revision_ids.is_empty() { return Ok(HashMap::new()); } diff --git a/src/web/items.rs b/src/web/items.rs index cdb5684d..4e05937c 100755 --- a/src/web/items.rs +++ b/src/web/items.rs @@ -285,6 +285,41 @@ pub struct NewQuery { basis: Option, } +#[derive(Deserialize, Default)] +pub struct SuggestQuery { + q: Option, + limit: Option, +} + +/// `GET /items/suggest?q=&limit=`: suggestions of the component picker of +/// the BOM (JSON for static/app.js, #419) – the item search with the +/// signed-in user's read rights, at most 10 rows, nothing for fewer than 2 +/// characters. Session cookie only; the REST twin is `GET /api/v1/items/suggest`. +pub async fn suggest( + State(st): State, + crate::auth::WebUser(me): crate::auth::WebUser, + Query(q): Query, +) -> AppResult { + let found = items::suggest(&st.db, &me, q.q.as_deref().unwrap_or(""), q.limit).await?; + let rows: Vec = found + .iter() + .map(|s| { + let mut row = json!(s); + row["thumbnail_url"] = match s.thumbnail_file_id { + Some(id) => json!(format!("/files/{id}/thumbnail")), + None => Value::Null, + }; + row + }) + .collect(); + let mut response = axum::Json(json!({ "items": rows })).into_response(); + response.headers_mut().insert( + header::CACHE_CONTROL, + header::HeaderValue::from_static("no-store"), + ); + Ok(response) +} + pub async fn new_form( State(st): State, ctx: WebCtx, diff --git a/src/web/mod.rs b/src/web/mod.rs index b6004f27..d3f04aaa 100755 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -116,6 +116,8 @@ pub fn router(state: &AppState) -> Router { .delete(uploads::abort), ) .route("/items/new", get(items::new_form)) + // component picker of the BOM (static/app.js, #419) + .route("/items/suggest", get(items::suggest)) .route("/items/{id}", get(items::show)) .route("/items/{id}/label", get(items::label)) .route("/items/{id}/qr.svg", get(items::qr_svg)) diff --git a/static/app.js b/static/app.js index bc31671b..113e7321 100755 --- a/static/app.js +++ b/static/app.js @@ -630,6 +630,143 @@ select.addEventListener("blur", apply); }); + // Component picker (#419): searches + // number, name and file name as the user types (from 2 characters, at most + // 10 rows, the user's read rights) and lists the matches in the listbox + // named by aria-controls; choosing one fills the item number. Without + // JavaScript the field takes the exact item number as before. + document.querySelectorAll("input[data-suggest]").forEach(function (input) { + var list = document.getElementById(input.getAttribute("aria-controls") || ""); + if (!list) return; + var url = input.getAttribute("data-suggest"); + var placeholder = input.getAttribute("data-suggest-placeholder"); + if (placeholder) input.placeholder = placeholder; + var timer = null, request = null, rows = [], active = -1, lastQuery = null; + + function close() { + list.classList.add("hidden"); + list.replaceChildren(); + input.setAttribute("aria-expanded", "false"); + input.removeAttribute("aria-activedescendant"); + rows = []; active = -1; + } + function highlight(index) { + rows.forEach(function (row, i) { row.el.setAttribute("aria-selected", i === index ? "true" : "false"); }); + active = index; + if (index >= 0 && rows[index]) { + input.setAttribute("aria-activedescendant", rows[index].el.id); + rows[index].el.scrollIntoView({ block: "nearest" }); + } else { + input.removeAttribute("aria-activedescendant"); + } + } + function choose(index) { + var row = rows[index]; + if (!row) return; + input.value = row.item.number; + lastQuery = row.item.number; + close(); + input.dispatchEvent(new Event("change", { bubbles: true })); + } + function text(tag, cls, value) { + var el = document.createElement(tag); + if (cls) el.className = cls; + el.textContent = value; + return el; + } + function render(items) { + list.replaceChildren(); + rows = []; + active = -1; + if (!items.length) { + var empty = text("li", "picker-empty", "No readable item matches."); + empty.setAttribute("role", "presentation"); + list.appendChild(empty); + } + items.forEach(function (item, i) { + var li = document.createElement("li"); + li.id = list.id + "-" + i; + li.className = "picker-option"; + li.setAttribute("role", "option"); + li.setAttribute("aria-selected", "false"); + if (item.thumbnail_url) { + var img = document.createElement("img"); + img.className = "picker-thumb"; + img.alt = ""; + img.loading = "lazy"; + img.src = item.thumbnail_url; + img.addEventListener("error", function () { img.remove(); }); + li.appendChild(img); + } else { + li.appendChild(text("span", "picker-thumb picker-thumb-none", "")); + } + var main = document.createElement("span"); + main.className = "picker-main"; + var head = document.createElement("span"); + head.appendChild(text("span", "mono", item.number + "/" + item.latest_code)); + head.appendChild(document.createTextNode(" ")); + head.appendChild(text("span", "badge badge-" + item.latest_state, item.latest_state.replace(/_/g, " "))); + if (item.project_code) { + head.appendChild(document.createTextNode(" ")); + head.appendChild(text("span", "small muted", item.project_code)); + } + main.appendChild(head); + main.appendChild(text("span", "picker-name", item.name)); + if (item.matched_file) main.appendChild(text("span", "small muted mono", item.matched_file)); + li.appendChild(main); + // mousedown, not click: the input must not lose focus (and close) first + li.addEventListener("mousedown", function (event) { event.preventDefault(); choose(i); }); + list.appendChild(li); + rows.push({ el: li, item: item }); + }); + list.classList.remove("hidden"); + input.setAttribute("aria-expanded", "true"); + } + function lookup() { + var q = input.value.trim(); + if (q === lastQuery) return; + lastQuery = q; + if (request) request.abort(); + if (q.length < 2) { close(); return; } + request = new AbortController(); + fetch(url + "?limit=10&q=" + encodeURIComponent(q), { + credentials: "same-origin", headers: { Accept: "application/json" }, signal: request.signal + }).then(function (response) { + if (!response.ok) throw new Error("HTTP " + response.status); + return response.json(); + }).then(function (body) { + if (input.value.trim() !== q) return; + render(body.items || []); + }).catch(function (err) { + if (err && err.name === "AbortError") return; + close(); // the field still takes an exact number + }); + } + input.addEventListener("input", function () { + clearTimeout(timer); + timer = setTimeout(lookup, 200); + }); + input.addEventListener("keydown", function (event) { + var open = !list.classList.contains("hidden") && rows.length > 0; + if (event.key === "ArrowDown") { + if (!open) { lastQuery = null; lookup(); return; } + event.preventDefault(); + highlight(active < rows.length - 1 ? active + 1 : 0); + } else if (event.key === "ArrowUp" && open) { + event.preventDefault(); + highlight(active > 0 ? active - 1 : rows.length - 1); + } else if (event.key === "Enter" && open && active >= 0) { + event.preventDefault(); // pick the row, do not submit yet + choose(active); + } else if (event.key === "Escape" && !list.classList.contains("hidden")) { + event.preventDefault(); + event.stopPropagation(); + close(); + } + }); + input.addEventListener("blur", function () { setTimeout(close, 100); }); + }); + // BOM tree: every line with lines below it gets a toggle button that folds // its branch. Without JavaScript all rows stay visible. Rows carry // data-level; the lines below a row are the following rows with a higher diff --git a/static/style.css b/static/style.css index 05e4cbaa..922e1c5c 100755 --- a/static/style.css +++ b/static/style.css @@ -784,7 +784,7 @@ form.inline input.item-no { width: 26ch; min-width: 18ch; max-width: 100%; } /* An inline form with short labels above its fields (Add component). */ form.inline.fields { align-items: flex-end; gap: var(--space-2); } :is(.empty, .table-wrap) + form.inline.fields { margin-top: var(--space-3); } -form.inline.fields > label { gap: 2px; font-size: 12px; line-height: 16px; } +form.inline.fields > label, form.inline.fields > .picker > label { gap: 2px; font-size: 12px; line-height: 16px; } form.inline.fields > label.grow { flex: 1 1 12rem; } form.inline.fields > label.grow input { width: 100%; } @@ -1524,3 +1524,20 @@ pre.json { max-height: 24rem; overflow: auto; white-space: pre-wrap; overflow-wr .section-nav .count { color: var(--text-dim); font-size: 12px; font-weight: 400; } /* anchors land below the top bar and the section nav */ .section-nav ~ * section.card[id], .section-nav ~ section.card[id] { scroll-margin-top: calc(var(--topbar-h) + 52px); } + +/* Component picker of the BOM (#419, static/app.js): suggestions under the + item field of *Add component*. */ +.picker { position: relative; display: inline-flex; flex-direction: column; } +.picker-list { + position: absolute; top: 100%; left: 0; z-index: 30; + min-width: 22rem; max-width: min(36rem, 90vw); max-height: 22rem; overflow-y: auto; + margin: 2px 0 0; padding: 4px 0; list-style: none; + background: var(--surface); border: 1px solid var(--border-strong); border-radius: 6px; + box-shadow: var(--shadow-pop); +} +.picker-option { display: flex; gap: var(--space-2, 8px); align-items: center; padding: 4px 8px; cursor: pointer; } +.picker-option:hover, .picker-option[aria-selected="true"] { background: var(--selected); } +.picker-thumb { flex: none; width: 40px; height: 40px; object-fit: contain; border-radius: 4px; background: var(--surface-sunken); } +.picker-main { display: flex; flex-direction: column; min-width: 0; } +.picker-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.picker-empty { padding: 6px 10px; color: var(--text-muted); } diff --git a/templates/revisions/show.html b/templates/revisions/show.html index 72955f67..ea91de93 100755 --- a/templates/revisions/show.html +++ b/templates/revisions/show.html @@ -859,7 +859,12 @@

Bill of materials (single level)

{% if can.edit %}

Add component

- + + + + diff --git a/tests/component_picker.rs b/tests/component_picker.rs new file mode 100644 index 00000000..4d746c42 --- /dev/null +++ b/tests/component_picker.rs @@ -0,0 +1,325 @@ +//! The component picker of the BOM (#419): `GET /items/suggest` (web, session +//! cookie) and `GET /api/v1/items/suggest` (REST) find items by part of the +//! number, name or file name, with the user's read rights – items of a +//! restricted group the user does not belong to never appear – and adding a +//! line still needs the user's own check-out, through the web form and the API. + +mod common; + +use axum::http::{Method, StatusCode}; +use serde_json::{json, Value}; +use teamcraft::domain::Role; + +macro_rules! app_or_skip { + () => { + match common::setup().await { + Some(app) => app, + None => return, + } + }; +} + +/// Numbers of the suggestions in a picker answer (`{"items": [...]}`). +fn numbers(body: &Value) -> Vec { + body["items"] + .as_array() + .unwrap_or_else(|| panic!("no items in {body}")) + .iter() + .map(|i| i["number"].as_str().unwrap().to_string()) + .collect() +} + +async fn web_suggest(app: &common::TestApp, cookie: &str, q: &str) -> Value { + let r = app + .get_page( + &format!("/items/suggest?q={}", teamcraft::util::pct_encode(q)), + Some(cookie), + ) + .await; + assert_eq!(r.status, StatusCode::OK, "suggest {q}: {}", r.text()); + r.json() +} + +async fn api_suggest(app: &common::TestApp, token: &str, q: &str) -> Value { + let r = app + .api( + Method::GET, + &format!("/api/v1/items/suggest?q={}", teamcraft::util::pct_encode(q)), + token, + None, + ) + .await; + assert_eq!(r.status, StatusCode::OK, "api suggest {q}: {}", r.text()); + r.json() +} + +#[tokio::test] +async fn suggestions_match_part_of_the_name_and_of_the_file_name() { + let app = app_or_skip!(); + let (_, eng) = app.user_in("eng", Role::Editor, &["ROCKET"]).await; + let bracket = app + .create_item( + &eng, + json!({ "item_type": "part", "name": "Fin bracket", "project": "ROCKET" }), + ) + .await; + let cone = app + .create_item( + &eng, + json!({ "item_type": "part", "name": "Tip", "project": "ROCKET" }), + ) + .await; + let r = app + .api_upload( + &format!("/api/v1/items/{cone}/revisions/A/files"), + &eng, + "nosecone-ogive.txt", + b"ogive", + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.text()); + let cookie = app.login("eng").await; + + // part of the name + let found = web_suggest(&app, &cookie, "bRACk").await; + assert_eq!(numbers(&found), vec![bracket.clone()], "{found}"); + let row = &found["items"][0]; + assert_eq!(row["name"], "Fin bracket"); + assert_eq!(row["latest_code"], "A"); + assert_eq!(row["latest_state"], "in_work"); + assert_eq!(row["project_code"], "ROCKET"); + assert!(row["thumbnail_url"].is_null(), "no preview image: {row}"); + + // part of the file name, with the file that matched + let found = web_suggest(&app, &cookie, "nosecone-og").await; + assert_eq!(numbers(&found), vec![cone.clone()], "{found}"); + assert_eq!(found["items"][0]["matched_file"], "nosecone-ogive.txt"); + + // part of the number + let digits = bracket.rsplit('-').next().unwrap(); + assert!(numbers(&web_suggest(&app, &cookie, digits).await).contains(&bracket)); + + // the REST twin answers the same + let found = api_suggest(&app, &eng, "nosecone").await; + assert_eq!(numbers(&found), vec![cone.clone()], "{found}"); + assert!(found["items"][0]["thumbnail_file_id"].is_null()); + + // fewer than 2 characters: nothing; the limit is capped at 10 + assert!(numbers(&web_suggest(&app, &cookie, "b").await).is_empty()); + assert!(numbers(&api_suggest(&app, &eng, " ").await).is_empty()); + for i in 0..12 { + app.create_item( + &eng, + json!({ "item_type": "part", "name": format!("Washer {i}"), "project": "ROCKET" }), + ) + .await; + } + let r = app + .get_page("/items/suggest?q=washer&limit=500", Some(&cookie)) + .await; + assert_eq!(numbers(&r.json()).len(), 10, "{}", r.text()); + let r = app + .api( + Method::GET, + "/api/v1/items/suggest?q=washer&limit=3", + &eng, + None, + ) + .await; + assert_eq!(numbers(&r.json()).len(), 3, "{}", r.text()); + app.teardown().await; +} + +#[tokio::test] +async fn items_of_a_restricted_group_never_appear_for_outsiders() { + let app = app_or_skip!(); + let (_, erika) = app.user("erika", Role::Editor).await; + let (_, vera) = app.user_in("vera", Role::Editor, &["ROCKET"]).await; + let r = app + .api( + Method::POST, + "/api/v1/projects", + &erika, + Some(json!({ "code": "NTK", "name": "Need to know", "visibility": "restricted" })), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.text()); + let secret = app + .create_item( + &erika, + json!({ "item_type": "part", "name": "Secret bracket", "project": "NTK" }), + ) + .await; + let r = app + .api_upload( + &format!("/api/v1/items/{secret}/revisions/A/files"), + &erika, + "secret-bracket.txt", + b"secret", + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.text()); + let open = app + .create_item( + &vera, + json!({ "item_type": "part", "name": "Open bracket", "project": "ROCKET" }), + ) + .await; + + // the member finds it + let erika_cookie = app.login("erika").await; + assert!(numbers(&web_suggest(&app, &erika_cookie, "secret").await).contains(&secret)); + + // the outsider does not – neither by name, file name nor number + let cookie = app.login("vera").await; + for q in ["bracket", "secret", "secret-bracket.txt", secret.as_str()] { + let web = web_suggest(&app, &cookie, q).await; + assert!(!numbers(&web).contains(&secret), "web {q}: {web}"); + assert!(!web.to_string().contains("Secret"), "web {q}: {web}"); + let api = api_suggest(&app, &vera, q).await; + assert!(!numbers(&api).contains(&secret), "api {q}: {api}"); + } + assert_eq!( + numbers(&web_suggest(&app, &cookie, "bracket").await), + vec![open] + ); + app.teardown().await; +} + +#[tokio::test] +async fn suggestions_need_a_signed_in_user() { + let app = app_or_skip!(); + let (_, eng) = app.user_in("eng", Role::Editor, &["ROCKET"]).await; + let number = app + .create_item( + &eng, + json!({ "item_type": "part", "name": "Fin bracket", "project": "ROCKET" }), + ) + .await; + // no session: refused (redirect to the sign-in or 401), nothing listed + let r = app.get_page("/items/suggest?q=bracket", None).await; + assert_ne!(r.status, StatusCode::OK, "{}", r.text()); + assert!(!r.text().contains(&number), "{}", r.text()); + // the web route takes the session cookie only, never a bearer token + let r = app + .send( + axum::http::Request::builder() + .uri("/items/suggest?q=bracket") + .header(axum::http::header::AUTHORIZATION, format!("Bearer {eng}")) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await; + assert_ne!(r.status, StatusCode::OK, "{}", r.text()); + assert!(!r.text().contains(&number)); + // the REST route needs a token + let r = app + .api( + Method::GET, + "/api/v1/items/suggest?q=bracket", + "tc_pat_invalid", + None, + ) + .await; + assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{}", r.text()); + app.teardown().await; +} + +#[tokio::test] +async fn a_line_needs_my_check_out_through_the_web_form_and_the_api() { + let app = app_or_skip!(); + let (_, erika) = app.user_in("erika", Role::Editor, &["ROCKET"]).await; + let (_, vera) = app.user_in("vera", Role::Editor, &["ROCKET"]).await; + let parent = app + .create_item( + &erika, + json!({ "item_type": "assembly", "name": "Fin can", "project": "ROCKET" }), + ) + .await; + let child = app + .create_item( + &erika, + json!({ "item_type": "part", "name": "Fin bracket", "project": "ROCKET" }), + ) + .await; + let rev_uri = format!("/api/v1/items/{parent}/revisions/A"); + let rev_id = app.api(Method::GET, &rev_uri, &erika, None).await.json()["revision"]["id"] + .as_str() + .unwrap() + .to_string(); + let bom_len = |token: String| { + let app = &app; + let rev_uri = rev_uri.clone(); + async move { + app.api(Method::GET, &rev_uri, &token, None).await.json()["bom"] + .as_array() + .map_or(0, Vec::len) + } + }; + let api_add = |token: String| { + let app = &app; + let uri = format!("{rev_uri}/bom"); + let child = child.clone(); + async move { + app.api( + Method::POST, + &uri, + &token, + Some(json!({ "child": child, "quantity": 2 })), + ) + .await + } + }; + let web_add = |user: &'static str| { + let app = &app; + let uri = format!("/revisions/{rev_id}/bom/lines"); + let child = child.clone(); + async move { + let cookie = app.login(user).await; + app.post_form( + &uri, + Some(&cookie), + Some("http://localhost:8080"), + &[ + ("child", child.as_str()), + ("quantity", "2"), + ("find_number", ""), + ("notes", ""), + ], + ) + .await + } + }; + + // not checked out by anyone: refused + let r = api_add(erika.clone()).await; + assert_eq!(r.status, StatusCode::CONFLICT, "{}", r.text()); + let r = web_add("erika").await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + assert_eq!( + bom_len(erika.clone()).await, + 0, + "the web form added a line without a check-out" + ); + + // checked out by erika: vera is refused through both + let r = app + .api(Method::POST, &format!("{rev_uri}/checkout"), &erika, None) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.text()); + let r = api_add(vera.clone()).await; + assert!(r.status.is_client_error(), "{} {}", r.status, r.text()); + let r = web_add("vera").await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + assert_eq!( + bom_len(erika.clone()).await, + 0, + "vera added a line to erika's check-out" + ); + + // erika's own check-out: the web form adds the line + let r = web_add("erika").await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + assert_eq!(bom_len(erika.clone()).await, 1); + app.teardown().await; +} From cc506e0f552f184039bb58537e32177ba0b0ac1a Mon Sep 17 00:00:00 2001 From: fork Date: Sun, 22 Nov 2026 20:46:51 +0100 Subject: [PATCH 2/2] Component picker: review findings (#419) - test: release the author's automatic check-out before the "not checked out" case, so the refusal is really exercised - desktop: drop a stale choice on typing, Esc closes only the suggestions, aria-activedescendant and a live status line - web: a late answer after blur no longer reopens the list Co-Authored-By: Claude Opus 5.5 --- desktop/README.md | 2 +- desktop/ui/js/bom-lines.js | 19 ++++++++++++++++--- docs/src/guide/desktop.md | 2 +- static/app.js | 12 ++++++++++-- tests/component_picker.rs | 11 +++++++++++ 5 files changed, 39 insertions(+), 7 deletions(-) diff --git a/desktop/README.md b/desktop/README.md index 66084aef..e70ace9f 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -46,7 +46,7 @@ TeamCraft server – it is a client, not an offline copy. | New on this computer | Worklist section (#359, editors): the parts and assemblies in the working folder that belong to no item yet, one suggestion per model file with its drawing and exports of the same name in the same folder, newest first, counted on the rail. A click opens *New* prefilled, *Create items…* creates the ticked ones after a summary of what is created and what is refused, *×* ignores a file (`.teamcraft/ignored.json`, *Show ignored*; entries of files that are gone are dropped after a complete scan). The scan (`desktop/src/newfiles.rs`, `new_files_scan`) skips tracked and added files, companions of tracked files, lock/backup/temporary files, `OldVersions` and hidden folders; at most 50 000 entries and 2 000 files per scan, run when the worklist opens or the window gets the focus back (at most every 15 s). Nothing is uploaded without the dialog or the summary | | App version | The version of the app above the logo at the bottom of the rail, always visible (#357) | | Import BOM | *Import BOM…* in the *Structure* tab (and the *More* menu) of a revision you have checked out, *Tools → Import BOM as New Assembly…* for a new one: a BOM exported by the CAD program (CSV, TSV, Excel, ODS or a STEP assembly, chosen in the native dialog) goes to the server's BOM import as a dry run first – the dialog shows the counts of lines, new and existing items, the notes and the first lines – and *Import* creates the lines and missing items in one transaction (numbers from the file or the group's numbering scheme, reuse of existing items optional) | -| BOM lines | *Add line…* in the *Structure* tab of a revision you have checked out (`js/bom-lines.js`, #419): a component picker searches number, name and file name (`GET /items/suggest`, older servers `GET /items?q=`; preview image, revision, state, group; ↑/↓ + Enter), then quantity, find number and notes (`POST /items/{n}/revisions/{c}/bom`); under the own check-out every first-level line has an editable quantity (`PATCH /bom-lines/{id}`) and *Remove* (`DELETE /bom-lines/{id}`, confirmed); the tab reloads after each change | +| BOM lines | *Add line…* in the *Structure* tab of a revision you have checked out (`js/bom-lines.js`, #419): a component picker searches number, name and file name (`GET /items/suggest`, older servers `GET /items?q=`; preview image, revision, state, group; ↑/↓ + Enter, Esc closes the list), then quantity, find number and notes (`POST /items/{n}/revisions/{c}/bom`); under the own check-out every first-level line has an editable quantity (`PATCH /bom-lines/{id}`) and *Remove* (`DELETE /bom-lines/{id}`, confirmed); the tab reloads after each change | | Release and changes | *Release…* creates and submits a change order – with the unreleased dependencies (BOM children, drawings) by default; the own user name is refused as reviewer, with nobody else in the group it creates a draft, and a refused revision or reviewer cancels the half-made draft again (#291); *Release readiness* panel with *Add all*; on a draft *Add reviewer* by user name, *Remove* and *Cancel change*, *Submit for review* disabled with the reason while a revision or reviewer is missing; approve/reject from the worklist | | Change requests | *Request change…* on a revision tab and *Request…* on a file (Files and Workspace tabs) raise a change request prefilled with item, revision and file name, with an optional screenshot or PDF (native file dialog, uploaded by the Rust side); request tabs with discussion, decision (accept / defer / reject), *Create change order*, attachments; *Requests assigned to me* and *My open requests* in the worklist | | Change propagation | *Dependents to check* grouped by dependent revision (one worklist line with a count, expandable; on the home page **Open**, **Revise**, **Acknowledge all…** per dependent and **Acknowledge…** per change), *Check needed* on the revision tab, references, *As released* rule, impact analysis | diff --git a/desktop/ui/js/bom-lines.js b/desktop/ui/js/bom-lines.js index 56ee8551..0041cb85 100644 --- a/desktop/ui/js/bom-lines.js +++ b/desktop/ui/js/bom-lines.js @@ -49,7 +49,7 @@ export function addLineDialog(rev) { var search = h("input", { type: "text", autocomplete: "off", placeholder: "Number, name or file name", role: "combobox", "aria-autocomplete": "list", "aria-expanded": "false", "aria-controls": "add-line-suggestions" }); var list = h("ul.picker-list.static", { id: "add-line-suggestions", role: "listbox", "aria-label": "Matching items" }); - var info = h("p.hint", { text: "Type at least 2 characters." }); + var info = h("p.hint", { text: "Type at least 2 characters.", role: "status", "aria-live": "polite" }); var qty = h("input.qty", { type: "text", value: "1", inputmode: "decimal" }); var find = h("input.find", { type: "text", placeholder: "auto", inputmode: "numeric" }); var notes = h("input", { type: "text", placeholder: "optional", maxlength: "500" }); @@ -57,7 +57,12 @@ export function addLineDialog(rev) { function highlight(i) { active = i; rows.forEach(function (r, k) { r.el.setAttribute("aria-selected", k === i || (i < 0 && chosen === r.item) ? "true" : "false"); }); - if (i >= 0 && rows[i]) rows[i].el.scrollIntoView({ block: "nearest" }); + if (i >= 0 && rows[i]) { + search.setAttribute("aria-activedescendant", rows[i].el.id); + rows[i].el.scrollIntoView({ block: "nearest" }); + } else { + search.removeAttribute("aria-activedescendant"); + } } function choose(i) { var r = rows[i]; @@ -74,6 +79,7 @@ export function addLineDialog(rev) { list.replaceChildren(); rows = []; active = -1; + search.removeAttribute("aria-activedescendant"); items.forEach(function (item, i) { var li = h("li.picker-option", { id: "add-line-option-" + i, role: "option", "aria-selected": "false", on: { mousedown: function (e) { e.preventDefault(); choose(i); } } }, [ @@ -101,12 +107,19 @@ export function addLineDialog(rev) { suggestItems(q).then(function (items) { if (search.value.trim() === q) render(items); }, function (err) { info.textContent = errorText(err); }); } - search.addEventListener("input", function () { clearTimeout(timer); timer = setTimeout(lookup, 200); }); + search.addEventListener("input", function () { + // a typed change drops the earlier choice at once, not after the debounce + if (chosen && search.value.trim() !== chosen.number) chosen = null; + clearTimeout(timer); + timer = setTimeout(lookup, 200); + }); search.addEventListener("keydown", function (e) { if (!rows.length) return; if (e.key === "ArrowDown") { e.preventDefault(); highlight(active < rows.length - 1 ? active + 1 : 0); } else if (e.key === "ArrowUp") { e.preventDefault(); highlight(active > 0 ? active - 1 : rows.length - 1); } else if (e.key === "Enter" && active >= 0) { e.preventDefault(); e.stopPropagation(); choose(active); } + // Escape closes the suggestions only, not the whole dialog + else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); render([]); info.textContent = ""; } }); var body = h("div.stack", null, [ diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index 81ea83cd..9d000705 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -89,7 +89,7 @@ check-outs and reviews, and a **local working folder**: * *Add line…* (also in the *Structure* tab of a revision you have checked out) adds a single component: type part of its number, name or file name and choose one of the matching items – shown with the preview image from - the CAD file, revision, state and project group (↑/↓ and Enter work too); + the CAD file, revision, state and project group (↑/↓ and Enter work too, Esc closes the list); enter quantity, find number (empty = next free one) and notes, *Add*. An exact item number works without choosing. Only items you may read are offered (restricted groups you are not in stay hidden). Under your diff --git a/static/app.js b/static/app.js index 113e7321..a25a0e77 100755 --- a/static/app.js +++ b/static/app.js @@ -735,7 +735,7 @@ if (!response.ok) throw new Error("HTTP " + response.status); return response.json(); }).then(function (body) { - if (input.value.trim() !== q) return; + if (input.value.trim() !== q || document.activeElement !== input) return; render(body.items || []); }).catch(function (err) { if (err && err.name === "AbortError") return; @@ -764,7 +764,15 @@ close(); } }); - input.addEventListener("blur", function () { setTimeout(close, 100); }); + input.addEventListener("blur", function () { + setTimeout(function () { + // a late answer must not reopen the list under a field without focus + clearTimeout(timer); + if (request) { request.abort(); request = null; } + lastQuery = null; // refocusing and typing searches again + close(); + }, 100); + }); }); // BOM tree: every line with lines below it gets a toggle button that folds diff --git a/tests/component_picker.rs b/tests/component_picker.rs index 4d746c42..641cd9f2 100644 --- a/tests/component_picker.rs +++ b/tests/component_picker.rs @@ -291,6 +291,17 @@ async fn a_line_needs_my_check_out_through_the_web_form_and_the_api() { } }; + // A new item is checked out to its author: release it first. + let r = app + .api( + Method::POST, + &format!("{rev_uri}/cancel-checkout"), + &erika, + None, + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.text()); + // not checked out by anyone: refused let r = api_add(erika.clone()).await; assert_eq!(r.status, StatusCode::CONFLICT, "{}", r.text());