package main import ( "encoding/json" "fmt" "net/http" "strconv" "strings" ) // ============================================================================= // ROOM TYPE HANDLER — Phase 8B-2 // ============================================================================= // // Endpoint: // GET /api/admin/room-types → handleRoomTypeList // POST /api/admin/room-types → handleRoomTypeCreate // GET /api/admin/room-types/{uuid} → handleRoomTypeShow // PUT /api/admin/room-types/{uuid} → handleRoomTypeUpdate // DELETE /api/admin/room-types/{uuid} → handleRoomTypeDelete (soft delete) // // Room Type adalah master kategori kamar (contoh: Deluxe, Suite, Standard). // Satu Room Type dapat dimiliki oleh banyak Room. // Room Type tidak dapat dihapus jika masih ada Room aktif yang menggunakannya. // ============================================================================= // RoomTypeItem adalah representasi data room type untuk response API. type RoomTypeItem struct { ID int `json:"id"` UUID string `json:"uuid"` Name string `json:"name"` Description string `json:"description"` BasePrice float64 `json:"base_price"` Capacity int `json:"capacity"` Amenities string `json:"amenities"` Active bool `json:"active"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } // handleRoomTypeDispatch menangani routing untuk /api/admin/room-types (collection). func handleRoomTypeDispatch(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: handleRoomTypeList(w, r) case http.MethodPost: handleRoomTypeCreate(w, r) default: writeDashError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method tidak diizinkan.", fmt.Sprintf("Method %s tidak didukung.", r.Method)) } } // handleRoomTypeItemDispatch menangani routing untuk /api/admin/room-types/{uuid}. func handleRoomTypeItemDispatch(w http.ResponseWriter, r *http.Request) { uuid := strings.TrimPrefix(r.URL.Path, "/api/admin/room-types/") if uuid == "" { writeDashError(w, http.StatusBadRequest, "BAD_REQUEST", "UUID room type tidak ditemukan di URL.", "") return } switch r.Method { case http.MethodGet: handleRoomTypeShow(w, r, uuid) case http.MethodPut: handleRoomTypeUpdate(w, r, uuid) case http.MethodDelete: handleRoomTypeDelete(w, r, uuid) default: writeDashError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method tidak diizinkan.", fmt.Sprintf("Method %s tidak didukung.", r.Method)) } } // handleRoomTypeList melayani GET /api/admin/room-types func handleRoomTypeList(w http.ResponseWriter, r *http.Request) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } page, _ := strconv.Atoi(r.URL.Query().Get("page")) if page < 1 { page = 1 } perPage, _ := strconv.Atoi(r.URL.Query().Get("per_page")) if perPage < 1 || perPage > 100 { perPage = 20 } search := strings.TrimSpace(r.URL.Query().Get("search")) var total int countQuery := `SELECT COUNT(*) FROM room_types WHERE active = 1` countArgs := []interface{}{} if search != "" { countQuery += ` AND name LIKE ?` countArgs = append(countArgs, "%"+search+"%") } DB.QueryRow(countQuery, countArgs...).Scan(&total) offset := masterOffset(page, perPage) dataQuery := ` SELECT id, uuid, name, description, base_price, capacity, amenities, active, created_at, updated_at FROM room_types WHERE active = 1` dataArgs := []interface{}{} if search != "" { dataQuery += ` AND name LIKE ?` dataArgs = append(dataArgs, "%"+search+"%") } dataQuery += ` ORDER BY id ASC LIMIT ? OFFSET ?` dataArgs = append(dataArgs, perPage, offset) rows, err := DB.Query(dataQuery, dataArgs...) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal mengambil data room type.", err.Error()) return } defer rows.Close() items := []RoomTypeItem{} for rows.Next() { var rt RoomTypeItem var activeInt int if err := rows.Scan(&rt.ID, &rt.UUID, &rt.Name, &rt.Description, &rt.BasePrice, &rt.Capacity, &rt.Amenities, &activeInt, &rt.CreatedAt, &rt.UpdatedAt); err != nil { continue } rt.Active = activeInt == 1 items = append(items, rt) } writeDashSuccess(w, map[string]interface{}{ "items": items, "pagination": masterPagination(page, perPage, total), }) } // handleRoomTypeCreate melayani POST /api/admin/room-types func handleRoomTypeCreate(w http.ResponseWriter, r *http.Request) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var input struct { Name string `json:"name"` Description string `json:"description"` BasePrice float64 `json:"base_price"` Capacity int `json:"capacity"` Amenities string `json:"amenities"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeDashError(w, http.StatusBadRequest, "INVALID_JSON", "Request body tidak valid.", err.Error()) return } input.Name = strings.TrimSpace(input.Name) if input.Name == "" { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Nama room type tidak boleh kosong.", "Field 'name' wajib diisi.") return } if input.BasePrice < 0 { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Harga dasar tidak valid.", "Field 'base_price' tidak boleh negatif.") return } if input.Capacity < 1 { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Kapasitas tidak valid.", "Field 'capacity' minimal 1.") return } // Cek nama duplikat var existingID int DB.QueryRow(`SELECT id FROM room_types WHERE name = ? AND active = 1`, input.Name).Scan(&existingID) if existingID > 0 { writeDashError(w, http.StatusUnprocessableEntity, "DUPLICATE_NAME", "Nama room type sudah digunakan.", fmt.Sprintf("Room Type '%s' sudah ada.", input.Name)) return } uuid := generateUUID() now := nowMySQL() result, err := DB.Exec(` INSERT INTO room_types (uuid, name, description, base_price, capacity, amenities, active, deleted_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 1, NULL, ?, ?)`, uuid, input.Name, input.Description, input.BasePrice, input.Capacity, input.Amenities, now, now) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal menyimpan room type.", err.Error()) return } id, _ := result.LastInsertId() rt := RoomTypeItem{ ID: int(id), UUID: uuid, Name: input.Name, Description: input.Description, BasePrice: input.BasePrice, Capacity: input.Capacity, Amenities: input.Amenities, Active: true, CreatedAt: now, UpdatedAt: now, } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(map[string]interface{}{ "success": true, "data": rt, "meta": newDashAPIMeta(), }) } // handleRoomTypeShow melayani GET /api/admin/room-types/{uuid} func handleRoomTypeShow(w http.ResponseWriter, r *http.Request, uuid string) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var rt RoomTypeItem var activeInt int err := DB.QueryRow(` SELECT id, uuid, name, description, base_price, capacity, amenities, active, created_at, updated_at FROM room_types WHERE uuid = ? AND active = 1`, uuid).Scan( &rt.ID, &rt.UUID, &rt.Name, &rt.Description, &rt.BasePrice, &rt.Capacity, &rt.Amenities, &activeInt, &rt.CreatedAt, &rt.UpdatedAt) if err != nil { writeDashError(w, http.StatusNotFound, "NOT_FOUND", "Room Type tidak ditemukan.", fmt.Sprintf("Room Type dengan UUID '%s' tidak ada.", uuid)) return } rt.Active = activeInt == 1 writeDashSuccess(w, rt) } // handleRoomTypeUpdate melayani PUT /api/admin/room-types/{uuid} func handleRoomTypeUpdate(w http.ResponseWriter, r *http.Request, uuid string) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var roomTypeID int DB.QueryRow(`SELECT id FROM room_types WHERE uuid = ? AND active = 1`, uuid).Scan(&roomTypeID) if roomTypeID == 0 { writeDashError(w, http.StatusNotFound, "NOT_FOUND", "Room Type tidak ditemukan.", fmt.Sprintf("Room Type dengan UUID '%s' tidak ada.", uuid)) return } var input struct { Name string `json:"name"` Description string `json:"description"` BasePrice float64 `json:"base_price"` Capacity int `json:"capacity"` Amenities string `json:"amenities"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeDashError(w, http.StatusBadRequest, "INVALID_JSON", "Request body tidak valid.", err.Error()) return } input.Name = strings.TrimSpace(input.Name) if input.Name == "" { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Nama room type tidak boleh kosong.", "Field 'name' wajib diisi.") return } if input.BasePrice < 0 { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Harga dasar tidak valid.", "Field 'base_price' tidak boleh negatif.") return } if input.Capacity < 1 { writeDashError(w, http.StatusUnprocessableEntity, "VALIDATION_ERROR", "Kapasitas tidak valid.", "Field 'capacity' minimal 1.") return } var existingID int DB.QueryRow(`SELECT id FROM room_types WHERE name = ? AND active = 1 AND id != ?`, input.Name, roomTypeID).Scan(&existingID) if existingID > 0 { writeDashError(w, http.StatusUnprocessableEntity, "DUPLICATE_NAME", "Nama room type sudah digunakan oleh room type lain.", fmt.Sprintf("Room Type '%s' sudah ada.", input.Name)) return } now := nowMySQL() _, err := DB.Exec(` UPDATE room_types SET name=?, description=?, base_price=?, capacity=?, amenities=?, updated_at=? WHERE uuid=? AND active=1`, input.Name, input.Description, input.BasePrice, input.Capacity, input.Amenities, now, uuid) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal memperbarui room type.", err.Error()) return } handleRoomTypeShow(w, r, uuid) } // handleRoomTypeDelete melayani DELETE /api/admin/room-types/{uuid} (soft delete) func handleRoomTypeDelete(w http.ResponseWriter, r *http.Request, uuid string) { if DB == nil { writeDashError(w, http.StatusServiceUnavailable, "DB_UNAVAILABLE", "Database Master Data tidak tersedia.", "") return } var roomTypeID int DB.QueryRow(`SELECT id FROM room_types WHERE uuid = ? AND active = 1`, uuid).Scan(&roomTypeID) if roomTypeID == 0 { writeDashError(w, http.StatusNotFound, "NOT_FOUND", "Room Type tidak ditemukan.", fmt.Sprintf("Room Type dengan UUID '%s' tidak ada.", uuid)) return } // Cek apakah masih ada room aktif dengan tipe ini var roomCount int DB.QueryRow(`SELECT COUNT(*) FROM rooms WHERE room_type_id = ? AND active = 1`, roomTypeID).Scan(&roomCount) if roomCount > 0 { writeDashError(w, http.StatusUnprocessableEntity, "HAS_ROOMS", "Room Type tidak dapat dihapus karena masih digunakan oleh kamar aktif.", fmt.Sprintf("Room Type ini digunakan oleh %d kamar aktif.", roomCount)) return } now := nowMySQL() _, err := DB.Exec(`UPDATE room_types SET active=0, deleted_at=?, updated_at=? WHERE uuid=?`, now, now, uuid) if err != nil { writeDashError(w, http.StatusInternalServerError, "DB_ERROR", "Gagal menghapus room type.", err.Error()) return } writeDashSuccess(w, map[string]interface{}{ "message": fmt.Sprintf("Room Type dengan UUID '%s' berhasil dihapus.", uuid), "uuid": uuid, }) }