Gruppen und Kategorien getrennt, EAN-Codes an der Gruppe automatisch gefuehrt

Die Umbenennung von Gruppen in "Kategorien" war falsch: Es sind zwei
verschiedene Dinge. Sie ist zurueckgenommen, Kategorien kommen als eigene Ebene
dazu.

GRUPPE zaehlt Bestaende mehrerer Marken zusammen - Mehl von Rewe, Aldi und
Migros ergeben "5 kg Mehl". Dafuer Mindestbestand mit Einheit und EAN-Codes.
KATEGORIE ordnet allein die Artikelliste ("zeig mir alle Suesswaren"), ist
verschachtelbar wie ein Lagerort und hat weder Bestand noch EAN-Codes. Ein
Artikel kann beides, eines oder keines haben.

Die Vermischung war aelter als die Umbenennung: guessGroup in offUtils.js hat
aus der Open-Food-Facts-KATEGORIE eine GRUPPE geraten. Das ist entfernt. Die
OFF-Einordnung steuert jetzt die Kategorie, wo sie hingehoert; eine Gruppe
entsteht nur ueber einen hinterlegten Gruppen-Code oder bewusste Auswahl.

EAN-Codes an der Gruppe: Das war kein Anzeigefehler. Beim Anlegen eines Artikels
wurde ausschliesslich group_id gesetzt - ein Gruppen-Code entstand nie, die
Liste war tatsaechlich leer. Die Meldung "bereits vergeben" kam daher, dass der
Code am Artikel hing. Jetzt pflegt services/group_codes.py den Code mit: beim
Zuordnen kommt er hinzu, beim Gruppenwechsel wandert er mit, beim Entfernen der
Gruppe oder Loeschen des Artikels verschwindet er. Beim Scannen aendert sich
nichts an der Reihenfolge - der Artikel wird weiterhin zuerst gefunden; der
Gruppen-Eintrag ist Beleg in der Verwaltung und Rueckfall. Traegt man denselben
Code von Hand nach, ist das kein Fehler mehr, sondern die Auskunft, dass er ueber
den Artikel bereits dort steht.

Kategorien im Backend: neue Tabelle mit parent_id (Muster von Location),
products.category_id per ADD COLUMN IF NOT EXISTS nachgezogen, deutsche
zweistufige Startliste analog zu den eingebauten Einheiten. Die Startliste wird
nur angelegt, wenn ueberhaupt noch keine Kategorie existiert - wer sie bewusst
leerraeumt, findet sie nicht wieder. Beim Setzen einer Oberkategorie wird
geprueft, dass keine Kategorie sich selbst oder einem eigenen Nachfahren
untergeordnet wird; sonst entstuende ein Ring und jede Baumdarstellung liefe
endlos. Der Produktfilter schliesst Unterkategorien ein, category_id=0 liefert
die Artikel ohne Kategorie. Export und Import fuehren die Kategorie als Pfad
("Suesswaren & Snacks > Schokolade") in einer Spalte, damit die CSV in Excel
bedienbar bleibt.

Web: neue Seite Kategorien mit Baumdarstellung, Filter ueber der Produktliste,
getrennte Auswahlfelder im Produktformular mit je einer Zeile Erklaerung, und
beim Einlagern laesst sich eine Gruppe samt Einheit und Mindestbestand direkt
anlegen, ohne den Vorgang zu verlassen.

iOS: Kategorie-Filter ueber der Produktliste, Unterkategorien eingerueckt. Die
Artikelzeile nennt jetzt das Gebinde und warnt, wenn der Mindestbestand
unterschritten ist (rot) oder weniger als ein Viertel Luft bleibt (orange).
Getrennte Auswahlfelder fuer Kategorie und Gruppe, Gruppe direkt anlegbar.

Ausserdem die Eingabefelder in der App: .textFieldStyle(.roundedBorder) zeichnet
in der dunklen Darstellung einen fast schwarzen Kasten. Ersetzt durch eine
Systemfuellung, die sich Hell und Dunkel anpasst und zurueckhaltend bleibt.

Getestet: 54 pytest-Tests gruen, 14 davon neu (Nachfahren-Sammler, OFF-Zuordnung
inklusive Vorrang der Unterkategorie, und die komplette Codepflege an der
Gruppe). Gegen die laufende API geprueft: Startliste ohne Dubletten, Filter auf
Ober- und Unterkategorie, Ringschutz, Loeschen einer Kategorie laesst Artikel
und Unterkategorien bestehen, Export/Import-Rundlauf mit Kategoriepfad, und der
Durchlauf aus der Meldung - Artikel mit Gruppe anlegen, Code steht danach in der
Gruppe. Web-Build und iOS-Geraetebuild fehler- und warnungsfrei.
Die Oberflaechen habe ich nicht selbst bedient.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Scarriffle
2026-07-22 20:59:14 +02:00
parent 8dcc17b22f
commit 158196f67b
36 changed files with 1503 additions and 140 deletions

View File

@@ -87,9 +87,17 @@ actor APIClient {
try await send(try makeRequest("/locations"), as: [StorageLocation].self)
}
func searchProducts(_ query: String) async throws -> [Product] {
let escaped = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
return try await send(try makeRequest("/products?q=\(escaped)"), as: [Product].self)
/// `categoryId == 0` liefert Artikel ohne Kategorie; eine echte ID schliesst
/// die Unterkategorien mit ein.
func searchProducts(_ query: String, categoryId: Int? = nil) async throws -> [Product] {
var parts: [String] = []
if !query.isEmpty {
let escaped = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
parts.append("q=\(escaped)")
}
if let categoryId { parts.append("category_id=\(categoryId)") }
let suffix = parts.isEmpty ? "" : "?" + parts.joined(separator: "&")
return try await send(try makeRequest("/products" + suffix), as: [Product].self)
}
func product(id: Int) async throws -> Product {
@@ -117,6 +125,16 @@ actor APIClient {
try await send(try makeRequest("/groups"), as: [GroupItem].self)
}
func categories() async throws -> [CategoryItem] {
try await send(try makeRequest("/categories"), as: [CategoryItem].self)
}
func createGroup(_ payload: NewGroupRequest) async throws -> GroupItem {
var request = try makeRequest("/groups", method: "POST")
try jsonBody(&request, payload)
return try await send(request, as: GroupItem.self)
}
func settings() async throws -> [SettingEntry] {
try await send(try makeRequest("/settings"), as: [SettingEntry].self)
}

View File

@@ -0,0 +1,105 @@
import SwiftUI
/// Auswahl einer Kategorie mit eingerueckten Unterkategorien.
///
/// Kategorie und Gruppe sind zwei verschiedene Dinge: Die Kategorie ordnet nur
/// die Artikelliste, die Gruppe zaehlt Bestaende mehrerer Marken zusammen.
struct CategoryPicker: View {
let categories: [CategoryItem]
@Binding var selection: Int?
var body: some View {
Picker("Kategorie", selection: $selection) {
Text(" keine ").tag(Int?.none)
ForEach(flattened(), id: \.item.id) { eintrag in
Text(String(repeating: " ", count: eintrag.depth) + eintrag.item.name)
.tag(Int?.some(eintrag.item.id))
}
}
}
private func flattened() -> [(item: CategoryItem, depth: Int)] {
let ids = Set(categories.map(\.id))
var result: [(CategoryItem, Int)] = []
func walk(_ node: CategoryItem, _ depth: Int) {
result.append((node, depth))
for child in categories.filter({ $0.parentId == node.id }) {
walk(child, depth + 1)
}
}
for root in categories.filter({ $0.parentId == nil || !ids.contains($0.parentId!) }) {
walk(root, 0)
}
return result
}
}
/// Legt eine Gruppe an Ort und Stelle an, damit man das Formular nicht
/// verlassen muss. Nur fuer Administratoren - POST /groups verlangt das.
struct NewGroupSheet: View {
let units: [Unit]
var onCreated: (GroupItem) -> Void
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var minStock = ""
@State private var unitId: Int?
@State private var busy = false
@State private var error: String?
var body: some View {
Form {
Section {
LabeledField(label: "Name", text: $name)
} footer: {
Text("Eine Gruppe zählt Bestände mehrerer Marken zusammen "
+ "z. B. Mehl von verschiedenen Herstellern als „5 kg Mehl“.")
}
Section("Mindestbestand (optional)") {
QuantityField(label: "Menge", text: $minStock)
Picker("Einheit", selection: $unitId) {
Text(" Basiseinheit ").tag(Int?.none)
ForEach(units) { unit in
Text(unit.name).tag(Int?.some(unit.id))
}
}
}
if let error {
Section { Text(error).foregroundStyle(.red).font(.callout) }
}
Section {
Button(busy ? "Anlegen…" : "Anlegen") { Task { await create() } }
.disabled(busy || name.trimmingCharacters(in: .whitespaces).isEmpty)
}
}
.navigationTitle("Neue Gruppe")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarLeading) { Button("Abbrechen") { dismiss() } }
}
}
private func create() async {
error = nil
busy = true
defer { busy = false }
do {
let created = try await APIClient.shared.createGroup(
NewGroupRequest(
name: name.trimmingCharacters(in: .whitespaces),
minStock: Double(minStock.replacingOccurrences(of: ",", with: ".")),
minStockUnitId: unitId
)
)
onCreated(created)
dismiss()
} catch {
self.error = error.localizedDescription
}
}
}

View File

@@ -6,6 +6,23 @@ struct LineRef: Identifiable {
let id: UUID
}
extension View {
/// Dezente Umrandung fuer Eingabefelder in einem Formular.
///
/// `.textFieldStyle(.roundedBorder)` zeichnet in der dunklen Darstellung
/// einen fast schwarzen Kasten, der sich hart von der Zeile abhebt. Eine
/// Systemfuellung passt sich Hell und Dunkel an und bleibt zurueckhaltend,
/// macht das Feld aber weiterhin als Eingabe erkennbar.
func fieldBox(width: CGFloat) -> some View {
self
.padding(.horizontal, 10)
.padding(.vertical, 6)
.frame(maxWidth: width)
.background(Color(.tertiarySystemFill))
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
/// Textzeile mit Beschriftung links und sichtbarem Rahmen.
struct LabeledField: View {
let label: String
@@ -19,8 +36,7 @@ struct LabeledField: View {
TextField(label, text: $text)
.keyboardType(keyboard)
.multilineTextAlignment(.trailing)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 190)
.fieldBox(width: 190)
}
}
}
@@ -41,8 +57,7 @@ struct QuantityField: View {
TextField(label, text: $text)
.keyboardType(.decimalPad)
.multilineTextAlignment(.trailing)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 110)
.fieldBox(width: 110)
if let suffix {
Text(suffix)
.foregroundStyle(.secondary)

View File

@@ -12,6 +12,7 @@ struct CheckInView: View {
@State private var suggestion: LookupResult.Suggestion?
@State private var suggestedGroupId: Int?
@State private var suggestedGroupName: String?
@State private var suggestedCategoryName: String?
@State private var unknownCode: String?
@State private var manualCodeShown = false
@State private var manualCode = ""
@@ -111,23 +112,33 @@ struct CheckInView: View {
.padding(.horizontal)
}
/// Sagt vor dem Anlegen, welche Kategorie der Artikel bekommt und warum.
/// Sagt vor dem Anlegen, welche Gruppe der Artikel bekommt und warum.
@ViewBuilder
private func categoryNote() -> some View {
if let name = suggestedGroupName {
HStack(alignment: .top, spacing: 6) {
Image(systemName: "tag")
VStack(alignment: .leading, spacing: 1) {
Text("Wird der Kategorie „\(name)“ zugeordnet").font(.caption).bold()
Text("Dieser EAN-Code ist dort hinterlegt.")
.font(.caption2).foregroundStyle(.secondary)
}
}
.padding(8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.accentColor.opacity(0.15))
.clipShape(RoundedRectangle(cornerRadius: 8))
private func groupNote() -> some View {
if let kategorie = suggestedCategoryName {
noteRow(symbol: "square.grid.2x2",
title: "Kategorie „\(kategorie)“ vorgeschlagen",
detail: "Aus der Einordnung bei Open Food Facts.")
}
if let name = suggestedGroupName {
noteRow(symbol: "tag",
title: "Wird der Gruppe „\(name)“ zugeordnet",
detail: "Dieser EAN-Code ist dort hinterlegt.")
}
}
private func noteRow(symbol: String, title: String, detail: String) -> some View {
HStack(alignment: .top, spacing: 6) {
Image(systemName: symbol)
VStack(alignment: .leading, spacing: 1) {
Text(title).font(.caption).bold()
Text(detail).font(.caption2).foregroundStyle(.secondary)
}
}
.padding(8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.accentColor.opacity(0.15))
.clipShape(RoundedRectangle(cornerRadius: 8))
}
private func suggestionCard(_ item: LookupResult.Suggestion) -> some View {
@@ -137,7 +148,7 @@ struct CheckInView: View {
.font(.caption).foregroundStyle(.secondary)
Text("Bei Open Food Facts gefunden, noch nicht im Katalog.")
.font(.caption2).foregroundStyle(.secondary)
categoryNote()
groupNote()
NavigationLink {
ProductFormView(prefillBarcode: item.barcode, groupId: suggestedGroupId,
suggestion: item) { created in
@@ -161,7 +172,7 @@ struct CheckInView: View {
Text("Unbekannter Code \(code)").font(.headline)
Text("Weder im Katalog noch bei Open Food Facts.")
.font(.caption).foregroundStyle(.secondary)
categoryNote()
groupNote()
NavigationLink {
ProductFormView(prefillBarcode: code, groupId: suggestedGroupId) { created in
unknownCode = nil
@@ -191,6 +202,7 @@ struct CheckInView: View {
let result = try await APIClient.shared.lookup(barcode: code)
suggestedGroupId = result.groupId
suggestedGroupName = result.groupName
suggestedCategoryName = result.categoryName
if let existing = result.existingProduct {
product = existing
} else if let hint = result.suggestion {

View File

@@ -5,10 +5,10 @@ func formatAmount(_ value: Double) -> String {
value == value.rounded() ? String(Int(value)) : String(format: "%.2f", value)
}
/// Kennzeichnung "Kategorie" an einer Listenzeile.
struct CategoryBadge: View {
/// Kennzeichnung "Gruppe" an einer Listenzeile.
struct GroupBadge: View {
var body: some View {
Text("Kategorie")
Text("Gruppe")
.font(.caption2)
.padding(.horizontal, 6)
.padding(.vertical, 2)
@@ -18,7 +18,7 @@ struct CategoryBadge: View {
}
}
/// Zeile mit Symbol links, damit Artikel und Kategorie unterscheidbar sind.
/// Zeile mit Symbol links, damit Artikel und Gruppe unterscheidbar sind.
struct ListRow<Trailing: View>: View {
let systemImage: String
let title: String
@@ -70,13 +70,13 @@ struct ShoppingListView: View {
}
}
if !groups.isEmpty {
Section("Kategorien unter Mindestbestand") {
Section("Gruppen unter Mindestbestand") {
ForEach(groups) { group in
ListRow(
systemImage: "square.stack.3d.up",
title: group.name,
subtitle: "fehlt \(formatAmount(group.deficit)) \(group.unitName) · \(group.productCount) Artikel"
) { CategoryBadge() }
) { GroupBadge() }
}
}
}
@@ -173,23 +173,49 @@ struct ExpiringView: View {
struct ProductListView: View {
@State private var query = ""
@State private var products: [Product] = []
@State private var categories: [CategoryItem] = []
/// nil = alle, 0 = ohne Kategorie, sonst die ID (Unterkategorien zaehlen mit).
@State private var categoryId: Int?
@State private var busy = false
private var filterLabel: String {
if categoryId == 0 { return "Ohne Kategorie" }
if let id = categoryId, let treffer = categories.first(where: { $0.id == id }) {
return treffer.name
}
return "Alle Kategorien"
}
var body: some View {
List {
ForEach(products) { product in
NavigationLink {
ProductDetailView(product: product)
Section {
Menu {
Button("Alle Kategorien") { pick(nil) }
Button("Ohne Kategorie") { pick(0) }
Divider()
ForEach(categoryTree()) { eintrag in
Button(eintrag.label) { pick(eintrag.item.id) }
}
} label: {
ListRow(
systemImage: "shippingbox",
title: product.name,
subtitle: "\(formatAmount(product.stockInArticleUnits)) \(product.articleUnitLabel)"
) { EmptyView() }
HStack {
Label("Kategorie", systemImage: "line.3.horizontal.decrease.circle")
Spacer()
Text(filterLabel).foregroundStyle(.secondary)
}
}
}
if products.isEmpty && !busy {
Text("Keine Treffer").foregroundStyle(.secondary)
Section {
ForEach(products) { product in
NavigationLink {
ProductDetailView(product: product)
} label: {
ProductRow(product: product)
}
}
if products.isEmpty && !busy {
Text("Keine Treffer").foregroundStyle(.secondary)
}
}
}
.searchable(text: $query, prompt: "Artikel suchen")
@@ -197,12 +223,89 @@ struct ProductListView: View {
.navigationTitle("Produkte")
.navigationBarTitleDisplayMode(.inline)
.refreshable { await load() }
.task { await load() }
.task {
categories = (try? await APIClient.shared.categories()) ?? []
await load()
}
}
private func pick(_ id: Int?) {
categoryId = id
Task { await load() }
}
/// Kategorien in Baumreihenfolge mit eingerueckter Beschriftung.
private struct TreeEntry: Identifiable {
let item: CategoryItem
let depth: Int
var id: Int { item.id }
var label: String { String(repeating: " ", count: depth) + item.name }
}
private func categoryTree() -> [TreeEntry] {
let ids = Set(categories.map(\.id))
var result: [TreeEntry] = []
func walk(_ node: CategoryItem, _ depth: Int) {
result.append(TreeEntry(item: node, depth: depth))
for child in categories.filter({ $0.parentId == node.id }) {
walk(child, depth + 1)
}
}
// Waisen (Oberkategorie geloescht) gelten als oberste Ebene.
for root in categories.filter({ $0.parentId == nil || !ids.contains($0.parentId!) }) {
walk(root, 0)
}
return result
}
private func load() async {
busy = true
defer { busy = false }
products = (try? await APIClient.shared.searchProducts(query)) ?? []
products = (try? await APIClient.shared.searchProducts(query, categoryId: categoryId)) ?? []
}
}
/// Artikelzeile mit Gebinde und Hinweis auf den Mindestbestand.
struct ProductRow: View {
let product: Product
var body: some View {
HStack(spacing: 12) {
Image(systemName: "shippingbox")
.font(.body).foregroundStyle(.secondary).frame(width: 24)
VStack(alignment: .leading, spacing: 2) {
Text(product.name)
Text(bestand)
.font(.caption).foregroundStyle(.secondary)
if let hinweis = mindestbestand {
Text(hinweis).font(.caption2).foregroundStyle(farbe)
}
}
Spacer()
}
}
private var bestand: String {
var text = "\(formatAmount(product.stockInArticleUnits)) \(product.articleUnitLabel)"
// Bei einem Gebinde die Basismenge dahinter, damit "2 Glas" greifbar wird.
if let size = product.packageSize, size > 0 {
text += " · à \(formatAmount(size)) \(DisplaySettings.baseUnitLabel(product.baseUnit))"
}
return text
}
private var mindestbestand: String? {
guard let anzeige = product.minStockDisplay else { return nil }
let einheit = product.minStockUnitLabel ?? ""
switch product.stockLevel {
case .below: return "unter Mindestbestand (\(formatAmount(anzeige)) \(einheit))"
case .close: return "bald nachkaufen (Minimum \(formatAmount(anzeige)) \(einheit))"
case .ok, .none: return nil
}
}
private var farbe: Color {
product.stockLevel == .below ? .red : .orange
}
}

View File

@@ -53,10 +53,20 @@ struct Product: Codable, Identifiable, Hashable {
let barcodes: [BarcodeEntry]
/// Welche MHD-Genauigkeit bei diesem Produkt ueblich ist ("day"/"month").
let datePrecision: String?
/// Kategorie: reine Ordnungshilfe fuer die Artikelliste (nicht die Gruppe).
let categoryId: Int?
let categoryName: String?
/// Mindestbestand in der erfassten Einheit, fuer die Anzeige.
let minStockDisplay: Double?
let minStockUnitLabel: String?
enum CodingKeys: String, CodingKey {
case id, barcode, name, brand, stock, kind, barcodes
case datePrecision = "date_precision"
case categoryId = "category_id"
case categoryName = "category_name"
case minStockDisplay = "min_stock_display"
case minStockUnitLabel = "min_stock_unit_label"
case imageUrl = "image_url"
case baseUnit = "base_unit"
case packageSize = "package_size"
@@ -81,6 +91,16 @@ struct Product: Codable, Identifiable, Hashable {
}
var stockInArticleUnits: Double { stock / articleUnitFactor }
/// Wie es um den Mindestbestand steht. Beides in Basiseinheiten verglichen.
enum StockLevel { case none, ok, close, below }
var stockLevel: StockLevel {
guard let minimum = minStock, minimum > 0 else { return .none }
if stock < minimum { return .below }
// Weniger als ein Viertel Luft: bald nachkaufen.
return stock < minimum * 1.25 ? .close : .ok
}
}
/// Auswahleintrag fuer Einheiten.
@@ -102,14 +122,20 @@ struct LookupResult: Codable {
let found: Bool
let existingProduct: Product?
let suggestion: Suggestion?
/// Gruppe: nur gesetzt, wenn der Code dort ausdruecklich hinterlegt ist.
let groupId: Int?
let groupName: String?
/// Kategorie: aus der Open-Food-Facts-Einordnung vorgeschlagen.
let categoryId: Int?
let categoryName: String?
enum CodingKeys: String, CodingKey {
case found, suggestion
case existingProduct = "existing_product"
case groupId = "group_id"
case groupName = "group_name"
case categoryId = "category_id"
case categoryName = "category_name"
}
struct Suggestion: Codable {
@@ -215,6 +241,7 @@ struct NewProductRequest: Codable {
let packageLabel: String?
let datePrecision: String
let groupId: Int?
let categoryId: Int?
enum CodingKeys: String, CodingKey {
case barcode, name, brand
@@ -224,6 +251,7 @@ struct NewProductRequest: Codable {
case packageLabel = "package_label"
case datePrecision = "date_precision"
case groupId = "group_id"
case categoryId = "category_id"
}
}
@@ -316,8 +344,8 @@ struct ProductUpdateRequest: Encodable {
var packageSize: Double?
var packageLabel: String?
var datePrecision: String?
/// Kategorie (heisst in der API weiterhin group_id).
var groupId: Int?
var categoryId: Int?
enum CodingKeys: String, CodingKey {
case name, brand
@@ -325,6 +353,7 @@ struct ProductUpdateRequest: Encodable {
case packageLabel = "package_label"
case datePrecision = "date_precision"
case groupId = "group_id"
case categoryId = "category_id"
}
func encode(to encoder: Encoder) throws {
@@ -335,6 +364,7 @@ struct ProductUpdateRequest: Encodable {
try container.encode(packageLabel, forKey: .packageLabel)
try container.encode(datePrecision, forKey: .datePrecision)
try container.encode(groupId, forKey: .groupId)
try container.encode(categoryId, forKey: .categoryId)
}
}
@@ -356,9 +386,33 @@ struct SettingEntry: Codable {
let value: String
}
/// Kategorie (heisst in der Datenbank und in der API weiterhin "group";
/// nur die Beschriftung in der Oberflaeche wurde auf "Kategorie" geaendert).
/// Gruppe: fasst Bestaende mehrerer Marken zusammen (z.B. "Mehl").
struct GroupItem: Codable, Identifiable, Hashable {
let id: Int
let name: String
}
/// Kategorie: ordnet nur die Artikelliste, verschachtelbar (Suesswaren -> Schokolade).
struct CategoryItem: Codable, Identifiable, Hashable {
let id: Int
let name: String
let parentId: Int?
enum CodingKeys: String, CodingKey {
case id, name
case parentId = "parent_id"
}
}
/// Neue Gruppe anlegen (nur fuer Administratoren).
struct NewGroupRequest: Codable {
let name: String
let minStock: Double?
let minStockUnitId: Int?
enum CodingKeys: String, CodingKey {
case name
case minStock = "min_stock"
case minStockUnitId = "min_stock_unit_id"
}
}

View File

@@ -19,7 +19,9 @@ struct ProductDetailView: View {
@State private var packageLabel = ""
@State private var datePrecision = "day"
@State private var groupId: Int?
@State private var categories: [GroupItem] = []
@State private var categoryId: Int?
@State private var groups: [GroupItem] = []
@State private var categories: [CategoryItem] = []
@State private var editLot: Lot?
@@ -58,18 +60,30 @@ struct ProductDetailView: View {
Picker("Bezeichnung", selection: $packageLabel) {
ForEach(labels, id: \.self) { Text($0.isEmpty ? "Packung (Standard)" : $0).tag($0) }
}
Picker("Kategorie", selection: $groupId) {
Text(" keine ").tag(Int?.none)
ForEach(categories) { kategorie in
Text(kategorie.name).tag(Int?.some(kategorie.id))
}
}
Picker("MHD-Angabe", selection: $datePrecision) {
Text("Tagesdatum").tag("day")
Text("nur Monat/Jahr").tag("month")
}
}
Section {
CategoryPicker(categories: categories, selection: $categoryId)
} footer: {
Text("Kategorie: nur für den Überblick in der Artikelliste.")
}
Section {
Picker("Gruppe", selection: $groupId) {
Text(" keine ").tag(Int?.none)
ForEach(groups) { gruppe in
Text(gruppe.name).tag(Int?.some(gruppe.id))
}
}
} footer: {
Text("Gruppe: zählt Bestände mehrerer Marken zusammen. Der EAN-Code "
+ "wandert bei einem Wechsel mit.")
}
Section("Erkennung") {
LabeledContent("Barcode", value: current.barcode ?? "")
if !current.barcodes.isEmpty {
@@ -129,10 +143,12 @@ struct ProductDetailView: View {
packageLabel = current.packageLabel ?? ""
datePrecision = current.datePrecision == "month" ? "month" : "day"
groupId = current.groupId
categoryId = current.categoryId
}
private func reload() async {
categories = (try? await APIClient.shared.groups()) ?? []
groups = (try? await APIClient.shared.groups()) ?? []
categories = (try? await APIClient.shared.categories()) ?? []
lots = (try? await APIClient.shared.lots(productId: current.id)) ?? []
if let frisch = try? await APIClient.shared.product(id: current.id) {
current = frisch
@@ -153,7 +169,8 @@ struct ProductDetailView: View {
packageSize: Double(packageSize.replacingOccurrences(of: ",", with: ".")),
packageLabel: packageLabel.isEmpty ? nil : packageLabel,
datePrecision: datePrecision,
groupId: groupId
groupId: groupId,
categoryId: categoryId
)
)
status = "Gespeichert."

View File

@@ -57,6 +57,7 @@ struct ProductFormView: View {
var onCreated: (Product) -> Void
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var session: Session
@State private var barcode = ""
@State private var name = ""
@@ -66,7 +67,11 @@ struct ProductFormView: View {
@State private var packageLabel = ""
@State private var datePrecision = "day"
@State private var selectedGroupId: Int?
@State private var categories: [GroupItem] = []
@State private var selectedCategoryId: Int?
@State private var groups: [GroupItem] = []
@State private var categories: [CategoryItem] = []
@State private var units: [Unit] = []
@State private var newGroupShown = false
@State private var busy = false
@State private var error: String?
@@ -80,12 +85,29 @@ struct ProductFormView: View {
LabeledField(label: "Barcode", text: $barcode, keyboard: .numberPad)
LabeledField(label: "Name", text: $name)
LabeledField(label: "Marke", text: $brand)
Picker("Kategorie", selection: $selectedGroupId) {
}
Section {
CategoryPicker(categories: categories, selection: $selectedCategoryId)
} footer: {
Text("Kategorie: nur für den Überblick in der Artikelliste.")
}
Section {
Picker("Gruppe", selection: $selectedGroupId) {
Text(" keine ").tag(Int?.none)
ForEach(categories) { kategorie in
Text(kategorie.name).tag(Int?.some(kategorie.id))
ForEach(groups) { gruppe in
Text(gruppe.name).tag(Int?.some(gruppe.id))
}
}
if session.isAdmin {
Button {
newGroupShown = true
} label: {
Label("Neue Gruppe anlegen", systemImage: "plus")
}
}
} footer: {
Text("Gruppe: zählt Bestände mehrerer Marken zusammen. Der EAN-Code "
+ "dieses Artikels erscheint danach automatisch bei der Gruppe.")
}
Section("Einheit") {
Picker("Basiseinheit", selection: $baseUnit) {
@@ -114,12 +136,24 @@ struct ProductFormView: View {
.navigationTitle("Neuer Artikel")
.navigationBarTitleDisplayMode(.inline)
.onAppear(perform: prefill)
.task { categories = (try? await APIClient.shared.groups()) ?? [] }
.task {
groups = (try? await APIClient.shared.groups()) ?? []
categories = (try? await APIClient.shared.categories()) ?? []
units = (try? await APIClient.shared.units()) ?? []
}
.sheet(isPresented: $newGroupShown) {
NavigationStack {
NewGroupSheet(units: units) { created in
groups.append(created)
selectedGroupId = created.id
}
}
}
}
private func prefill() {
barcode = suggestion?.barcode ?? prefillBarcode ?? ""
// Aus dem gescannten Code vorgeschlagene Kategorie uebernehmen.
// Aus dem gescannten Code vorgeschlagene Gruppe uebernehmen.
selectedGroupId = groupId
if let suggestion {
name = suggestion.name
@@ -144,7 +178,8 @@ struct ProductFormView: View {
packageSize: Double(packageSize.replacingOccurrences(of: ",", with: ".")),
packageLabel: packageLabel.isEmpty ? nil : packageLabel,
datePrecision: datePrecision,
groupId: selectedGroupId
groupId: selectedGroupId,
categoryId: selectedCategoryId
)
)
onCreated(product)