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 Product struct { } // GetPage 获取Product列表 func (e *Product) GetPage(c *dto.ProductPageReq, list *[]models.Product, count *int64, p *actions.DataPermission) error { var err error var data models.Product 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 获取Product对象 func (e *Product) Get(d *dto.ProductGetReq, productModel *models.Product, 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 创建Product对象 func (e *Product) Insert(c *dto.ProductInsertReq) error { var err error var data models.Product 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 修改Product对象 func (e *Product) Update(c *dto.ProductUpdateReq) error { var productModel = models.Product{} 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 删除Product func (e *Product) Remove(d *dto.ProductDeleteReq) error { var err error var data models.Product 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 }