package handlers import ( "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 } clients, err := db.ListClients(DB, 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") w.Write([]byte(`

Services

`)) for _, s := range services { w.Write([]byte(``)) } w.Write([]byte(`
NamePriceDurationActions
` + s.Name + `` + strconv.FormatFloat(s.Price, 'f', 2, 64) + `` + s.Duration + `View
`)) } 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, 64) 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`)) } func UpdateService(w http.ResponseWriter, r *http.Request) { id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) r.ParseForm() clientID, _ := strconv.ParseInt(r.FormValue("client_id"), 10, 64) price, _ := strconv.ParseFloat(r.FormValue("price"), 64) _, err := DB.Exec("UPDATE services SET client_id=?, name=?, price=?, description=?, duration=? WHERE service_id=?", clientID, r.FormValue("name"), price, r.FormValue("description"), r.FormValue("duration"), id) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("HX-Refresh", "true") } func DeleteService(w http.ResponseWriter, r *http.Request) { id, _ := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) DB.Exec("DELETE FROM services WHERE service_id = ?", id) }