order.go 963 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package cosy
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/model"
  5. "gorm.io/gorm"
  6. "net/http"
  7. )
  8. func (c *Ctx[T]) UpdateOrder() {
  9. var json struct {
  10. TargetID int `json:"target_id"`
  11. Direction int `json:"direction" binding:"oneof=-1 1"`
  12. AffectedIDs []int `json:"affected_ids"`
  13. }
  14. if !api.BindAndValid(c.ctx, &json) {
  15. return
  16. }
  17. affectedLen := len(json.AffectedIDs)
  18. db := model.UseDB()
  19. if c.table != "" {
  20. db = db.Table(c.table, c.tableArgs...)
  21. }
  22. // update target
  23. err := db.Model(&c.Model).Where("id = ?", json.TargetID).Update("order_id", gorm.Expr("order_id + ?", affectedLen*(-json.Direction))).Error
  24. if err != nil {
  25. api.ErrHandler(c.ctx, err)
  26. return
  27. }
  28. // update affected
  29. err = db.Model(&c.Model).Where("id in ?", json.AffectedIDs).Update("order_id", gorm.Expr("order_id + ?", json.Direction)).Error
  30. if err != nil {
  31. api.ErrHandler(c.ctx, err)
  32. return
  33. }
  34. c.ctx.JSON(http.StatusOK, json)
  35. }