package services import ( "Medical_ERP/common/actions" cDto "Medical_ERP/common/dto" "Medical_ERP/common/global" db "Medical_ERP/common/initialize" "errors" "github.com/beego/beego/v2/core/logs" "gorm.io/gorm" "Medical_ERP/dto" "Medical_ERP/models" ) type Unit struct { } // GetPage 获取Unit列表 func (e *Unit) GetPage(c *dto.UnitPageReq, list *[]models.Unit, count *int64, p *actions.DataPermission) error { var err error var data models.Unit err = db.DB.Model(&data). Scopes( cDto.MakeCondition(c.GetNeedSearch()), cDto.Paginate(c.GetPageSize(), c.GetPageIndex()), actions.Permission(data.TableName(), p), ). Find(list).Limit(-1).Offset(-1). Count(count).Error if err != nil { logs.Error("db error: %s ", err) return global.GetFailedErr } return nil } // Get 获取Unit对象 func (e *Unit) Get(d *dto.UnitGetReq, productModel *models.Unit, p *actions.DataPermission) error { err := db.DB. Scopes(actions.Permission(productModel.TableName(), p)). First(productModel, d.GetId()).Error if err != nil { logs.Error("db error: %s", err) if errors.Is(err, gorm.ErrRecordNotFound) { return global.GetNotFoundOrNoPermissionErr } return global.GetFailedErr } return nil } // Insert 创建Unit对象 func (e *Unit) Insert(c *dto.UnitInsertReq) error { var err error var data models.Unit err = db.DB.Where("name = ? AND dept_id = ?", c.Name, c.DeptId).First(&data).Error if err != nil { // 没有则创建 if errors.Is(err, gorm.ErrRecordNotFound) { c.Generate(&data) err = db.DB.Create(&data).Error if err != nil { logs.Error("db error: %s", err) return global.CreateFailedErr } c.Id = data.Id return nil } logs.Error("db error: %s", err) return global.CreateFailedErr } c.Id = data.Id return nil } // Update 修改Unit对象 func (e *Unit) Update(c *dto.UnitUpdateReq) error { var productModel = models.Unit{} err := db.DB.First(&productModel, c.GetId()).Error if err != nil { logs.Error("db error: %s", err) if errors.Is(err, gorm.ErrRecordNotFound) { return global.UpdateNotFoundOrNoPermissionErr } return global.UpdateFailedErr } c.Generate(&productModel) err = db.DB.Save(&productModel).Error if err != nil { logs.Error("db error: %s", err) return global.UpdateFailedErr } return nil } // Remove 删除Unit func (e *Unit) Remove(d *dto.UnitDeleteReq) error { var err error var data models.Unit var Count int64 err = db.DB.Table(models.GetMedicineInfoTableName(d.DeptId)).Where("unit_id = ?", d.GetId()).Count(&Count).Error if err != nil { logs.Error("Delete error: %s", err) return global.DeleteFailedErr } if Count > 0 { return errors.New("该单位已被关联,禁止删除") } result := db.DB.Model(&data).Delete(&data, d.GetId()) if err = result.Error; err != nil { logs.Error("Delete error: %s", err) return global.DeleteFailedErr } if result.RowsAffected == 0 { return global.DeleteNotFoundOrNoPermissionErr } return nil }