package handlers
import (
"database/sql"
"net/http"
"strconv"
"time"
"go-crm/internal/db"
"github.com/go-chi/chi/v5"
)
func ListServices(w http.ResponseWriter, r *http.Request) {
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(DB, clientID, limit, offset)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`
Services
| Name | Price | Duration | Actions |
`))
for _, s := range services {
w.Write([]byte(`| ` + s.Name + ` | ` + strconv.FormatFloat(s.Price, 'f', 2, 64) + ` | ` + s.Duration + ` | View |
`))
}
w.Write([]byte(`
`))
}
func CreateService(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64)
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(DB); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("HX-Refresh", "true")
}
func ViewService(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10)
var s db.Service
err := 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")
w.Write([]byte(`` + s.Name + `
Price: ` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `
Description: ` + s.Description + `
Duration: ` + s.Duration + `
Back