1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package service
 
import (
    "aps_crm/constvar"
    "aps_crm/model"
    "aps_crm/model/request"
    "aps_crm/pkg/ecode"
    "github.com/shopspring/decimal"
    "gorm.io/gorm"
)
 
type InvoiceService struct{}
 
func NewInvoiceService() InvoiceService {
    return InvoiceService{}
}
 
func (InvoiceService) AddInvoice(invoice *model.Invoice) int {
 
    if invoice.SourceType == constvar.InvoiceSourceTypeServiceContract {
        serviceContract, err := model.NewServiceContractSearch().SetId(invoice.SourceId).First()
        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
}
 
func (InvoiceService) DeleteInvoice(id int) int {
    err := model.NewInvoiceSearch().SetId(id).Delete()
    if err != nil {
        return ecode.DBErr
    }
    return ecode.OK
}
 
func (InvoiceService) GetInvoiceList() ([]*model.Invoice, int64, int) {
    list, total, err := model.NewInvoiceSearch().Find()
    if err != nil {
        return nil, 0, ecode.DBErr
    }
 
    return list, total, ecode.OK
}
 
func (InvoiceService) UpdateInvoices(Invoices []*request.UpdateInvoice) int {
    for _, v := range Invoices {
        // check Invoice exist
        _, err := model.NewInvoiceSearch().SetId(v.Id).First()
        if err != nil {
            return ecode.DBErr
        }
 
        err = model.NewInvoiceSearch().SetId(v.Id).Updates(map[string]interface{}{})
        if err != nil {
            return ecode.DBErr
        }
    }
 
    return ecode.OK
}
 
func (InvoiceService) UpdateInvoice(invoice *model.Invoice) int {
    err := model.NewInvoiceSearch().SetId(invoice.Id).Save(invoice)
    if err != nil {
        return ecode.DBErr
    }
    return ecode.OK
}