| | |
| | | "aps_crm/model" |
| | | "aps_crm/pkg/ecode" |
| | | "github.com/shopspring/decimal" |
| | | "gorm.io/gorm" |
| | | ) |
| | | |
| | | type SContractService struct{} |
| | |
| | | |
| | | func (SContractService) UpdateServiceContract(serviceContract *model.ServiceContract) int { |
| | | // check serviceContract exist |
| | | old, err := model.NewServiceContractSearch().SetId(serviceContract.Id).First() |
| | | old, err := model.NewServiceContractSearch().SetId(serviceContract.Id).SetPreload(true).First() |
| | | if err != nil { |
| | | return ecode.SContractNotExist |
| | | } |
| | | var totalAmount decimal.Decimal |
| | | totalAmount = serviceContract.AmountTotal |
| | | newProducts, removedProducts := NewProductsService().PickDiffProducts(serviceContract.Products, old.Products) |
| | | for _, product := range newProducts { |
| | | for _, product := range serviceContract.Products { |
| | | totalAmount = totalAmount.Add(product.Amount.Mul(product.Price)) |
| | | } |
| | | removedProductIds := make([]uint, 0, len(removedProducts)) |
| | | for _, product := range removedProducts { |
| | | totalAmount = totalAmount.Sub(product.Amount.Mul(product.Price)) |
| | | removedProductIds = append(removedProductIds, product.Id) |
| | | } |
| | | serviceContract.AmountTotal = totalAmount.Round(2) |
| | | serviceContract.AmountReceivable = serviceContract.AmountTotal.Sub(serviceContract.AmountReceived) |
| | | serviceContract.AmountUnInvoiced = serviceContract.AmountTotal.Sub(serviceContract.AmountInvoiced) |
| | | err = model.WithTransaction(func(db *gorm.DB) error { |
| | | err := model.NewServiceContractSearch().Create(serviceContract) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | if len(removedProducts) > 0 { |
| | | removedProductIds := make([]uint, 0, len(removedProducts)) |
| | | for _, product := range removedProducts { |
| | | removedProductIds = append(removedProductIds, product.Id) |
| | | } |
| | | err = model.NewProductSearch(db).SetIds(removedProductIds).Delete() |
| | | if err != nil { |
| | | return err |
| | | } |
| | | } |
| | | if len(newProducts) > 0 { |
| | | for _, p := range newProducts { |
| | | p.Id = 0 |
| | | } |
| | | err = model.NewProductSearch(db).CreateBatch(newProducts) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | var rel []*model.ServiceContractProduct |
| | | for _, p := range newProducts { |
| | | rel = append(rel, &model.ServiceContractProduct{ |
| | | ServiceContractId: serviceContract.Id, |
| | | ProductId: p.Id, |
| | | }) |
| | | } |
| | | err = model.NewServiceContractProductSearch().CreateBatch(rel) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | } |
| | | return nil |
| | | }) |
| | | |
| | | err = model.NewServiceContractSearch().SetId(serviceContract.Id).Update(serviceContract) |
| | | if err != nil { |
| | | return ecode.SContractSetErr |
| | | return ecode.DBErr |
| | | } |
| | | |
| | | return ecode.OK |