package service import ( "aps_crm/constvar" "aps_crm/model" "aps_crm/pkg/ecode" "github.com/shopspring/decimal" "gorm.io/gorm" ) type SalesReturnService struct{} func (slf SalesReturnService) AddSalesReturn(salesReturn *model.SalesReturn) int { salesReturn.AmountShouldRefund = decimal.Zero salesReturn.AmountHasRefund = decimal.Zero salesReturn.AmountTotal = decimal.Zero for _, product := range salesReturn.Products { salesReturn.AmountTotal = salesReturn.AmountTotal.Add(product.Amount.Mul(product.Price)) } salesReturn.AmountShouldRefund = salesReturn.AmountTotal err := model.NewSalesReturnSearch().Create(salesReturn) if err != nil { return ecode.SalesReturnExist } return ecode.OK } func (slf SalesReturnService) DeleteSalesReturn(id int) int { _, err := model.NewSalesReturnSearch().SetId(id).First() if err != nil { return ecode.SalesReturnNotExist } err = model.WithTransaction(func(db *gorm.DB) error { err = model.NewSalesReturnSearch().SetId(id).Delete() if err != nil { return err } err = model.NewSalesRefundSearch().SetSourceType(constvar.RefundSourceTypeSalesReturn).SetSourceId(id).Delete() if err != nil { return err } return nil }) if err != nil { return ecode.SalesReturnNotExist } return ecode.OK } func (slf SalesReturnService) BatchDeleteSalesReturn(ids []int) (failIds []int, code int) { for _, id := range ids { code = slf.DeleteSalesReturn(id) if code != ecode.OK { failIds = append(failIds, id) } } return failIds, code } func (SalesReturnService) UpdateSalesReturn(salesReturn *model.SalesReturn) int { // check salesReturn exist _, err := model.NewSalesReturnSearch().SetId(salesReturn.Id).First() if err != nil { return ecode.SalesReturnNotExist } salesReturn.AmountShouldRefund = decimal.Zero salesReturn.AmountHasRefund = decimal.Zero salesReturn.AmountTotal = decimal.Zero for _, product := range salesReturn.Products { salesReturn.AmountTotal = salesReturn.AmountTotal.Add(product.Amount.Mul(product.Price)) } salesReturn.AmountShouldRefund = salesReturn.AmountTotal err = model.NewSalesReturnSearch().SetId(salesReturn.Id).Update(salesReturn) if err != nil { return ecode.SalesReturnSetErr } return ecode.OK } func (SalesReturnService) GetSalesReturnList(page, pageSize int, keywordType constvar.SalesReturnKeywordType, keyword string) ([]*model.SalesReturn, int64, int) { // get contact list contacts, total, err := model.NewSalesReturnSearch(). SetKeywordType(keywordType). SetKeyword(keyword). SetPage(page, pageSize). SetPreload(true). FindAll() if err != nil { return nil, 0, ecode.SalesReturnListErr } return contacts, total, ecode.OK } func (SalesReturnService) GetSalesReturnListByIds(ids []int) ([]*model.SalesReturn, int) { // get contact list salesReturns, err := model.NewSalesReturnSearch(). SetIds(ids). Find() if err != nil { return nil, ecode.SalesReturnListErr } return salesReturns, ecode.OK }