refactor: add helper functions for subtotal, cart empty, and cart item count

This commit is contained in:
2026-04-24 10:29:15 +02:00
parent 280585c2d0
commit abe11853f6
6 changed files with 32 additions and 19 deletions

View File

@@ -28,7 +28,7 @@ func (m Model) updateCartViewport() Model {
}
func (m Model) generateCartContent() string {
if len(m.Cart) == 0 {
if m.IsCartEmpty() {
emptyStyle := m.theme.TextDim().
Align(lipgloss.Center).
Width(m.widthContent).
@@ -179,7 +179,7 @@ func (m Model) CartUpdate(msg tea.Msg) (Model, tea.Cmd) {
return m, m.syncCartItemCmd(coffeeID, newQty)
}
case "p", "enter":
if len(m.Cart) > 0 {
if !m.IsCartEmpty() {
return m.ShippingSwitch()
}
}

View File

@@ -150,10 +150,8 @@ func (m Model) generateReviewContent() string {
}
view.WriteString("\n")
subtotal := 0
for _, item := range m.GetCartItemsSlice() {
subtotal += item.Coffee.Price * item.Quantity
}
subtotal := m.CalculateSubtotal()
view.WriteString(fmt.Sprintf("subtotal: %s\n", formatUSD(subtotal)))
view.WriteString(m.theme.TextAccent().Render(fmt.Sprintf("total: %s", formatUSD(subtotal))) + "\n")
view.WriteString("\n")

View File

@@ -135,7 +135,7 @@ func (m Model) BuildFooter() string {
}
} else if m.currentPage == cartPage {
// In cart view, show proceed option
if len(m.Cart) > 0 {
if !m.IsCartEmpty() {
footerText = fmt.Sprintf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s",
keybindStyle.Render("j/k"),
descStyle.Render("items"),

View File

@@ -8,12 +8,8 @@ import (
func (m Model) BuildHeader() string {
// Calculate cart total and item count
total := 0
itemCount := 0
for _, item := range m.Cart {
total += item.Quantity * item.Coffee.Price
itemCount += item.Quantity
}
total := m.CalculateSubtotal()
itemCount := m.CartItemCount()
// Define colors
grayStyle := m.theme.TextBody()

View File

@@ -32,12 +32,8 @@ func (m Model) BuildMenuView() string {
hint := base.Render("press esc to close")
itemCount := 0
total := 0
for _, item := range m.Cart {
total += item.Quantity * item.Coffee.Price
itemCount += item.Quantity
}
total := m.CalculateSubtotal()
itemCount := m.CartItemCount()
cartHint := base.Render(fmt.Sprintf("cart $%.2f [%d]", float64(total)/100, itemCount))

View File

@@ -755,6 +755,29 @@ func (m Model) GetCartItemsSlice() []*models.CartItem {
return items
}
// IsCartEmpty returns true when the cart has no items
func (m Model) IsCartEmpty() bool {
return len(m.Cart) == 0
}
// CartItemCount returns the total number of items (sum of quanities) in the cart
func (m Model) CartItemCount() int {
count := 0
for _, item := range m.Cart {
count += item.Quantity
}
return count
}
// CalculateSubtotal returns the cart subtotal in cents
func (m Model) CalculateSubtotal() int {
subtotal := 0
for _, item := range m.Cart {
subtotal += item.Coffee.Price * item.Quantity
}
return subtotal
}
// NewModel creates a new model using the default renderer.
func NewModel(username string) Model {
return newModelWithRenderer(username, lipgloss.DefaultRenderer())