package main import ( "encoding/json" "fmt" "net/http" "strings" ) // ============================================================================= // HOTEL CONFIG HANDLER — Phase 8B-2 // ============================================================================= // // Endpoint: // GET /api/admin/hotel-config → handleHotelConfigGet (semua config) // PUT /api/admin/hotel-config → handleHotelConfigUpdate (bulk update) // GET /api/admin/hotel-config/{key} → handleHotelConfigGetKey (satu key) // PUT /api/admin/hotel-config/{key} → handleHotelConfigUpdateKey (satu key) // // Hotel Config menggunakan key-value pattern. // Key-key standar di-seed saat DB pertama kali dibuat (hotel_master_db.go). // Consumer API mendapatkan semua config sekaligus (map[key]={value, label, desc}). // Update bisa bulk (PUT /hotel-config dengan array) atau single key. // ============================================================================= // HotelConfigItem adalah representasi satu item konfigurasi. type HotelConfigItem struct { ID int `json:"id"` Key string `json:"key"` Value string `json:"value"` Label string `json:"label"` Description string `json:"description"` UpdatedAt string `json:"updated_at"` } // handleHotelConfigDispatch menangani routing untuk /api/admin/hotel-config // dan /api/admin/hotel-config/{key} func handleHotelConfigDispatch(w http.ResponseWriter, r *http.Request) { // Path: /api/admin/hotel-config atau /api/admin/hotel-config/some_key path := strings.TrimPrefix(r.URL.Path, "/api/admin/hotel-config") path = strings.TrimPrefix(path, "/") key := strings.TrimSpace(path) if key == "" { // Collection endpoint switch r.Method { case http.MethodGet: handleHotelConfigGet(w, r) case http.MethodPut: handleHotelConfigUpdate(w, r) default: writeDashError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method tidak diizinkan.", fmt.Sprintf("Method %s tidak didukung.", r.Method)) } return } // Single key endpoint switch r.Method { case http.MethodGet: handleHotelConfigGetKey(w, r, key) case http.MethodPut: handleHotelConfigUpdateKey(w, r, key) default: writeDashError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method tidak diizinkan.", fmt.Sprintf("Method %s tidak didukung.", r.Method)) } } // handleHotelConfigGet melayani GET /api/admin/hotel-config // Mengembalikan semua config sebagai map key → HotelConfigItem func handleHotelConfigGet(w http.ResponseWriter, r *http.Request) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } rows, err := DB.Query(` SELECT id, `+"`key`"+`, value, label, description, updated_at FROM hotel_configs ORDER BY id ASC`) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal mengambil konfigurasi.", err.Error()) return } defer rows.Close() configs := map[string]HotelConfigItem{} configList := []HotelConfigItem{} for rows.Next() { var c HotelConfigItem if err := rows.Scan(&c.ID, &c.Key, &c.Value, &c.Label, &c.Description, &c.UpdatedAt); err != nil { continue } configs[c.Key] = c configList = append(configList, c) } writeDashSuccess(w, map[string]interface{}{ "configs": configs, "list": configList, }) } // handleHotelConfigGetKey melayani GET /api/admin/hotel-config/{key} func handleHotelConfigGetKey(w http.ResponseWriter, r *http.Request, key string) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var c HotelConfigItem err := DB.QueryRow(` SELECT id, `+"`key`"+`, value, label, description, updated_at FROM hotel_configs WHERE `+"`key`"+` = ?`, key).Scan( &c.ID, &c.Key, &c.Value, &c.Label, &c.Description, &c.UpdatedAt) if err != nil { writeDashError(w, http.StatusNotFound, "NOT_FOUND", "Konfigurasi tidak ditemukan.", fmt.Sprintf("Config key '%s' tidak ada.", key)) return } writeDashSuccess(w, c) } // handleHotelConfigUpdate melayani PUT /api/admin/hotel-config (bulk update) // Input: { "updates": { "key1": "value1", "key2": "value2" } } func handleHotelConfigUpdate(w http.ResponseWriter, r *http.Request) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var input struct { Updates map[string]string `json:"updates"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeDashError(w, http.StatusBadRequest, "INVALID_JSON", "Request body tidak valid.", err.Error()) return } if len(input.Updates) == 0 { writeDashError(w, http.StatusBadRequest, "EMPTY_UPDATES", "Tidak ada data yang diperbarui.", "Field 'updates' tidak boleh kosong.") return } now := nowMySQL() updated := []string{} notFound := []string{} for key, value := range input.Updates { // Validasi key tidak kosong key = strings.TrimSpace(key) if key == "" { continue } result, err := DB.Exec(`UPDATE hotel_configs SET value=?, updated_at=? WHERE `+"`key`"+`=?`, value, now, key) if err != nil { continue } rows, _ := result.RowsAffected() if rows == 0 { notFound = append(notFound, key) } else { updated = append(updated, key) } } writeDashSuccess(w, map[string]interface{}{ "updated": updated, "not_found": notFound, "message": fmt.Sprintf("%d konfigurasi berhasil diperbarui.", len(updated)), }) } // handleHotelConfigUpdateKey melayani PUT /api/admin/hotel-config/{key} // Input: { "value": "new_value" } func handleHotelConfigUpdateKey(w http.ResponseWriter, r *http.Request, key string) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var input struct { Value string `json:"value"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeDashError(w, http.StatusBadRequest, "INVALID_JSON", "Request body tidak valid.", err.Error()) return } now := nowMySQL() result, err := DB.Exec(`UPDATE hotel_configs SET value=?, updated_at=? WHERE `+"`key`"+`=?`, input.Value, now, key) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal memperbarui konfigurasi.", err.Error()) return } rows, _ := result.RowsAffected() if rows == 0 { // Key belum ada — insert baru (upsert behavior) _, err = DB.Exec(` INSERT INTO hotel_configs (`+"`key`"+`, value, label, description, updated_at) VALUES (?, ?, ?, '', ?)`, key, input.Value, key, now) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal menyimpan konfigurasi baru.", err.Error()) return } } handleHotelConfigGetKey(w, r, key) }