| | |
| | | package service |
| | | |
| | | import ( |
| | | "aps_crm/constvar" |
| | | "aps_crm/model" |
| | | "aps_crm/model/request" |
| | | "aps_crm/pkg/ecode" |
| | | "github.com/shopspring/decimal" |
| | | "gorm.io/gorm" |
| | | ) |
| | | |
| | |
| | | |
| | | func (InvoiceService) AddInvoice(invoice *model.Invoice) int { |
| | | |
| | | err := model.WithTransaction(func(db *gorm.DB) error { |
| | | err := model.NewInvoiceSearch().Create(invoice) |
| | | if invoice.SourceType == constvar.InvoiceSourceTypeServiceContract { |
| | | serviceContract, err := model.NewServiceContractSearch().SetId(invoice.SourceId).First() |
| | | if err != nil { |
| | | return err |
| | | return ecode.DBErr |
| | | } |
| | | //if invoice.SourceType == constvar.InvoiceSourceTypeServiceContract { |
| | | // contract,err := model.NewServiceContractSearch().SetId(invoice.SourceId).First() |
| | | // if err != nil { |
| | | // return err |
| | | // } |
| | | // AmountInvoiced := contract.AmountReceived.Add() |
| | | // err := model.NewServiceContractSearch().SetId(invoice.SourceId).UpdateByMap(map[string]interface{}{ |
| | | // "amount_received" : |
| | | // }) |
| | | // if err != nil { |
| | | // return err |
| | | // } |
| | | //} |
| | | |
| | | return nil |
| | | }) |
| | | |
| | | if err != nil { |
| | | return ecode.DBErr |
| | | var amountInvoiced decimal.Decimal |
| | | for _, product := range invoice.Products { |
| | | amountInvoiced = serviceContract.AmountInvoiced.Add(product.Amount.Mul(product.Price)) |
| | | } |
| | | amountInvoiced = amountInvoiced.Round(2) |
| | | if amountInvoiced.GreaterThan(serviceContract.AmountReceivable) { |
| | | return ecode.SContractInvoiceProductPriceGreaterThanReceivableAmountErr |
| | | } |
| | | err = model.WithTransaction(func(db *gorm.DB) error { |
| | | err = model.NewInvoiceSearch().Create(invoice) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | err = model.NewServiceContractSearch().SetId(invoice.SourceId).UpdateByMap(map[string]interface{}{ |
| | | "amount_invoiced": amountInvoiced, |
| | | }) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | return nil |
| | | }) |
| | | if err != nil { |
| | | return ecode.DBErr |
| | | } |
| | | } |
| | | |
| | | return ecode.OK |