package handlers
import (
"net/http"
"strconv"
"time"
"go-crm/internal/db"
"github.com/go-chi/chi/v5"
)
func (a *App) ListServices(w http.ResponseWriter, r *http.Request) {
accountID, ok := a.requireAuth(w, r)
if !ok {
return
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
clientID, _ := strconv.ParseInt(r.URL.Query().Get("client_id"), 10, 64)
if limit == 0 {
limit = 20
}
services, err := db.ListServices(a.DB, accountID, clientID, limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
clients, err := db.ListClients(a.DB, accountID, limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var clientOptions string
for _, c := range clients {
clientOptions += ``
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(`
Services
`))
}
func (a *App) CreateService(w http.ResponseWriter, r *http.Request) {
accountID, ok := a.requireAuth(w, r)
if !ok {
return
}
r.ParseForm()
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
var checkID int64
err := a.DB.QueryRow("SELECT client_id FROM clients WHERE client_id = ? AND account_id = ?", clientID, accountID).Scan(&checkID)
if err != nil {
http.Error(w, "Invalid client", http.StatusBadRequest)
return
}
price, _ := strconv.ParseFloat(r.FormValue("price"), 64)
service := db.Service{
ClientID: clientID,
Name: r.FormValue("name"),
Price: price,
Description: r.FormValue("description"),
Duration: r.FormValue("duration"),
CreatedAt: time.Now().Unix(),
}
if err := service.Create(a.DB); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("HX-Refresh", "true")
}
func (a *App) ViewService(w http.ResponseWriter, r *http.Request) {
_, ok := a.requireAuth(w, r)
if !ok {
return
}
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
var s db.Service
err := a.DB.QueryRow("SELECT service_id, client_id, name, price, description, duration, created_at FROM services WHERE service_id = ?", id).Scan(&s.ServiceID, &s.ClientID, &s.Name, &s.Price, &s.Description, &s.Duration, &s.CreatedAt)
if err != nil {
http.Error(w, "Service not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(`` + s.Name + `
Price: ` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `
Description: ` + s.Description + `
Duration: ` + s.Duration + `
Back