Compare commits
3 Commits
3f47e273ad
...
9a11e3cfc6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a11e3cfc6 | ||
|
|
f88a459e12 | ||
|
|
b49546b297 |
@@ -10,6 +10,20 @@ from ..schemas import LocationCreate, LocationOut, LocationUpdate
|
|||||||
router = APIRouter(prefix="/locations", tags=["locations"])
|
router = APIRouter(prefix="/locations", tags=["locations"])
|
||||||
|
|
||||||
|
|
||||||
|
def _descendant_ids(db: Session, location_id: int) -> set[int]:
|
||||||
|
"""Alle Unterorte (rekursiv) – als Ziel beim Umhängen ausgeschlossen, sonst
|
||||||
|
entstünde ein Ring."""
|
||||||
|
result: set[int] = set()
|
||||||
|
stack = [location_id]
|
||||||
|
while stack:
|
||||||
|
cur = stack.pop()
|
||||||
|
for kid in db.query(Location).filter(Location.parent_id == cur).all():
|
||||||
|
if kid.id not in result:
|
||||||
|
result.add(kid.id)
|
||||||
|
stack.append(kid.id)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=list[LocationOut])
|
@router.get("", response_model=list[LocationOut])
|
||||||
def list_locations(
|
def list_locations(
|
||||||
db: Session = Depends(get_db), _: User = Depends(get_current_user)
|
db: Session = Depends(get_db), _: User = Depends(get_current_user)
|
||||||
@@ -37,12 +51,16 @@ def update_location(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
_: User = Depends(require_admin),
|
_: User = Depends(require_admin),
|
||||||
) -> Location:
|
) -> Location:
|
||||||
"""Umbenennen. Chargen haengen an der ID, behalten ihren Lagerort also."""
|
"""Umbenennen und/oder umhängen. Chargen haengen an der ID, behalten ihren
|
||||||
|
Lagerort also."""
|
||||||
loc = db.get(Location, location_id)
|
loc = db.get(Location, location_id)
|
||||||
if loc is None:
|
if loc is None:
|
||||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Lagerort nicht gefunden")
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Lagerort nicht gefunden")
|
||||||
|
|
||||||
name = payload.name.strip()
|
data = payload.model_dump(exclude_unset=True)
|
||||||
|
|
||||||
|
if "name" in data and data["name"]:
|
||||||
|
name = data["name"].strip()
|
||||||
doppelt = (
|
doppelt = (
|
||||||
db.query(Location)
|
db.query(Location)
|
||||||
.filter(func.lower(Location.name) == name.lower(), Location.id != location_id)
|
.filter(func.lower(Location.name) == name.lower(), Location.id != location_id)
|
||||||
@@ -50,8 +68,24 @@ def update_location(
|
|||||||
)
|
)
|
||||||
if doppelt is not None:
|
if doppelt is not None:
|
||||||
raise HTTPException(status.HTTP_409_CONFLICT, "Diesen Lagerort gibt es bereits")
|
raise HTTPException(status.HTTP_409_CONFLICT, "Diesen Lagerort gibt es bereits")
|
||||||
|
|
||||||
loc.name = name
|
loc.name = name
|
||||||
|
|
||||||
|
# parent_id nur anfassen, wenn ausdrücklich mitgeschickt (None = oberste Ebene).
|
||||||
|
if "parent_id" in data:
|
||||||
|
neu = data["parent_id"]
|
||||||
|
if neu is not None:
|
||||||
|
if db.get(Location, neu) is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status.HTTP_404_NOT_FOUND, "Übergeordneter Lagerort nicht gefunden"
|
||||||
|
)
|
||||||
|
if neu == location_id or neu in _descendant_ids(db, location_id):
|
||||||
|
raise HTTPException(
|
||||||
|
status.HTTP_400_BAD_REQUEST,
|
||||||
|
"Ein Lagerort kann nicht sich selbst oder einem seiner Unterorte "
|
||||||
|
"untergeordnet werden.",
|
||||||
|
)
|
||||||
|
loc.parent_id = neu
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(loc)
|
db.refresh(loc)
|
||||||
return loc
|
return loc
|
||||||
|
|||||||
@@ -235,7 +235,8 @@ class LocationCreate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class LocationUpdate(BaseModel):
|
class LocationUpdate(BaseModel):
|
||||||
name: str = Field(min_length=1, max_length=120)
|
name: str | None = Field(default=None, min_length=1, max_length=120)
|
||||||
|
parent_id: int | None = None
|
||||||
|
|
||||||
|
|
||||||
# ---- Gebinde (Packung, Glas, …) ----
|
# ---- Gebinde (Packung, Glas, …) ----
|
||||||
|
|||||||
71
backend/tests/test_locations.py
Normal file
71
backend/tests/test_locations.py
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
"""Lagerorte: Umbenennen und Umhängen (mit Schutz vor Ringen)."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from app.models import Location, Role, User
|
||||||
|
from app.routers.locations import update_location
|
||||||
|
from app.schemas import LocationUpdate
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def admin(db):
|
||||||
|
person = User(username="admin", password_hash="x", role=Role.admin)
|
||||||
|
db.add(person)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(person)
|
||||||
|
return person
|
||||||
|
|
||||||
|
|
||||||
|
def _orte(db):
|
||||||
|
"""Keller → Regal → Fach."""
|
||||||
|
keller = Location(name="Keller")
|
||||||
|
db.add(keller)
|
||||||
|
db.flush()
|
||||||
|
regal = Location(name="Regal", parent_id=keller.id)
|
||||||
|
db.add(regal)
|
||||||
|
db.flush()
|
||||||
|
fach = Location(name="Fach", parent_id=regal.id)
|
||||||
|
db.add(fach)
|
||||||
|
db.commit()
|
||||||
|
return keller, regal, fach
|
||||||
|
|
||||||
|
|
||||||
|
def test_umbenennen_ohne_parent_bleibt_hierarchie(db, admin):
|
||||||
|
keller, regal, _ = _orte(db)
|
||||||
|
out = update_location(regal.id, LocationUpdate(name="Regal links"), db=db, _=admin)
|
||||||
|
assert out.name == "Regal links"
|
||||||
|
assert out.parent_id == keller.id # Umhängen war nicht gemeint
|
||||||
|
|
||||||
|
|
||||||
|
def test_umhaengen_setzt_neuen_parent(db, admin):
|
||||||
|
keller, _, fach = _orte(db)
|
||||||
|
out = update_location(fach.id, LocationUpdate(parent_id=keller.id), db=db, _=admin)
|
||||||
|
assert out.parent_id == keller.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_umhaengen_auf_oberste_ebene(db, admin):
|
||||||
|
_, regal, _ = _orte(db)
|
||||||
|
out = update_location(regal.id, LocationUpdate(parent_id=None), db=db, _=admin)
|
||||||
|
assert out.parent_id is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_umhaengen_auf_sich_selbst_wird_abgelehnt(db, admin):
|
||||||
|
keller, _, _ = _orte(db)
|
||||||
|
with pytest.raises(HTTPException) as ex:
|
||||||
|
update_location(keller.id, LocationUpdate(parent_id=keller.id), db=db, _=admin)
|
||||||
|
assert ex.value.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_umhaengen_in_eigenen_unterort_wird_abgelehnt(db, admin):
|
||||||
|
keller, _, fach = _orte(db)
|
||||||
|
with pytest.raises(HTTPException) as ex:
|
||||||
|
update_location(keller.id, LocationUpdate(parent_id=fach.id), db=db, _=admin)
|
||||||
|
assert ex.value.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_umhaengen_auf_unbekannten_ort_ist_404(db, admin):
|
||||||
|
_, _, fach = _orte(db)
|
||||||
|
with pytest.raises(HTTPException) as ex:
|
||||||
|
update_location(fach.id, LocationUpdate(parent_id=99999), db=db, _=admin)
|
||||||
|
assert ex.value.status_code == 404
|
||||||
@@ -280,6 +280,29 @@ actor APIClient {
|
|||||||
try await send(try makeRequest("/categories/\(categoryId)/fields"), as: [FieldDefinition].self)
|
try await send(try makeRequest("/categories/\(categoryId)/fields"), as: [FieldDefinition].self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Nur die *eigenen* Felder einer Kategorie (ohne vererbte) – fuer die
|
||||||
|
/// Feldverwaltung, wo man sie anlegt, bearbeitet und loescht.
|
||||||
|
func ownFieldDefinitions(categoryId: Int) async throws -> [FieldDefinition] {
|
||||||
|
try await send(try makeRequest("/field-definitions?category_id=\(categoryId)"),
|
||||||
|
as: [FieldDefinition].self)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createFieldDefinition(_ payload: FieldDefinitionCreate) async throws -> FieldDefinition {
|
||||||
|
var request = try makeRequest("/field-definitions", method: "POST")
|
||||||
|
try jsonBody(&request, payload)
|
||||||
|
return try await send(request, as: FieldDefinition.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateFieldDefinition(id: Int, _ payload: FieldDefinitionUpdate) async throws -> FieldDefinition {
|
||||||
|
var request = try makeRequest("/field-definitions/\(id)", method: "PATCH")
|
||||||
|
try jsonBody(&request, payload)
|
||||||
|
return try await send(request, as: FieldDefinition.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteFieldDefinition(id: Int) async throws {
|
||||||
|
try await sendNoContent(try makeRequest("/field-definitions/\(id)", method: "DELETE"))
|
||||||
|
}
|
||||||
|
|
||||||
/// Menge eines Gegenstands an einem Lagerort erhoehen.
|
/// Menge eines Gegenstands an einem Lagerort erhoehen.
|
||||||
func objectCheckIn(_ payload: ObjectCheckInRequest) async throws -> StockResponse {
|
func objectCheckIn(_ payload: ObjectCheckInRequest) async throws -> StockResponse {
|
||||||
var request = try makeRequest("/stock/checkin", method: "POST")
|
var request = try makeRequest("/stock/checkin", method: "POST")
|
||||||
@@ -358,6 +381,12 @@ actor APIClient {
|
|||||||
return try await send(request, as: StorageLocation.self)
|
return try await send(request, as: StorageLocation.self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func updateLocation(id: Int, _ payload: LocationUpdateRequest) async throws -> StorageLocation {
|
||||||
|
var request = try makeRequest("/locations/\(id)", method: "PATCH")
|
||||||
|
try jsonBody(&request, payload)
|
||||||
|
return try await send(request, as: StorageLocation.self)
|
||||||
|
}
|
||||||
|
|
||||||
func deleteLocation(id: Int) async throws {
|
func deleteLocation(id: Int) async throws {
|
||||||
try await sendNoContent(try makeRequest("/locations/\(id)", method: "DELETE"))
|
try await sendNoContent(try makeRequest("/locations/\(id)", method: "DELETE"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -430,9 +430,9 @@ struct LocationsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lagerort anlegen (mit optionalem Elternort, um die Hierarchie aufzubauen)
|
/// Lagerort anlegen oder bearbeiten: Name **und** übergeordneter Ort. So lässt
|
||||||
/// oder umbenennen. Umhängen unterstützt der Server nicht – beim Bearbeiten
|
/// sich die Hierarchie auch nachträglich ändern (umhängen). Beim Bearbeiten sind
|
||||||
/// gibt es deshalb nur den Namen.
|
/// der Ort selbst und seine Unterorte als Ziel ausgeschlossen (kein Ring).
|
||||||
struct LocationEditor: View {
|
struct LocationEditor: View {
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
@@ -453,31 +453,33 @@ struct LocationEditor: View {
|
|||||||
_parentId = State(initialValue: item?.parentId)
|
_parentId = State(initialValue: item?.parentId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var parentOptions: [StorageLocation] {
|
||||||
|
guard let item else { return all }
|
||||||
|
let verboten = LocationEditor.descendants(of: item.id, in: all).union([item.id])
|
||||||
|
return all.filter { !verboten.contains($0.id) }
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationStack {
|
NavigationStack {
|
||||||
Form {
|
Form {
|
||||||
Section("Name") {
|
Section("Name") {
|
||||||
TextField("z. B. Keller", text: $name)
|
TextField("z. B. Keller", text: $name)
|
||||||
}
|
}
|
||||||
// Elternort nur beim Anlegen: der Server kann bestehende Orte
|
|
||||||
// nicht umhängen.
|
|
||||||
if item == nil {
|
|
||||||
Section {
|
Section {
|
||||||
Picker("Übergeordnet", selection: $parentId) {
|
Picker("Übergeordnet", selection: $parentId) {
|
||||||
Text("– oberste Ebene –").tag(Int?.none)
|
Text("– oberste Ebene –").tag(Int?.none)
|
||||||
ForEach(all) { loc in
|
ForEach(parentOptions) { loc in
|
||||||
Text(LocationEditor.pfad(loc, in: all)).tag(Int?.some(loc.id))
|
Text(LocationEditor.pfad(loc, in: all)).tag(Int?.some(loc.id))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} header: {
|
} header: {
|
||||||
Text("Übergeordneter Lagerort (optional)")
|
Text("Übergeordneter Lagerort (optional)")
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if let error {
|
if let error {
|
||||||
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.navigationTitle(item == nil ? "Lagerort anlegen" : "Lagerort umbenennen")
|
.navigationTitle(item == nil ? "Lagerort anlegen" : "Lagerort bearbeiten")
|
||||||
.navigationBarTitleDisplayMode(.inline)
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
.toolbar {
|
.toolbar {
|
||||||
ToolbarItem(placement: .topBarLeading) {
|
ToolbarItem(placement: .topBarLeading) {
|
||||||
@@ -497,7 +499,8 @@ struct LocationEditor: View {
|
|||||||
let n = name.trimmingCharacters(in: .whitespaces)
|
let n = name.trimmingCharacters(in: .whitespaces)
|
||||||
do {
|
do {
|
||||||
if let item {
|
if let item {
|
||||||
_ = try await APIClient.shared.renameLocation(id: item.id, name: n)
|
_ = try await APIClient.shared.updateLocation(
|
||||||
|
id: item.id, LocationUpdateRequest(name: n, parentId: parentId))
|
||||||
} else {
|
} else {
|
||||||
_ = try await APIClient.shared.createLocation(
|
_ = try await APIClient.shared.createLocation(
|
||||||
NewLocationRequest(name: n, parentId: parentId))
|
NewLocationRequest(name: n, parentId: parentId))
|
||||||
@@ -509,6 +512,18 @@ struct LocationEditor: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Alle Unterorte (rekursiv) – als Ziel beim Umhängen ausgeschlossen.
|
||||||
|
private static func descendants(of id: Int, in all: [StorageLocation]) -> Set<Int> {
|
||||||
|
var result: Set<Int> = []
|
||||||
|
var stack = [id]
|
||||||
|
while let cur = stack.popLast() {
|
||||||
|
for kid in all where kid.parentId == cur {
|
||||||
|
if result.insert(kid.id).inserted { stack.append(kid.id) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
/// "Keller → Regal" – der Pfad macht gleiche Namen im flachen Picker
|
/// "Keller → Regal" – der Pfad macht gleiche Namen im flachen Picker
|
||||||
/// unterscheidbar.
|
/// unterscheidbar.
|
||||||
private static func pfad(_ loc: StorageLocation, in all: [StorageLocation]) -> String {
|
private static func pfad(_ loc: StorageLocation, in all: [StorageLocation]) -> String {
|
||||||
@@ -754,8 +769,8 @@ struct CategoriesView: View {
|
|||||||
.padding(.horizontal)
|
.padding(.horizontal)
|
||||||
.padding(.vertical, 8)
|
.padding(.vertical, 8)
|
||||||
},
|
},
|
||||||
editor: { item, _, done in
|
editor: { item, all, done in
|
||||||
CategoryEditor(item: item, done: done)
|
CategoryEditor(item: item, all: all, done: done)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -765,33 +780,60 @@ struct CategoriesView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Kategorie anlegen oder bearbeiten: Name und Verwaltungsart (Lebensmittel vs.
|
/// Kategorie anlegen oder bearbeiten: Name, Verwaltungsart und – beim Anlegen –
|
||||||
/// Gegenstand). Neue Kategorien entstehen auf oberster Ebene; Verschachteln
|
/// eine optionale Oberkategorie (Unterkategorie). Bei bestehenden Kategorien
|
||||||
/// bleibt der Web-Oberfläche vorbehalten.
|
/// führt ein Link zur Verwaltung der eigenen Felder.
|
||||||
struct CategoryEditor: View {
|
struct CategoryEditor: View {
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
let item: CategoryItem?
|
let item: CategoryItem?
|
||||||
|
let all: [CategoryItem]
|
||||||
let done: () -> Void
|
let done: () -> Void
|
||||||
|
|
||||||
@State private var name: String
|
@State private var name: String
|
||||||
@State private var tracking: String
|
@State private var tracking: String
|
||||||
|
@State private var parentId: Int? // nur beim Anlegen
|
||||||
@State private var error: String?
|
@State private var error: String?
|
||||||
@State private var busy = false
|
@State private var busy = false
|
||||||
|
|
||||||
init(item: CategoryItem?, done: @escaping () -> Void) {
|
init(item: CategoryItem?, all: [CategoryItem], done: @escaping () -> Void) {
|
||||||
self.item = item
|
self.item = item
|
||||||
|
self.all = all
|
||||||
self.done = done
|
self.done = done
|
||||||
_name = State(initialValue: item?.name ?? "")
|
_name = State(initialValue: item?.name ?? "")
|
||||||
_tracking = State(initialValue: item?.tracking ?? "object")
|
_tracking = State(initialValue: item?.tracking ?? "object")
|
||||||
|
_parentId = State(initialValue: nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Mit gewählter Oberkategorie erbt die neue Kategorie deren Art – dann ist
|
||||||
|
// die Art-Auswahl gegenstandslos.
|
||||||
|
private var erbtVonEltern: Bool { item == nil && parentId != nil }
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationStack {
|
NavigationStack {
|
||||||
Form {
|
Form {
|
||||||
Section("Name") {
|
Section("Name") {
|
||||||
TextField("z. B. Elektronik", text: $name)
|
TextField("z. B. Elektronik", text: $name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if item == nil {
|
||||||
|
Section {
|
||||||
|
Picker("Übergeordnet", selection: $parentId) {
|
||||||
|
Text("– oberste Ebene –").tag(Int?.none)
|
||||||
|
ForEach(all) { c in
|
||||||
|
Text(CategoryEditor.pfad(c, in: all)).tag(Int?.some(c.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} header: {
|
||||||
|
Text("Übergeordnete Kategorie (optional)")
|
||||||
|
} footer: {
|
||||||
|
Text(erbtVonEltern
|
||||||
|
? "Erbt die Verwaltungsart der Oberkategorie."
|
||||||
|
: "Ohne Oberkategorie unten die Verwaltungsart wählen.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !erbtVonEltern {
|
||||||
Section {
|
Section {
|
||||||
Picker("Art", selection: $tracking) {
|
Picker("Art", selection: $tracking) {
|
||||||
Text("Lebensmittel").tag("food")
|
Text("Lebensmittel").tag("food")
|
||||||
@@ -803,6 +845,18 @@ struct CategoryEditor: View {
|
|||||||
} footer: {
|
} footer: {
|
||||||
Text("Lebensmittel: Chargen mit Mindesthaltbarkeit. Gegenstand: Menge je Lagerort bzw. Einzelstücke. Unterkategorien erben die Art.")
|
Text("Lebensmittel: Chargen mit Mindesthaltbarkeit. Gegenstand: Menge je Lagerort bzw. Einzelstücke. Unterkategorien erben die Art.")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let item {
|
||||||
|
Section {
|
||||||
|
NavigationLink {
|
||||||
|
CategoryFieldsView(categoryId: item.id, categoryName: item.name)
|
||||||
|
} label: {
|
||||||
|
Label("Eigene Felder verwalten", systemImage: "tag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let error {
|
if let error {
|
||||||
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
||||||
}
|
}
|
||||||
@@ -830,8 +884,239 @@ struct CategoryEditor: View {
|
|||||||
_ = try await APIClient.shared.updateCategory(
|
_ = try await APIClient.shared.updateCategory(
|
||||||
id: item.id, CategoryUpdateRequest(name: n, tracking: tracking))
|
id: item.id, CategoryUpdateRequest(name: n, tracking: tracking))
|
||||||
} else {
|
} else {
|
||||||
|
// Mit Oberkategorie die Art erben (tracking = nil), sonst die
|
||||||
|
// gewählte Art.
|
||||||
_ = try await APIClient.shared.createCategory(
|
_ = try await APIClient.shared.createCategory(
|
||||||
NewCategoryRequest(name: n, parentId: nil, tracking: tracking))
|
NewCategoryRequest(name: n, parentId: parentId,
|
||||||
|
tracking: parentId == nil ? tracking : nil))
|
||||||
|
}
|
||||||
|
done()
|
||||||
|
dismiss()
|
||||||
|
} catch {
|
||||||
|
self.error = error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func pfad(_ c: CategoryItem, in all: [CategoryItem]) -> String {
|
||||||
|
let byId = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })
|
||||||
|
var teile = [c.name]
|
||||||
|
var pid = c.parentId
|
||||||
|
while let cur = pid, let parent = byId[cur] {
|
||||||
|
teile.insert(parent.name, at: 0)
|
||||||
|
pid = parent.parentId
|
||||||
|
}
|
||||||
|
return teile.joined(separator: " → ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Eigene Felder je Kategorie
|
||||||
|
|
||||||
|
/// Eigene Felder einer Kategorie verwalten (anlegen, bearbeiten, löschen). Zeigt
|
||||||
|
/// nur die *eigenen* Felder – geerbte werden in der Oberkategorie gepflegt.
|
||||||
|
struct CategoryFieldsView: View {
|
||||||
|
let categoryId: Int
|
||||||
|
let categoryName: String
|
||||||
|
|
||||||
|
@State private var fields: [FieldDefinition] = []
|
||||||
|
@State private var busy = true
|
||||||
|
@State private var error: String?
|
||||||
|
@State private var editing: FieldDefinition?
|
||||||
|
@State private var addShown = false
|
||||||
|
@State private var pendingDeletion: FieldDefinition?
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
List {
|
||||||
|
if let error {
|
||||||
|
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
||||||
|
}
|
||||||
|
ForEach(fields) { f in
|
||||||
|
Button { editing = f } label: {
|
||||||
|
HStack {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(f.label).foregroundStyle(.primary)
|
||||||
|
Text(CategoryFieldsView.untertitel(f))
|
||||||
|
.font(.caption).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
if f.required {
|
||||||
|
Text("Pflicht").font(.caption2).foregroundStyle(.orange)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.swipeActions(edge: .trailing) {
|
||||||
|
Button("Löschen", role: .destructive) { pendingDeletion = f }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fields.isEmpty && !busy {
|
||||||
|
Text("Noch keine eigenen Felder.").foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.navigationTitle("Felder: \(categoryName)")
|
||||||
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button("Hinzufügen", systemImage: "plus") { addShown = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.sheet(isPresented: $addShown) {
|
||||||
|
FieldEditor(categoryId: categoryId, field: nil) { Task { await reload() } }
|
||||||
|
}
|
||||||
|
.sheet(item: $editing) { f in
|
||||||
|
FieldEditor(categoryId: categoryId, field: f) { Task { await reload() } }
|
||||||
|
}
|
||||||
|
.confirmationDialog(
|
||||||
|
pendingDeletion.map { "„\($0.label)“ löschen?" } ?? "",
|
||||||
|
isPresented: Binding(get: { pendingDeletion != nil },
|
||||||
|
set: { if !$0 { pendingDeletion = nil } }),
|
||||||
|
titleVisibility: .visible
|
||||||
|
) {
|
||||||
|
Button("Löschen", role: .destructive) {
|
||||||
|
if let f = pendingDeletion { Task { await remove(f) } }
|
||||||
|
pendingDeletion = nil
|
||||||
|
}
|
||||||
|
Button("Abbrechen", role: .cancel) { pendingDeletion = nil }
|
||||||
|
} message: {
|
||||||
|
Text("Die zu diesem Feld erfassten Werte gehen an allen Artikeln verloren.")
|
||||||
|
}
|
||||||
|
.refreshable { await reload() }
|
||||||
|
.task { await reload() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func untertitel(_ f: FieldDefinition) -> String {
|
||||||
|
var teile = [FieldEditor.typLabel(f.fieldType)]
|
||||||
|
if f.fieldType == "number", let u = f.unit, !u.isEmpty { teile.append(u) }
|
||||||
|
if f.fieldType == "select", !f.options.isEmpty {
|
||||||
|
teile.append(f.options.joined(separator: ", "))
|
||||||
|
}
|
||||||
|
return teile.joined(separator: " · ")
|
||||||
|
}
|
||||||
|
|
||||||
|
private func reload() async {
|
||||||
|
busy = true
|
||||||
|
defer { busy = false }
|
||||||
|
do {
|
||||||
|
fields = try await APIClient.shared.ownFieldDefinitions(categoryId: categoryId)
|
||||||
|
error = nil
|
||||||
|
} catch {
|
||||||
|
self.error = error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func remove(_ f: FieldDefinition) async {
|
||||||
|
do {
|
||||||
|
try await APIClient.shared.deleteFieldDefinition(id: f.id)
|
||||||
|
error = nil
|
||||||
|
await reload()
|
||||||
|
} catch {
|
||||||
|
self.error = error.localizedDescription
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Eigenes Feld anlegen oder bearbeiten: Name, Typ, (Einheit bei Zahl,
|
||||||
|
/// Auswahlmöglichkeiten bei Auswahlliste) und Pflicht.
|
||||||
|
struct FieldEditor: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
|
||||||
|
let categoryId: Int
|
||||||
|
let field: FieldDefinition?
|
||||||
|
let done: () -> Void
|
||||||
|
|
||||||
|
@State private var label: String
|
||||||
|
@State private var fieldType: String
|
||||||
|
@State private var unit: String
|
||||||
|
@State private var options: String // Komma-getrennt
|
||||||
|
@State private var required: Bool
|
||||||
|
@State private var error: String?
|
||||||
|
@State private var busy = false
|
||||||
|
|
||||||
|
static let typen: [(String, String)] = [
|
||||||
|
("text", "Text (einzeilig)"),
|
||||||
|
("textarea", "Text (mehrzeilig)"),
|
||||||
|
("number", "Zahl (mit Einheit)"),
|
||||||
|
("date", "Datum"),
|
||||||
|
("select", "Auswahlliste"),
|
||||||
|
("boolean", "Ja/Nein"),
|
||||||
|
]
|
||||||
|
|
||||||
|
static func typLabel(_ v: String) -> String { typen.first { $0.0 == v }?.1 ?? v }
|
||||||
|
|
||||||
|
init(categoryId: Int, field: FieldDefinition?, done: @escaping () -> Void) {
|
||||||
|
self.categoryId = categoryId
|
||||||
|
self.field = field
|
||||||
|
self.done = done
|
||||||
|
_label = State(initialValue: field?.label ?? "")
|
||||||
|
_fieldType = State(initialValue: field?.fieldType ?? "text")
|
||||||
|
_unit = State(initialValue: field?.unit ?? "")
|
||||||
|
_options = State(initialValue: (field?.options ?? []).joined(separator: ", "))
|
||||||
|
_required = State(initialValue: field?.required ?? false)
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
Form {
|
||||||
|
Section("Feldname") {
|
||||||
|
TextField("z. B. Kapazität", text: $label)
|
||||||
|
}
|
||||||
|
Section("Typ") {
|
||||||
|
Picker("Typ", selection: $fieldType) {
|
||||||
|
ForEach(FieldEditor.typen, id: \.0) { Text($0.1).tag($0.0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fieldType == "number" {
|
||||||
|
Section("Einheit (optional)") {
|
||||||
|
TextField("z. B. mAh", text: $unit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fieldType == "select" {
|
||||||
|
Section {
|
||||||
|
TextField("z. B. S, M, L, XL", text: $options)
|
||||||
|
} header: {
|
||||||
|
Text("Auswahlmöglichkeiten")
|
||||||
|
} footer: {
|
||||||
|
Text("Mit Komma trennen.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Section {
|
||||||
|
Toggle("Pflichtfeld", isOn: $required)
|
||||||
|
}
|
||||||
|
if let error {
|
||||||
|
Section { Text(error).foregroundStyle(.red).font(.callout) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.navigationTitle(field == nil ? "Feld anlegen" : "Feld bearbeiten")
|
||||||
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarLeading) {
|
||||||
|
Button("Abbrechen") { dismiss() }
|
||||||
|
}
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button(busy ? "Sichern…" : "Sichern") { Task { await submit() } }
|
||||||
|
.disabled(busy || label.trimmingCharacters(in: .whitespaces).isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func submit() async {
|
||||||
|
busy = true
|
||||||
|
defer { busy = false }
|
||||||
|
let l = label.trimmingCharacters(in: .whitespaces)
|
||||||
|
let u = fieldType == "number" ? unit.trimmingCharacters(in: .whitespaces) : ""
|
||||||
|
let opts = fieldType == "select"
|
||||||
|
? options.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }
|
||||||
|
.filter { !$0.isEmpty }
|
||||||
|
: []
|
||||||
|
do {
|
||||||
|
if let field {
|
||||||
|
_ = try await APIClient.shared.updateFieldDefinition(
|
||||||
|
id: field.id,
|
||||||
|
FieldDefinitionUpdate(label: l, fieldType: fieldType, unit: u,
|
||||||
|
options: opts, required: required))
|
||||||
|
} else {
|
||||||
|
_ = try await APIClient.shared.createFieldDefinition(
|
||||||
|
FieldDefinitionCreate(categoryId: categoryId, label: l, fieldType: fieldType,
|
||||||
|
unit: u, options: opts, required: required))
|
||||||
}
|
}
|
||||||
done()
|
done()
|
||||||
dismiss()
|
dismiss()
|
||||||
|
|||||||
@@ -854,6 +854,54 @@ struct NewLocationRequest: Codable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Lagerort umbenennen und/oder umhängen. `parentId` wird bewusst immer gesendet
|
||||||
|
/// (auch `null` = oberste Ebene), damit „auf oberste Ebene holen" ankommt.
|
||||||
|
struct LocationUpdateRequest: Codable {
|
||||||
|
let name: String
|
||||||
|
let parentId: Int?
|
||||||
|
|
||||||
|
enum CodingKeys: String, CodingKey {
|
||||||
|
case name
|
||||||
|
case parentId = "parent_id"
|
||||||
|
}
|
||||||
|
|
||||||
|
func encode(to encoder: Encoder) throws {
|
||||||
|
var c = encoder.container(keyedBy: CodingKeys.self)
|
||||||
|
try c.encode(name, forKey: .name)
|
||||||
|
try c.encode(parentId, forKey: .parentId) // encodet null bei nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Eigenes Feld einer Kategorie anlegen. `unit`/`options` werden immer
|
||||||
|
/// mitgeschickt; der Server ignoriert sie bei unpassendem Typ.
|
||||||
|
struct FieldDefinitionCreate: Codable {
|
||||||
|
let categoryId: Int
|
||||||
|
let label: String
|
||||||
|
let fieldType: String
|
||||||
|
let unit: String
|
||||||
|
let options: [String]
|
||||||
|
let required: Bool
|
||||||
|
|
||||||
|
enum CodingKeys: String, CodingKey {
|
||||||
|
case label, unit, options, required
|
||||||
|
case categoryId = "category_id"
|
||||||
|
case fieldType = "field_type"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FieldDefinitionUpdate: Codable {
|
||||||
|
let label: String
|
||||||
|
let fieldType: String
|
||||||
|
let unit: String
|
||||||
|
let options: [String]
|
||||||
|
let required: Bool
|
||||||
|
|
||||||
|
enum CodingKeys: String, CodingKey {
|
||||||
|
case label, unit, options, required
|
||||||
|
case fieldType = "field_type"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct NewUnitRequest: Codable {
|
struct NewUnitRequest: Codable {
|
||||||
let name: String
|
let name: String
|
||||||
let kind: String
|
let kind: String
|
||||||
|
|||||||
@@ -204,6 +204,7 @@ export const api = {
|
|||||||
// Stammdaten
|
// Stammdaten
|
||||||
listLocations: () => request("/locations"),
|
listLocations: () => request("/locations"),
|
||||||
createLocation: (body) => request("/locations", { method: "POST", body }),
|
createLocation: (body) => request("/locations", { method: "POST", body }),
|
||||||
|
updateLocation: (id, body) => request(`/locations/${id}`, { method: "PATCH", body }),
|
||||||
deleteLocation: (id) => request(`/locations/${id}`, { method: "DELETE" }),
|
deleteLocation: (id) => request(`/locations/${id}`, { method: "DELETE" }),
|
||||||
|
|
||||||
// Kategorien: Ordnungshilfe + Verwaltungsart (food/object), verschachtelbar
|
// Kategorien: Ordnungshilfe + Verwaltungsart (food/object), verschachtelbar
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { api } from "../api";
|
import { api } from "../api";
|
||||||
import { useConfirm } from "../confirm";
|
import { useConfirm } from "../confirm";
|
||||||
import Icon from "../components/Icon";
|
import Icon from "../components/Icon";
|
||||||
|
import CategorySelect from "../components/CategorySelect";
|
||||||
import { QrImg, printQrLabels } from "../qr";
|
import { QrImg, printQrLabels } from "../qr";
|
||||||
|
|
||||||
export default function Locations() {
|
export default function Locations() {
|
||||||
@@ -10,6 +11,10 @@ export default function Locations() {
|
|||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [parentId, setParentId] = useState("");
|
const [parentId, setParentId] = useState("");
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
// Inline-Bearbeiten (Umbenennen + Umhängen) eines vorhandenen Orts.
|
||||||
|
const [editId, setEditId] = useState(null);
|
||||||
|
const [editName, setEditName] = useState("");
|
||||||
|
const [editParent, setEditParent] = useState(null);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
@@ -34,6 +39,44 @@ export default function Locations() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function startEdit(l) {
|
||||||
|
setEditId(l.id);
|
||||||
|
setEditName(l.name);
|
||||||
|
setEditParent(l.parent_id ?? null);
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelEdit() {
|
||||||
|
setEditId(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveEdit() {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await api.updateLocation(editId, {
|
||||||
|
name: editName.trim(),
|
||||||
|
parent_id: editParent == null ? null : Number(editParent),
|
||||||
|
});
|
||||||
|
setEditId(null);
|
||||||
|
load();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Eigene Unterorte (rekursiv) – als Ziel beim Umhängen ausgeschlossen.
|
||||||
|
function descendantIds(id) {
|
||||||
|
const result = new Set();
|
||||||
|
const stack = [id];
|
||||||
|
while (stack.length) {
|
||||||
|
const cur = stack.pop();
|
||||||
|
for (const c of locations.filter((l) => l.parent_id === cur)) {
|
||||||
|
if (!result.has(c.id)) { result.add(c.id); stack.push(c.id); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
async function remove(id) {
|
async function remove(id) {
|
||||||
const ok = await confirm({
|
const ok = await confirm({
|
||||||
title: "Lagerort löschen?",
|
title: "Lagerort löschen?",
|
||||||
@@ -65,6 +108,11 @@ export default function Locations() {
|
|||||||
}
|
}
|
||||||
for (const r of locations.filter(isRoot)) walk(r, 0);
|
for (const r of locations.filter(isRoot)) walk(r, 0);
|
||||||
|
|
||||||
|
// Mögliche neue Elternorte beim Bearbeiten: alle außer dem Ort selbst und
|
||||||
|
// seinen Unterorten (sonst entstünde ein Ring).
|
||||||
|
const editDesc = editId != null ? descendantIds(editId) : new Set();
|
||||||
|
const editParentNodes = ordered.filter((o) => o.id !== editId && !editDesc.has(o.id));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="page-head">
|
<div className="page-head">
|
||||||
@@ -106,6 +154,31 @@ export default function Locations() {
|
|||||||
|
|
||||||
<ul className="simple-list">
|
<ul className="simple-list">
|
||||||
{ordered.map((l) => (
|
{ordered.map((l) => (
|
||||||
|
editId === l.id ? (
|
||||||
|
<li key={l.id}>
|
||||||
|
<div className="row" style={{ width: "100%", gap: 8, alignItems: "flex-end" }}>
|
||||||
|
<label className="grow" style={{ margin: 0 }}>
|
||||||
|
Name
|
||||||
|
<input value={editName} onChange={(e) => setEditName(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<label className="grow" style={{ margin: 0 }}>
|
||||||
|
Übergeordnet
|
||||||
|
<CategorySelect
|
||||||
|
value={editParent}
|
||||||
|
nodes={editParentNodes}
|
||||||
|
rootLabel="– keiner (oberste Ebene) –"
|
||||||
|
onChange={(id) => setEditParent(id == null ? null : id)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<span style={{ display: "flex", gap: 6 }}>
|
||||||
|
<button className="btn primary" onClick={saveEdit} disabled={!editName.trim()}>
|
||||||
|
<Icon name="check" size={16} />Speichern
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn ghost" onClick={cancelEdit}>Abbrechen</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
) : (
|
||||||
<li key={l.id}>
|
<li key={l.id}>
|
||||||
<span style={{ display: "flex", alignItems: "center", gap: 8, paddingLeft: l.depth * 22 }}>
|
<span style={{ display: "flex", alignItems: "center", gap: 8, paddingLeft: l.depth * 22 }}>
|
||||||
{l.depth > 0 && <span className="muted">↳</span>}
|
{l.depth > 0 && <span className="muted">↳</span>}
|
||||||
@@ -117,11 +190,15 @@ export default function Locations() {
|
|||||||
</span>
|
</span>
|
||||||
<span style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
<span style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||||
<QrImg text={`${window.location.origin}/l/${l.id}`} size={44} />
|
<QrImg text={`${window.location.origin}/l/${l.id}`} size={44} />
|
||||||
|
<button className="btn-icon" onClick={() => startEdit(l)} title="Bearbeiten">
|
||||||
|
<Icon name="edit" size={16} />
|
||||||
|
</button>
|
||||||
<button className="btn-icon danger" onClick={() => remove(l.id)} title="Löschen">
|
<button className="btn-icon danger" onClick={() => remove(l.id)} title="Löschen">
|
||||||
<Icon name="trash" size={16} />
|
<Icon name="trash" size={16} />
|
||||||
</button>
|
</button>
|
||||||
</span>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
|
)
|
||||||
))}
|
))}
|
||||||
{locations.length === 0 && <li className="empty">Noch keine Lagerorte.</li>}
|
{locations.length === 0 && <li className="empty">Noch keine Lagerorte.</li>}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ function buildLabelCsv(rows, origin, delim = ",") {
|
|||||||
const delimRe = delim === "\t" ? "\\t" : delim;
|
const delimRe = delim === "\t" ? "\\t" : delim;
|
||||||
const needsQuote = new RegExp(`[${delimRe}"\\n\\r]`);
|
const needsQuote = new RegExp(`[${delimRe}"\\n\\r]`);
|
||||||
const esc = (v) => {
|
const esc = (v) => {
|
||||||
const s = String(v ?? "");
|
let s = String(v ?? "");
|
||||||
|
// Formel-Injektion verhindern: Beginnt eine Zelle mit = + - @ (oder Tab/CR),
|
||||||
|
// koennte Excel/P-touch sie als Formel ausfuehren. Ein vorangestelltes
|
||||||
|
// Apostroph macht sie zu reinem Text.
|
||||||
|
if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
|
||||||
return needsQuote.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
return needsQuote.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||||
};
|
};
|
||||||
const lines = [head.map(esc).join(delim)];
|
const lines = [head.map(esc).join(delim)];
|
||||||
|
|||||||
Reference in New Issue
Block a user