improve tag creation and association when adding expenses

This commit is contained in:
juancwu 2026-01-15 02:27:00 +00:00
commit d7cdb19c3e
7 changed files with 83 additions and 37 deletions

View file

@ -342,7 +342,7 @@ func (h *SpaceHandler) CreateExpense(w http.ResponseWriter, r *http.Request) {
amountStr := r.FormValue("amount")
typeStr := r.FormValue("type")
dateStr := r.FormValue("date")
tagIDs := r.Form["tags"] // For multi-select
tagNames := r.Form["tags"] // Contains tag names
// --- Validation & Conversion ---
if description == "" || amountStr == "" || typeStr == "" || dateStr == "" {
@ -369,6 +369,49 @@ func (h *SpaceHandler) CreateExpense(w http.ResponseWriter, r *http.Request) {
return
}
// --- Tag Processing ---
existingTags, err := h.tagService.GetTagsForSpace(spaceID)
if err != nil {
slog.Error("failed to get tags for space", "error", err, "space_id", spaceID)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
existingTagsMap := make(map[string]string)
for _, t := range existingTags {
existingTagsMap[t.Name] = t.ID
}
var finalTagIDs []string
processedTags := make(map[string]bool)
for _, rawTagName := range tagNames {
tagName := service.NormalizeTagName(rawTagName)
if tagName == "" {
continue
}
if processedTags[tagName] {
continue
}
if id, exists := existingTagsMap[tagName]; exists {
finalTagIDs = append(finalTagIDs, id)
} else {
// Create new tag
newTag, err := h.tagService.CreateTag(spaceID, tagName, nil)
if err != nil {
slog.Error("failed to create new tag from expense form", "error", err, "tag_name", tagName)
// Continue processing other tags? Or fail?
// Let's continue, maybe the tag was invalid or duplicate race condition.
// If duplicate race condition, we could try fetching it again, but for now simple log.
continue
}
finalTagIDs = append(finalTagIDs, newTag.ID)
existingTagsMap[tagName] = newTag.ID // Update map in case repeated in this request (though processedTags handles that)
}
processedTags[tagName] = true
}
// --- DTO Creation & Service Call ---
dto := service.CreateExpenseDTO{
SpaceID: spaceID,
@ -377,7 +420,7 @@ func (h *SpaceHandler) CreateExpense(w http.ResponseWriter, r *http.Request) {
Amount: amountCents,
Type: expenseType,
Date: date,
TagIDs: tagIDs,
TagIDs: finalTagIDs,
ItemIDs: []string{}, // TODO: Add item IDs from form
}

View file

@ -18,8 +18,12 @@ func NewTagService(tagRepo repository.TagRepository) *TagService {
return &TagService{tagRepo: tagRepo}
}
func NormalizeTagName(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
func (s *TagService) CreateTag(spaceID, name string, color *string) (*model.Tag, error) {
name = strings.TrimSpace(name)
name = NormalizeTagName(name)
if name == "" {
return nil, fmt.Errorf("tag name cannot be empty")
}
@ -51,7 +55,7 @@ func (s *TagService) GetTagByID(id string) (*model.Tag, error) {
}
func (s *TagService) UpdateTag(id, name string, color *string) (*model.Tag, error) {
name = strings.TrimSpace(name)
name = NormalizeTagName(name)
if name == "" {
return nil, fmt.Errorf("tag name cannot be empty")
}

View file

@ -6,6 +6,7 @@ import (
"git.juancwu.dev/juancwu/budgit/internal/ui/components/button"
"git.juancwu.dev/juancwu/budgit/internal/ui/components/csrf"
"git.juancwu.dev/juancwu/budgit/internal/ui/components/input"
"git.juancwu.dev/juancwu/budgit/internal/ui/components/tagsinput"
"time"
)
@ -28,56 +29,53 @@ templ AddExpenseForm(space *model.Space, tags []*model.Tag, lists []*model.Shopp
<span class="label-text ml-2">Top-up</span>
</label>
</div>
// Description
<div>
<label for="description" class="label">Description</label>
@input.Input(input.Props{
Name: "description",
ID: "description",
Name: "description",
ID: "description",
Attributes: templ.Attributes{"required": "true"},
})
</div>
// Amount
<div>
<label for="amount" class="label">Amount</label>
@input.Input(input.Props{
Name: "amount",
ID: "amount",
Type: "number",
Name: "amount",
ID: "amount",
Type: "number",
Attributes: templ.Attributes{"step": "0.01", "required": "true"},
})
</div>
// Date
<div>
<label for="date" class="label">Date</label>
@input.Input(input.Props{
Name: "date",
ID: "date",
Type: "date",
Value: time.Now().Format("2006-01-02"),
Name: "date",
ID: "date",
Type: "date",
Value: time.Now().Format("2006-01-02"),
Attributes: templ.Attributes{"required": "true"},
})
</div>
// Tags
if len(tags) > 0 {
<div>
<label class="label">Tags</label>
<select name="tags" multiple class="select select-bordered w-full h-32">
for _, tag := range tags {
<option value={ tag.ID }>{ tag.Name }</option>
}
</select>
</div>
}
<div>
<label class="label">Tags</label>
<datalist id="available-tags">
for _, tag := range tags {
<option value={ tag.Name }></option>
}
</datalist>
@tagsinput.TagsInput(tagsinput.Props{
Name: "tags",
Placeholder: "Add tags (press enter)",
Attributes: templ.Attributes{"list": "available-tags"},
})
</div>
// TODO: Shopping list items selector
<div class="flex justify-end">
@button.Button(button.Props{ Type: button.TypeSubmit }) {
@button.Button(button.Props{Type: button.TypeSubmit}) {
Save Transaction
}
</div>

View file

@ -26,6 +26,9 @@ templ TagsInput(props ...Props) {
if len(props) > 0 {
{{ p = props[0] }}
}
if p.ID == "" {
{{ p.ID = utils.RandomID() }}
}
<div
id={ p.ID + "-container" }
class={

View file

@ -11,6 +11,7 @@ import "git.juancwu.dev/juancwu/budgit/internal/ui/components/toast"
import "git.juancwu.dev/juancwu/budgit/internal/ui/components/calendar"
import "git.juancwu.dev/juancwu/budgit/internal/ui/components/datepicker"
import "git.juancwu.dev/juancwu/budgit/internal/ui/components/progress"
import "git.juancwu.dev/juancwu/budgit/internal/ui/components/tagsinput"
import "fmt"
import "time"
@ -36,6 +37,7 @@ templ Base(props ...SEOProps) {
<link rel="icon" type="image/x-icon" href="/assets/favicon/favicon.ico"/>
<link href={ "/assets/css/output.css?v=" + templ.EscapeString(fmt.Sprintf("%d", time.Now().Unix())) } rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.7/dist/htmx.min.js" integrity="sha384-ZBXiYtYQ6hJ2Y0ZNoYuI+Nq5MqWBr+chMrS/RkXpNzQCApHEhOt2aY8EJgqwHLkJ" crossorigin="anonymous"></script>
<script src="https://unpkg.com/hyperscript.org@0.9.14"></script>
// Component scripts
@input.Script()
@sidebar.Script()
@ -47,6 +49,7 @@ templ Base(props ...SEOProps) {
@calendar.Script()
@datepicker.Script()
@progress.Script()
@tagsinput.Script()
// Site-wide enhancements
@themeScript()
// Must run before body to prevent flash

View file

@ -76,7 +76,7 @@ templ Space(title string, space *model.Space) {
IsActive: ctxkeys.URLPath(ctx) == "/app/spaces/"+space.ID+"/expenses",
Tooltip: "Expenses",
}) {
@icon.Landmark(icon.Props{Class: "size-4"})
@icon.DollarSign(icon.Props{Class: "size-4"})
<span>Expenses</span>
}
}

View file

@ -19,7 +19,7 @@ templ SpaceTagsPage(space *model.Space, tags []*model.Tag) {
hx-post={ "/app/spaces/" + space.ID + "/tags" }
hx-target="#tags-container"
hx-swap="beforeend"
_="on htmx:afterRequest reset() me"
_="on htmx:afterOnLoad if event.detail.xhr.status == 200 reset() me"
class="flex gap-2 items-start"
>
@csrf.Token()
@ -27,11 +27,6 @@ templ SpaceTagsPage(space *model.Space, tags []*model.Tag) {
Name: "name",
Placeholder: "New tag name...",
})
@input.Input(input.Props{
Type: "color",
Name: "color",
Class: "w-14",
})
@button.Button(button.Props{
Type: button.TypeSubmit,
}) {