resource_controller.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. package controllers
  2. import (
  3. "fmt"
  4. "ems-backend/models"
  5. "encoding/json"
  6. "net/http"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/google/uuid"
  10. "gorm.io/datatypes"
  11. "bytes"
  12. "io"
  13. "strings"
  14. )
  15. // --- Integration Source Controllers ---
  16. type HAConfig struct {
  17. URL string `json:"url"`
  18. Token string `json:"token"`
  19. }
  20. type HAEntity struct {
  21. EntityID string `json:"entity_id"`
  22. State string `json:"state"`
  23. Attributes map[string]interface{} `json:"attributes"`
  24. LastChanged time.Time `json:"last_changed"`
  25. LastUpdated time.Time `json:"last_updated"`
  26. DeviceID string `json:"device_id"` // Augmented field
  27. DeviceName string `json:"device_name"` // Augmented field
  28. }
  29. // HA Template Request
  30. type HATemplateReq struct {
  31. Template string `json:"template"`
  32. }
  33. // Struct for template result parsing
  34. type HATemplateResult struct {
  35. ID string `json:"id"`
  36. State string `json:"s"`
  37. Name string `json:"n"`
  38. DID string `json:"did"`
  39. DName string `json:"dn"`
  40. }
  41. // HADevice represents a Home Assistant Device
  42. type HADevice struct {
  43. ID string `json:"id"`
  44. Name string `json:"name"`
  45. Model string `json:"model"`
  46. Manufacturer string `json:"manufacturer"`
  47. }
  48. func fetchHADevices(config datatypes.JSON) ([]HADevice, error) {
  49. var haConfig HAConfig
  50. b, err := config.MarshalJSON()
  51. if err != nil {
  52. return nil, fmt.Errorf("config error: %v", err)
  53. }
  54. if err := json.Unmarshal(b, &haConfig); err != nil {
  55. return nil, fmt.Errorf("invalid configuration format: %v", err)
  56. }
  57. if haConfig.URL == "" || haConfig.Token == "" {
  58. return nil, fmt.Errorf("URL and Token are required")
  59. }
  60. client := &http.Client{Timeout: 10 * time.Second}
  61. url := haConfig.URL
  62. // Robust URL handling: remove trailing slash and /api suffix
  63. url = strings.TrimSuffix(url, "/")
  64. url = strings.TrimSuffix(url, "/api")
  65. // Use Template API to get devices efficiently
  66. // Simplified template avoiding list.append due to sandbox restrictions
  67. template := `
  68. {% set ns = namespace(result=[], devs=[]) %}
  69. {% for state in states %}
  70. {% set d = device_id(state.entity_id) %}
  71. {% if d and d not in ns.devs %}
  72. {% set ns.devs = ns.devs + [d] %}
  73. {% set name = device_attr(d, 'name_by_user') %}
  74. {% if not name %}
  75. {% set name = device_attr(d, 'name') %}
  76. {% endif %}
  77. {% if not name %}
  78. {% set name = 'Unknown' %}
  79. {% endif %}
  80. {% set entry = {
  81. "id": d,
  82. "name": name,
  83. "model": device_attr(d, 'model') or "",
  84. "manufacturer": device_attr(d, 'manufacturer') or ""
  85. } %}
  86. {% set ns.result = ns.result + [entry] %}
  87. {% endif %}
  88. {% endfor %}
  89. {{ ns.result | to_json }}
  90. `
  91. reqBody, _ := json.Marshal(HATemplateReq{Template: template})
  92. req, err := http.NewRequest("POST", url+"/api/template", bytes.NewBuffer(reqBody))
  93. if err != nil {
  94. return nil, fmt.Errorf("failed to create request: %v", err)
  95. }
  96. req.Header.Set("Authorization", "Bearer "+haConfig.Token)
  97. req.Header.Set("Content-Type", "application/json")
  98. resp, err := client.Do(req)
  99. if err != nil {
  100. return nil, fmt.Errorf("connection failed: %v", err)
  101. }
  102. defer resp.Body.Close()
  103. // Read body for better error reporting
  104. bodyBytes, err := io.ReadAll(resp.Body)
  105. if err != nil {
  106. return nil, fmt.Errorf("failed to read response body: %v", err)
  107. }
  108. if resp.StatusCode != 200 {
  109. fmt.Printf("DEBUG: HA Status Error: %s, Body: %s\n", resp.Status, string(bodyBytes))
  110. return nil, fmt.Errorf("Home Assistant returned status: %s. Body: %s", resp.Status, string(bodyBytes))
  111. }
  112. var devices []HADevice
  113. if err := json.Unmarshal(bodyBytes, &devices); err != nil {
  114. // Try to see if it's because empty result or format
  115. fmt.Printf("DEBUG: Failed to decode HA response: %s\nError: %v\n", string(bodyBytes), err)
  116. return nil, fmt.Errorf("failed to decode response: %v. Body: %s", err, string(bodyBytes))
  117. }
  118. fmt.Printf("DEBUG: Successfully fetched %d devices\n", len(devices))
  119. return devices, nil
  120. }
  121. func fetchHAEntitiesByDevice(config datatypes.JSON, deviceID string) ([]HAEntity, error) {
  122. var haConfig HAConfig
  123. b, err := config.MarshalJSON()
  124. if err != nil {
  125. return nil, fmt.Errorf("config error: %v", err)
  126. }
  127. if err := json.Unmarshal(b, &haConfig); err != nil {
  128. return nil, fmt.Errorf("invalid configuration format: %v", err)
  129. }
  130. if haConfig.URL == "" || haConfig.Token == "" {
  131. return nil, fmt.Errorf("URL and Token are required")
  132. }
  133. client := &http.Client{Timeout: 10 * time.Second}
  134. url := haConfig.URL
  135. // Robust URL handling
  136. url = strings.TrimSuffix(url, "/")
  137. url = strings.TrimSuffix(url, "/api")
  138. // Template to fetch entities for a specific device
  139. // Using strings.Replace to avoid fmt.Sprintf interpreting Jinja2 tags {% as format specifiers
  140. rawTemplate := `
  141. {% set ns = namespace(result=[]) %}
  142. {% set device_entities = device_entities('__DEVICE_ID__') %}
  143. {% for entity_id in device_entities %}
  144. {% set state = states[entity_id] %}
  145. {% if state %}
  146. {% set name = state.attributes.friendly_name %}
  147. {% if name is not defined or name is none %}
  148. {% set name = entity_id %}
  149. {% endif %}
  150. {% set entry = {
  151. "id": entity_id,
  152. "s": state.state,
  153. "n": name,
  154. "did": '__DEVICE_ID__',
  155. "dn": ''
  156. } %}
  157. {% set ns.result = ns.result + [entry] %}
  158. {% endif %}
  159. {% endfor %}
  160. {{ ns.result | to_json }}
  161. `
  162. template := strings.ReplaceAll(rawTemplate, "__DEVICE_ID__", deviceID)
  163. reqBody, _ := json.Marshal(HATemplateReq{Template: template})
  164. req, err := http.NewRequest("POST", url+"/api/template", bytes.NewBuffer(reqBody))
  165. if err != nil {
  166. return nil, fmt.Errorf("failed to create request: %v", err)
  167. }
  168. req.Header.Set("Authorization", "Bearer "+haConfig.Token)
  169. req.Header.Set("Content-Type", "application/json")
  170. resp, err := client.Do(req)
  171. if err != nil {
  172. return nil, fmt.Errorf("connection failed: %v", err)
  173. }
  174. defer resp.Body.Close()
  175. // Read body for better error reporting
  176. bodyBytes, err := io.ReadAll(resp.Body)
  177. if err != nil {
  178. return nil, fmt.Errorf("failed to read response body: %v", err)
  179. }
  180. if resp.StatusCode != 200 {
  181. fmt.Printf("DEBUG: HA Status Error (Entities): %s, Body: %s\n", resp.Status, string(bodyBytes))
  182. return nil, fmt.Errorf("Home Assistant returned status: %s. Body: %s", resp.Status, string(bodyBytes))
  183. }
  184. var tmplResults []HATemplateResult
  185. if err := json.Unmarshal(bodyBytes, &tmplResults); err != nil {
  186. fmt.Printf("DEBUG: Failed to decode HA response (Entities): %s\nError: %v\n", string(bodyBytes), err)
  187. return nil, fmt.Errorf("failed to decode response: %v. Body: %s", err, string(bodyBytes))
  188. }
  189. fmt.Printf("DEBUG: Successfully fetched %d entities for device %s\n", len(tmplResults), deviceID)
  190. entities := make([]HAEntity, len(tmplResults))
  191. for i, r := range tmplResults {
  192. entities[i] = HAEntity{
  193. EntityID: r.ID,
  194. State: r.State,
  195. Attributes: map[string]interface{}{"friendly_name": r.Name},
  196. DeviceID: r.DID,
  197. DeviceName: r.DName,
  198. }
  199. }
  200. return entities, nil
  201. }
  202. func fetchHAEntities(config datatypes.JSON) ([]HAEntity, error) {
  203. var haConfig HAConfig
  204. b, err := config.MarshalJSON()
  205. if err != nil {
  206. return nil, fmt.Errorf("config error: %v", err)
  207. }
  208. if err := json.Unmarshal(b, &haConfig); err != nil {
  209. return nil, fmt.Errorf("invalid configuration format: %v", err)
  210. }
  211. if haConfig.URL == "" || haConfig.Token == "" {
  212. return nil, fmt.Errorf("URL and Token are required")
  213. }
  214. client := &http.Client{Timeout: 10 * time.Second}
  215. url := haConfig.URL
  216. // Robust URL handling
  217. url = strings.TrimSuffix(url, "/")
  218. url = strings.TrimSuffix(url, "/api")
  219. // Try Template API first to get device info
  220. // Using namespace to avoid list.append security restriction
  221. template := `
  222. {% set ns = namespace(result=[]) %}
  223. {% for state in states %}
  224. {% set name = state.attributes.friendly_name %}
  225. {% if name is not defined or name is none %}
  226. {% set name = state.entity_id %}
  227. {% endif %}
  228. {% set d = device_id(state.entity_id) %}
  229. {% if d %}
  230. {% set d_name = device_attr(d, 'name_by_user') or device_attr(d, 'name') or 'Unknown' %}
  231. {% set entry = {
  232. "id": state.entity_id,
  233. "s": state.state,
  234. "n": name,
  235. "did": d,
  236. "dn": d_name
  237. } %}
  238. {% set ns.result = ns.result + [entry] %}
  239. {% else %}
  240. {% set entry = {
  241. "id": state.entity_id,
  242. "s": state.state,
  243. "n": name,
  244. "did": "",
  245. "dn": ""
  246. } %}
  247. {% set ns.result = ns.result + [entry] %}
  248. {% endif %}
  249. {% endfor %}
  250. {{ ns.result | to_json }}
  251. `
  252. // Clean up newlines/spaces for template req? Not strictly needed for JSON but good practice
  253. // Actually JSON marshalling handles it.
  254. reqBody, _ := json.Marshal(HATemplateReq{Template: template})
  255. req, err := http.NewRequest("POST", url+"/api/template", bytes.NewBuffer(reqBody))
  256. if err == nil {
  257. req.Header.Set("Authorization", "Bearer "+haConfig.Token)
  258. req.Header.Set("Content-Type", "application/json")
  259. resp, err := client.Do(req)
  260. if err == nil && resp.StatusCode == 200 {
  261. defer resp.Body.Close()
  262. // Parse template result
  263. // HA returns string body which IS the rendered template (JSON)
  264. // But careful: sometimes it's plain text.
  265. // "to_json" filter ensures it's JSON.
  266. var tmplResults []HATemplateResult
  267. if err := json.NewDecoder(resp.Body).Decode(&tmplResults); err == nil {
  268. // Convert to HAEntity
  269. entities := make([]HAEntity, len(tmplResults))
  270. for i, r := range tmplResults {
  271. entities[i] = HAEntity{
  272. EntityID: r.ID,
  273. State: r.State,
  274. Attributes: map[string]interface{}{"friendly_name": r.Name}, // Simplified attributes
  275. DeviceID: r.DID,
  276. DeviceName: r.DName,
  277. }
  278. }
  279. return entities, nil
  280. }
  281. // If decode failed, fallthrough to legacy method
  282. }
  283. }
  284. // Fallback to /api/states
  285. req, err = http.NewRequest("GET", url+"/api/states", nil)
  286. if err != nil {
  287. return nil, fmt.Errorf("failed to create request: %v", err)
  288. }
  289. req.Header.Set("Authorization", "Bearer "+haConfig.Token)
  290. req.Header.Set("Content-Type", "application/json")
  291. resp, err := client.Do(req)
  292. if err != nil {
  293. return nil, fmt.Errorf("connection failed: %v", err)
  294. }
  295. defer resp.Body.Close()
  296. if resp.StatusCode != 200 {
  297. return nil, fmt.Errorf("Home Assistant returned status: %s", resp.Status)
  298. }
  299. var entities []HAEntity
  300. if err := json.NewDecoder(resp.Body).Decode(&entities); err != nil {
  301. return nil, fmt.Errorf("failed to decode response: %v", err)
  302. }
  303. return entities, nil
  304. }
  305. func testHAConnection(config datatypes.JSON) (bool, string) {
  306. var haConfig HAConfig
  307. b, err := config.MarshalJSON()
  308. if err != nil {
  309. return false, "Config error"
  310. }
  311. if err := json.Unmarshal(b, &haConfig); err != nil {
  312. return false, "Invalid configuration format"
  313. }
  314. if haConfig.URL == "" || haConfig.Token == "" {
  315. return false, "URL and Token are required"
  316. }
  317. client := &http.Client{Timeout: 5 * time.Second}
  318. // Removing trailing slash if present to avoid double slash
  319. url := haConfig.URL
  320. url = strings.TrimSuffix(url, "/")
  321. url = strings.TrimSuffix(url, "/api")
  322. req, err := http.NewRequest("GET", url+"/api/", nil)
  323. if err != nil {
  324. return false, "Failed to create request: " + err.Error()
  325. }
  326. req.Header.Set("Authorization", "Bearer "+haConfig.Token)
  327. req.Header.Set("Content-Type", "application/json")
  328. resp, err := client.Do(req)
  329. if err != nil {
  330. return false, "Connection failed: " + err.Error()
  331. }
  332. defer resp.Body.Close()
  333. if resp.StatusCode == 200 {
  334. return true, "Success"
  335. }
  336. return false, "Home Assistant returned status: " + resp.Status
  337. }
  338. func GetSources(c *gin.Context) {
  339. var sources []models.IntegrationSource
  340. if err := models.DB.Find(&sources).Error; err != nil {
  341. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  342. return
  343. }
  344. c.JSON(http.StatusOK, sources)
  345. }
  346. func CreateSource(c *gin.Context) {
  347. var source models.IntegrationSource
  348. if err := c.ShouldBindJSON(&source); err != nil {
  349. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  350. return
  351. }
  352. // DEBUG LOG
  353. fmt.Printf("DEBUG: CreateSource received: %+v, Status: %s\n", source, source.Status)
  354. if err := models.DB.Create(&source).Error; err != nil {
  355. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  356. return
  357. }
  358. c.JSON(http.StatusCreated, source)
  359. }
  360. func UpdateSource(c *gin.Context) {
  361. id := c.Param("id")
  362. var source models.IntegrationSource
  363. if err := models.DB.First(&source, "id = ?", id).Error; err != nil {
  364. c.JSON(http.StatusNotFound, gin.H{"error": "Source not found"})
  365. return
  366. }
  367. if err := c.ShouldBindJSON(&source); err != nil {
  368. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  369. return
  370. }
  371. // DEBUG LOG
  372. fmt.Printf("DEBUG: UpdateSource received: %+v, Status: %s\n", source, source.Status)
  373. models.DB.Save(&source)
  374. c.JSON(http.StatusOK, source)
  375. }
  376. func DeleteSource(c *gin.Context) {
  377. id := c.Param("id")
  378. if err := models.DB.Delete(&models.IntegrationSource{}, "id = ?", id).Error; err != nil {
  379. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  380. return
  381. }
  382. c.JSON(http.StatusOK, gin.H{"message": "Source deleted"})
  383. }
  384. // TestSourceConnection 测试连接
  385. func TestSourceConnection(c *gin.Context) {
  386. var source models.IntegrationSource
  387. // 允许直接传参测试,或者传 ID 测试已有
  388. if err := c.ShouldBindJSON(&source); err != nil {
  389. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  390. return
  391. }
  392. var success bool
  393. var msg string
  394. switch source.DriverType {
  395. case "HOME_ASSISTANT":
  396. success, msg = testHAConnection(source.Config)
  397. default:
  398. // Mock others for now
  399. success = true
  400. msg = "Connection simulated (driver not implemented)"
  401. }
  402. if success {
  403. // If the source has an ID, update its status in DB
  404. if source.ID != uuid.Nil {
  405. models.DB.Model(&models.IntegrationSource{}).Where("id = ?", source.ID).Update("status", "ONLINE")
  406. }
  407. c.JSON(http.StatusOK, gin.H{"success": true, "message": "Connection successful"})
  408. } else {
  409. if source.ID != uuid.Nil {
  410. models.DB.Model(&models.IntegrationSource{}).Where("id = ?", source.ID).Update("status", "OFFLINE")
  411. }
  412. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": msg})
  413. }
  414. }
  415. // SyncSource 同步数据
  416. func SyncSource(c *gin.Context) {
  417. id := c.Param("id")
  418. // TODO: 触发异步任务同步设备
  419. c.JSON(http.StatusOK, gin.H{"message": "Sync started for source " + id})
  420. }
  421. // GetSourceDevices 获取设备列表
  422. func GetSourceDevices(c *gin.Context) {
  423. id := c.Param("id")
  424. var source models.IntegrationSource
  425. if err := models.DB.First(&source, "id = ?", id).Error; err != nil {
  426. c.JSON(http.StatusNotFound, gin.H{"error": "Source not found"})
  427. return
  428. }
  429. if source.DriverType != "HOME_ASSISTANT" {
  430. c.JSON(http.StatusBadRequest, gin.H{"error": "Only Home Assistant sources are supported"})
  431. return
  432. }
  433. devices, err := fetchHADevices(source.Config)
  434. if err != nil {
  435. fmt.Printf("DEBUG: GetSourceDevices error: %v\n", err)
  436. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  437. return
  438. }
  439. c.JSON(http.StatusOK, devices)
  440. }
  441. // GetSourceDeviceEntities 获取指定设备的实体列表
  442. func GetSourceDeviceEntities(c *gin.Context) {
  443. id := c.Param("id")
  444. deviceID := c.Param("deviceId")
  445. var source models.IntegrationSource
  446. if err := models.DB.First(&source, "id = ?", id).Error; err != nil {
  447. c.JSON(http.StatusNotFound, gin.H{"error": "Source not found"})
  448. return
  449. }
  450. if source.DriverType != "HOME_ASSISTANT" {
  451. c.JSON(http.StatusBadRequest, gin.H{"error": "Only Home Assistant sources are supported"})
  452. return
  453. }
  454. entities, err := fetchHAEntitiesByDevice(source.Config, deviceID)
  455. if err != nil {
  456. fmt.Printf("DEBUG: GetSourceDeviceEntities error: %v\n", err)
  457. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  458. return
  459. }
  460. c.JSON(http.StatusOK, entities)
  461. }
  462. // GetSourceCandidates 获取数据源候选设备列表 (Deprecated or kept for backward compat)
  463. func GetSourceCandidates(c *gin.Context) {
  464. id := c.Param("id")
  465. var source models.IntegrationSource
  466. if err := models.DB.First(&source, "id = ?", id).Error; err != nil {
  467. c.JSON(http.StatusNotFound, gin.H{"error": "Source not found"})
  468. return
  469. }
  470. if source.DriverType != "HOME_ASSISTANT" {
  471. c.JSON(http.StatusBadRequest, gin.H{"error": "Only Home Assistant sources are supported for candidate fetching currently"})
  472. return
  473. }
  474. entities, err := fetchHAEntities(source.Config)
  475. if err != nil {
  476. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  477. return
  478. }
  479. c.JSON(http.StatusOK, entities)
  480. }
  481. // --- Device Controllers ---
  482. func GetDevices(c *gin.Context) {
  483. var devices []models.Device
  484. // Support filtering by location_id or source_id if provided
  485. locationID := c.Query("location_id")
  486. sourceID := c.Query("source_id")
  487. query := models.DB
  488. if locationID != "" {
  489. query = query.Where("location_id = ?", locationID)
  490. }
  491. if sourceID != "" {
  492. query = query.Where("source_id = ?", sourceID)
  493. }
  494. if err := query.Find(&devices).Error; err != nil {
  495. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  496. return
  497. }
  498. c.JSON(http.StatusOK, devices)
  499. }
  500. func CreateDevice(c *gin.Context) {
  501. var device models.Device
  502. if err := c.ShouldBindJSON(&device); err != nil {
  503. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  504. return
  505. }
  506. if err := models.DB.Create(&device).Error; err != nil {
  507. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  508. return
  509. }
  510. c.JSON(http.StatusCreated, device)
  511. }
  512. func UpdateDevice(c *gin.Context) {
  513. id := c.Param("id")
  514. var device models.Device
  515. if err := models.DB.First(&device, "id = ?", id).Error; err != nil {
  516. c.JSON(http.StatusNotFound, gin.H{"error": "Device not found"})
  517. return
  518. }
  519. if err := c.ShouldBindJSON(&device); err != nil {
  520. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  521. return
  522. }
  523. models.DB.Save(&device)
  524. c.JSON(http.StatusOK, device)
  525. }
  526. func DeleteDevice(c *gin.Context) {
  527. id := c.Param("id")
  528. if err := models.DB.Delete(&models.Device{}, "id = ?", id).Error; err != nil {
  529. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  530. return
  531. }
  532. c.JSON(http.StatusOK, gin.H{"message": "Device deleted"})
  533. }
  534. // --- Location Controllers ---
  535. func GetLocations(c *gin.Context) {
  536. var locations []models.SysLocation
  537. if err := models.DB.Find(&locations).Error; err != nil {
  538. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  539. return
  540. }
  541. c.JSON(http.StatusOK, locations)
  542. }
  543. func CreateLocation(c *gin.Context) {
  544. var location models.SysLocation
  545. if err := c.ShouldBindJSON(&location); err != nil {
  546. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  547. return
  548. }
  549. if err := models.DB.Create(&location).Error; err != nil {
  550. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  551. return
  552. }
  553. c.JSON(http.StatusCreated, location)
  554. }
  555. func UpdateLocation(c *gin.Context) {
  556. id := c.Param("id")
  557. var location models.SysLocation
  558. if err := models.DB.First(&location, "id = ?", id).Error; err != nil {
  559. c.JSON(http.StatusNotFound, gin.H{"error": "Location not found"})
  560. return
  561. }
  562. if err := c.ShouldBindJSON(&location); err != nil {
  563. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  564. return
  565. }
  566. models.DB.Save(&location)
  567. c.JSON(http.StatusOK, location)
  568. }
  569. func DeleteLocation(c *gin.Context) {
  570. id := c.Param("id")
  571. if err := models.DB.Delete(&models.SysLocation{}, "id = ?", id).Error; err != nil {
  572. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  573. return
  574. }
  575. c.JSON(http.StatusOK, gin.H{"message": "Location deleted"})
  576. }