feat(backend): add done-for-day summary with DailySummary, week aggregation, exceptional hours support

Introduce DoneForDay state and DailySummary struct in current-next endpoint. Adds computeAggregateSummary for daily/weekly revenue, tips, duration, customer stats, and new booking services. Adds isDayOpen, findWeekSummaryRange, and getClosingTime with exceptional hours lookup. Scopes all current/next queries to today's date range.

Ultraworked with Sisyphus

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-06-15 20:27:36 +01:00
co-authored by Sisyphus
parent 6c27a44302
commit 2b942a48bd
2 changed files with 807 additions and 24 deletions
+354 -2
View File
@@ -10,6 +10,9 @@ package admin
// - GetTodayAppointmentsHandler: GET /api/admin/today/appointments - Get today's bookings // - GetTodayAppointmentsHandler: GET /api/admin/today/appointments - Get today's bookings
// - GetPendingApprovalsHandler: GET /api/admin/today/pending-approvals - Get pending bookings // - GetPendingApprovalsHandler: GET /api/admin/today/pending-approvals - Get pending bookings
// - Auto-status transitions: Silent background updates on GET requests // - Auto-status transitions: Silent background updates on GET requests
// - Closed day summary: done_for_day=true, summary_scope="week", total_bookings excludes cancelled
// - Week summary on tomorrow-closed: day summary + week_summary when tomorrow is closed
// - Exceptional hours: Exceptional closed day via groups + applications overrides defaults
// //
// Authentication: All endpoints require admin role (403 for non-admins). // Authentication: All endpoints require admin role (403 for non-admins).
// //
@@ -107,10 +110,12 @@ func TestAdminToday_CurrentNext(t *testing.T) {
func TestAdminToday_CurrentNext_ClosingTime(t *testing.T) { func TestAdminToday_CurrentNext_ClosingTime(t *testing.T) {
resetTestData(t) resetTestData(t)
// Seed working hours for today (query uses current weekday) // Seed working hours for today (DB uses 0=Monday, 6=Sunday)
todayWeekday := int(time.Now().Weekday()) todayWeekday := int(time.Now().Weekday())
if todayWeekday == 0 { if todayWeekday == 0 {
todayWeekday = 7 todayWeekday = 6
} else {
todayWeekday -= 1
} }
_, err := db.DB.Exec(context.Background(), ` _, err := db.DB.Exec(context.Background(), `
INSERT INTO working_hours (weekday, start_time, end_time, is_open) INSERT INTO working_hours (weekday, start_time, end_time, is_open)
@@ -596,6 +601,353 @@ func TestAdminToday_AutoTransition_CurrentNextHandler(t *testing.T) {
} }
} }
// =============================================================================
// Week Summary Tests — covering "Closed today" and "Tomorrow is closed" states
// =============================================================================
// TestAdminToday_ClosedDay_Summary verifies that on a closed day:
// - done_for_day = true
// - summary_scope = "week" (closed day summary)
// - total_bookings counts non-cancelled bookings, excluding cancelled/no_show
// - The range includes bookings from both the closed day and prior open days
func TestAdminToday_ClosedDay_Summary(t *testing.T) {
resetTestData(t)
ctx := context.Background()
now := time.Now()
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
yesterdayStart := todayStart.AddDate(0, 0, -1)
// Create test user
var userID string
err := db.DB.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Seed working hours: today is CLOSED, all other days OPEN
todayWeekday := int(now.Weekday())
if todayWeekday == 0 {
todayWeekday = 6
} else {
todayWeekday -= 1
}
_, err = db.DB.Exec(ctx, `
INSERT INTO working_hours (weekday, start_time, end_time, is_open)
VALUES ($1, '00:00', '00:00', false)
ON CONFLICT (weekday) DO UPDATE SET start_time = '00:00', end_time = '00:00', is_open = false
`, todayWeekday)
if err != nil {
t.Fatalf("failed to seed today as closed: %v", err)
}
// Mark all other weekdays as open
for wd := 0; wd <= 6; wd++ {
if wd != todayWeekday {
_, err = db.DB.Exec(ctx, `
INSERT INTO working_hours (weekday, start_time, end_time, is_open)
VALUES ($1, '09:00', '17:00', true)
ON CONFLICT (weekday) DO UPDATE SET start_time = '09:00', end_time = '17:00', is_open = true
`, wd)
if err != nil {
t.Fatalf("failed to seed weekday %d as open: %v", wd, err)
}
}
}
// Create bookings:
// - Yesterday: 1 completed
// - Today: 2 completed, 1 client_cancelled, 1 no_show
// total_bookings should count: 1 (yesterday) + 2 (today completed) = 3
// NOT counting: client_cancelled, no_show
yesterdayBookings := []struct {
startTime time.Time
status string
}{
{yesterdayStart.Add(9 * time.Hour), "completed"},
}
todayBookings := []struct {
startTime time.Time
status string
}{
{todayStart.Add(9 * time.Hour), "completed"},
{todayStart.Add(10 * time.Hour), "completed"},
{todayStart.Add(11 * time.Hour), "client_cancelled"},
{todayStart.Add(12 * time.Hour), "no_show"},
}
for _, b := range yesterdayBookings {
_, err = db.DB.Exec(ctx, `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, $2, $3, NOW())
`, userID, b.startTime, b.status)
if err != nil {
t.Fatalf("failed to create yesterday %s booking: %v", b.status, err)
}
}
for _, b := range todayBookings {
_, err = db.DB.Exec(ctx, `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, $2, $3, NOW())
`, userID, b.startTime, b.status)
if err != nil {
t.Fatalf("failed to create today %s booking: %v", b.status, err)
}
}
handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.CurrentNextResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.DoneForDay == nil || !*response.DoneForDay {
t.Error("expected done_for_day = true on a closed day")
}
if response.Summary == nil {
t.Fatal("expected summary on a closed day")
}
if response.Summary.SummaryScope != "week" {
t.Errorf("expected summary_scope 'week' for closed day, got '%s'", response.Summary.SummaryScope)
}
if response.Summary.TotalBookings != 3 {
t.Errorf("expected total_bookings = 3 (1 yesterday + 2 today completed, excluding cancelled/no_show), got %d", response.Summary.TotalBookings)
}
if response.Summary.CustomersServed != 1 {
t.Errorf("expected customers_served = 1 (all non-cancelled bookings are by same distinct user), got %d", response.Summary.CustomersServed)
}
}
// TestAdminToday_WeekSummary_TomorrowClosed verifies that when today is open
// and all current+next appointments are done, but tomorrow is closed:
// - summary_scope = "day" (today's summary)
// - week_summary is present with summary_scope = "week"
func TestAdminToday_WeekSummary_TomorrowClosed(t *testing.T) {
resetTestData(t)
ctx := context.Background()
now := time.Now()
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
// Create test user
var userID string
err := db.DB.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Compute weekdays
sundayGo := int(time.Sunday)
todayWeekday := int(now.Weekday())
if todayWeekday == 0 {
todayWeekday = 6
} else {
todayWeekday -= 1
}
tomorrowWeekday := (todayWeekday + 1) % 7
// Mark today as OPEN, tomorrow as CLOSED
for wd := 0; wd <= 6; wd++ {
isOpen := true
startTime := "09:00"
endTime := "17:00"
if wd == tomorrowWeekday {
isOpen = false
startTime = "00:00"
endTime = "00:00"
}
_, err = db.DB.Exec(ctx, `
INSERT INTO working_hours (weekday, start_time, end_time, is_open)
VALUES ($1, $2, $3, $4)
ON CONFLICT (weekday) DO UPDATE SET start_time = $2, end_time = $3, is_open = $4
`, wd, startTime, endTime, isOpen)
if err != nil {
t.Fatalf("failed to seed working_hours weekday %d: %v", wd, err)
}
}
_ = sundayGo // unused but kept for clarity
// Create a completed booking for today (so we're done-for-day but today is open)
_, err = db.DB.Exec(ctx, `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, $2, 'completed', NOW())
`, userID, todayStart.Add(9*time.Hour))
if err != nil {
t.Fatalf("failed to create completed booking: %v", err)
}
handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.CurrentNextResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.DoneForDay == nil || !*response.DoneForDay {
t.Error("expected done_for_day = true (no upcoming bookings)")
}
if response.Summary == nil {
t.Fatal("expected daily summary")
}
if response.Summary.SummaryScope != "day" {
t.Errorf("expected summary_scope 'day' for open day, got '%s'", response.Summary.SummaryScope)
}
if response.WeekSummary == nil {
t.Fatal("expected week_summary when tomorrow is closed")
}
if response.WeekSummary.SummaryScope != "week" {
t.Errorf("expected week_summary summary_scope 'week', got '%s'", response.WeekSummary.SummaryScope)
}
}
// TestAdminToday_ExceptionalHours_ClosedDay verifies that exceptional hours
// (via exceptional_working_hours + groups + applications) correctly make today
// a closed day, even when default working_hours says today is open.
// This tests the column name fix: monday_week_start → week_start.
func TestAdminToday_ExceptionalHours_ClosedDay(t *testing.T) {
resetTestData(t)
ctx := context.Background()
now := time.Now()
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
// Compute today's weekday (our system: 0=Monday, 6=Sunday)
todayWeekday := int(now.Weekday())
if todayWeekday == 0 {
todayWeekday = 6
} else {
todayWeekday -= 1
}
// Seed DEFAULT working_hours: today is OPEN (this should be overridden by exceptional hours)
_, err := db.DB.Exec(ctx, `
INSERT INTO working_hours (weekday, start_time, end_time, is_open)
VALUES ($1, '09:00', '17:00', true)
ON CONFLICT (weekday) DO UPDATE SET start_time = '09:00', end_time = '17:00', is_open = true
`, todayWeekday)
if err != nil {
t.Fatalf("failed to seed default working_hours: %v", err)
}
// Make all other weekdays open too
for wd := 0; wd <= 6; wd++ {
if wd != todayWeekday {
_, err = db.DB.Exec(ctx, `
INSERT INTO working_hours (weekday, start_time, end_time, is_open)
VALUES ($1, '09:00', '17:00', true)
ON CONFLICT (weekday) DO UPDATE SET start_time = '09:00', end_time = '17:00', is_open = true
`, wd)
if err != nil {
t.Fatalf("failed to seed default working_hours weekday %d: %v", wd, err)
}
}
}
// Now seed EXCEPTIONAL hours making today CLOSED.
// Need: group → hours → application with week_start = Monday of this week
weekday := now.Weekday()
daysSinceMonday := int(weekday) - 1
if daysSinceMonday < 0 {
daysSinceMonday = 6
}
monday := now.AddDate(0, 0, -daysSinceMonday)
mondayStr := monday.Format("2006-01-02")
var groupID int
err = db.DB.QueryRow(ctx, `
INSERT INTO exceptional_working_hours_groups (name, description)
VALUES ('Test Closure', 'Exceptional closure for test')
RETURNING id
`).Scan(&groupID)
if err != nil {
t.Fatalf("failed to create exceptional hours group: %v", err)
}
_, err = db.DB.Exec(ctx, `
INSERT INTO exceptional_working_hours (group_id, weekday, start_time, end_time, is_open)
VALUES ($1, $2, '00:00', '00:00', false)
`, groupID, todayWeekday)
if err != nil {
t.Fatalf("failed to seed exceptional hours: %v", err)
}
_, err = db.DB.Exec(ctx, `
INSERT INTO exceptional_group_applications (group_id, week_start)
VALUES ($1, $2::date)
`, groupID, mondayStr)
if err != nil {
t.Fatalf("failed to seed exceptional group application: %v", err)
}
// Create a completed booking on today (to populate summary)
var userID string
err = db.DB.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
_, err = db.DB.Exec(ctx, `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, $2, 'completed', NOW())
`, userID, todayStart.Add(9*time.Hour))
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Call the handler — with exceptional hours making today closed,
// it should use the closed-day branch (summary_scope = "week")
handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.CurrentNextResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.DoneForDay == nil || !*response.DoneForDay {
t.Error("expected done_for_day = true (exceptional closed day)")
}
if response.Summary == nil {
t.Fatal("expected summary on exceptional closed day")
}
// summary_scope should be "week" because today is a closed day via exceptional hours
if response.Summary.SummaryScope != "week" {
t.Errorf("expected summary_scope 'week' for exceptional closed day, got '%s'", response.Summary.SummaryScope)
}
if response.ClosingTime != nil {
t.Errorf("expected no closing_time on closed day, got '%s'", *response.ClosingTime)
}
if response.Summary.TotalBookings != 1 {
t.Errorf("expected total_bookings = 1 (completed booking), got %d", response.Summary.TotalBookings)
}
}
// TestAdminNotifications_List is skipped (WIP) - tests that an admin // TestAdminNotifications_List is skipped (WIP) - tests that an admin
// can list all their notifications. // can list all their notifications.
func TestAdminNotifications_List(t *testing.T) { func TestAdminNotifications_List(t *testing.T) {
+453 -22
View File
@@ -3,8 +3,10 @@ package today
import ( import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt"
"log" "log"
"net/http" "net/http"
"strings"
"time" "time"
"crussell/db" "crussell/db"
@@ -36,15 +38,44 @@ type AppointmentInfo struct {
TotalAmount float64 `json:"total_amount"` TotalAmount float64 `json:"total_amount"`
} }
type ServiceBookingCount struct {
ServiceName string `json:"service_name"`
Count int `json:"count"`
}
type DailySummary struct {
TotalPaymentsToday float64 `json:"total_payments_today"`
TotalTipsToday float64 `json:"total_tips_today"`
AmountDueToday float64 `json:"amount_due_today"`
TotalDurationSpent int `json:"total_duration_spent"`
CustomersServed int `json:"customers_served"`
TotalBookings int `json:"total_bookings"`
NewCustomers int `json:"new_customers"`
ReturningCustomers int `json:"returning_customers"`
GuestCustomers int `json:"guest_customers"`
GiftCardsSold int `json:"gift_cards_sold"`
LastCustomerName string `json:"last_customer_name,omitempty"`
LastCustomerVisits int `json:"last_customer_visits,omitempty"`
NewBookingServices []ServiceBookingCount `json:"new_booking_services,omitempty"`
SummaryScope string `json:"summary_scope"`
SummaryStartDate string `json:"summary_start_date"`
SummaryEndDate string `json:"summary_end_date"`
}
type CurrentNextResponse struct { type CurrentNextResponse struct {
Current *AppointmentInfo `json:"current"` Current *AppointmentInfo `json:"current"`
Next *AppointmentInfo `json:"next"` Next *AppointmentInfo `json:"next"`
ClosingTime *string `json:"closing_time,omitempty"` // "HH:MM" format ClosingTime *string `json:"closing_time,omitempty"`
DoneForDay *bool `json:"done_for_day,omitempty"`
Summary *DailySummary `json:"summary,omitempty"`
WeekSummary *DailySummary `json:"week_summary,omitempty"`
} }
// GET /api/admin/today/current-next // GET /api/admin/today/current-next
func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) { func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) {
now := time.Now() now := time.Now()
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
todayEnd := todayStart.Add(24 * time.Hour)
// Auto-transition confirmed bookings that have started but not ended to in_progress // Auto-transition confirmed bookings that have started but not ended to in_progress
_, err := db.DB.Exec(r.Context(), ` _, err := db.DB.Exec(r.Context(), `
@@ -107,41 +138,44 @@ func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) {
SELECT b.id, b.start_time, b.status, b.notes, b.user_id SELECT b.id, b.start_time, b.status, b.notes, b.user_id
FROM bookings b FROM bookings b
WHERE b.status = 'in_progress' WHERE b.status = 'in_progress'
AND b.start_time >= $1
AND b.start_time < $2
ORDER BY b.start_time ASC ORDER BY b.start_time ASC
LIMIT 1 LIMIT 1
`) `, todayStart, todayEnd)
if err != nil && err != sql.ErrNoRows { if err != nil && err != sql.ErrNoRows {
log.Printf("Error querying current appointment: %v", err) log.Printf("Error querying current appointment: %v", err)
// Don't fail, continue to find next
} }
if err == nil && currentBooking != nil { if err == nil && currentBooking != nil {
current = currentBooking current = currentBooking
// Also fetch the appointment AFTER this one for free time calculation // Also fetch the appointment AFTER this one within today
nextBooking, err := fetchAppointment(r, ` nextBooking, err := fetchAppointment(r, `
SELECT b.id, b.start_time, b.status, b.notes, b.user_id SELECT b.id, b.start_time, b.status, b.notes, b.user_id
FROM bookings b FROM bookings b
WHERE b.start_time > $1 WHERE b.start_time > $1
AND b.start_time < $2
AND (b.status = 'confirmed' OR b.status = 'pending' OR b.status = 'in_progress') AND (b.status = 'confirmed' OR b.status = 'pending' OR b.status = 'in_progress')
ORDER BY b.start_time ASC ORDER BY b.start_time ASC
LIMIT 1 LIMIT 1
`, currentBooking.StartTime) `, currentBooking.StartTime, todayEnd)
if err == nil && nextBooking != nil { if err == nil && nextBooking != nil {
next = nextBooking next = nextBooking
} }
} else { } else {
// No current in-progress appointment, find the next upcoming one // No current in-progress appointment, find the next upcoming one within today
nextBooking, err := fetchAppointment(r, ` nextBooking, err := fetchAppointment(r, `
SELECT b.id, b.start_time, b.status, b.notes, b.user_id SELECT b.id, b.start_time, b.status, b.notes, b.user_id
FROM bookings b FROM bookings b
WHERE b.start_time >= $1 WHERE b.start_time >= $1
AND b.start_time < $2
AND (b.status = 'confirmed' OR b.status = 'pending') AND (b.status = 'confirmed' OR b.status = 'pending')
ORDER BY b.start_time ASC ORDER BY b.start_time ASC
LIMIT 1 LIMIT 1
`, now) `, now, todayEnd)
if err != nil && err != sql.ErrNoRows { if err != nil && err != sql.ErrNoRows {
log.Printf("Error querying next appointment: %v", err) log.Printf("Error querying next appointment: %v", err)
@@ -155,10 +189,11 @@ func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) {
SELECT b.id, b.start_time, b.status, b.notes, b.user_id SELECT b.id, b.start_time, b.status, b.notes, b.user_id
FROM bookings b FROM bookings b
WHERE b.start_time > $1 WHERE b.start_time > $1
AND b.start_time < $2
AND (b.status = 'confirmed' OR b.status = 'pending' OR b.status = 'in_progress') AND (b.status = 'confirmed' OR b.status = 'pending' OR b.status = 'in_progress')
ORDER BY b.start_time ASC ORDER BY b.start_time ASC
LIMIT 1 LIMIT 1
`, nextBooking.StartTime) `, nextBooking.StartTime, todayEnd)
if err == nil && afterNext != nil { if err == nil && afterNext != nil {
next = afterNext next = afterNext
@@ -171,16 +206,47 @@ func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) {
Next: next, Next: next,
} }
weekday := int(now.Weekday()) // Get closing time respecting exceptional hours
if weekday == 0 { todayOpen := isDayOpen(r, now)
weekday = 7 if todayOpen {
closeTime := getClosingTime(r, now)
if closeTime != "" {
response.ClosingTime = &closeTime
}
} }
var closingTime sql.NullString
_ = db.DB.QueryRow(r.Context(), ` // Determine if we're done for the day: no current, no next
SELECT end_time::text FROM working_hours WHERE weekday = $1 AND is_open = true if current == nil && next == nil {
`, weekday).Scan(&closingTime) done := true
if closingTime.Valid { response.DoneForDay = &done
response.ClosingTime = &closingTime.String
if todayOpen {
// Regular done-for-the-day: show daily summary
summary := computeAggregateSummary(r, todayStart, todayEnd)
summary.SummaryScope = "day"
summary.SummaryStartDate = todayStart.Format("2006-01-02")
summary.SummaryEndDate = todayEnd.Format("2006-01-02")
response.Summary = summary
// If tomorrow is closed, also compute a week summary
tomorrow := now.AddDate(0, 0, 1)
if !isDayOpen(r, tomorrow) {
weekStart, _ := findWeekSummaryRange(r, tomorrow)
ws := computeAggregateSummary(r, weekStart, todayEnd)
ws.SummaryScope = "week"
ws.SummaryStartDate = weekStart.Format("2006-01-02")
ws.SummaryEndDate = todayStart.Format("2006-01-02")
response.WeekSummary = ws
}
} else {
// Closed day: show week summary — from start of last work period to now
weekStart, _ := findWeekSummaryRange(r, now)
summary := computeAggregateSummary(r, weekStart, todayEnd)
summary.SummaryScope = "week"
summary.SummaryStartDate = weekStart.Format("2006-01-02")
summary.SummaryEndDate = todayStart.Format("2006-01-02")
response.Summary = summary
}
} }
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
@@ -192,6 +258,371 @@ func GetCurrentAndNextHandler(w http.ResponseWriter, r *http.Request) {
} }
} }
func computeAggregateSummary(r *http.Request, rangeStart, rangeEnd time.Time) *DailySummary {
summary := &DailySummary{}
// 1. Total payments today (non-tip, completed)
_ = db.DB.QueryRow(r.Context(), `
SELECT COALESCE(SUM(p.amount), 0)
FROM bookings b
JOIN payments p ON p.booking_id = b.id
WHERE b.start_time >= $1 AND b.start_time < $2
AND p.status = 'completed'
AND p.payment_type != 'tip'
`, rangeStart, rangeEnd).Scan(&summary.TotalPaymentsToday)
// 2. Total tips today (completed)
_ = db.DB.QueryRow(r.Context(), `
SELECT COALESCE(SUM(p.amount), 0)
FROM bookings b
JOIN payments p ON p.booking_id = b.id
WHERE b.start_time >= $1 AND b.start_time < $2
AND p.status = 'completed'
AND p.payment_type = 'tip'
`, rangeStart, rangeEnd).Scan(&summary.TotalTipsToday)
// 3. Amount still due from today's non-cancelled bookings
_ = db.DB.QueryRow(r.Context(), `
SELECT COALESCE(SUM(sub.amount_due), 0)
FROM (
SELECT
b.id,
COALESCE(service_total, 0) - COALESCE(payment_total, 0) AS amount_due
FROM bookings b
LEFT JOIN (
SELECT booking_id, SUM(amount) AS payment_total
FROM payments
WHERE status = 'completed'
GROUP BY booking_id
) p ON p.booking_id = b.id
LEFT JOIN (
SELECT bs.booking_id, SUM(COALESCE(bs.override_price, s.price)) AS service_total
FROM booking_services bs
JOIN services s ON bs.service_id = s.id
GROUP BY bs.booking_id
) s ON s.booking_id = b.id
LEFT JOIN (
SELECT bcs.booking_id, SUM(COALESCE(bcs.override_price, cs.price)) AS service_total
FROM booking_custom_services bcs
JOIN custom_services cs ON bcs.custom_service_id = cs.id
GROUP BY bcs.booking_id
) cs ON cs.booking_id = b.id
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status NOT IN ('client_cancelled', 'we_cancelled', 'no_show', 'no_deposit')
) sub
WHERE sub.amount_due > 0
`, rangeStart, rangeEnd).Scan(&summary.AmountDueToday)
// 4. Total duration spent in completed + in_progress appointments
_ = db.DB.QueryRow(r.Context(), `
SELECT COALESCE(SUM(duration_minutes), 0) FROM (
SELECT
b.id,
COALESCE(SUM(COALESCE(bs.override_duration_minutes, s.duration_minutes)), 0)
+ COALESCE(SUM(COALESCE(bcs.override_duration_minutes, cs.duration_minutes)), 0)
AS duration_minutes
FROM bookings b
LEFT JOIN booking_services bs ON bs.booking_id = b.id
LEFT JOIN services s ON s.id = bs.service_id
LEFT JOIN booking_custom_services bcs ON bcs.booking_id = b.id
LEFT JOIN custom_services cs ON cs.id = bcs.custom_service_id
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status IN ('completed', 'in_progress')
GROUP BY b.id
) sub
`, rangeStart, rangeEnd).Scan(&summary.TotalDurationSpent)
// 5. Total bookings (completed + in-progress + confirmed, excluding cancelled/no-show)
_ = db.DB.QueryRow(r.Context(), `
SELECT COUNT(DISTINCT b.id)
FROM bookings b
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status NOT IN ('client_cancelled', 'we_cancelled', 'no_show', 'no_deposit')
`, rangeStart, rangeEnd).Scan(&summary.TotalBookings)
// 6. New vs returning customers
_ = db.DB.QueryRow(r.Context(), `
WITH range_customers AS (
SELECT DISTINCT b.user_id
FROM bookings b
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status NOT IN ('client_cancelled', 'we_cancelled', 'no_show')
AND b.user_id IS NOT NULL
)
SELECT
COALESCE(COUNT(*) FILTER (WHERE NOT EXISTS (
SELECT 1 FROM bookings b2
WHERE b2.user_id = rc.user_id AND b2.start_time < $1
LIMIT 1
)), 0) AS new_customers,
COALESCE(COUNT(*) FILTER (WHERE EXISTS (
SELECT 1 FROM bookings b2
WHERE b2.user_id = rc.user_id AND b2.start_time < $1
LIMIT 1
)), 0) AS returning_customers
FROM range_customers rc
`, rangeStart, rangeEnd).Scan(&summary.NewCustomers, &summary.ReturningCustomers)
// 7. Gift cards sold today (non-inventory)
_ = db.DB.QueryRow(r.Context(), `
SELECT COUNT(*)
FROM gift_cards
WHERE created_at >= $1 AND created_at < $2
AND is_inventory = false
`, rangeStart, rangeEnd).Scan(&summary.GiftCardsSold)
// 8. Last completed customer and their total visit count
_ = db.DB.QueryRow(r.Context(), `
SELECT u.fn, COUNT(b2.id)
FROM bookings b
JOIN users u ON u.id = b.user_id
LEFT JOIN bookings b2 ON b2.user_id = b.user_id AND b2.status NOT IN ('client_cancelled', 'we_cancelled')
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status = 'completed'
AND b.user_id IS NOT NULL
GROUP BY u.id, u.fn, b.start_time
ORDER BY b.start_time DESC
LIMIT 1
`, rangeStart, rangeEnd).Scan(&summary.LastCustomerName, &summary.LastCustomerVisits)
// 9. Guest customers (user_id IS NULL)
_ = db.DB.QueryRow(r.Context(), `
SELECT COUNT(DISTINCT b.id)
FROM bookings b
WHERE b.start_time >= $1 AND b.start_time < $2
AND b.status NOT IN ('client_cancelled', 'we_cancelled', 'no_show')
AND b.user_id IS NULL
`, rangeStart, rangeEnd).Scan(&summary.GuestCustomers)
// Customers served = new + returning + guest (distinct people, not bookings)
summary.CustomersServed = summary.NewCustomers + summary.ReturningCustomers + summary.GuestCustomers
// 10. New bookings since last working day close
summary.NewBookingServices = findNewBookingServices(r, rangeStart)
return summary
}
func findNewBookingServices(r *http.Request, rangeStart time.Time) []ServiceBookingCount {
now := time.Now()
// Walk back up to 14 days to find the last working day's closing time
var lastClose time.Time
found := false
for i := 1; i <= 14; i++ {
d := now.AddDate(0, 0, -i)
dateStart := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
weekday := int(d.Weekday())
if weekday == 0 {
weekday = 6
} else {
weekday -= 1
}
// Check if this day has exceptional hours making it open
var exceptionalClose sql.NullString
_ = db.DB.QueryRow(r.Context(), `
SELECT ewh.end_time::text
FROM exceptional_working_hours ewh
JOIN exceptional_working_hours_groups ewhg ON ewhg.id = ewh.group_id
JOIN exceptional_group_applications ega ON ega.group_id = ewhg.id
WHERE ewh.weekday = $1
AND ega.week_start <= $2
AND ega.week_start + INTERVAL '7 days' > $2
AND ewh.is_open = true
LIMIT 1
`, weekday, dateStart).Scan(&exceptionalClose)
if exceptionalClose.Valid {
closeTime := exceptionalClose.String
parts := strings.Split(closeTime, ":")
h, m := 0, 0
fmt.Sscanf(parts[0], "%d", &h)
if len(parts) > 1 {
fmt.Sscanf(parts[1], "%d", &m)
}
lastClose = time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, d.Location())
found = true
break
}
// Check default working hours
var defaultClose sql.NullString
_ = db.DB.QueryRow(r.Context(), `
SELECT end_time::text FROM working_hours
WHERE weekday = $1 AND is_open = true
LIMIT 1
`, weekday).Scan(&defaultClose)
if defaultClose.Valid {
closeTime := defaultClose.String
parts := strings.Split(closeTime, ":")
h, m := 0, 0
fmt.Sscanf(parts[0], "%d", &h)
if len(parts) > 1 {
fmt.Sscanf(parts[1], "%d", &m)
}
lastClose = time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, d.Location())
found = true
break
}
}
if !found {
// Fallback: 5pm yesterday
lastClose = time.Date(now.Year(), now.Month(), now.Day()-1, 17, 0, 0, 0, now.Location())
}
// Query services across all new bookings, aggregated by service name
rows, err := db.DB.Query(r.Context(), `
SELECT name, COUNT(*) as count
FROM (
SELECT s.name FROM booking_services bs2
JOIN services s ON s.id = bs2.service_id
JOIN bookings b ON b.id = bs2.booking_id
WHERE b.created_at > $1 AND b.created_at <= $2
AND b.status != 'pending'
UNION ALL
SELECT cs.name FROM booking_custom_services bcs2
JOIN custom_services cs ON cs.id = bcs2.custom_service_id
JOIN bookings b ON b.id = bcs2.booking_id
WHERE b.created_at > $1 AND b.created_at <= $2
AND b.status != 'pending'
) all_services
GROUP BY name
ORDER BY count DESC, name ASC
`, lastClose, now)
if err != nil {
log.Printf("Failed to fetch new booking services since close: %v", err)
return nil
}
defer rows.Close()
var items []ServiceBookingCount
for rows.Next() {
var item ServiceBookingCount
if err := rows.Scan(&item.ServiceName, &item.Count); err != nil {
log.Printf("Failed to scan new booking service row: %v", err)
continue
}
items = append(items, item)
}
return items
}
func isDayOpen(r *http.Request, date time.Time) bool {
weekday := int(date.Weekday())
if weekday == 0 {
weekday = 6
} else {
weekday -= 1
}
dateStart := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
var exceptionalOpen sql.NullBool
err := db.DB.QueryRow(r.Context(), `
SELECT ewh.is_open
FROM exceptional_working_hours ewh
JOIN exceptional_working_hours_groups ewhg ON ewhg.id = ewh.group_id
JOIN exceptional_group_applications ega ON ega.group_id = ewhg.id
WHERE ewh.weekday = $1
AND ega.week_start <= $2
AND ega.week_start + INTERVAL '7 days' > $2
LIMIT 1
`, weekday, dateStart).Scan(&exceptionalOpen)
if err == nil {
return exceptionalOpen.Bool
}
var isOpen bool
err = db.DB.QueryRow(r.Context(), `
SELECT is_open FROM working_hours WHERE weekday = $1
`, weekday).Scan(&isOpen)
return err == nil && isOpen
}
// findWeekSummaryRange returns the start and end of the working period
// before the current run of consecutive closed days.
// For adjacent closed days (e.g. Sat+Sun), both days show stats for the
// same working period (e.g. Mon-Fri).
func findWeekSummaryRange(r *http.Request, today time.Time) (time.Time, time.Time) {
// Find the start of this run of consecutive closed days
closedRunStart := today
for i := 0; i <= 14; i++ {
d := today.AddDate(0, 0, -i)
if !isDayOpen(r, d) {
closedRunStart = d
} else {
break
}
}
// The working period ends the day before the closed run starts
workingEnd := closedRunStart.AddDate(0, 0, -1)
workingEndStart := time.Date(workingEnd.Year(), workingEnd.Month(), workingEnd.Day(), 0, 0, 0, 0, workingEnd.Location())
// Walk back from workingEnd to find where the previous closed run ended
workingStart := workingEndStart
for i := 0; i <= 14; i++ {
d := workingEnd.AddDate(0, 0, -i)
if !isDayOpen(r, d) {
workingStart = d.AddDate(0, 0, 1) // day after the closed day
workingStart = time.Date(workingStart.Year(), workingStart.Month(), workingStart.Day(), 0, 0, 0, 0, workingStart.Location())
break
}
}
// workingEndEnd is the end boundary (exclusive)
workingEndEnd := workingEndStart.Add(24 * time.Hour)
return workingStart, workingEndEnd
}
func getClosingTime(r *http.Request, date time.Time) string {
weekday := int(date.Weekday())
if weekday == 0 {
weekday = 6
} else {
weekday -= 1
}
dateStart := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
// Check exceptional hours first
var exceptionalClose sql.NullString
err := db.DB.QueryRow(r.Context(), `
SELECT ewh.end_time::text
FROM exceptional_working_hours ewh
JOIN exceptional_working_hours_groups ewhg ON ewhg.id = ewh.group_id
JOIN exceptional_group_applications ega ON ega.group_id = ewhg.id
WHERE ewh.weekday = $1
AND ega.week_start <= $2
AND ega.week_start + INTERVAL '7 days' > $2
AND ewh.is_open = true
LIMIT 1
`, weekday, dateStart).Scan(&exceptionalClose)
if err == nil && exceptionalClose.Valid {
return exceptionalClose.String
}
// Fall back to default working hours
var defaultClose sql.NullString
err = db.DB.QueryRow(r.Context(), `
SELECT end_time::text FROM working_hours WHERE weekday = $1 AND is_open = true
`, weekday).Scan(&defaultClose)
if err == nil && defaultClose.Valid {
return defaultClose.String
}
return ""
}
// Helper function to fetch a single appointment with all details // Helper function to fetch a single appointment with all details
func fetchAppointment(r *http.Request, query string, args ...interface{}) (*AppointmentInfo, error) { func fetchAppointment(r *http.Request, query string, args ...interface{}) (*AppointmentInfo, error) {
var bookingID string var bookingID string
@@ -377,8 +808,8 @@ func GetTodayAppointmentsHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Failed to auto-transition bookings to completed: %v", err) log.Printf("Failed to auto-transition bookings to completed: %v", err)
} }
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) rangeStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
todayEnd := todayStart.Add(24 * time.Hour) todayEnd := rangeStart.Add(24 * time.Hour)
// Fetch all bookings for today // Fetch all bookings for today
rows, err := db.DB.Query(r.Context(), ` rows, err := db.DB.Query(r.Context(), `
@@ -393,7 +824,7 @@ func GetTodayAppointmentsHandler(w http.ResponseWriter, r *http.Request) {
WHERE b.start_time >= $1 WHERE b.start_time >= $1
AND b.start_time < $2 AND b.start_time < $2
ORDER BY b.start_time ASC ORDER BY b.start_time ASC
`, todayStart, todayEnd) `, rangeStart, todayEnd)
if err != nil { if err != nil {
log.Printf("Failed to fetch today's appointments: %v", err) log.Printf("Failed to fetch today's appointments: %v", err)