order.go 898 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // update target
  20. err := db.Model(&c.Model).Where("id = ?", json.TargetID).Update("order_id", gorm.Expr("order_id + ?", affectedLen*(-json.Direction))).Error
  21. if err != nil {
  22. api.ErrHandler(c.ctx, err)
  23. return
  24. }
  25. // update affected
  26. err = db.Model(&c.Model).Where("id in ?", json.AffectedIDs).Update("order_id", gorm.Expr("order_id + ?", json.Direction)).Error
  27. if err != nil {
  28. api.ErrHandler(c.ctx, err)
  29. return
  30. }
  31. c.ctx.JSON(http.StatusOK, json)
  32. }