diff --git a/cmd/web/handlers:equipment.go b/cmd/web/handlers:equipment.go index b1bc473..6453984 100644 --- a/cmd/web/handlers:equipment.go +++ b/cmd/web/handlers:equipment.go @@ -17,14 +17,14 @@ import ( "github.com/bit8bytes/gearberg/internal/database" "github.com/bit8bytes/gearberg/internal/equipment" "github.com/bit8bytes/gearberg/internal/equipment/categories" - "github.com/bit8bytes/gearberg/internal/equipment/locations" - "github.com/bit8bytes/gearberg/internal/equipment/manufacturers" "github.com/bit8bytes/gearberg/internal/httperr" imgpkg "github.com/bit8bytes/gearberg/internal/image" "github.com/bit8bytes/gearberg/internal/pagination" "github.com/bit8bytes/gearberg/internal/serial" "github.com/bit8bytes/gearberg/internal/storage" + "github.com/bit8bytes/gearberg/internal/templates/fragments" "github.com/bit8bytes/gearberg/internal/templates/pages" + "github.com/bit8bytes/gearberg/pkg/htmx" "github.com/segmentio/ksuid" ) @@ -56,27 +56,20 @@ type equipmentPrintData struct { } type equipmentItemData struct { - OrgID string - Item *equipment.Equipment - ID string - Categories []categories.EquipmentCategory - Manufacturers []manufacturers.Manufacturer - Locations []locations.Location - Currency string - PartOf []equipment.PartOf - ActiveTab string + OrgID string + Item *equipment.Equipment + ID string + ActiveTab string } type equipmentUnitsData struct { - OrgID string - ID string - ItemName string - ItemCode int64 - Units []equipment.Unit - Item *equipment.Equipment - Categories []categories.EquipmentCategory - PartOf []equipment.PartOf - ActiveTab string + OrgID string + ID string + ItemName string + ItemCode int64 + Units []equipment.Unit + Item *equipment.Equipment + ActiveTab string } type equipmentContentData struct { @@ -85,16 +78,36 @@ type equipmentContentData struct { Item *equipment.Equipment Content []equipment.ContentItem AllEquipment []equipment.Equipment - PartOf []equipment.PartOf ActiveTab string } -func (app *application) loadPartOf(ctx context.Context, equipmentID string) ([]equipment.PartOf, *httperr.Error) { - partOf, err := app.services.equipment.ListContainers(ctx, equipmentID) +type equipmentPartOfData struct { + OrgID string + PartOf []equipment.PartOf +} + +func (app *application) getEquipmentPartOfFragment(w http.ResponseWriter, r *http.Request) *httperr.Error { + ctx := r.Context() + orgID := r.PathValue("org_id") + itemID := r.PathValue("id") + + if !htmx.IsRequest(r) { + http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/equipment/"+url.PathEscape(itemID), http.StatusSeeOther) + return nil + } + + partOf, err := app.services.equipment.ListContainers(ctx, itemID) if err != nil { - return nil, &httperr.Error{Error: err, Message: "Failed to load container memberships.", Code: http.StatusInternalServerError} + return &httperr.Error{ + Error: fmt.Errorf("getEquipmentPartOfFragment: %w", err), + Message: "Failed to load container memberships.", + Code: http.StatusInternalServerError, + } } - return partOf, nil + + tmplData := app.html.TemplateData(r) + tmplData.Data = equipmentPartOfData{OrgID: orgID, PartOf: partOf} + return app.html.RenderFragment(w, r, http.StatusOK, fragments.EquipmentPartOf, tmplData) } func (app *application) getEquipment(w http.ResponseWriter, r *http.Request) *httperr.Error { @@ -149,15 +162,9 @@ func (app *application) getEquipment(w http.ResponseWriter, r *http.Request) *ht func (app *application) getEquipmentNew(w http.ResponseWriter, r *http.Request) *httperr.Error { id := r.PathValue("org_id") - - deps, appErr := app.loadEquipmentFormDeps(r, id) - if appErr != nil { - return appErr - } - data := app.html.TemplateData(r) data.Form = &equipment.NewForm{} - data.Data = equipmentItemData{OrgID: id, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency} + data.Data = equipmentItemData{OrgID: id} return app.html.Render(w, r, http.StatusOK, pages.EquipmentNew, data) } @@ -171,13 +178,9 @@ func (app *application) postEquipmentNew(w http.ResponseWriter, r *http.Request) } reRender := func(f *equipment.NewForm) *httperr.Error { - deps, appErr := app.loadEquipmentFormDeps(r, id) - if appErr != nil { - return appErr - } data := app.html.TemplateData(r) data.Form = f - data.Data = equipmentItemData{OrgID: id, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency} + data.Data = equipmentItemData{OrgID: id} return app.html.Render(w, r, http.StatusUnprocessableEntity, pages.EquipmentNew, data) } @@ -199,9 +202,9 @@ func (app *application) postEquipmentNew(w http.ResponseWriter, r *http.Request) ManufacturerID: form.ManufacturerID, LocationID: database.StringOrNil(form.LocationID), HasContent: form.HasContentBool(), - PurchasePrice: form.PurchasePriceCents(), - RentalPrice: form.RentalPriceCents(), Notes: form.Notes, + Pricing: form.ToPricing(), + Properties: form.ToProperties(), } eqType := equipment.TypeFromString(form.TypeID) @@ -211,8 +214,8 @@ func (app *application) postEquipmentNew(w http.ResponseWriter, r *http.Request) eq, err := app.services.equipment.Create(ctx, equipment.CreateEquipment{ Type: eqType, Base: base, - TotalStock: form.CountInt64(), - UnitCount: form.CountInt64(), + TotalStock: form.Count, + UnitCount: form.Count, }) if err != nil { return &httperr.Error{Error: err, Message: "Failed to create inventory item.", Code: http.StatusInternalServerError} @@ -230,6 +233,32 @@ func (app *application) postEquipmentNew(w http.ResponseWriter, r *http.Request) return nil } +func (app *application) resolveDetailsFormRefs(r *http.Request, orgID string, form *equipment.DetailsForm) *httperr.Error { + ctx := r.Context() + if form.CategoryID == "" && form.CategoryName != "" { + catID, err := app.services.equipmentcategories.EnsureByName(ctx, orgID, form.CategoryName) + if err != nil { + return &httperr.Error{Error: err, Message: "Failed to resolve category.", Code: http.StatusInternalServerError} + } + form.CategoryID = catID + } + if form.ManufacturerID == "" && form.ManufacturerName != "" { + mfrID, err := app.services.manufacturers.EnsureByName(ctx, orgID, form.ManufacturerName) + if err != nil { + return &httperr.Error{Error: err, Message: "Failed to resolve manufacturer.", Code: http.StatusInternalServerError} + } + form.ManufacturerID = mfrID + } + if form.LocationID == "" && form.LocationName != "" { + locID, err := app.services.locations.EnsureByName(ctx, orgID, form.LocationName) + if err != nil { + return &httperr.Error{Error: err, Message: "Failed to resolve location.", Code: http.StatusInternalServerError} + } + form.LocationID = locID + } + return nil +} + func (app *application) resolveNewFormRefs(r *http.Request, orgID string, form *equipment.NewForm) *httperr.Error { ctx := r.Context() if form.CategoryID == "" && form.CategoryName != "" { @@ -271,20 +300,9 @@ func (app *application) getEquipmentItem(w http.ResponseWriter, r *http.Request) app.resolveItemURLs(item) - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } - data := app.html.TemplateData(r) data.Form = &equipment.DetailsForm{} - itemData := equipmentItemData{OrgID: orgID, Item: item, ID: itemID, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency, PartOf: partOf, ActiveTab: "details"} - data.Data = itemData + data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, ActiveTab: "details"} return app.html.Render(w, r, http.StatusOK, pages.EquipmentDetail, data) } @@ -307,21 +325,16 @@ func (app *application) postEquipmentItemDetails(w http.ResponseWriter, r *http. if err != nil { return &httperr.Error{Error: err, Message: "Failed to retrieve inventory item.", Code: http.StatusInternalServerError} } - app.resolveItemURLs(item) - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } data := app.html.TemplateData(r) data.Form = &form - data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency, PartOf: partOf, ActiveTab: "details"} + data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, ActiveTab: "details"} return app.html.Render(w, r, http.StatusUnprocessableEntity, pages.EquipmentDetail, data) } + if appErr := app.resolveDetailsFormRefs(r, orgID, &form); appErr != nil { + return appErr + } + itemType := equipment.TypeFromString(form.TypeID) if err := app.services.equipment.UpdateDetails(ctx, equipment.UpdateEquipmentDetails{ ID: itemID, @@ -331,7 +344,7 @@ func (app *application) postEquipmentItemDetails(w http.ResponseWriter, r *http. ManufacturerID: form.ManufacturerID, LocationID: form.LocationID, Notes: form.Notes, - TotalStock: form.TotalStockInt64(), + TotalStock: form.TotalStock, }); err != nil { return &httperr.Error{Error: err, Message: "Failed to update inventory item.", Code: http.StatusInternalServerError} } @@ -351,15 +364,8 @@ func (app *application) postEquipmentItemProperties(w http.ResponseWriter, r *ht } if err := app.services.equipment.UpdateProperties(ctx, equipment.UpdateEquipmentProperties{ - ID: itemID, - WeightG: form.WeightGInt64(), - WidthMM: form.WidthMMInt64(), - HeightMM: form.HeightMMInt64(), - DepthMM: form.DepthMMInt64(), - VoltageV: form.VoltageVInt64(), - PowerMW: form.PowerMW(), - CurrentMA: form.CurrentMA(), - WireGaugeMM2X100: form.WireGaugeMM2X100Int64(), + ID: itemID, + Properties: form.ToProperties(), }); err != nil { return &httperr.Error{Error: err, Message: "Failed to update inventory item.", Code: http.StatusInternalServerError} } @@ -383,19 +389,10 @@ func (app *application) getEquipmentItemPricing(w http.ResponseWriter, r *http.R app.resolveItemURLs(item) - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } - data := app.html.TemplateData(r) - data.Form = &equipment.PricingForm{} - data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency, PartOf: partOf, ActiveTab: "pricing"} + f := equipment.PricingFormFromEquipment(item) + data.Form = &f + data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, ActiveTab: "pricing"} return app.html.Render(w, r, http.StatusOK, pages.EquipmentPricing, data) } @@ -414,25 +411,16 @@ func (app *application) postEquipmentItemPricing(w http.ResponseWriter, r *http. if err != nil { return &httperr.Error{Error: err, Message: "Failed to retrieve inventory item.", Code: http.StatusInternalServerError} } - app.resolveItemURLs(item) - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } + data := app.html.TemplateData(r) data.Form = &form - data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency, PartOf: partOf, ActiveTab: "pricing"} + data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, ActiveTab: "pricing"} return app.html.Render(w, r, http.StatusUnprocessableEntity, pages.EquipmentPricing, data) } if err := app.services.equipment.UpdatePricing(ctx, equipment.UpdateEquipmentPricing{ - ID: itemID, - PurchasePrice: form.PurchasePriceCents(), - RentalPrice: form.RentalPriceCents(), + ID: itemID, + Pricing: form.ToPricing(), }); err != nil { return &httperr.Error{Error: err, Message: "Failed to update inventory item.", Code: http.StatusInternalServerError} } @@ -456,19 +444,10 @@ func (app *application) getEquipmentItemProperties(w http.ResponseWriter, r *htt app.resolveItemURLs(item) - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } - data := app.html.TemplateData(r) - data.Form = &equipment.PropertiesForm{} - data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, Categories: deps.Categories, Manufacturers: deps.Manufacturers, Locations: deps.Locations, Currency: deps.Currency, PartOf: partOf, ActiveTab: "properties"} + f := equipment.PropertiesFormFromEquipment(item) + data.Form = &f + data.Data = equipmentItemData{OrgID: orgID, Item: item, ID: itemID, ActiveTab: "properties"} return app.html.Render(w, r, http.StatusOK, pages.EquipmentProperties, data) } @@ -521,13 +500,13 @@ func (app *application) postEquipmentUpdateUnit(w http.ResponseWriter, r *http.R if err := app.services.equipment.UpdateUnit(ctx, equipment.UpdateUnit{ ID: unitID, - StatusID: form.StatusIDInt64(), + StatusID: form.StatusID, ManufacturerSerialNumber: form.ManufacturerSerialNumber, Code: form.Code, Notes: form.Notes, - PurchasePrice: form.PurchasePriceCents(), - PurchasedAt: form.PurchasedAtUnix(), - NextInspectionAt: form.NextInspectionAtUnix(), + PurchasePrice: form.PurchasePrice, + PurchasedAt: form.PurchasedAt, + NextInspectionAt: form.NextInspectionAt, }); err != nil { return &httperr.Error{Error: err, Message: "Failed to update unit.", Code: http.StatusInternalServerError} } @@ -601,26 +580,14 @@ func (app *application) getEquipmentUnits(w http.ResponseWriter, r *http.Request return &httperr.Error{Error: err, Message: "Failed to retrieve units.", Code: http.StatusInternalServerError} } - deps, appErr := app.loadEquipmentFormDeps(r, orgID) - if appErr != nil { - return appErr - } - - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } - data := app.html.TemplateData(r) data.Data = equipmentUnitsData{ - OrgID: orgID, - ID: itemID, - ItemName: item.Name, - Units: units, - Item: item, - Categories: deps.Categories, - PartOf: partOf, - ActiveTab: "units", + OrgID: orgID, + ID: itemID, + ItemName: item.Name, + Units: units, + Item: item, + ActiveTab: "units", } return app.html.Render(w, r, http.StatusOK, pages.EquipmentUnits, data) } @@ -810,35 +777,6 @@ func (app *application) resolveEquipmentURLs(items []equipment.Equipment) { } } -type equipmentFormDeps struct { - Categories []categories.EquipmentCategory - Manufacturers []manufacturers.Manufacturer - Locations []locations.Location - Currency string -} - -func (app *application) loadEquipmentFormDeps(r *http.Request, orgID string) (equipmentFormDeps, *httperr.Error) { - ctx := r.Context() - cats, err := app.services.equipment.ListCategories(ctx, orgID) - if err != nil { - return equipmentFormDeps{}, &httperr.Error{Error: err, Message: "Failed to retrieve categories.", Code: http.StatusInternalServerError} - } - mfrs, err := app.services.equipment.ListManufacturers(ctx, orgID) - if err != nil { - return equipmentFormDeps{}, &httperr.Error{Error: err, Message: "Failed to retrieve manufacturers.", Code: http.StatusInternalServerError} - } - locs, err := app.services.equipment.ListLocations(ctx, orgID) - if err != nil { - return equipmentFormDeps{}, &httperr.Error{Error: err, Message: "Failed to retrieve locations.", Code: http.StatusInternalServerError} - } - orgSettings, _ := app.services.orgsettings.GetByOrgID(ctx, orgID) - currency := "" - if orgSettings != nil { - currency = orgSettings.Currency - } - return equipmentFormDeps{Categories: cats, Manufacturers: mfrs, Locations: locs, Currency: currency}, nil -} - // linkEquipmentImage associates a storage object with an inventory item. func (app *application) linkEquipmentImage(r *http.Request, itemID, storageObjectID string) *httperr.Error { if err := app.services.equipment.SetImage(r.Context(), equipment.SetImage{ @@ -931,14 +869,9 @@ func (app *application) getEquipmentContent(w http.ResponseWriter, r *http.Reque } app.resolveItemURLs(item) - partOf, loadPartOfErr := app.loadPartOf(ctx, itemID) - if loadPartOfErr != nil { - return loadPartOfErr - } - data := app.html.TemplateData(r) data.Form = &equipment.ContentForm{} - data.Data = equipmentContentData{OrgID: orgID, ID: itemID, Item: item, Content: content, AllEquipment: all, PartOf: partOf, ActiveTab: "content"} + data.Data = equipmentContentData{OrgID: orgID, ID: itemID, Item: item, Content: content, AllEquipment: all, ActiveTab: "content"} return app.html.Render(w, r, http.StatusOK, pages.EquipmentContent, data) } @@ -984,13 +917,12 @@ func (app *application) postEquipmentAssignContent(w http.ResponseWriter, r *htt return appErr } app.resolveItemURLs(item) - partOf, _ := app.loadPartOf(ctx, itemID) if extraErr != "" { f.AddError("assign", extraErr) } data := app.html.TemplateData(r) data.Form = f - data.Data = equipmentContentData{OrgID: orgID, ID: itemID, Item: item, Content: content, AllEquipment: all, PartOf: partOf, ActiveTab: "content"} + data.Data = equipmentContentData{OrgID: orgID, ID: itemID, Item: item, Content: content, AllEquipment: all, ActiveTab: "content"} return app.html.Render(w, r, http.StatusUnprocessableEntity, pages.EquipmentContent, data) } @@ -1011,7 +943,7 @@ func (app *application) postEquipmentAssignContent(w http.ResponseWriter, r *htt ID: ksuid.New().String(), EquipmentID: itemID, MemberID: memberID, - Quantity: form.QuantityInt64(), + Quantity: form.Quantity, }) if err != nil { if errors.Is(err, database.ErrUniqueConstraint) { diff --git a/cmd/web/handlers:equipment:categories.go b/cmd/web/handlers:equipment:categories.go index 4f49305..0c5033f 100644 --- a/cmd/web/handlers:equipment:categories.go +++ b/cmd/web/handlers:equipment:categories.go @@ -9,7 +9,9 @@ import ( "github.com/bit8bytes/gearberg/internal/database" "github.com/bit8bytes/gearberg/internal/equipment/categories" "github.com/bit8bytes/gearberg/internal/httperr" + "github.com/bit8bytes/gearberg/internal/templates/fragments" "github.com/bit8bytes/gearberg/internal/templates/pages" + "github.com/bit8bytes/gearberg/pkg/htmx" "github.com/segmentio/ksuid" ) @@ -17,6 +19,8 @@ type equipmentCategoriesData struct { OrgID string Categories []categories.EquipmentCategory MaxCategories int + SelectedID string + SelectedName string } type equipmentCategoryData struct { @@ -205,3 +209,29 @@ func (app *application) postDeleteEquipmentCategory(w http.ResponseWriter, r *ht http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/settings/equipment-categories", http.StatusSeeOther) return nil } + +func (app *application) getEquipmentCategoriesFragment(w http.ResponseWriter, r *http.Request) *httperr.Error { + ctx := r.Context() + orgID := r.PathValue("org_id") + + if !htmx.IsRequest(r) { + http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/settings/equipment-categories", http.StatusSeeOther) + return nil + } + + selected := r.URL.Query().Get("selected") + selectedName := r.URL.Query().Get("selected_name") + + cats, err := app.services.equipmentcategories.GetByOrgID(ctx, orgID) + if err != nil { + return &httperr.Error{ + Error: fmt.Errorf("getEquipmentCategoriesFragment: %w", err), + Message: "Failed to retrieve categories.", + Code: http.StatusInternalServerError, + } + } + + tmplData := app.html.TemplateData(r) + tmplData.Data = equipmentCategoriesData{OrgID: orgID, Categories: cats, SelectedID: selected, SelectedName: selectedName} + return app.html.RenderFragment(w, r, http.StatusOK, fragments.EquipmentCategories, tmplData) +} diff --git a/cmd/web/handlers:equipment:export.go b/cmd/web/handlers:equipment:export.go index 18f074c..f8bb279 100644 --- a/cmd/web/handlers:equipment:export.go +++ b/cmd/web/handlers:equipment:export.go @@ -2,7 +2,6 @@ package main import ( "encoding/csv" - "fmt" "net/http" "strconv" @@ -47,34 +46,20 @@ func (app *application) getEquipmentExport(w http.ResponseWriter, r *http.Reques item.CategoryName, mfrByID[item.ManufacturerID], item.LocationName, - exportPrice(item.RentalPrice), - exportPrice(item.PurchasePrice), + item.Pricing.RentalPrice.ToDecimal(), + item.Pricing.PurchasePrice.ToDecimal(), item.Notes, - exportOptInt(item.WeightG), - exportOptInt(item.WidthMM), - exportOptInt(item.HeightMM), - exportOptInt(item.DepthMM), - exportOptInt(item.VoltageV), - exportOptInt(item.CurrentMA), - exportOptInt(item.PowerMW), - exportOptInt(item.WireGaugeMM2X100), + item.Properties.Weight.ToKG(), + item.Properties.Width.ToCM(), + item.Properties.Height.ToCM(), + item.Properties.Depth.ToCM(), + item.Properties.Voltage.ToV(), + item.Properties.Current.ToA(), + item.Properties.Power.ToW(), + item.Properties.WireGauge.String(), strconv.FormatInt(item.TotalStock, 10), }) } cw.Flush() return nil } - -func exportPrice(v *int64) string { - if v == nil { - return "" - } - return fmt.Sprintf("%.2f", float64(*v)/100) -} - -func exportOptInt(v *int64) string { - if v == nil { - return "" - } - return strconv.FormatInt(*v, 10) -} diff --git a/cmd/web/handlers:equipment:import.go b/cmd/web/handlers:equipment:import.go index 6f2706d..dadf0e3 100644 --- a/cmd/web/handlers:equipment:import.go +++ b/cmd/web/handlers:equipment:import.go @@ -63,7 +63,7 @@ func (app *application) postEquipmentImport(w http.ResponseWriter, r *http.Reque rawRows, parseErr := parseImportCSV(f) if parseErr != "" { - return reRender("Failed to parse CSV.") + return reRender(parseErr) } importID, err := app.services.equipmentImports.Stage(ctx, orgID, rawRows) @@ -125,9 +125,9 @@ func (app *application) postEquipmentImportConfirm(w http.ResponseWriter, r *htt return nil } -const importTemplateCSV = "Name,Type,Usage,Category,Manufacturer,Location,Rental Price,Resale Price,Notes,Weight (g),Width (mm),Height (mm),Depth (mm),Voltage (V),Current (mA),Power (mW),Wire Gauge (mm² ×100),Quantity\n" + - "Shure SM58,Bulk,Rental,Audio,Shure,Main Warehouse,15.00,99.00,Cardioid dynamic vocal microphone,298,47,47,162,,,,,7\n" + - "Sony SRS-XB43,Serialized,Rental,Audio,Sony,Main Warehouse,25.00,180.00,Portable Bluetooth speaker with extra bass,900,220,220,95,5,2400,12000,,4\n" +const importTemplateCSV = "Name,Type,Usage,Category,Manufacturer,Location,Rental Price,Resale Price,Notes,Weight (kg),Width (cm),Height (cm),Depth (cm),Voltage (V),Current (A),Power (W),Wire Gauge (mm² ×100),Quantity\n" + + "Shure SM58,Bulk,Rental,Audio,Shure,Main Warehouse,15.00,99.00,Cardioid dynamic vocal microphone,0.298,4.7,4.7,16.2,,,,,7\n" + + "Sony SRS-XB43,Serialized,Rental,Audio,Sony,Main Warehouse,25.00,180.00,Portable Bluetooth speaker with extra bass,0.9,22,22,9.5,5,2.4,12,,4\n" // getEquipmentImportTemplate serves a ready-to-fill CSV template for download. func (app *application) getEquipmentImportTemplate(w http.ResponseWriter, _ *http.Request) *httperr.Error { @@ -199,8 +199,8 @@ func readImportRows(cr *csv.Reader) ([]imports.RawRow, string) { HeightMm: strings.TrimSpace(record[11]), DepthMm: strings.TrimSpace(record[12]), VoltageV: strings.TrimSpace(record[13]), - CurrentMa: strings.TrimSpace(record[14]), - PowerMw: strings.TrimSpace(record[15]), + CurrentA: strings.TrimSpace(record[14]), + PowerW: strings.TrimSpace(record[15]), WireGaugeMM2X100: strings.TrimSpace(record[16]), Quantity: strings.TrimSpace(record[17]), }) diff --git a/cmd/web/handlers:equipment:locations.go b/cmd/web/handlers:equipment:locations.go index 038f340..7594095 100644 --- a/cmd/web/handlers:equipment:locations.go +++ b/cmd/web/handlers:equipment:locations.go @@ -9,7 +9,9 @@ import ( "github.com/bit8bytes/gearberg/internal/database" "github.com/bit8bytes/gearberg/internal/equipment/locations" "github.com/bit8bytes/gearberg/internal/httperr" + "github.com/bit8bytes/gearberg/internal/templates/fragments" "github.com/bit8bytes/gearberg/internal/templates/pages" + "github.com/bit8bytes/gearberg/pkg/htmx" "github.com/segmentio/ksuid" ) @@ -17,6 +19,8 @@ type locationsData struct { OrgID string Locations []locations.Location MaxLocations int + SelectedID string + SelectedName string } type locationData struct { @@ -192,3 +196,29 @@ func (app *application) postDeleteLocation(w http.ResponseWriter, r *http.Reques http.Redirect(w, r, dest, http.StatusSeeOther) //nolint:gosec // dest is a hard-coded path with org_id from path value. return nil } + +func (app *application) getEquipmentLocationsFragment(w http.ResponseWriter, r *http.Request) *httperr.Error { + ctx := r.Context() + orgID := r.PathValue("org_id") + + if !htmx.IsRequest(r) { + http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/settings/locations", http.StatusSeeOther) + return nil + } + + selected := r.URL.Query().Get("selected") + selectedName := r.URL.Query().Get("selected_name") + + locs, err := app.services.locations.GetByOrgID(ctx, orgID) + if err != nil { + return &httperr.Error{ + Error: fmt.Errorf("getEquipmentLocationsFragment: %w", err), + Message: "Failed to retrieve locations.", + Code: http.StatusInternalServerError, + } + } + + tmplData := app.html.TemplateData(r) + tmplData.Data = locationsData{OrgID: orgID, Locations: locs, SelectedID: selected, SelectedName: selectedName} + return app.html.RenderFragment(w, r, http.StatusOK, fragments.WarehouseLocations, tmplData) +} diff --git a/cmd/web/handlers:equipment:manufacturers.go b/cmd/web/handlers:equipment:manufacturers.go index 0bd6998..b233ff5 100644 --- a/cmd/web/handlers:equipment:manufacturers.go +++ b/cmd/web/handlers:equipment:manufacturers.go @@ -9,7 +9,9 @@ import ( "github.com/bit8bytes/gearberg/internal/database" "github.com/bit8bytes/gearberg/internal/equipment/manufacturers" "github.com/bit8bytes/gearberg/internal/httperr" + "github.com/bit8bytes/gearberg/internal/templates/fragments" "github.com/bit8bytes/gearberg/internal/templates/pages" + "github.com/bit8bytes/gearberg/pkg/htmx" "github.com/segmentio/ksuid" ) @@ -17,6 +19,8 @@ type manufacturersData struct { OrgID string Manufacturers []manufacturers.Manufacturer MaxManufacturers int + SelectedID string + SelectedName string } type manufacturerData struct { @@ -207,3 +211,29 @@ func (app *application) postDeleteManufacturer(w http.ResponseWriter, r *http.Re http.Redirect(w, r, dest, http.StatusSeeOther) //nolint:gosec return nil } + +func (app *application) getEquipmentManufacturersFragment(w http.ResponseWriter, r *http.Request) *httperr.Error { + ctx := r.Context() + orgID := r.PathValue("org_id") + + if !htmx.IsRequest(r) { + http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/settings/manufacturers", http.StatusSeeOther) + return nil + } + + selected := r.URL.Query().Get("selected") + selectedName := r.URL.Query().Get("selected_name") + + mfrs, err := app.services.manufacturers.GetByOrgID(ctx, orgID) + if err != nil { + return &httperr.Error{ + Error: fmt.Errorf("getEquipmentManufacturersFragment: %w", err), + Message: "Failed to retrieve manufacturers.", + Code: http.StatusInternalServerError, + } + } + + tmplData := app.html.TemplateData(r) + tmplData.Data = manufacturersData{OrgID: orgID, Manufacturers: mfrs, SelectedID: selected, SelectedName: selectedName} + return app.html.RenderFragment(w, r, http.StatusOK, fragments.EquipmentManufacturers, tmplData) +} diff --git a/cmd/web/handlers:orgs.go b/cmd/web/handlers:orgs.go index d434050..fe3ec39 100644 --- a/cmd/web/handlers:orgs.go +++ b/cmd/web/handlers:orgs.go @@ -8,6 +8,7 @@ import ( "github.com/bit8bytes/gearberg/internal/database" "github.com/bit8bytes/gearberg/internal/httperr" "github.com/bit8bytes/gearberg/internal/orgs" + "github.com/bit8bytes/gearberg/internal/orgs/settings" "github.com/bit8bytes/gearberg/internal/storage" "github.com/bit8bytes/gearberg/internal/templates/pages" "github.com/segmentio/ksuid" @@ -84,6 +85,21 @@ func (app *application) postOrgsNew(w http.ResponseWriter, r *http.Request) *htt } } + _, err = app.services.orgsettings.Upsert(ctx, settings.UpsertOrgSettings{ + ID: ksuid.New().String(), + OrgID: org.ID, + Currency: app.options.DefaultCurrency, + VatRate: app.options.DefaultVatRateBasisPoints(), + Timezone: app.options.DefaultTimezone, + }) + if err != nil { + return &httperr.Error{ + Error: fmt.Errorf("postOrgsNew: seed default settings: %w", err), + Message: "Failed to initialise org settings.", + Code: http.StatusInternalServerError, + } + } + http.Redirect(w, r, fmt.Sprintf("/orgs/%s/equipment", org.ID), http.StatusSeeOther) return nil } diff --git a/cmd/web/handlers:orgs:settings.go b/cmd/web/handlers:orgs:settings.go index 0c3272e..97009a1 100644 --- a/cmd/web/handlers:orgs:settings.go +++ b/cmd/web/handlers:orgs:settings.go @@ -1,11 +1,15 @@ package main import ( + "fmt" "net/http" + "net/url" "github.com/bit8bytes/gearberg/internal/httperr" "github.com/bit8bytes/gearberg/internal/orgs/settings" + "github.com/bit8bytes/gearberg/internal/templates/fragments" "github.com/bit8bytes/gearberg/internal/templates/pages" + "github.com/bit8bytes/gearberg/pkg/htmx" "github.com/segmentio/ksuid" ) @@ -14,6 +18,38 @@ type orgSettingsData struct { OrgID string } +type orgCurrencyData struct { + Currency string +} + +func (app *application) getOrgCurrencyFragment(w http.ResponseWriter, r *http.Request) *httperr.Error { + ctx := r.Context() + orgID := r.PathValue("org_id") + + if !htmx.IsRequest(r) { + http.Redirect(w, r, "/orgs/"+url.PathEscape(orgID)+"/settings", http.StatusSeeOther) + return nil + } + + s, err := app.services.orgsettings.GetByOrgID(ctx, orgID) + if err != nil { + return &httperr.Error{ + Error: fmt.Errorf("getOrgCurrencyFragment: %w", err), + Message: "Failed to retrieve org settings.", + Code: http.StatusInternalServerError, + } + } + + currency := "" + if s != nil { + currency = s.Currency + } + + tmplData := app.html.TemplateData(r) + tmplData.Data = orgCurrencyData{Currency: currency} + return app.html.RenderFragment(w, r, http.StatusOK, fragments.OrgCurrency, tmplData) +} + func (app *application) getOrgSettings(w http.ResponseWriter, r *http.Request) *httperr.Error { ctx := r.Context() id := r.PathValue("org_id") diff --git a/cmd/web/main.go b/cmd/web/main.go index 8a2649e..0970724 100644 --- a/cmd/web/main.go +++ b/cmd/web/main.go @@ -85,12 +85,12 @@ func runServe(args []string) error { log := setupLogger(options.LogLevel.Level()) - cache, err := parseTemplates() + base, cache, err := parseTemplates() if err != nil { return fmt.Errorf("load templates: %w", err) } - html := htmlpkg.New(log, cache, revision) + html := htmlpkg.New(log, base, cache, revision) db, err := setupDatabase(ctx, options) if err != nil { diff --git a/cmd/web/middleware.go b/cmd/web/middleware.go index 175ce84..3c8e9c2 100644 --- a/cmd/web/middleware.go +++ b/cmd/web/middleware.go @@ -10,8 +10,8 @@ import ( "github.com/bit8bytes/gearberg/internal/nonce" "github.com/bit8bytes/gearberg/internal/storage" - "github.com/bit8bytes/gearberg/internal/tokens" "github.com/bit8bytes/gearberg/internal/trace" + "github.com/bit8bytes/gearberg/pkg/tokens" ) func withTrace(next http.Handler) http.Handler { diff --git a/cmd/web/options.go b/cmd/web/options.go index 4bef799..3388d58 100644 --- a/cmd/web/options.go +++ b/cmd/web/options.go @@ -4,8 +4,11 @@ import ( "flag" "fmt" "log/slog" + "math" "os" "slices" + + "github.com/bit8bytes/gearberg/internal/orgs/settings" ) type options struct { @@ -20,6 +23,9 @@ type options struct { MaxOrgManufacturers int MaxOrgLocations int MaxStorageBytes int64 + DefaultCurrency string + DefaultVatRate float64 // percentage e.g. 19.0 + DefaultTimezone string } func registerCommonFlags(fs *flag.FlagSet, cfg *options) { @@ -41,6 +47,9 @@ func parseServeOptions(args []string) (*options, error) { fs.IntVar(&cfg.MaxOrgLocations, "max-locations", 100, "maximum number of locations per org") fs.StringVar(&cfg.StorageDSN, "storage-dsn", envOr("STORAGE_DSN", "./var/data"), "storage backend DSN") fs.Int64Var(&cfg.MaxStorageBytes, "max-storage-bytes", 1<<30, "maximum storage bytes per org (default 1 GiB)") + fs.StringVar(&cfg.DefaultCurrency, "default-currency", "EUR", "default currency for new org settings (ISO-4217)") + fs.Float64Var(&cfg.DefaultVatRate, "default-vat-rate", 19.0, "default VAT rate for new org settings (percentage)") + fs.StringVar(&cfg.DefaultTimezone, "default-timezone", "Europe/Berlin", "default timezone for new org settings (IANA)") if err := fs.Parse(args); err != nil { return nil, fmt.Errorf("parseServeOptions: %w", err) @@ -82,9 +91,23 @@ func (cfg *options) validate() error { if cfg.MaxOrgLocations <= 0 { return fmt.Errorf("max locations must be greater than 0") } + if !slices.Contains(settings.PermittedCurrencies, cfg.DefaultCurrency) { + return fmt.Errorf("default-currency %q is not a permitted ISO-4217 code", cfg.DefaultCurrency) + } + if cfg.DefaultVatRate < 0 || cfg.DefaultVatRate > 100 { + return fmt.Errorf("default-vat-rate must be between 0 and 100") + } + if !slices.Contains(settings.PermittedTimezones, cfg.DefaultTimezone) { + return fmt.Errorf("default-timezone %q is not a permitted IANA timezone", cfg.DefaultTimezone) + } return nil } +// DefaultVatRateBasisPoints converts DefaultVatRate from a percentage to basis points (e.g. 19.0 → 1900). +func (cfg *options) DefaultVatRateBasisPoints() int64 { + return int64(math.Round(cfg.DefaultVatRate * 100)) +} + func parseVerifyOptions(args []string) (*options, error) { cfg := &options{LogLevel: logLevel{level: slog.LevelError}} fs := flag.NewFlagSet("verify", flag.ContinueOnError) diff --git a/cmd/web/routes.go b/cmd/web/routes.go index 812e0e4..52971d5 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -57,6 +57,11 @@ func (app *application) routes() (http.Handler, error) { mux.HandleFunc("GET /orgs/{org_id}/equipment/{id}/content", app.html.Handle(app.getEquipmentContent)) mux.HandleFunc("POST /orgs/{org_id}/equipment/{id}/content", app.html.Handle(app.postEquipmentAssignContent)) mux.HandleFunc("POST /orgs/{org_id}/equipment/{id}/content/{content_id}/delete", app.html.Handle(app.postEquipmentRemoveContent)) + mux.HandleFunc("GET /orgs/{org_id}/equipment/{id}/part-of", app.html.Handle(app.getEquipmentPartOfFragment)) + mux.HandleFunc("GET /orgs/{org_id}/currency", app.html.Handle(app.getOrgCurrencyFragment)) + mux.HandleFunc("GET /orgs/{org_id}/equipment-categories", app.html.Handle(app.getEquipmentCategoriesFragment)) + mux.HandleFunc("GET /orgs/{org_id}/equipment-manufacturers", app.html.Handle(app.getEquipmentManufacturersFragment)) + mux.HandleFunc("GET /orgs/{org_id}/warehouse-locations", app.html.Handle(app.getEquipmentLocationsFragment)) mux.HandleFunc("GET /orgs/{org_id}/settings", app.html.Handle(app.getOrgSettings)) mux.HandleFunc("POST /orgs/{org_id}/settings", app.html.Handle(app.postOrgSettings)) mux.HandleFunc("GET /orgs/{org_id}/settings/equipment-categories", app.html.Handle(app.getEquipmentCategories)) diff --git a/cmd/web/setup.go b/cmd/web/setup.go index 50aa2b2..fc255d0 100644 --- a/cmd/web/setup.go +++ b/cmd/web/setup.go @@ -67,10 +67,10 @@ func templateFuncs() template.FuncMap { } } -func parseTemplates() (map[string]*template.Template, error) { - base, err := template.New("root").Funcs(templateFuncs()).ParseFS(templates.EmbedFS, "layouts/root.tmpl", "components/*.tmpl") +func parseTemplates() (*template.Template, map[string]*template.Template, error) { + base, err := template.New("root").Funcs(templateFuncs()).ParseFS(templates.EmbedFS, "layouts/root.tmpl", "components/*.tmpl", "fragments/*.tmpl") if err != nil { - return nil, fmt.Errorf("base template: %w", err) + return nil, nil, fmt.Errorf("base template: %w", err) } allPages := pages.All @@ -78,11 +78,11 @@ func parseTemplates() (map[string]*template.Template, error) { for _, page := range allPages { t, err := pageTemplate(templates.EmbedFS, base, page) if err != nil { - return nil, fmt.Errorf("page template %s: %w", page.File, err) + return nil, nil, fmt.Errorf("page template %s: %w", page.File, err) } tmpls[page.File] = t } - return tmpls, nil + return base, tmpls, nil } func pageTemplate(fsys fs.FS, base *template.Template, page pages.Page) (*template.Template, error) { diff --git a/cmd/www/main.go b/cmd/www/main.go index 025f0c1..cbd8f91 100644 --- a/cmd/www/main.go +++ b/cmd/www/main.go @@ -79,7 +79,7 @@ func runServe(args []string) error { log := setupLogger(options.LogLevel.Level()) - cache, err := parseTemplates() + base, cache, err := parseTemplates() if err != nil { return fmt.Errorf("load templates: %w", err) } @@ -87,7 +87,7 @@ func runServe(args []string) error { app := &application{ logger: log, options: options, - html: htmlpkg.New(log, cache, revision), + html: htmlpkg.New(log, base, cache, revision), } return app.serve(ctx) diff --git a/cmd/www/middleware.go b/cmd/www/middleware.go index 4882c67..9601f30 100644 --- a/cmd/www/middleware.go +++ b/cmd/www/middleware.go @@ -9,8 +9,8 @@ import ( "strings" "github.com/bit8bytes/gearberg/internal/nonce" - "github.com/bit8bytes/gearberg/internal/tokens" "github.com/bit8bytes/gearberg/internal/trace" + "github.com/bit8bytes/gearberg/pkg/tokens" ) func withTrace(next http.Handler) http.Handler { diff --git a/cmd/www/setup.go b/cmd/www/setup.go index 6eca42e..386a562 100644 --- a/cmd/www/setup.go +++ b/cmd/www/setup.go @@ -55,10 +55,10 @@ func templateFuncs() template.FuncMap { } } -func parseTemplates() (map[string]*template.Template, error) { +func parseTemplates() (*template.Template, map[string]*template.Template, error) { base, err := template.New("root").Funcs(templateFuncs()).ParseFS(templates.EmbedFS, "layouts/landing.tmpl", "components/*.tmpl") if err != nil { - return nil, fmt.Errorf("base template: %w", err) + return nil, nil, fmt.Errorf("base template: %w", err) } allPages := pages.All @@ -66,11 +66,11 @@ func parseTemplates() (map[string]*template.Template, error) { for _, page := range allPages { t, err := pageTemplate(templates.EmbedFS, base, page) if err != nil { - return nil, fmt.Errorf("page template %s: %w", page.File, err) + return nil, nil, fmt.Errorf("page template %s: %w", page.File, err) } tmpls[page.File] = t } - return tmpls, nil + return base, tmpls, nil } func pageTemplate(fsys fs.FS, base *template.Template, page pages.Page) (*template.Template, error) { diff --git a/internal/assets/dist/components.js b/internal/assets/dist/components.js index eff4e8f..54bc93b 100644 --- a/internal/assets/dist/components.js +++ b/internal/assets/dist/components.js @@ -81,8 +81,7 @@ class ComboBox extends LitElement { } get _filtered() { - const q = this._inputValue.trim().toLowerCase(); - return this._options.filter((o) => !q || o.label.toLowerCase().includes(q)); + return this._options; } get _showCreate() { @@ -140,6 +139,7 @@ class ComboBox extends LitElement { .value=${this._inputValue} @input=${this._onInput} @focus=${this._onFocus} + @click=${this._onClick} @keydown=${this._onKeydown} @blur=${this._onBlur} > @@ -184,13 +184,17 @@ class ComboBox extends LitElement { _onInput(e) { this._inputValue = e.target.value; - this._isOpen = this._inputValue.trim().length > 0; + this._isOpen = this._options.length > 0 || this._inputValue.trim().length > 0; this._activeIndex = -1; } _onFocus() { - if (this._inputValue.trim()) { - this._isOpen = true; + this._isOpen = this._options.length > 0 || this._inputValue.trim().length > 0; + } + + _onClick() { + if (!this._isOpen) { + this._isOpen = this._options.length > 0 || this._inputValue.trim().length > 0; } } @@ -241,6 +245,11 @@ class ComboBox extends LitElement { this._currentNewName = ''; return; } + const exactMatch = this._options.find((o) => o.label.toLowerCase() === typed.toLowerCase()); + if (exactMatch) { + this._selectExisting(exactMatch.value, exactMatch.label); + return; + } const matched = this._options.find((o) => o.value === this._currentId); if (!matched || matched.label !== typed) { this._selectNew(typed); diff --git a/internal/assets/dist/htmx.min.js b/internal/assets/dist/htmx.min.js new file mode 100644 index 0000000..b90e82c --- /dev/null +++ b/internal/assets/dist/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true},parseInterval:null,location:location,_:null,version:"2.0.5"};Q.onLoad=j;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=zn;Q.removeExtension=$n;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:B,findThisElement:Se,filterValues:yn,swap:$e,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Tn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Re,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:jt};const de=["get","post","put","delete","patch"];const T=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function D(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function X(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function B(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function z(e,t){e=w(e);if(t){b().setTimeout(function(){z(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(D(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=D(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return D(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function $e(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=P(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Bt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"||e.type==="click"){t=ce(e.target)||t;if(t.tagName==="FORM"){return true}if(t.form&&t.type==="submit"){return true}if(t instanceof HTMLAnchorElement&&t.href&&(t.getAttribute("href")==="#"||t.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,l)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);return oe(n)}function It(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Pt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Dt(t){De(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!B()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);$e(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});_t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:zt(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){$e(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});_t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Pn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=X(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;jt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Pn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Rn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Tn(e,t){return le(Hn(e,t),Rn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Pn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Dn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Dn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||jn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let X=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{X=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const P=oe(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){p=P.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=X;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=ne(r,"hx-prompt");if(B){var y=prompt(B);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const j=U.formData;if(i.values){hn(j,Pn(i.values))}const V=Pn(Tn(r,o));const v=hn(j,V);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const _=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Pn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let H=n;if(E){H=$;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const D in x){if(x.hasOwnProperty(D)){const Y=x[D];qn(g,D,Y)}}}const R={xhr:g,target:c,requestConfig:C,etc:i,boosted:_,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);R.pathInfo.responsePath=An(g);M(r,R);if(R.keepIndicators!==true){rn(T,q)}ae(r,"htmx:afterRequest",R);ae(r,"htmx:afterOnLoad",R);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",R);ae(e,"htmx:afterOnLoad",R)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},R));throw e}finally{m()}};g.onerror=function(){rn(T,q);fe(r,"htmx:afterRequest",R);fe(r,"htmx:sendError",R);re(l);m()};g.onabort=function(){rn(T,q);fe(r,"htmx:afterRequest",R);fe(r,"htmx:sendAbort",R);re(l);m()};g.ontimeout=function(){rn(T,q);fe(r,"htmx:afterRequest",R);fe(r,"htmx:timeout",R);re(l);m()};if(!ae(r,"htmx:beforeRequest",R)){re(s);m();return e}var T=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",R);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=ne(e,"hx-push-url");const c=ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Xn(e){for(var t=0;t ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/internal/assets/dist/index.css b/internal/assets/dist/index.css index 925d3ea..972efbb 100644 --- a/internal/assets/dist/index.css +++ b/internal/assets/dist/index.css @@ -46,6 +46,7 @@ --font-weight-semibold: 600; --font-weight-bold: 700; --tracking-wider: 0.05em; + --radius-sm: 0.25rem; --radius-md: 0.375rem; --radius-lg: 0.5rem; --radius-2xl: 1rem; @@ -6549,6 +6550,9 @@ .h-6 { height: calc(var(--spacing) * 6); } + .h-10 { + height: calc(var(--spacing) * 10); + } .h-12 { height: calc(var(--spacing) * 12); } @@ -7227,6 +7231,9 @@ .rounded-selector { border-radius: var(--radius-selector); } + .rounded-sm { + border-radius: var(--radius-sm); + } .rounded-t-box { border-top-left-radius: var(--radius-box); border-top-right-radius: var(--radius-box); @@ -7399,6 +7406,10 @@ border-style: var(--tw-border-style); border-width: 1px; } + .border-0 { + border-style: var(--tw-border-style); + border-width: 0px; + } .border-2 { border-style: var(--tw-border-style); border-width: 2px; @@ -7733,6 +7744,9 @@ .bg-teal-400 { background-color: var(--color-teal-400); } + .bg-transparent { + background-color: transparent; + } .divider-accent { @layer daisyui.l1.l2 { &:before, &:after { @@ -9513,6 +9527,10 @@ --btn-fg: var(--color-warning-content); } } + .outline-none { + --tw-outline-style: none; + outline-style: none; + } .timeline-snap-icon { @layer daisyui.l1.l2 { > li { @@ -9872,6 +9890,28 @@ --tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); } } + .hover\:link { + &:hover { + @media (hover: hover) { + @layer daisyui.l1.l2.l3 { + cursor: pointer; + text-decoration-line: underline; + &:focus { + --tw-outline-style: none; + outline-style: none; + @media (forced-colors: active) { + outline: 2px solid transparent; + outline-offset: 2px; + } + } + &:focus-visible { + outline: 2px solid currentColor; + outline-offset: 2px; + } + } + } + } + } .hover\:bg-base-200 { &:hover { @media (hover: hover) { @@ -10206,6 +10246,16 @@ transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,); } } + .\[\&\:\:-webkit-inner-spin-button\]\:hidden { + &::-webkit-inner-spin-button { + display: none; + } + } + .\[\&\:\:-webkit-outer-spin-button\]\:hidden { + &::-webkit-outer-spin-button { + display: none; + } + } .\[\&\>svg\]\:h-4 { &>svg { height: calc(var(--spacing) * 4); diff --git a/internal/database/database.go b/internal/database/database.go index abd3b23..25e61d2 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -129,6 +129,23 @@ func NullInt64Ptr(v *int64) sql.NullInt64 { return sql.NullInt64{Int64: *v, Valid: true} } +// NullOf converts a pointer to any int64-backed type to sql.NullInt64. +func NullOf[T ~int64](v *T) sql.NullInt64 { + if v == nil { + return sql.NullInt64{} + } + return sql.NullInt64{Int64: int64(*v), Valid: true} +} + +// NullAs converts a sql.NullInt64 to a pointer of any int64-backed type. +func NullAs[T ~int64](n sql.NullInt64) *T { + if !n.Valid { + return nil + } + v := T(n.Int64) + return &v +} + // NullFloat64 converts a float64 to sql.NullFloat64, treating 0 as NULL. func NullFloat64(v float64) sql.NullFloat64 { return sql.NullFloat64{Float64: v, Valid: v != 0} diff --git a/internal/database/migrations/sqlite/20260521110354_equipment.sql b/internal/database/migrations/sqlite/20260521110354_equipment.sql index 44ecc90..ab254f5 100644 --- a/internal/database/migrations/sqlite/20260521110354_equipment.sql +++ b/internal/database/migrations/sqlite/20260521110354_equipment.sql @@ -20,7 +20,7 @@ CREATE TABLE equipment ( width_mm INTEGER, height_mm INTEGER, depth_mm INTEGER, - voltage_v INTEGER, + voltage_mv INTEGER, current_ma INTEGER, power_mw INTEGER, wire_gauge_mm2_x100 INTEGER, diff --git a/internal/database/queries/gen/equipment/equipment.sql.go b/internal/database/queries/gen/equipment/equipment.sql.go index e247ad9..91443c1 100644 --- a/internal/database/queries/gen/equipment/equipment.sql.go +++ b/internal/database/queries/gen/equipment/equipment.sql.go @@ -42,7 +42,7 @@ INSERT INTO equipment ( width_mm, height_mm, depth_mm, - voltage_v, + voltage_mv, current_ma, power_mw, wire_gauge_mm2_x100 @@ -89,7 +89,7 @@ INSERT INTO equipment ( width_mm, height_mm, depth_mm, - voltage_v, + voltage_mv, current_ma, power_mw, wire_gauge_mm2_x100, @@ -115,7 +115,7 @@ type CreateParams struct { WidthMm sql.NullInt64 HeightMm sql.NullInt64 DepthMm sql.NullInt64 - VoltageV sql.NullInt64 + VoltageMv sql.NullInt64 CurrentMa sql.NullInt64 PowerMw sql.NullInt64 WireGaugeMm2X100 sql.NullInt64 @@ -141,7 +141,7 @@ type CreateRow struct { WidthMm sql.NullInt64 HeightMm sql.NullInt64 DepthMm sql.NullInt64 - VoltageV sql.NullInt64 + VoltageMv sql.NullInt64 CurrentMa sql.NullInt64 PowerMw sql.NullInt64 WireGaugeMm2X100 sql.NullInt64 @@ -168,7 +168,7 @@ func (q *Queries) Create(ctx context.Context, arg CreateParams) (CreateRow, erro arg.WidthMm, arg.HeightMm, arg.DepthMm, - arg.VoltageV, + arg.VoltageMv, arg.CurrentMa, arg.PowerMw, arg.WireGaugeMm2X100, @@ -194,7 +194,7 @@ func (q *Queries) Create(ctx context.Context, arg CreateParams) (CreateRow, erro &i.WidthMm, &i.HeightMm, &i.DepthMm, - &i.VoltageV, + &i.VoltageMv, &i.CurrentMa, &i.PowerMw, &i.WireGaugeMm2X100, @@ -242,7 +242,7 @@ SELECT e.width_mm, e.height_mm, e.depth_mm, - e.voltage_v, + e.voltage_mv, e.current_ma, e.power_mw, e.wire_gauge_mm2_x100, @@ -279,7 +279,7 @@ type GetByIDRow struct { WidthMm sql.NullInt64 HeightMm sql.NullInt64 DepthMm sql.NullInt64 - VoltageV sql.NullInt64 + VoltageMv sql.NullInt64 CurrentMa sql.NullInt64 PowerMw sql.NullInt64 WireGaugeMm2X100 sql.NullInt64 @@ -314,7 +314,7 @@ func (q *Queries) GetByID(ctx context.Context, id string) (GetByIDRow, error) { &i.WidthMm, &i.HeightMm, &i.DepthMm, - &i.VoltageV, + &i.VoltageMv, &i.CurrentMa, &i.PowerMw, &i.WireGaugeMm2X100, @@ -345,10 +345,19 @@ SELECT WHEN tt.name = 'serialized' THEN (SELECT COUNT(*) FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id) ELSE 0 END AS total_stock, + e.has_content, e.is_archived, e.rental_price, e.resale_price, e.notes, + e.weight_g, + e.width_mm, + e.height_mm, + e.depth_mm, + e.voltage_mv, + e.current_ma, + e.power_mw, + e.wire_gauge_mm2_x100, e.updated_at, e.created_at, COUNT(*) OVER() AS total_records @@ -360,7 +369,7 @@ LEFT JOIN tracking_types tt ON tt.id = e.tracking_type_id WHERE e.org_id = ?1 AND (?2 = '' OR e.name LIKE '%' || ?2 || '%' OR EXISTS (SELECT 1 FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id AND (esi.code LIKE '%' || ?2 || '%' OR esi.serial_number LIKE '%' || ?2 || '%'))) AND (?3 = '' OR ec.name = ?3) - AND e.is_archived = ?4 + AND (?4 = -1 OR e.is_archived = ?4) ORDER BY e.name ASC LIMIT ?6 OFFSET ?5 ` @@ -369,7 +378,7 @@ type ListParams struct { OrgID string NameQuery interface{} Category interface{} - IsArchived int64 + IsArchived interface{} PageOffset int64 PageLimit int64 } @@ -390,10 +399,19 @@ type ListRow struct { TrackingTypeName string UsageTypeID int64 TotalStock int64 + HasContent int64 IsArchived int64 RentalPrice sql.NullInt64 ResalePrice sql.NullInt64 Notes sql.NullString + WeightG sql.NullInt64 + WidthMm sql.NullInt64 + HeightMm sql.NullInt64 + DepthMm sql.NullInt64 + VoltageMv sql.NullInt64 + CurrentMa sql.NullInt64 + PowerMw sql.NullInt64 + WireGaugeMm2X100 sql.NullInt64 UpdatedAt int64 CreatedAt int64 TotalRecords int64 @@ -431,127 +449,6 @@ func (q *Queries) List(ctx context.Context, arg ListParams) ([]ListRow, error) { &i.TrackingTypeName, &i.UsageTypeID, &i.TotalStock, - &i.IsArchived, - &i.RentalPrice, - &i.ResalePrice, - &i.Notes, - &i.UpdatedAt, - &i.CreatedAt, - &i.TotalRecords, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - -const listAllByOrgID = `-- name: ListAllByOrgID :many -SELECT - e.id, - e.org_id, - e.name, - e.category_id, - COALESCE(ec.name, '') AS category_name, - e.manufacturer_id, - e.location_id, - COALESCE(wl.name, '') AS location_name, - e.storage_object_id, - e.equipment_type_id, - COALESCE(et.name, '') AS equipment_type_name, - e.tracking_type_id, - e.usage_type_id, - CASE - WHEN tt.name = 'bulk' THEN COALESCE((SELECT SUM(ebi.quantity) FROM equipment_bulk_items ebi WHERE ebi.equipment_id = e.id), 0) - WHEN tt.name = 'serialized' THEN (SELECT COUNT(*) FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id) - ELSE 0 - END AS total_stock, - e.has_content, - e.is_archived, - e.rental_price, - e.resale_price, - e.notes, - e.weight_g, - e.width_mm, - e.height_mm, - e.depth_mm, - e.voltage_v, - e.current_ma, - e.power_mw, - e.wire_gauge_mm2_x100, - e.updated_at, - e.created_at -FROM equipment e -LEFT JOIN equipment_categories ec ON ec.id = e.category_id -LEFT JOIN warehouse_locations wl ON wl.id = e.location_id -LEFT JOIN equipment_types et ON et.id = e.equipment_type_id -LEFT JOIN tracking_types tt ON tt.id = e.tracking_type_id -WHERE e.org_id = ? -ORDER BY e.name ASC -` - -type ListAllByOrgIDRow struct { - ID string - OrgID string - Name string - CategoryID sql.NullString - CategoryName string - ManufacturerID sql.NullString - LocationID sql.NullString - LocationName string - StorageObjectID sql.NullString - EquipmentTypeID int64 - EquipmentTypeName string - TrackingTypeID sql.NullInt64 - UsageTypeID int64 - TotalStock int64 - HasContent int64 - IsArchived int64 - RentalPrice sql.NullInt64 - ResalePrice sql.NullInt64 - Notes sql.NullString - WeightG sql.NullInt64 - WidthMm sql.NullInt64 - HeightMm sql.NullInt64 - DepthMm sql.NullInt64 - VoltageV sql.NullInt64 - CurrentMa sql.NullInt64 - PowerMw sql.NullInt64 - WireGaugeMm2X100 sql.NullInt64 - UpdatedAt int64 - CreatedAt int64 -} - -func (q *Queries) ListAllByOrgID(ctx context.Context, orgID string) ([]ListAllByOrgIDRow, error) { - rows, err := q.db.QueryContext(ctx, listAllByOrgID, orgID) - if err != nil { - return nil, err - } - defer rows.Close() - var items []ListAllByOrgIDRow - for rows.Next() { - var i ListAllByOrgIDRow - if err := rows.Scan( - &i.ID, - &i.OrgID, - &i.Name, - &i.CategoryID, - &i.CategoryName, - &i.ManufacturerID, - &i.LocationID, - &i.LocationName, - &i.StorageObjectID, - &i.EquipmentTypeID, - &i.EquipmentTypeName, - &i.TrackingTypeID, - &i.UsageTypeID, - &i.TotalStock, &i.HasContent, &i.IsArchived, &i.RentalPrice, @@ -561,12 +458,13 @@ func (q *Queries) ListAllByOrgID(ctx context.Context, orgID string) ([]ListAllBy &i.WidthMm, &i.HeightMm, &i.DepthMm, - &i.VoltageV, + &i.VoltageMv, &i.CurrentMa, &i.PowerMw, &i.WireGaugeMm2X100, &i.UpdatedAt, &i.CreatedAt, + &i.TotalRecords, ); err != nil { return nil, err } @@ -787,7 +685,7 @@ SET width_mm = ?2, height_mm = ?3, depth_mm = ?4, - voltage_v = ?5, + voltage_mv = ?5, current_ma = ?6, power_mw = ?7, wire_gauge_mm2_x100 = ?8, @@ -800,7 +698,7 @@ type UpdatePropertiesParams struct { WidthMm sql.NullInt64 HeightMm sql.NullInt64 DepthMm sql.NullInt64 - VoltageV sql.NullInt64 + VoltageMv sql.NullInt64 CurrentMa sql.NullInt64 PowerMw sql.NullInt64 WireGaugeMm2X100 sql.NullInt64 @@ -813,7 +711,7 @@ func (q *Queries) UpdateProperties(ctx context.Context, arg UpdatePropertiesPara arg.WidthMm, arg.HeightMm, arg.DepthMm, - arg.VoltageV, + arg.VoltageMv, arg.CurrentMa, arg.PowerMw, arg.WireGaugeMm2X100, diff --git a/internal/database/queries/gen/equipment/querier.go b/internal/database/queries/gen/equipment/querier.go index d4b0400..950de1a 100644 --- a/internal/database/queries/gen/equipment/querier.go +++ b/internal/database/queries/gen/equipment/querier.go @@ -14,7 +14,6 @@ type Querier interface { Delete(ctx context.Context, id string) error GetByID(ctx context.Context, id string) (GetByIDRow, error) List(ctx context.Context, arg ListParams) ([]ListRow, error) - ListAllByOrgID(ctx context.Context, orgID string) ([]ListAllByOrgIDRow, error) ListBySerialNumber(ctx context.Context, arg ListBySerialNumberParams) ([]ListBySerialNumberRow, error) UpdateArchived(ctx context.Context, arg UpdateArchivedParams) error UpdateDetails(ctx context.Context, arg UpdateDetailsParams) error diff --git a/internal/database/queries/sqlite/equipment.sql b/internal/database/queries/sqlite/equipment.sql index 9b0d375..a33de02 100644 --- a/internal/database/queries/sqlite/equipment.sql +++ b/internal/database/queries/sqlite/equipment.sql @@ -19,10 +19,19 @@ SELECT WHEN tt.name = 'serialized' THEN (SELECT COUNT(*) FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id) ELSE 0 END AS total_stock, + e.has_content, e.is_archived, e.rental_price, e.resale_price, e.notes, + e.weight_g, + e.width_mm, + e.height_mm, + e.depth_mm, + e.voltage_mv, + e.current_ma, + e.power_mw, + e.wire_gauge_mm2_x100, e.updated_at, e.created_at, COUNT(*) OVER() AS total_records @@ -34,7 +43,7 @@ LEFT JOIN tracking_types tt ON tt.id = e.tracking_type_id WHERE e.org_id = sqlc.arg(org_id) AND (sqlc.arg(name_query) = '' OR e.name LIKE '%' || sqlc.arg(name_query) || '%' OR EXISTS (SELECT 1 FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id AND (esi.code LIKE '%' || sqlc.arg(name_query) || '%' OR esi.serial_number LIKE '%' || sqlc.arg(name_query) || '%'))) AND (sqlc.arg(category) = '' OR ec.name = sqlc.arg(category)) - AND e.is_archived = sqlc.arg(is_archived) + AND (sqlc.arg(is_archived) = -1 OR e.is_archived = sqlc.arg(is_archived)) ORDER BY e.name ASC LIMIT sqlc.arg(page_limit) OFFSET sqlc.arg(page_offset); @@ -102,7 +111,7 @@ INSERT INTO equipment ( width_mm, height_mm, depth_mm, - voltage_v, + voltage_mv, current_ma, power_mw, wire_gauge_mm2_x100 @@ -125,7 +134,7 @@ INSERT INTO equipment ( sqlc.arg(width_mm), sqlc.arg(height_mm), sqlc.arg(depth_mm), - sqlc.arg(voltage_v), + sqlc.arg(voltage_mv), sqlc.arg(current_ma), sqlc.arg(power_mw), sqlc.arg(wire_gauge_mm2_x100) @@ -149,7 +158,7 @@ INSERT INTO equipment ( width_mm, height_mm, depth_mm, - voltage_v, + voltage_mv, current_ma, power_mw, wire_gauge_mm2_x100, @@ -184,7 +193,7 @@ SELECT e.width_mm, e.height_mm, e.depth_mm, - e.voltage_v, + e.voltage_mv, e.current_ma, e.power_mw, e.wire_gauge_mm2_x100, @@ -222,7 +231,7 @@ SET width_mm = sqlc.arg(width_mm), height_mm = sqlc.arg(height_mm), depth_mm = sqlc.arg(depth_mm), - voltage_v = sqlc.arg(voltage_v), + voltage_mv = sqlc.arg(voltage_mv), current_ma = sqlc.arg(current_ma), power_mw = sqlc.arg(power_mw), wire_gauge_mm2_x100 = sqlc.arg(wire_gauge_mm2_x100), @@ -238,49 +247,6 @@ WHERE id = sqlc.arg(id); DELETE FROM equipment WHERE id = ?; --- name: ListAllByOrgID :many -SELECT - e.id, - e.org_id, - e.name, - e.category_id, - COALESCE(ec.name, '') AS category_name, - e.manufacturer_id, - e.location_id, - COALESCE(wl.name, '') AS location_name, - e.storage_object_id, - e.equipment_type_id, - COALESCE(et.name, '') AS equipment_type_name, - e.tracking_type_id, - e.usage_type_id, - CASE - WHEN tt.name = 'bulk' THEN COALESCE((SELECT SUM(ebi.quantity) FROM equipment_bulk_items ebi WHERE ebi.equipment_id = e.id), 0) - WHEN tt.name = 'serialized' THEN (SELECT COUNT(*) FROM equipment_serialized_items esi WHERE esi.equipment_id = e.id) - ELSE 0 - END AS total_stock, - e.has_content, - e.is_archived, - e.rental_price, - e.resale_price, - e.notes, - e.weight_g, - e.width_mm, - e.height_mm, - e.depth_mm, - e.voltage_v, - e.current_ma, - e.power_mw, - e.wire_gauge_mm2_x100, - e.updated_at, - e.created_at -FROM equipment e -LEFT JOIN equipment_categories ec ON ec.id = e.category_id -LEFT JOIN warehouse_locations wl ON wl.id = e.location_id -LEFT JOIN equipment_types et ON et.id = e.equipment_type_id -LEFT JOIN tracking_types tt ON tt.id = e.tracking_type_id -WHERE e.org_id = ? -ORDER BY e.name ASC; - -- name: UpdateArchived :exec UPDATE equipment SET diff --git a/internal/equipment/form.go b/internal/equipment/form.go index e8f1bca..2f0a186 100644 --- a/internal/equipment/form.go +++ b/internal/equipment/form.go @@ -2,12 +2,9 @@ package equipment import ( "fmt" - "math" "mime/multipart" "net/http" - "strconv" "strings" - "time" "github.com/bit8bytes/toolbox/validator" ) @@ -16,57 +13,57 @@ const maxUploadBytes = 10 << 20 // 10 MiB // DetailsForm holds parsed input and validation state for the details tab. type DetailsForm struct { - TypeID string // hidden field: "bulk" or "serialized" - Name string - CategoryID string - ManufacturerID string - LocationID string - TotalStock string // only used for bulk items - Notes string - Image multipart.File - ImageHeader *multipart.FileHeader + TypeID string // hidden field: "bulk" or "serialized" + Name string + CategoryID string + CategoryName string // set when user typed a new category name not yet in the DB + ManufacturerID string + ManufacturerName string // set when user typed a new manufacturer name not yet in the DB + LocationID string + LocationName string // set when user typed a new location name not yet in the DB + TotalStock int64 // only used for bulk items; 0 means blank/unprovided + Notes string + Image multipart.File + ImageHeader *multipart.FileHeader validator.Validator } // PricingForm holds parsed input and validation state for the pricing tab. type PricingForm struct { - PurchasePrice string - RentalPrice string + PurchasePrice *Cents + RentalPrice *Cents validator.Validator } // PropertiesForm holds parsed input and validation state for the properties tab. type PropertiesForm struct { - WeightG string - WidthMM string - HeightMM string - DepthMM string - VoltageV string // user enters volts; stored as volts (integer) - PowerW string // user enters watts; stored as milliwatts - CurrentA string // user enters amps; stored as milliamps - WireGaugeMM2X100 string // user enters mm²×100 e.g. 150 = 1.5 mm² + Weight *Grams // user enters kg; stored as grams + Width *Millimeters // user enters cm; stored as mm + Height *Millimeters // user enters cm; stored as mm + Depth *Millimeters // user enters cm; stored as mm + Power *Milliwatts // user enters W; stored as mW + Current *Milliamps // user enters A; stored as mA + Voltage *Millivolts // user enters and stored as whole volts + WireGauge *WireGauge // user enters mm²×100 integer; stored as-is validator.Validator } -// normalizeDecimal replaces comma with dot so both European and US number -// formats are accepted before parsing (e.g. "19,99" → "19.99"). -func normalizeDecimal(s string) string { - return strings.ReplaceAll(s, ",", ".") -} - // ParseDetails reads the details-tab form fields from r, including an optional image upload. func ParseDetails(r *http.Request) (DetailsForm, error) { if err := r.ParseMultipartForm(maxUploadBytes); err != nil { //nolint:gosec // maxUploadBytes is a bounded constant (10 MiB) return DetailsForm{}, fmt.Errorf("parse form: %w", err) } f := DetailsForm{ - TypeID: strings.TrimSpace(r.PostForm.Get("type_id")), - Name: strings.TrimSpace(r.PostForm.Get("name")), - CategoryID: strings.TrimSpace(r.PostForm.Get("category_id")), - ManufacturerID: strings.TrimSpace(r.PostForm.Get("manufacturer_id")), - LocationID: strings.TrimSpace(r.PostForm.Get("location_id")), - TotalStock: strings.TrimSpace(r.PostForm.Get("total_stock")), - Notes: strings.TrimSpace(r.PostForm.Get("notes")), + TypeID: strings.TrimSpace(r.PostForm.Get("type_id")), + Name: strings.TrimSpace(r.PostForm.Get("name")), + CategoryID: strings.TrimSpace(r.PostForm.Get("category_id")), + CategoryName: strings.TrimSpace(r.PostForm.Get("category_name")), + ManufacturerID: strings.TrimSpace(r.PostForm.Get("manufacturer_id")), + ManufacturerName: strings.TrimSpace(r.PostForm.Get("manufacturer_name")), + LocationID: strings.TrimSpace(r.PostForm.Get("location_id")), + LocationName: strings.TrimSpace(r.PostForm.Get("location_name")), + TotalStock: ParseQuantity(r.PostForm.Get("total_stock")), + Notes: strings.TrimSpace(r.PostForm.Get("notes")), } file, header, err := r.FormFile("image") if err == nil { @@ -82,8 +79,8 @@ func ParsePricing(r *http.Request) (PricingForm, error) { return PricingForm{}, fmt.Errorf("parse form: %w", err) } return PricingForm{ - PurchasePrice: strings.TrimSpace(r.PostForm.Get("purchase_price")), - RentalPrice: strings.TrimSpace(r.PostForm.Get("rental_price")), + PurchasePrice: ParseCents(r.PostForm.Get("purchase_price")), + RentalPrice: ParseCents(r.PostForm.Get("rental_price")), }, nil } @@ -93,14 +90,14 @@ func ParseProperties(r *http.Request) (PropertiesForm, error) { return PropertiesForm{}, fmt.Errorf("parse form: %w", err) } return PropertiesForm{ - WeightG: strings.TrimSpace(r.PostForm.Get("weight_g")), - WidthMM: strings.TrimSpace(r.PostForm.Get("width_mm")), - HeightMM: strings.TrimSpace(r.PostForm.Get("height_mm")), - DepthMM: strings.TrimSpace(r.PostForm.Get("depth_mm")), - VoltageV: strings.TrimSpace(r.PostForm.Get("voltage_v")), - PowerW: strings.TrimSpace(r.PostForm.Get("power_w")), - CurrentA: strings.TrimSpace(r.PostForm.Get("current_a")), - WireGaugeMM2X100: strings.TrimSpace(r.PostForm.Get("wire_gauge_mm2_x100")), + Weight: ParseGrams(r.PostForm.Get("weight_kg")), + Width: ParseMillimeters(r.PostForm.Get("width_cm")), + Height: ParseMillimeters(r.PostForm.Get("height_cm")), + Depth: ParseMillimeters(r.PostForm.Get("depth_cm")), + Power: ParseMilliwatts(r.PostForm.Get("power_w")), + Current: ParseMilliamps(r.PostForm.Get("current_a")), + Voltage: ParseVolts(r.PostForm.Get("voltage_v")), + WireGauge: ParseWireGauge(r.PostForm.Get("wire_gauge_mm2_x100")), }, nil } @@ -110,106 +107,60 @@ func (f *DetailsForm) Validate() bool { f.Check(validator.MaxChars(f.Name, 200), "name", "This field cannot exceed 200 characters") if f.TypeID == "bulk" { - if validator.NotBlank(f.TotalStock) { - n, err := strconv.ParseInt(f.TotalStock, 10, 64) - f.Check(err == nil, "total_stock", "Must be a whole number") - f.Check(err != nil || n >= 1, "total_stock", "Must be at least 1") - } else { - f.AddError("total_stock", "This field cannot be blank") - } + f.Check(f.TotalStock >= 1, "total_stock", "Must be at least 1") } return f.Valid() } // Validate checks PricingForm fields and returns true when all pass. -func (f *PricingForm) Validate() bool { - if validator.NotBlank(f.PurchasePrice) { - _, err := strconv.ParseFloat(normalizeDecimal(f.PurchasePrice), 64) - f.Check(err == nil, "purchase_price", "Must be a valid number") - } - - if validator.NotBlank(f.RentalPrice) { - _, err := strconv.ParseFloat(normalizeDecimal(f.RentalPrice), 64) - f.Check(err == nil, "rental_price", "Must be a valid number") - } - - return f.Valid() -} +func (f *PricingForm) Validate() bool { return f.Valid() } // Validate checks PropertiesForm fields and returns true when all pass. -// All fields are optional; this method exists for a consistent call pattern. func (f *PropertiesForm) Validate() bool { return f.Valid() } -// InspectionForm holds parsed input and validation state for the inspection tab. -type InspectionForm struct { - IntervalDays string - validator.Validator -} - -// ParseInspection reads the inspection-tab form fields from r. -func ParseInspection(r *http.Request) (InspectionForm, error) { - if err := r.ParseForm(); err != nil { - return InspectionForm{}, fmt.Errorf("parse form: %w", err) +// ToProperties converts the form's parsed values into a Properties sub-struct. +func (f *PropertiesForm) ToProperties() Properties { + return Properties{ + Weight: f.Weight, + Width: f.Width, + Height: f.Height, + Depth: f.Depth, + Power: f.Power, + Current: f.Current, + Voltage: f.Voltage, + WireGauge: f.WireGauge, } - return InspectionForm{ - IntervalDays: strings.TrimSpace(r.PostForm.Get("inspection_interval_days")), - }, nil } -// Validate checks InspectionForm fields and returns true when all pass. -func (f *InspectionForm) Validate() bool { - if validator.NotBlank(f.IntervalDays) { - n, err := strconv.ParseInt(f.IntervalDays, 10, 64) - f.Check(err == nil, "inspection_interval_days", "Must be a whole number") - f.Check(err != nil || n >= 1, "inspection_interval_days", "Must be at least 1") +// ToPricing converts the form's parsed values into a Pricing sub-struct. +func (f *PricingForm) ToPricing() Pricing { + return Pricing{ + PurchasePrice: f.PurchasePrice, + RentalPrice: f.RentalPrice, } - return f.Valid() -} - -// IntervalDaysInt64 returns the parsed interval as *int64 (nil when blank). -func (f *InspectionForm) IntervalDaysInt64() *int64 { return parseOptionalInt64(f.IntervalDays) } - -// TotalStockInt64 returns the parsed TotalStock value. Call only after Validate() returns true. -func (f *DetailsForm) TotalStockInt64() int64 { - n, _ := strconv.ParseInt(f.TotalStock, 10, 64) - return n -} - -// PurchasePriceCents returns the purchase price in the smallest currency unit, or nil when blank. -func (f *PricingForm) PurchasePriceCents() *int64 { - return parseOptionalCents(f.PurchasePrice) } -// RentalPriceCents returns the rental price in the smallest currency unit, or nil when blank. -func (f *PricingForm) RentalPriceCents() *int64 { - return parseOptionalCents(f.RentalPrice) +// PricingFormFromEquipment pre-populates a PricingForm from an existing Equipment's stored values. +func PricingFormFromEquipment(e *Equipment) PricingForm { + return PricingForm{ + PurchasePrice: e.Pricing.PurchasePrice, + RentalPrice: e.Pricing.RentalPrice, + } } -// WeightGInt64 returns weight_g as *int64 (nil when blank). -func (f *PropertiesForm) WeightGInt64() *int64 { return parseOptionalInt64(f.WeightG) } - -// WidthMMInt64 returns width_mm as *int64 (nil when blank). -func (f *PropertiesForm) WidthMMInt64() *int64 { return parseOptionalInt64(f.WidthMM) } - -// HeightMMInt64 returns height_mm as *int64 (nil when blank). -func (f *PropertiesForm) HeightMMInt64() *int64 { return parseOptionalInt64(f.HeightMM) } - -// DepthMMInt64 returns depth_mm as *int64 (nil when blank). -func (f *PropertiesForm) DepthMMInt64() *int64 { return parseOptionalInt64(f.DepthMM) } - -// VoltageVInt64 returns voltage_v as *int64 (nil when blank). -func (f *PropertiesForm) VoltageVInt64() *int64 { return parseOptionalInt64(f.VoltageV) } - -// PowerMW converts the user-entered watts string to milliwatts, or nil when blank. -func (f *PropertiesForm) PowerMW() *int64 { return parseOptionalWattsToMW(f.PowerW) } - -// CurrentMA converts the user-entered amps string to milliamps, or nil when blank. -func (f *PropertiesForm) CurrentMA() *int64 { return parseOptionalAmpsToMA(f.CurrentA) } - -// WireGaugeMM2X100Int64 returns wire_gauge_mm2_x100 as *int64 (nil when blank). -func (f *PropertiesForm) WireGaugeMM2X100Int64() *int64 { - return parseOptionalInt64(f.WireGaugeMM2X100) +// PropertiesFormFromEquipment pre-populates a PropertiesForm from an existing Equipment's stored values. +func PropertiesFormFromEquipment(e *Equipment) PropertiesForm { + return PropertiesForm{ + Weight: e.Properties.Weight, + Width: e.Properties.Width, + Height: e.Properties.Height, + Depth: e.Properties.Depth, + Power: e.Properties.Power, + Current: e.Properties.Current, + Voltage: e.Properties.Voltage, + WireGauge: e.Properties.WireGauge, + } } // UnitForm holds parsed input and validation state for adding or updating a serialized unit. @@ -217,11 +168,11 @@ type UnitForm struct { Code string ManufacturerSerialNumber string Notes string - Quantity string - PurchasePrice string // decimal e.g. "19.99" - PurchasedAt string // YYYY-MM-DD - NextInspectionAt string // YYYY-MM-DD - StatusID string + Quantity int64 + PurchasePrice *Cents + PurchasedAt *int64 // Unix timestamp + NextInspectionAt *int64 // Unix timestamp + StatusID int64 validator.Validator } @@ -230,77 +181,25 @@ func ParseUnit(r *http.Request) (UnitForm, error) { if err := r.ParseForm(); err != nil { return UnitForm{}, fmt.Errorf("parse form: %w", err) } + qty := ParseQuantity(r.PostForm.Get("quantity")) + if qty <= 0 { + qty = 1 + } return UnitForm{ Code: strings.TrimSpace(r.PostForm.Get("code")), ManufacturerSerialNumber: strings.TrimSpace(r.PostForm.Get("serial_number")), Notes: strings.TrimSpace(r.PostForm.Get("notes")), - Quantity: strings.TrimSpace(r.PostForm.Get("quantity")), - PurchasePrice: strings.TrimSpace(r.PostForm.Get("purchase_price")), - PurchasedAt: strings.TrimSpace(r.PostForm.Get("purchased_at")), - NextInspectionAt: strings.TrimSpace(r.PostForm.Get("next_inspection_at")), - StatusID: strings.TrimSpace(r.PostForm.Get("status_id")), + Quantity: qty, + PurchasePrice: ParseCents(r.PostForm.Get("purchase_price")), + PurchasedAt: parseUnixDate(r.PostForm.Get("purchased_at")), + NextInspectionAt: parseUnixDate(r.PostForm.Get("next_inspection_at")), + StatusID: parseCheckbox(r.PostForm.Get("status_id")), }, nil } // Validate checks UnitForm fields. All fields are optional. func (f *UnitForm) Validate() bool { return f.Valid() } -// StatusIDInt64 returns the parsed StatusID as int64. Returns 0 when blank. -func (f *UnitForm) StatusIDInt64() int64 { - n, _ := strconv.ParseInt(f.StatusID, 10, 64) - return n -} - -// QuantityInt64 returns the parsed Quantity as int64. Returns 1 when blank or invalid. -func (f *UnitForm) QuantityInt64() int64 { - n, _ := strconv.ParseInt(f.Quantity, 10, 64) - if n <= 0 { - return 1 - } - return n -} - -// PurchasePriceCents parses a decimal price string (e.g. "19.99") into integer cents. -// Returns nil when blank or unparseable. -func (f *UnitForm) PurchasePriceCents() *int64 { - s := strings.ReplaceAll(f.PurchasePrice, ",", ".") - if s == "" { - return nil - } - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil - } - cents := int64(math.Round(v * 100)) - return ¢s -} - -// PurchasedAtUnix parses the YYYY-MM-DD date and returns a *int64 Unix timestamp, or nil when blank. -func (f *UnitForm) PurchasedAtUnix() *int64 { - if f.PurchasedAt == "" { - return nil - } - t, err := time.Parse("2006-01-02", f.PurchasedAt) - if err != nil { - return nil - } - v := t.UTC().Unix() - return &v -} - -// NextInspectionAtUnix parses the YYYY-MM-DD date and returns a *int64 Unix timestamp, or nil when blank. -func (f *UnitForm) NextInspectionAtUnix() *int64 { - if f.NextInspectionAt == "" { - return nil - } - t, err := time.Parse("2006-01-02", f.NextInspectionAt) - if err != nil { - return nil - } - v := t.UTC().Unix() - return &v -} - // NewForm holds the parsed form input and validation state for inventory creation (both types). type NewForm struct { TypeID string // "bulk" or "serialized" @@ -312,17 +211,17 @@ type NewForm struct { ManufacturerName string // set when user typed a new manufacturer name not yet in the DB LocationID string LocationName string // set when user typed a new location name not yet in the DB - Count string // total_stock for bulk; number of units to generate for serialized + Count int64 // total_stock for bulk; number of units to generate for serialized HasContent string // "1" when checked, "" when unchecked - PurchasePrice string - RentalPrice string + PurchasePrice *Cents + RentalPrice *Cents Notes string - WeightG string - WidthMM string - HeightMM string - DepthMM string - PowerW string - CurrentA string + Weight *Grams + Width *Millimeters + Height *Millimeters + Depth *Millimeters + Power *Milliwatts + Current *Milliamps Image multipart.File ImageHeader *multipart.FileHeader validator.Validator @@ -343,17 +242,17 @@ func ParseNew(r *http.Request) (NewForm, error) { ManufacturerName: strings.TrimSpace(r.PostForm.Get("manufacturer_name")), LocationID: strings.TrimSpace(r.PostForm.Get("location_id")), LocationName: strings.TrimSpace(r.PostForm.Get("location_name")), - Count: strings.TrimSpace(r.PostForm.Get("count")), + Count: ParseQuantity(r.PostForm.Get("count")), HasContent: r.PostForm.Get("has_content"), - PurchasePrice: strings.TrimSpace(r.PostForm.Get("purchase_price")), - RentalPrice: strings.TrimSpace(r.PostForm.Get("rental_price")), + PurchasePrice: ParseCents(r.PostForm.Get("purchase_price")), + RentalPrice: ParseCents(r.PostForm.Get("rental_price")), Notes: strings.TrimSpace(r.PostForm.Get("notes")), - WeightG: strings.TrimSpace(r.PostForm.Get("weight_g")), - WidthMM: strings.TrimSpace(r.PostForm.Get("width_mm")), - HeightMM: strings.TrimSpace(r.PostForm.Get("height_mm")), - DepthMM: strings.TrimSpace(r.PostForm.Get("depth_mm")), - PowerW: strings.TrimSpace(r.PostForm.Get("power_w")), - CurrentA: strings.TrimSpace(r.PostForm.Get("current_a")), + Weight: ParseGrams(r.PostForm.Get("weight_g")), + Width: ParseMillimeters(r.PostForm.Get("width_mm")), + Height: ParseMillimeters(r.PostForm.Get("height_mm")), + Depth: ParseMillimeters(r.PostForm.Get("depth_mm")), + Power: ParseMilliwatts(r.PostForm.Get("power_w")), + Current: ParseMilliamps(r.PostForm.Get("current_a")), } file, header, err := r.FormFile("image") if err == nil { @@ -369,108 +268,38 @@ func (f *NewForm) Validate() bool { f.Check(f.UsageTypeID == "rental" || f.UsageTypeID == "sale", "usage_type_id", "Must be rental or sale") f.Check(validator.NotBlank(f.Name), "name", "This field cannot be blank") f.Check(validator.MaxChars(f.Name, 200), "name", "This field cannot exceed 200 characters") - if validator.NotBlank(f.Count) { - n, err := strconv.ParseInt(f.Count, 10, 64) - f.Check(err == nil, "count", "Must be a whole number") - f.Check(err != nil || n >= 1, "count", "Must be at least 1") - } else { - f.AddError("count", "This field cannot be blank") - } - - if validator.NotBlank(f.PurchasePrice) { - _, err := strconv.ParseFloat(normalizeDecimal(f.PurchasePrice), 64) - f.Check(err == nil, "purchase_price", "Must be a valid number") - } - - if validator.NotBlank(f.RentalPrice) { - _, err := strconv.ParseFloat(normalizeDecimal(f.RentalPrice), 64) - f.Check(err == nil, "rental_price", "Must be a valid number") - } - + f.Check(f.Count >= 1, "count", "Must be at least 1") return f.Valid() } // HasContentBool returns true when the has_content checkbox was checked. func (f *NewForm) HasContentBool() bool { return f.HasContent == "1" } -// WeightGInt64 returns weight_g as *int64 (nil when blank). -func (f *NewForm) WeightGInt64() *int64 { return parseOptionalInt64(f.WeightG) } - -// WidthMMInt64 returns width_mm as *int64 (nil when blank). -func (f *NewForm) WidthMMInt64() *int64 { return parseOptionalInt64(f.WidthMM) } - -// HeightMMInt64 returns height_mm as *int64 (nil when blank). -func (f *NewForm) HeightMMInt64() *int64 { return parseOptionalInt64(f.HeightMM) } - -// DepthMMInt64 returns depth_mm as *int64 (nil when blank). -func (f *NewForm) DepthMMInt64() *int64 { return parseOptionalInt64(f.DepthMM) } - -// PowerMW converts the user-entered watts string to milliwatts, or nil when blank. -func (f *NewForm) PowerMW() *int64 { return parseOptionalWattsToMW(f.PowerW) } - -// CurrentMA converts the user-entered amps string to milliamps, or nil when blank. -func (f *NewForm) CurrentMA() *int64 { return parseOptionalAmpsToMA(f.CurrentA) } - -// CountInt64 returns the parsed Count value. Call only after Validate() returns true. -func (f *NewForm) CountInt64() int64 { - n, _ := strconv.ParseInt(f.Count, 10, 64) - return n -} - -// PurchasePriceCents returns the purchase price in the smallest currency unit, or nil when blank. -func (f *NewForm) PurchasePriceCents() *int64 { - return parseOptionalCents(f.PurchasePrice) -} - -// RentalPriceCents returns the rental price in the smallest currency unit, or nil when blank. -func (f *NewForm) RentalPriceCents() *int64 { - return parseOptionalCents(f.RentalPrice) -} - -// parseOptionalCents parses a decimal price string (accepting both "." and "," as -// the decimal separator) and returns the value in the smallest currency unit (cents). -// Returns nil when s is blank or unparseable. -func parseOptionalCents(s string) *int64 { - if s == "" { - return nil - } - f, err := strconv.ParseFloat(normalizeDecimal(s), 64) - if err != nil { - return nil +// ToProperties converts the form's parsed values into a Properties sub-struct. +// Note: NewForm only captures a subset of properties (no Voltage or WireGauge). +func (f *NewForm) ToProperties() Properties { + return Properties{ + Weight: f.Weight, + Width: f.Width, + Height: f.Height, + Depth: f.Depth, + Power: f.Power, + Current: f.Current, } - v := int64(math.Round(f * 100)) - return &v } -// parseOptionalInt64 parses a whole-number string. Returns nil when s is blank or unparseable. -func parseOptionalInt64(s string) *int64 { - if s == "" { - return nil +// ToPricing converts the form's parsed values into a Pricing sub-struct. +func (f *NewForm) ToPricing() Pricing { + return Pricing{ + PurchasePrice: f.PurchasePrice, + RentalPrice: f.RentalPrice, } - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return nil - } - return &n -} - -// parseOptionalWattsToMW parses a decimal watts string and returns milliwatts. Returns nil when blank. -func parseOptionalWattsToMW(s string) *int64 { - if s == "" { - return nil - } - f, err := strconv.ParseFloat(normalizeDecimal(s), 64) - if err != nil { - return nil - } - v := int64(math.Round(f * 1000)) - return &v } // ContentForm holds parsed input and validation state for assigning content to an equipment item. type ContentForm struct { MemberName string - Quantity string + Quantity int64 validator.Validator } @@ -481,38 +310,13 @@ func ParseContent(r *http.Request) (ContentForm, error) { } return ContentForm{ MemberName: strings.TrimSpace(r.PostForm.Get("member_name")), - Quantity: strings.TrimSpace(r.PostForm.Get("quantity")), + Quantity: ParseQuantity(r.PostForm.Get("quantity")), }, nil } // Validate checks ContentForm fields and returns true when all checks pass. func (f *ContentForm) Validate() bool { f.Check(validator.NotBlank(f.MemberName), "member_name", "An item must be selected") - if validator.NotBlank(f.Quantity) { - n, err := strconv.ParseInt(f.Quantity, 10, 64) - f.Check(err == nil, "quantity", "Must be a whole number") - f.Check(err != nil || n >= 1, "quantity", "Must be at least 1") - } else { - f.AddError("quantity", "This field cannot be blank") - } + f.Check(f.Quantity >= 1, "quantity", "Must be at least 1") return f.Valid() } - -// QuantityInt64 returns the parsed Quantity. Call only after Validate() returns true. -func (f *ContentForm) QuantityInt64() int64 { - n, _ := strconv.ParseInt(f.Quantity, 10, 64) - return n -} - -// parseOptionalAmpsToMA parses a decimal amps string and returns milliamps. Returns nil when blank. -func parseOptionalAmpsToMA(s string) *int64 { - if s == "" { - return nil - } - f, err := strconv.ParseFloat(normalizeDecimal(s), 64) - if err != nil { - return nil - } - v := int64(math.Round(f * 1000)) - return &v -} diff --git a/internal/equipment/helpers.go b/internal/equipment/helpers.go new file mode 100644 index 0000000..61da073 --- /dev/null +++ b/internal/equipment/helpers.go @@ -0,0 +1,141 @@ +package equipment + +import ( + "math" + "strconv" + "strings" + "time" +) + +// parseCheckbox returns 1 if s is non-empty (checkbox was checked), 0 otherwise. +func parseCheckbox(s string) int64 { + if strings.TrimSpace(s) != "" { + return 1 + } + return 0 +} + +// ParseQuantity parses a whole-number string. Returns 0 when blank or unparseable. +func ParseQuantity(s string) int64 { + s = strings.TrimSpace(s) + if s == "" { + return 1 + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil || n < 1 { + return 1 + } + return n +} + +// ParseCents parses a decimal price string and returns the value in cents. Returns nil when blank. +func ParseCents(s string) *Cents { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Cents(math.Round(f * 100)) + return &v +} + +// ParseGrams parses a kg decimal string and returns the value in grams. Returns nil when blank. +func ParseGrams(s string) *Grams { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Grams(math.Round(f * 1000)) + return &v +} + +// ParseMillimeters parses a cm decimal string and returns the value in mm. Returns nil when blank. +func ParseMillimeters(s string) *Millimeters { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Millimeters(math.Round(f * 10)) + return &v +} + +// ParseMilliwatts parses a W decimal string and returns the value in mW. Returns nil when blank. +func ParseMilliwatts(s string) *Milliwatts { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Milliwatts(math.Round(f * 1000)) + return &v +} + +// ParseMilliamps parses an A decimal string and returns the value in mA. Returns nil when blank. +func ParseMilliamps(s string) *Milliamps { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Milliamps(math.Round(f * 1000)) + return &v +} + +// ParseVolts parses a decimal volt string and returns the value in millivolts. Returns nil when blank. +func ParseVolts(s string) *Millivolts { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + v := Millivolts(math.Round(f * 1000)) + return &v +} + +// ParseWireGauge parses a whole-number mm²×100 string. Returns nil when blank. +func ParseWireGauge(s string) *WireGauge { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return nil + } + v := WireGauge(n) + return &v +} + +// parseUnixDate parses a YYYY-MM-DD date string and returns a Unix timestamp pointer. Returns nil when blank. +func parseUnixDate(s string) *int64 { + s = strings.TrimSpace(s) + if s == "" { + return nil + } + t, err := time.Parse("2006-01-02", s) + if err != nil { + return nil + } + v := t.UTC().Unix() + return &v +} diff --git a/internal/equipment/imports/model.go b/internal/equipment/imports/model.go index 2b5201a..670e008 100644 --- a/internal/equipment/imports/model.go +++ b/internal/equipment/imports/model.go @@ -68,8 +68,8 @@ type RawRow struct { HeightMm string DepthMm string VoltageV string - CurrentMa string - PowerMw string + CurrentA string + PowerW string WireGaugeMM2X100 string Quantity string } @@ -78,7 +78,7 @@ type RawRow struct { var ExpectedHeaders = []string{ "Name", "Type", "Usage", "Category", "Manufacturer", "Location", "Rental Price", "Resale Price", "Notes", - "Weight (g)", "Width (mm)", "Height (mm)", "Depth (mm)", "Voltage (V)", "Current (mA)", "Power (mW)", + "Weight (kg)", "Width (cm)", "Height (cm)", "Depth (cm)", "Voltage (V)", "Current (A)", "Power (W)", "Wire Gauge (mm² ×100)", "Quantity", } diff --git a/internal/equipment/imports/service.go b/internal/equipment/imports/service.go index 6a5beb7..4fe51a7 100644 --- a/internal/equipment/imports/service.go +++ b/internal/equipment/imports/service.go @@ -4,8 +4,6 @@ import ( "context" "database/sql" "fmt" - "math" - "strconv" "strings" "github.com/bit8bytes/gearberg/internal/equipment" @@ -87,8 +85,8 @@ func (s *Service) Stage(ctx context.Context, orgID string, rawRows []RawRow) (st HeightMm: raw.HeightMm, DepthMm: raw.DepthMm, VoltageV: raw.VoltageV, - CurrentMa: raw.CurrentMa, - PowerMw: raw.PowerMw, + CurrentMa: raw.CurrentA, + PowerMw: raw.PowerW, WireGaugeMM2X100: raw.WireGaugeMM2X100, Quantity: raw.Quantity, } @@ -257,37 +255,41 @@ func (s *Service) createRow(ctx context.Context, tx *sql.Tx, row Row, catID, mfr itemID := ksuid.New().String() base := equipment.Base{ - ID: itemID, - OrgID: row.OrgID, - UsageTypeID: usageType.ID(), - Name: row.Name, - CategoryID: catID, - ManufacturerID: mfrID, - LocationID: locID, - PurchasePrice: parseCents(row.ResalePrice), - RentalPrice: parseCents(row.RentalPrice), - Notes: row.Notes, - WeightG: parseOptionalInt64(row.WeightG), - WidthMM: parseOptionalInt64(row.WidthMm), - HeightMM: parseOptionalInt64(row.HeightMm), - DepthMM: parseOptionalInt64(row.DepthMm), - PowerMW: parseOptionalInt64(row.PowerMw), - CurrentMA: parseOptionalInt64(row.CurrentMa), - VoltageV: parseOptionalInt64(row.VoltageV), - WireGaugeMM2X100: parseOptionalInt64(row.WireGaugeMM2X100), + ID: itemID, + OrgID: row.OrgID, + UsageTypeID: usageType.ID(), + Name: row.Name, + CategoryID: catID, + ManufacturerID: mfrID, + LocationID: locID, + Notes: row.Notes, + Pricing: equipment.Pricing{ + PurchasePrice: equipment.ParseCents(row.ResalePrice), + RentalPrice: equipment.ParseCents(row.RentalPrice), + }, + Properties: equipment.Properties{ + Weight: equipment.ParseGrams(row.WeightG), + Width: equipment.ParseMillimeters(row.WidthMm), + Height: equipment.ParseMillimeters(row.HeightMm), + Depth: equipment.ParseMillimeters(row.DepthMm), + Power: equipment.ParseMilliwatts(row.PowerMw), + Current: equipment.ParseMilliamps(row.CurrentMa), + Voltage: equipment.ParseVolts(row.VoltageV), + WireGauge: equipment.ParseWireGauge(row.WireGaugeMM2X100), + }, } if !strings.EqualFold(row.TypeLabel, "serialized") { if _, err := s.inventory.CreateBulkTx(ctx, tx, equipment.CreateBulkEquipment{ Base: base, - TotalStock: parseQuantity(row.Quantity), + TotalStock: equipment.ParseQuantity(row.Quantity), }); err != nil { return fmt.Errorf("createRow: bulk: %w", err) } return nil } - qty := parseQuantity(row.Quantity) + qty := equipment.ParseQuantity(row.Quantity) units := make([]equipment.CreateUnit, qty) for i := range units { units[i] = equipment.CreateUnit{ @@ -322,41 +324,3 @@ func validateRow(raw RawRow) string { } return "" } - -func parseQuantity(s string) int64 { - s = strings.TrimSpace(s) - if s == "" { - return 1 - } - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || n < 1 { - return 1 - } - return n -} - -func parseOptionalInt64(s string) *int64 { - s = strings.TrimSpace(s) - if s == "" { - return nil - } - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return nil - } - return &n -} - -func parseCents(s string) *int64 { - s = strings.TrimSpace(s) - if s == "" { - return nil - } - s = strings.ReplaceAll(s, ",", ".") - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil - } - v := int64(math.Round(f * 100)) - return &v -} diff --git a/internal/equipment/mapping.go b/internal/equipment/mapping.go new file mode 100644 index 0000000..255b95c --- /dev/null +++ b/internal/equipment/mapping.go @@ -0,0 +1,66 @@ +package equipment + +import ( + "github.com/bit8bytes/gearberg/internal/database" + genequip "github.com/bit8bytes/gearberg/internal/database/queries/gen/equipment" +) + +func pricingFromListRow(row genequip.ListRow) Pricing { + return Pricing{ + PurchasePrice: database.NullAs[Cents](row.ResalePrice), + RentalPrice: database.NullAs[Cents](row.RentalPrice), + } +} + +func propertiesFromCreateRow(row genequip.CreateRow) Properties { + return Properties{ + Weight: database.NullAs[Grams](row.WeightG), + Width: database.NullAs[Millimeters](row.WidthMm), + Height: database.NullAs[Millimeters](row.HeightMm), + Depth: database.NullAs[Millimeters](row.DepthMm), + Power: database.NullAs[Milliwatts](row.PowerMw), + Current: database.NullAs[Milliamps](row.CurrentMa), + Voltage: database.NullAs[Millivolts](row.VoltageMv), + WireGauge: database.NullAs[WireGauge](row.WireGaugeMm2X100), + } +} + +func pricingFromCreateRow(row genequip.CreateRow) Pricing { + return Pricing{ + PurchasePrice: database.NullAs[Cents](row.ResalePrice), + RentalPrice: database.NullAs[Cents](row.RentalPrice), + } +} + +func propertiesFromGetByIDRow(row genequip.GetByIDRow) Properties { + return Properties{ + Weight: database.NullAs[Grams](row.WeightG), + Width: database.NullAs[Millimeters](row.WidthMm), + Height: database.NullAs[Millimeters](row.HeightMm), + Depth: database.NullAs[Millimeters](row.DepthMm), + Power: database.NullAs[Milliwatts](row.PowerMw), + Current: database.NullAs[Milliamps](row.CurrentMa), + Voltage: database.NullAs[Millivolts](row.VoltageMv), + WireGauge: database.NullAs[WireGauge](row.WireGaugeMm2X100), + } +} + +func pricingFromGetByIDRow(row genequip.GetByIDRow) Pricing { + return Pricing{ + PurchasePrice: database.NullAs[Cents](row.ResalePrice), + RentalPrice: database.NullAs[Cents](row.RentalPrice), + } +} + +func propertiesFromListRow(row genequip.ListRow) Properties { + return Properties{ + Weight: database.NullAs[Grams](row.WeightG), + Width: database.NullAs[Millimeters](row.WidthMm), + Height: database.NullAs[Millimeters](row.HeightMm), + Depth: database.NullAs[Millimeters](row.DepthMm), + Power: database.NullAs[Milliwatts](row.PowerMw), + Current: database.NullAs[Milliamps](row.CurrentMa), + Voltage: database.NullAs[Millivolts](row.VoltageMv), + WireGauge: database.NullAs[WireGauge](row.WireGaugeMm2X100), + } +} diff --git a/internal/equipment/model.go b/internal/equipment/model.go index bf14254..57842eb 100644 --- a/internal/equipment/model.go +++ b/internal/equipment/model.go @@ -7,71 +7,102 @@ import ( "time" ) -// PurchasePriceInput formats the purchase price as a plain decimal string for use in -// form inputs (e.g. 1999 → "19.99"). Returns "" when nil. -func (inv *Equipment) PurchasePriceInput() string { return priceInput(inv.PurchasePrice) } +// Cents is a monetary amount in the smallest currency unit (e.g. 1999 = €19.99). +type Cents int64 -// RentalPriceInput formats the rental price as a plain decimal string for use in -// form inputs (e.g. 1999 → "19.99"). Returns "" when nil. -func (inv *Equipment) RentalPriceInput() string { return priceInput(inv.RentalPrice) } - -// priceInput formats cents as "%.2f" using dot separator. Form parsers accept both -// dot and comma, so dot is always safe as a display format for editable inputs. -func priceInput(v *int64) string { - if v == nil { +// ToDecimal formats the amount as a decimal string for form inputs (e.g. 1999 → "19.99"). +// Returns "" when nil. +func (c *Cents) ToDecimal() string { + if c == nil { return "" } - return fmt.Sprintf("%.2f", float64(*v)/100) + return fmt.Sprintf("%.2f", float64(*c)/100) } -// InspectionIntervalDaysInput returns inspection interval in days as a string, or "" when nil. -func (inv *Equipment) InspectionIntervalDaysInput() string { - return optionalInt64Input(inv.InspectionIntervalDays) -} +// Grams is a weight stored in grams; users enter and see kilograms. +type Grams int64 -// WeightGInput returns weight in grams as a string, or "" when nil. -func (inv *Equipment) WeightGInput() string { return optionalInt64Input(inv.WeightG) } +// ToKG returns the weight in kg as a string for form inputs (e.g. 1500 → "1.5"). Returns "" when nil. +func (g *Grams) ToKG() string { + if g == nil { + return "" + } + return fmt.Sprintf("%g", float64(*g)/1000) +} -// WidthMMInput returns width in mm as a string, or "" when nil. -func (inv *Equipment) WidthMMInput() string { return optionalInt64Input(inv.WidthMM) } +// Millimeters is a length stored in millimetres; users enter and see centimetres. +type Millimeters int64 -// HeightMMInput returns height in mm as a string, or "" when nil. -func (inv *Equipment) HeightMMInput() string { return optionalInt64Input(inv.HeightMM) } +// ToCM returns the length in cm as a string for form inputs (e.g. 100 → "10"). Returns "" when nil. +func (m *Millimeters) ToCM() string { + if m == nil { + return "" + } + return fmt.Sprintf("%g", float64(*m)/10) +} -// DepthMMInput returns depth in mm as a string, or "" when nil. -func (inv *Equipment) DepthMMInput() string { return optionalInt64Input(inv.DepthMM) } +// Milliwatts is power stored in milliwatts; users enter and see watts. +type Milliwatts int64 -// PowerWattsInput converts milliwatts to watts for display (e.g. 500000 → "500"). Returns "" when nil. -func (inv *Equipment) PowerWattsInput() string { - if inv.PowerMW == nil { +// ToW returns the power in W as a string for form inputs (e.g. 1500 → "1.5"). Returns "" when nil. +func (m *Milliwatts) ToW() string { + if m == nil { return "" } - w := float64(*inv.PowerMW) / 1000 - return fmt.Sprintf("%g", w) + return fmt.Sprintf("%g", float64(*m)/1000) } -// CurrentAmpsInput converts milliamps to amps for display (e.g. 1500 → "1.5"). Returns "" when nil. -func (inv *Equipment) CurrentAmpsInput() string { - if inv.CurrentMA == nil { +// Milliamps is current stored in milliamps; users enter and see amps. +type Milliamps int64 + +// ToA returns the current in A as a string for form inputs (e.g. 500 → "0.5"). Returns "" when nil. +func (m *Milliamps) ToA() string { + if m == nil { return "" } - a := float64(*inv.CurrentMA) / 1000 - return fmt.Sprintf("%g", a) + return fmt.Sprintf("%g", float64(*m)/1000) } -// VoltageVInput returns voltage in volts as a string, or "" when nil. -func (inv *Equipment) VoltageVInput() string { return optionalInt64Input(inv.VoltageV) } +// Millivolts is voltage stored and displayed as whole volts. +type Millivolts int64 -// WireGaugeMM2X100Input returns wire_gauge_mm2_x100 as a string, or "" when nil. -func (inv *Equipment) WireGaugeMM2X100Input() string { - return optionalInt64Input(inv.WireGaugeMM2X100) +// ToV returns the voltage as a string for form inputs. Returns "" when nil. +func (v *Millivolts) ToV() string { + if v == nil { + return "" + } + return fmt.Sprintf("%g", float64(*v)/1000) } -func optionalInt64Input(v *int64) string { - if v == nil { +// WireGauge stores wire cross-section area as mm²×100 (e.g. 150 = 1.5 mm²); displayed as-is. +type WireGauge int64 + +// String returns the raw mm²×100 value as a string for form inputs. Returns "" when nil. +func (w *WireGauge) String() string { + if w == nil { return "" } - return fmt.Sprintf("%d", *v) + return fmt.Sprintf("%d", *w) +} + +// Properties holds the physical specification fields shown on the Properties tab. +// Adding a new physical property field only requires updating this struct, +// the mapper functions in mapping.go, and PropertiesForm in form.go. +type Properties struct { + Weight *Grams + Width *Millimeters + Height *Millimeters + Depth *Millimeters + Power *Milliwatts + Current *Milliamps + Voltage *Millivolts + WireGauge *WireGauge +} + +// Pricing holds the price fields shown on the Pricing tab. +type Pricing struct { + PurchasePrice *Cents + RentalPrice *Cents } // Equipment represents a single inventory item. @@ -93,18 +124,10 @@ type Equipment struct { ContentCount int64 HasContent bool IsArchived bool - PurchasePrice *int64 - RentalPrice *int64 Notes string - WeightG *int64 - WidthMM *int64 - HeightMM *int64 - DepthMM *int64 - PowerMW *int64 - CurrentMA *int64 - VoltageV *int64 - WireGaugeMM2X100 *int64 InspectionIntervalDays *int64 + Pricing Pricing + Properties Properties CreatedAt int64 UpdatedAt int64 } @@ -140,25 +163,17 @@ type PartOf struct { // Base holds fields shared between bulk and serialized creation. type Base struct { - ID string - OrgID string - UsageTypeID int64 - Name string - CategoryID string - ManufacturerID string - LocationID *string - HasContent bool - PurchasePrice *int64 - RentalPrice *int64 - Notes string - WeightG *int64 - WidthMM *int64 - HeightMM *int64 - DepthMM *int64 - PowerMW *int64 - CurrentMA *int64 - VoltageV *int64 - WireGaugeMM2X100 *int64 + ID string + OrgID string + UsageTypeID int64 + Name string + CategoryID string + ManufacturerID string + LocationID *string + HasContent bool + Notes string + Pricing Pricing + Properties Properties } // CreateBulkEquipment holds the data required to create a bulk inventory item. @@ -201,17 +216,13 @@ type Unit struct { Code string ManufacturerSerialNumber string Notes string - PurchasePrice *int64 + PurchasePrice *Cents PurchasedAt *int64 NextInspectionAt *int64 CreatedAt int64 UpdatedAt int64 } -// PurchasePriceInput formats the purchase price as a plain decimal string for use in -// form inputs (e.g. 1999 → "19.99"). Returns "" when nil. -func (u *Unit) PurchasePriceInput() string { return priceInput(u.PurchasePrice) } - // PurchasedAtInput formats the purchased_at timestamp as "YYYY-MM-DD" for use in // a date input. Returns "" when nil. func (u *Unit) PurchasedAtInput() string { @@ -264,22 +275,14 @@ type UpdateEquipmentDetails struct { // UpdateEquipmentPricing holds the data required to update the pricing tab fields. type UpdateEquipmentPricing struct { - ID string - PurchasePrice *int64 - RentalPrice *int64 + ID string + Pricing Pricing } // UpdateEquipmentProperties holds the data required to update the properties tab fields. type UpdateEquipmentProperties struct { - ID string - WeightG *int64 - WidthMM *int64 - HeightMM *int64 - DepthMM *int64 - VoltageV *int64 - PowerMW *int64 - CurrentMA *int64 - WireGaugeMM2X100 *int64 + ID string + Properties Properties } // ArchiveEquipment holds the data required to archive or unarchive an equipment item. @@ -327,7 +330,7 @@ type UpdateUnit struct { Code string ManufacturerSerialNumber string Notes string - PurchasePrice *int64 + PurchasePrice *Cents PurchasedAt *int64 NextInspectionAt *int64 } diff --git a/internal/equipment/repository.go b/internal/equipment/repository.go index 944a14c..52fca7b 100644 --- a/internal/equipment/repository.go +++ b/internal/equipment/repository.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "math" "github.com/bit8bytes/gearberg/internal/database" genequip "github.com/bit8bytes/gearberg/internal/database/queries/gen/equipment" @@ -62,6 +63,10 @@ func (r *Repository) List(ctx context.Context, orgID, query, category string, sh if err != nil { return nil, 0, fmt.Errorf("List: %w", err) } + return listRowsToEquipment(rows) +} + +func listRowsToEquipment(rows []genequip.ListRow) ([]Equipment, int, error) { var totalRecords int64 items := make([]Equipment, 0, len(rows)) for _, row := range rows { @@ -80,10 +85,11 @@ func (r *Repository) List(ctx context.Context, orgID, query, category string, sh LocationName: row.LocationName, StorageObjectID: database.StringPtr(row.StorageObjectID), TotalStock: row.TotalStock, + HasContent: row.HasContent == 1, IsArchived: row.IsArchived == 1, - PurchasePrice: database.Int64Ptr(row.ResalePrice), - RentalPrice: database.Int64Ptr(row.RentalPrice), Notes: database.String(row.Notes), + Pricing: pricingFromListRow(row), + Properties: propertiesFromListRow(row), UpdatedAt: row.UpdatedAt, CreatedAt: row.CreatedAt, }) @@ -101,34 +107,26 @@ func (r *Repository) GetByID(ctx context.Context, id string) (*Equipment, error) return nil, fmt.Errorf("GetByID: %w", err) } m := Equipment{ - ID: row.ID, - OrgID: row.OrgID, - Kind: KindFromString(row.EquipmentTypeName), - Type: Type(row.TrackingTypeID.Int64), - UsageType: UsageType(row.UsageTypeID), - Name: row.Name, - CategoryID: database.String(row.CategoryID), - ManufacturerID: database.String(row.ManufacturerID), - LocationID: database.String(row.LocationID), - LocationName: row.LocationName, - StorageObjectID: database.StringPtr(row.StorageObjectID), - TotalStock: row.TotalStock, - ContentCount: row.ContentCount, - HasContent: row.HasContent == 1, - IsArchived: row.IsArchived == 1, - PurchasePrice: database.Int64Ptr(row.ResalePrice), - RentalPrice: database.Int64Ptr(row.RentalPrice), - Notes: database.String(row.Notes), - WeightG: database.Int64Ptr(row.WeightG), - WidthMM: database.Int64Ptr(row.WidthMm), - HeightMM: database.Int64Ptr(row.HeightMm), - DepthMM: database.Int64Ptr(row.DepthMm), - PowerMW: database.Int64Ptr(row.PowerMw), - CurrentMA: database.Int64Ptr(row.CurrentMa), - VoltageV: database.Int64Ptr(row.VoltageV), - WireGaugeMM2X100: database.Int64Ptr(row.WireGaugeMm2X100), - CreatedAt: row.CreatedAt, - UpdatedAt: row.UpdatedAt, + ID: row.ID, + OrgID: row.OrgID, + Kind: KindFromString(row.EquipmentTypeName), + Type: Type(row.TrackingTypeID.Int64), + UsageType: UsageType(row.UsageTypeID), + Name: row.Name, + CategoryID: database.String(row.CategoryID), + ManufacturerID: database.String(row.ManufacturerID), + LocationID: database.String(row.LocationID), + LocationName: row.LocationName, + StorageObjectID: database.StringPtr(row.StorageObjectID), + TotalStock: row.TotalStock, + ContentCount: row.ContentCount, + HasContent: row.HasContent == 1, + IsArchived: row.IsArchived == 1, + Notes: database.String(row.Notes), + Pricing: pricingFromGetByIDRow(row), + Properties: propertiesFromGetByIDRow(row), + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, } return &m, nil } @@ -159,17 +157,17 @@ func (r *Repository) createBulkWith(ctx context.Context, eqQ *genequip.Queries, Name: c.Name, HasContent: database.Bool(c.HasContent), IsArchived: 0, - RentalPrice: database.NullInt64Ptr(c.RentalPrice), - ResalePrice: database.NullInt64Ptr(c.PurchasePrice), + RentalPrice: database.NullOf(c.Pricing.RentalPrice), + ResalePrice: database.NullOf(c.Pricing.PurchasePrice), Notes: database.NullString(database.StringOrNil(c.Notes)), - WeightG: database.NullInt64Ptr(c.WeightG), - WidthMm: database.NullInt64Ptr(c.WidthMM), - HeightMm: database.NullInt64Ptr(c.HeightMM), - DepthMm: database.NullInt64Ptr(c.DepthMM), - CurrentMa: database.NullInt64Ptr(c.CurrentMA), - PowerMw: database.NullInt64Ptr(c.PowerMW), - VoltageV: database.NullInt64Ptr(c.VoltageV), - WireGaugeMm2X100: database.NullInt64Ptr(c.WireGaugeMM2X100), + WeightG: database.NullOf(c.Properties.Weight), + WidthMm: database.NullOf(c.Properties.Width), + HeightMm: database.NullOf(c.Properties.Height), + DepthMm: database.NullOf(c.Properties.Depth), + CurrentMa: database.NullOf(c.Properties.Current), + PowerMw: database.NullOf(c.Properties.Power), + VoltageMv: database.NullOf(c.Properties.Voltage), + WireGaugeMm2X100: database.NullOf(c.Properties.WireGauge), }) if err != nil { return nil, fmt.Errorf("createBulkWith: %w", database.NormalizeError(err)) @@ -182,52 +180,28 @@ func (r *Repository) createBulkWith(ctx context.Context, eqQ *genequip.Queries, return nil, fmt.Errorf("createBulkWith: equipment_bulk_items: %w", database.NormalizeError(err)) } m := Equipment{ - ID: row.ID, - OrgID: row.OrgID, - Kind: Physical, - Type: Type(row.TrackingTypeID.Int64), - UsageType: UsageType(row.UsageTypeID), - Name: row.Name, - CategoryID: database.String(row.CategoryID), - ManufacturerID: database.String(row.ManufacturerID), - LocationID: database.String(row.LocationID), - StorageObjectID: database.StringPtr(row.StorageObjectID), - TotalStock: c.TotalStock, - HasContent: row.HasContent == 1, - PurchasePrice: database.Int64Ptr(row.ResalePrice), - RentalPrice: database.Int64Ptr(row.RentalPrice), - Notes: database.String(row.Notes), - WeightG: database.Int64Ptr(row.WeightG), - WidthMM: database.Int64Ptr(row.WidthMm), - HeightMM: database.Int64Ptr(row.HeightMm), - DepthMM: database.Int64Ptr(row.DepthMm), - PowerMW: database.Int64Ptr(row.PowerMw), - CurrentMA: database.Int64Ptr(row.CurrentMa), - WireGaugeMM2X100: database.Int64Ptr(row.WireGaugeMm2X100), - CreatedAt: row.CreatedAt, + ID: row.ID, + OrgID: row.OrgID, + Kind: Physical, + Type: Type(row.TrackingTypeID.Int64), + UsageType: UsageType(row.UsageTypeID), + Name: row.Name, + CategoryID: database.String(row.CategoryID), + ManufacturerID: database.String(row.ManufacturerID), + LocationID: database.String(row.LocationID), + StorageObjectID: database.StringPtr(row.StorageObjectID), + TotalStock: c.TotalStock, + HasContent: row.HasContent == 1, + Notes: database.String(row.Notes), + Pricing: pricingFromCreateRow(row), + Properties: propertiesFromCreateRow(row), + CreatedAt: row.CreatedAt, } return &m, nil } -// CreateBulk inserts a new bulk inventory item and its equipment_bulk_items row atomically. -func (r *Repository) CreateBulk(ctx context.Context, c CreateBulkEquipment) (*Equipment, error) { - tx, err := r.db.BeginTx(ctx, nil) - if err != nil { - return nil, fmt.Errorf("CreateBulk: %w", err) - } - defer tx.Rollback() //nolint:errcheck - m, err := r.createBulkWith(ctx, r.equipment.WithTx(tx), r.bulkItems.WithTx(tx), c) - if err != nil { - return nil, fmt.Errorf("CreateBulk: %w", err) - } - if err := tx.Commit(); err != nil { - return nil, fmt.Errorf("CreateBulk: commit: %w", err) - } - return m, nil -} - -// CreateBulkTx inserts a new bulk inventory item within an existing transaction. -func (r *Repository) CreateBulkTx(ctx context.Context, tx *sql.Tx, c CreateBulkEquipment) (*Equipment, error) { +// CreateBulk inserts a new bulk inventory item within an existing transaction. +func (r *Repository) CreateBulk(ctx context.Context, tx *sql.Tx, c CreateBulkEquipment) (*Equipment, error) { m, err := r.createBulkWith(ctx, r.equipment.WithTx(tx), r.bulkItems.WithTx(tx), c) if err != nil { return nil, fmt.Errorf("CreateBulkTx: %w", err) @@ -251,17 +225,17 @@ func (r *Repository) CreateSerialized(ctx context.Context, tx *sql.Tx, c CreateS Name: c.Name, HasContent: database.Bool(c.HasContent), IsArchived: 0, - RentalPrice: database.NullInt64Ptr(c.RentalPrice), - ResalePrice: database.NullInt64Ptr(c.PurchasePrice), + RentalPrice: database.NullOf(c.Pricing.RentalPrice), + ResalePrice: database.NullOf(c.Pricing.PurchasePrice), Notes: database.NullString(database.StringOrNil(c.Notes)), - WeightG: database.NullInt64Ptr(c.WeightG), - WidthMm: database.NullInt64Ptr(c.WidthMM), - HeightMm: database.NullInt64Ptr(c.HeightMM), - DepthMm: database.NullInt64Ptr(c.DepthMM), - CurrentMa: database.NullInt64Ptr(c.CurrentMA), - PowerMw: database.NullInt64Ptr(c.PowerMW), - VoltageV: database.NullInt64Ptr(c.VoltageV), - WireGaugeMm2X100: database.NullInt64Ptr(c.WireGaugeMM2X100), + WeightG: database.NullOf(c.Properties.Weight), + WidthMm: database.NullOf(c.Properties.Width), + HeightMm: database.NullOf(c.Properties.Height), + DepthMm: database.NullOf(c.Properties.Depth), + CurrentMa: database.NullOf(c.Properties.Current), + PowerMw: database.NullOf(c.Properties.Power), + VoltageMv: database.NullOf(c.Properties.Voltage), + WireGaugeMm2X100: database.NullOf(c.Properties.WireGauge), }) if err != nil { return nil, fmt.Errorf("CreateSerialized: %w", database.NormalizeError(err)) @@ -281,29 +255,22 @@ func (r *Repository) CreateSerialized(ctx context.Context, tx *sql.Tx, c CreateS } m := Equipment{ - ID: row.ID, - OrgID: row.OrgID, - Kind: Physical, - Type: Type(row.TrackingTypeID.Int64), - UsageType: UsageType(row.UsageTypeID), - Name: row.Name, - CategoryID: database.String(row.CategoryID), - ManufacturerID: database.String(row.ManufacturerID), - LocationID: database.String(row.LocationID), - StorageObjectID: database.StringPtr(row.StorageObjectID), - TotalStock: int64(len(c.Units)), - HasContent: row.HasContent == 1, - PurchasePrice: database.Int64Ptr(row.ResalePrice), - RentalPrice: database.Int64Ptr(row.RentalPrice), - Notes: database.String(row.Notes), - WeightG: database.Int64Ptr(row.WeightG), - WidthMM: database.Int64Ptr(row.WidthMm), - HeightMM: database.Int64Ptr(row.HeightMm), - DepthMM: database.Int64Ptr(row.DepthMm), - PowerMW: database.Int64Ptr(row.PowerMw), - CurrentMA: database.Int64Ptr(row.CurrentMa), - WireGaugeMM2X100: database.Int64Ptr(row.WireGaugeMm2X100), - CreatedAt: row.CreatedAt, + ID: row.ID, + OrgID: row.OrgID, + Kind: Physical, + Type: Type(row.TrackingTypeID.Int64), + UsageType: UsageType(row.UsageTypeID), + Name: row.Name, + CategoryID: database.String(row.CategoryID), + ManufacturerID: database.String(row.ManufacturerID), + LocationID: database.String(row.LocationID), + StorageObjectID: database.StringPtr(row.StorageObjectID), + TotalStock: int64(len(c.Units)), + HasContent: row.HasContent == 1, + Notes: database.String(row.Notes), + Pricing: pricingFromCreateRow(row), + Properties: propertiesFromCreateRow(row), + CreatedAt: row.CreatedAt, } return &m, nil } @@ -360,8 +327,8 @@ func (r *Repository) UpdateDetailsBulk(ctx context.Context, u UpdateEquipmentDet func (r *Repository) UpdatePricing(ctx context.Context, u UpdateEquipmentPricing) error { if err := r.equipment.UpdatePricing(ctx, genequip.UpdatePricingParams{ ID: u.ID, - ResalePrice: database.NullInt64Ptr(u.PurchasePrice), - RentalPrice: database.NullInt64Ptr(u.RentalPrice), + ResalePrice: database.NullOf(u.Pricing.PurchasePrice), + RentalPrice: database.NullOf(u.Pricing.RentalPrice), }); err != nil { return fmt.Errorf("UpdatePricing: %w", database.NormalizeError(err)) } @@ -372,14 +339,14 @@ func (r *Repository) UpdatePricing(ctx context.Context, u UpdateEquipmentPricing func (r *Repository) UpdateProperties(ctx context.Context, u UpdateEquipmentProperties) error { if err := r.equipment.UpdateProperties(ctx, genequip.UpdatePropertiesParams{ ID: u.ID, - WeightG: database.NullInt64Ptr(u.WeightG), - WidthMm: database.NullInt64Ptr(u.WidthMM), - HeightMm: database.NullInt64Ptr(u.HeightMM), - DepthMm: database.NullInt64Ptr(u.DepthMM), - VoltageV: database.NullInt64Ptr(u.VoltageV), - CurrentMa: database.NullInt64Ptr(u.CurrentMA), - PowerMw: database.NullInt64Ptr(u.PowerMW), - WireGaugeMm2X100: database.NullInt64Ptr(u.WireGaugeMM2X100), + WeightG: database.NullOf(u.Properties.Weight), + WidthMm: database.NullOf(u.Properties.Width), + HeightMm: database.NullOf(u.Properties.Height), + DepthMm: database.NullOf(u.Properties.Depth), + VoltageMv: database.NullOf(u.Properties.Voltage), + CurrentMa: database.NullOf(u.Properties.Current), + PowerMw: database.NullOf(u.Properties.Power), + WireGaugeMm2X100: database.NullOf(u.Properties.WireGauge), }); err != nil { return fmt.Errorf("UpdateProperties: %w", database.NormalizeError(err)) } @@ -402,7 +369,7 @@ func (r *Repository) ListUnits(ctx context.Context, equipmentID string) ([]Unit, Code: database.String(row.Code), ManufacturerSerialNumber: database.String(row.ManufacturerSerial), Notes: database.String(row.Remark), - PurchasePrice: database.Int64Ptr(row.PurchasePrice), + PurchasePrice: database.NullAs[Cents](row.PurchasePrice), PurchasedAt: database.Int64Ptr(row.PurchasedAt), NextInspectionAt: database.Int64Ptr(row.NextInspectionAt), CreatedAt: row.CreatedAt, @@ -413,45 +380,21 @@ func (r *Repository) ListUnits(ctx context.Context, equipmentID string) ([]Unit, } // ListAll returns all inventory items for orgID ordered by name, with no pagination. +// Passes -1 as the is_archived sentinel to skip the archived filter and return all items. func (r *Repository) ListAll(ctx context.Context, orgID string) ([]Equipment, error) { - rows, err := r.equipment.ListAllByOrgID(ctx, orgID) + rows, err := r.equipment.List(ctx, genequip.ListParams{ + OrgID: orgID, + NameQuery: "", + Category: "", + IsArchived: -1, + PageOffset: 0, + PageLimit: math.MaxInt32, + }) if err != nil { return nil, fmt.Errorf("ListAll: %w", err) } - items := make([]Equipment, 0, len(rows)) - for _, row := range rows { - items = append(items, Equipment{ - ID: row.ID, - OrgID: row.OrgID, - Kind: KindFromString(row.EquipmentTypeName), - Type: Type(row.TrackingTypeID.Int64), - UsageType: UsageType(row.UsageTypeID), - Name: row.Name, - CategoryID: database.String(row.CategoryID), - CategoryName: row.CategoryName, - ManufacturerID: database.String(row.ManufacturerID), - LocationID: database.String(row.LocationID), - LocationName: row.LocationName, - StorageObjectID: database.StringPtr(row.StorageObjectID), - TotalStock: row.TotalStock, - HasContent: row.HasContent == 1, - IsArchived: row.IsArchived == 1, - PurchasePrice: database.Int64Ptr(row.ResalePrice), - RentalPrice: database.Int64Ptr(row.RentalPrice), - Notes: database.String(row.Notes), - WeightG: database.Int64Ptr(row.WeightG), - WidthMM: database.Int64Ptr(row.WidthMm), - HeightMM: database.Int64Ptr(row.HeightMm), - DepthMM: database.Int64Ptr(row.DepthMm), - VoltageV: database.Int64Ptr(row.VoltageV), - CurrentMA: database.Int64Ptr(row.CurrentMa), - PowerMW: database.Int64Ptr(row.PowerMw), - WireGaugeMM2X100: database.Int64Ptr(row.WireGaugeMm2X100), - UpdatedAt: row.UpdatedAt, - CreatedAt: row.CreatedAt, - }) - } - return items, nil + items, _, err := listRowsToEquipment(rows) + return items, err } // Archive sets the is_archived flag on an inventory item. @@ -491,7 +434,7 @@ func (r *Repository) GetUnit(ctx context.Context, id string) (*Unit, error) { Code: database.String(row.Code), ManufacturerSerialNumber: database.String(row.ManufacturerSerial), Notes: database.String(row.Remark), - PurchasePrice: database.Int64Ptr(row.PurchasePrice), + PurchasePrice: database.NullAs[Cents](row.PurchasePrice), PurchasedAt: database.Int64Ptr(row.PurchasedAt), NextInspectionAt: database.Int64Ptr(row.NextInspectionAt), CreatedAt: row.CreatedAt, @@ -530,7 +473,7 @@ func (r *Repository) UpdateUnit(ctx context.Context, u UpdateUnit) error { Code: database.NullString(database.StringOrNil(u.Code)), IsActive: u.StatusID, Remark: database.NullString(database.StringOrNil(u.Notes)), - PurchasePrice: database.NullInt64Ptr(u.PurchasePrice), + PurchasePrice: database.NullOf(u.PurchasePrice), PurchasedAt: database.NullInt64Ptr(u.PurchasedAt), NextInspectionAt: database.NullInt64Ptr(u.NextInspectionAt), ManufacturerSerial: database.NullString(database.StringOrNil(u.ManufacturerSerialNumber)), diff --git a/internal/equipment/service.go b/internal/equipment/service.go index ec78eb8..c2e38b6 100644 --- a/internal/equipment/service.go +++ b/internal/equipment/service.go @@ -45,9 +45,6 @@ func NewService(repo *Repository, db *sql.DB, cats CategoryLister, mfrs Manufact // Create creates a new inventory item, dispatching to the correct path based on type. // Serialized creation runs inside a transaction managed by the service. func (s *Service) Create(ctx context.Context, c CreateEquipment) (*Equipment, error) { - if c.Type == Bulk { - return s.CreateBulk(ctx, CreateBulkEquipment{Base: c.Base, TotalStock: c.TotalStock}) - } units := make([]CreateUnit, c.UnitCount) for i := range units { units[i] = CreateUnit{ID: ksuid.New().String(), OrgID: c.OrgID, EquipmentID: c.ID, SerialNumber: serial.New()} @@ -57,7 +54,18 @@ func (s *Service) Create(ctx context.Context, c CreateEquipment) (*Equipment, er return nil, fmt.Errorf("Create: %w", err) } defer func() { _ = tx.Rollback() }() - item, err := s.repo.CreateSerialized(ctx, tx, CreateSerializedEquipment{Base: c.Base, Units: units}) + + // Both types go through the same tx path; Bulk doesn't need atomicity but a + // single code path is easier to maintain than two separate non-tx branches. + var item *Equipment + switch c.Type { + case Bulk: + item, err = s.repo.CreateBulk(ctx, tx, CreateBulkEquipment{Base: c.Base, TotalStock: c.TotalStock}) + case Serialized: + item, err = s.repo.CreateSerialized(ctx, tx, CreateSerializedEquipment{Base: c.Base, Units: units}) + default: + return nil, fmt.Errorf("Create: unknown equipment type %q", c.Type) + } if err != nil { return nil, fmt.Errorf("Create: %w", err) } @@ -97,18 +105,9 @@ func (s *Service) GetByID(ctx context.Context, id string) (*Equipment, error) { return item, nil } -// CreateBulk creates a new bulk inventory item with an auto-assigned code. -func (s *Service) CreateBulk(ctx context.Context, c CreateBulkEquipment) (*Equipment, error) { - item, err := s.repo.CreateBulk(ctx, c) - if err != nil { - return nil, fmt.Errorf("CreateBulk: %w", err) - } - return item, nil -} - // CreateBulkTx creates a new bulk inventory item within an existing transaction. func (s *Service) CreateBulkTx(ctx context.Context, tx *sql.Tx, c CreateBulkEquipment) (*Equipment, error) { - item, err := s.repo.CreateBulkTx(ctx, tx, c) + item, err := s.repo.CreateBulk(ctx, tx, c) if err != nil { return nil, fmt.Errorf("CreateBulkTx: %w", err) } diff --git a/internal/html/html.go b/internal/html/html.go index 0d9da98..ed907c0 100644 --- a/internal/html/html.go +++ b/internal/html/html.go @@ -36,13 +36,14 @@ type TemplateData struct { // HTML renders HTML responses and adapts httperr.HandlerFunc into standard http.HandlerFunc. type HTML struct { logger *slog.Logger + base *template.Template cache map[string]*template.Template revision string } // New returns a Renderer backed by the given logger, template cache, and revision string. -func New(logger *slog.Logger, cache map[string]*template.Template, revision string) *HTML { - return &HTML{logger: logger, cache: cache, revision: revision} +func New(logger *slog.Logger, base *template.Template, cache map[string]*template.Template, revision string) *HTML { + return &HTML{logger: logger, base: base, cache: cache, revision: revision} } // Handle adapts an httperr.HandlerFunc into a standard http.HandlerFunc. When the handler @@ -101,6 +102,31 @@ func (rnd *HTML) Render(w http.ResponseWriter, _ *http.Request, status int, page return nil } +// RenderFragment executes a named fragment block directly from the base template, +// returning only the fragment HTML with no surrounding page shell. +func (rnd *HTML) RenderFragment(w http.ResponseWriter, _ *http.Request, status int, name string, data any) *httperr.Error { + buffer := new(bytes.Buffer) + if err := rnd.base.ExecuteTemplate(buffer, name, data); err != nil { + return &httperr.Error{ + Error: fmt.Errorf("render fragment %q: %w", name, err), + Message: "Failed to render fragment.", + Code: http.StatusInternalServerError, + } + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + + if _, err := buffer.WriteTo(w); err != nil { + return &httperr.Error{ + Error: err, + Message: "Failed to write response.", + Code: http.StatusInternalServerError, + } + } + return nil +} + // TemplateData builds the base template data shared by every page. func (rnd *HTML) TemplateData(r *http.Request) *TemplateData { return &TemplateData{ diff --git a/internal/orgs/settings/form.go b/internal/orgs/settings/form.go index cea437a..e3a9678 100644 --- a/internal/orgs/settings/form.go +++ b/internal/orgs/settings/form.go @@ -11,15 +11,15 @@ import ( "github.com/bit8bytes/toolbox/validator" ) -// permittedCurrencies lists the ISO-4217 codes exposed in the UI. -var permittedCurrencies = []string{ +// PermittedCurrencies lists the ISO-4217 codes exposed in the UI. +var PermittedCurrencies = []string{ "USD", "EUR", "GBP", "CHF", "CAD", "AUD", "JPY", "CNY", "INR", "BRL", "MXN", "SEK", "NOK", "DKK", "PLN", "CZK", "HUF", "RON", "SGD", "HKD", "NZD", "ZAR", "TRY", "AED", "SAR", } -// permittedTimezones lists the IANA timezone identifiers exposed in the UI. -var permittedTimezones = []string{ +// PermittedTimezones lists the IANA timezone identifiers exposed in the UI. +var PermittedTimezones = []string{ "Africa/Cairo", "Africa/Johannesburg", "Africa/Lagos", "Africa/Nairobi", "America/Anchorage", "America/Argentina/Buenos_Aires", "America/Bogota", "America/Chicago", "America/Denver", "America/Los_Angeles", "America/Mexico_City", @@ -62,7 +62,7 @@ func Parse(r *http.Request) (Form, error) { // Validate checks form fields and returns true when all checks pass. func (f *Form) Validate() bool { - f.Check(validator.PermittedValue(f.Currency, permittedCurrencies...), "currency", "Must be a valid ISO-4217 currency code") + f.Check(validator.PermittedValue(f.Currency, PermittedCurrencies...), "currency", "Must be a valid ISO-4217 currency code") if validator.NotBlank(f.VatRate) { v, err := strconv.ParseFloat(strings.ReplaceAll(f.VatRate, ",", "."), 64) f.Check(err == nil, "vat_rate", "Must be a valid number") @@ -70,7 +70,7 @@ func (f *Form) Validate() bool { } else { f.AddError("vat_rate", "This field cannot be blank") } - f.Check(validator.PermittedValue(f.Timezone, permittedTimezones...), "timezone", "Must be a valid IANA timezone") + f.Check(validator.PermittedValue(f.Timezone, PermittedTimezones...), "timezone", "Must be a valid IANA timezone") return f.Valid() } diff --git a/internal/templates/components/equipment-header.tmpl b/internal/templates/components/equipment-header.tmpl index 1a5e60b..231f752 100644 --- a/internal/templates/components/equipment-header.tmpl +++ b/internal/templates/components/equipment-header.tmpl @@ -9,12 +9,11 @@
  • {{ .Data.Item.Name }}
  • - {{ if and (eq .Data.Item.Kind 1) .Data.PartOf }} -
    - Part of: - {{ range $i, $p := .Data.PartOf }}{{ if $i }}, {{ end }}{{ $p.Name }}{{ end }} +
    - {{ end }}
    - - + +
    + {{ template "equipment-categories-skeleton" . }} +
    {{ with index .Form.Errors "category_id" }}

    {{ . }}

    {{ end }}
    - - + +
    + {{ template "equipment-manufacturers-skeleton" . }} +
    - - + +
    + {{ template "warehouse-locations-skeleton" . }} +
    {{ if .Data.Item }}{{ if eq .Data.Item.Type 1 }} diff --git a/internal/templates/pages/equipment/new.tmpl b/internal/templates/pages/equipment/new.tmpl index 62fe659..5ea6603 100644 --- a/internal/templates/pages/equipment/new.tmpl +++ b/internal/templates/pages/equipment/new.tmpl @@ -45,8 +45,8 @@
    {{ with index .Form.Errors "rental_price" }}

    {{ . }}

    @@ -55,26 +55,36 @@
    - - - +
    + {{ template "equipment-categories-skeleton" . }} +
    {{ with index .Form.Errors "category_id" }}

    {{ . }}

    {{ end }}
    + +
    + +
    + {{ template "equipment-manufacturers-skeleton" . }} +
    +
    + +
    + +
    + {{ template "warehouse-locations-skeleton" . }} +
    +
    diff --git a/internal/templates/pages/equipment/pricing.tmpl b/internal/templates/pages/equipment/pricing.tmpl index 26e30de..9d39f01 100644 --- a/internal/templates/pages/equipment/pricing.tmpl +++ b/internal/templates/pages/equipment/pricing.tmpl @@ -16,13 +16,15 @@
    {{ with index .Form.Errors "purchase_price" }} @@ -33,13 +35,15 @@
    {{ with index .Form.Errors "rental_price" }} diff --git a/internal/templates/pages/equipment/print.tmpl b/internal/templates/pages/equipment/print.tmpl index e5b2ba3..34cd852 100644 --- a/internal/templates/pages/equipment/print.tmpl +++ b/internal/templates/pages/equipment/print.tmpl @@ -42,7 +42,7 @@ {{ .CategoryName }} {{ .TotalStock }} - {{ .RentalPriceInput }} + {{ .Pricing.RentalPrice.ToDecimal }} {{ end }} diff --git a/internal/templates/pages/equipment/properties.tmpl b/internal/templates/pages/equipment/properties.tmpl index 1fdd705..8a923df 100644 --- a/internal/templates/pages/equipment/properties.tmpl +++ b/internal/templates/pages/equipment/properties.tmpl @@ -14,27 +14,33 @@
    - - + +
    - - + +
    - - + +
    - - + + +
    + +
    + +
    @@ -48,25 +54,19 @@
    + value="{{ .Form.Voltage.ToV }}" />
    - +
    - -
    - -
    - - +
    diff --git a/internal/templates/pages/equipment/units.tmpl b/internal/templates/pages/equipment/units.tmpl index 343f28d..98ebdd4 100644 --- a/internal/templates/pages/equipment/units.tmpl +++ b/internal/templates/pages/equipment/units.tmpl @@ -64,7 +64,12 @@ {{ end }} {{ else }}{{ end }} - {{ if .PurchasePriceInput }}{{ .PurchasePriceInput }}{{ else }}{{ end }} + + {{ if .PurchasePrice }} + + {{ else }}{{ end }} + {{ if .PurchasedAtInput }}{{ .PurchasedAtInput }}{{ else }}{{ end }} {{ if .Notes }}{{ .Notes }}{{ else }}{{ end }} @@ -169,7 +174,7 @@
    - +
    diff --git a/internal/templates/pages/orgs/settings.tmpl b/internal/templates/pages/orgs/settings.tmpl index a03fda7..89bed19 100644 --- a/internal/templates/pages/orgs/settings.tmpl +++ b/internal/templates/pages/orgs/settings.tmpl @@ -49,11 +49,14 @@ % {{ with index .Form.Errors "vat_rate" }} diff --git a/internal/templates/templates.go b/internal/templates/templates.go index 1ade32b..af94bfa 100644 --- a/internal/templates/templates.go +++ b/internal/templates/templates.go @@ -7,5 +7,5 @@ import "embed" // EmbedFS contains all template directories embedded at compile time. // -//go:embed components layouts pages partials +//go:embed components layouts pages partials fragments var EmbedFS embed.FS diff --git a/pkg/htmx/htmx.go b/pkg/htmx/htmx.go new file mode 100644 index 0000000..a296d03 --- /dev/null +++ b/pkg/htmx/htmx.go @@ -0,0 +1,44 @@ +// Package htmx provides helpers for working with HTMX HTTP headers. +package htmx + +import ( + "net/http" + urlpkg "net/url" +) + +// Redirect sends an HTMX client-side redirect by setting the HX-Redirect header. +// The url may be a path relative to the request path and will be resolved accordingly. +// +// The provided code should be in the 3xx range and is usually [StatusMovedPermanently], [StatusFound], [StatusSeeOther], or [StatusOK]. +// +// This function is specifically designed for HTMX requests. For standard HTTP redirects, use http.Redirect instead. +func Redirect(w http.ResponseWriter, r *http.Request, url string, code int) { + // Let http.Redirect do the URL normalization + if u, err := urlpkg.Parse(url); err == nil { + if u.Scheme == "" && u.Host == "" { + // Use stdlib's URL resolution + url = r.URL.ResolveReference(u).String() + } + } + + w.Header().Set("HX-Redirect", url) + w.WriteHeader(code) +} + +// StatusOK writes a 200 OK status code to the response. +// This is useful for HTMX requests that don't require a response body. +func StatusOK(w http.ResponseWriter) { + w.WriteHeader(http.StatusOK) +} + +// IsRequest checks if the request is an HTMX request +// by looking for the "HX-IsRequest" header. +func IsRequest(r *http.Request) bool { + return r.Header.Get("HX-Request") == "true" +} + +// SetTrigger sets the HX-Trigger response header, instructing HTMX to fire +// a client-side event with the given name after the response is processed. +func SetTrigger(w http.ResponseWriter, event string) { + w.Header().Set("HX-Trigger", event) +} diff --git a/internal/tokens/tokens.go b/pkg/tokens/tokens.go similarity index 63% rename from internal/tokens/tokens.go rename to pkg/tokens/tokens.go index 919d943..2d0dcfe 100644 --- a/internal/tokens/tokens.go +++ b/pkg/tokens/tokens.go @@ -29,6 +29,22 @@ func (t Token) Hex() string { return hex.EncodeToString(t[:]) } +// ShortToken is 8 cryptographically random bytes, suitable for trace IDs and +// other short-lived identifiers where a full 32-byte token is unnecessary. +type ShortToken [8]byte + +// GenerateShort returns a new cryptographically secure random ShortToken. +func GenerateShort() ShortToken { + var token ShortToken + _, _ = io.ReadFull(rand.Reader, token[:]) + return token +} + +// Hex returns the token as a lowercase hexadecimal string. +func (t ShortToken) Hex() string { + return hex.EncodeToString(t[:]) +} + // Hash returns the SHA-256 hash of a plaintext token string (e.g. read back from a cookie). func Hash(plaintext string) []byte { sum := sha256.Sum256([]byte(plaintext))