liujiandao
2024-01-03 3f5aa5f14c56e55a05902c7e3b9b112eb23ee80d
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package purchase
 
import (
    "context"
    "errors"
    "github.com/shopspring/decimal"
    "github.com/spf13/cast"
    "gorm.io/gorm"
    "srm/global"
    "srm/model/purchase"
    purchaserequest "srm/model/purchase/request"
    "srm/proto/qualityinspect"
    "srm/service/test"
)
 
type PurchaseService struct{}
 
func NewPurchaseService() *PurchaseService {
    return &PurchaseService{}
}
 
//@function: CreatePurchase
//@description: 创建采购单
//@param: params *purchaserequest.AddPurchase
//@return: err error
 
func (slf *PurchaseService) CreatePurchase(record *purchase.Purchase, productList []*purchase.PurchaseProducts) (err error) {
    err = DealPrice(record, productList)
    if err != nil {
        return err
    }
    err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
        err = tx.Create(&record).Error
        if err != nil {
            return err
        }
        for _, product := range productList {
            product.PurchaseId = cast.ToInt(record.ID)
        }
        return tx.Create(productList).Error
    })
 
    return err
}
 
func DealPrice(record *purchase.Purchase, productList []*purchase.PurchaseProducts) error {
    var quantity decimal.Decimal
    var totalPrice decimal.Decimal
    var realTotalPrice decimal.Decimal
    for _, product := range productList {
        quantity = quantity.Add(product.Amount)
        totalPrice = totalPrice.Add(product.Price.Mul(product.Amount))
    }
    record.Quantity = quantity
    if !totalPrice.Equal(record.TotalPrice) {
        return errors.New("价税总计计算错误")
    }
    realTotalPrice = record.CalcRealTotalPrice()
    if !realTotalPrice.Equal(record.RealTotalPrice) {
        return errors.New("最终价格计算错误")
    }
    record.UnInvoiceAmount = record.RealTotalPrice
    record.ShouldPayAmount = record.RealTotalPrice
    return nil
}
 
//@function: DeletePurchase
//@description: 删除采购单
//@param: id uint
//@return: err error
 
func (slf *PurchaseService) DeletePurchase(id uint) (err error) {
    err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
        err = tx.Where("id = ?", id).Delete(&purchase.Purchase{}).Error
        if err != nil {
            return err
        }
        return tx.Where("purchase_id = ?", id).Delete(&purchase.PurchaseProducts{}).Error
    })
    return err
}
 
//@function: UpdatePurchase
//@description: 更新采购单
//@param: params *purchaserequest.AddPurchase
//@return: err error
 
func (slf *PurchaseService) UpdatePurchase(params *purchase.Purchase, productList []*purchase.PurchaseProducts) (err error) {
    err = DealPrice(params, productList)
    if err != nil {
        return err
    }
    err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
        err = tx.Where("id = ?", params.ID).Updates(params).Error
        if err != nil {
            return err
        }
        err = tx.Where("purchase_id = ?", params.ID).Delete(&purchase.PurchaseProducts{}).Error
        if err != nil {
            return err
        }
        for _, product := range productList {
            product.ID = 0
            product.PurchaseId = cast.ToInt(params.ID)
        }
        return tx.Create(productList).Error
    })
    return err
}
 
//@function: GetPurchase
//@description: 获取采购单信息
//@param: id uint
//@return: purchase model.Purchase, err error
 
func (slf *PurchaseService) GetPurchase(id uint) (purchase purchase.Purchase, err error) {
    err = global.GVA_DB.Where("id = ?", id).Preload("Supplier").First(&purchase).Error
    return
}
 
//@function: GetPurchaseList
//@description: 分页获取采购单列表
//@param: info request.PageInfo
//@return: list interface{}, total int64, err error
 
func (slf *PurchaseService) GetPurchaseList(info purchaserequest.PurchaseSearch) (list interface{}, total int64, err error) {
    limit := info.PageSize
    offset := info.PageSize * (info.Page - 1)
    db := global.GVA_DB.Model(&purchase.Purchase{})
    var ids []uint
    var purchaseList = make([]*purchase.Purchase, 0)
    if info.Keyword != "" {
        db.Distinct("srm_purchase.id").Joins("left join srm_purchase_products on srm_purchase_products.purchase_id = srm_purchase.id").
            Joins("left join srm_supplier_material on srm_supplier_material.supplier_id = srm_purchase.id").
            Joins("left join srm_supplier on srm_supplier.Id = srm_purchase.supplier_id").
            Where("srm_purchase.name like ?", "%"+info.Keyword+"%").
            Or("srm_supplier_material.name like ?", "%"+info.Keyword+"%").
            Or("srm_supplier.name like ?", "%"+info.Keyword+"%")
        err = db.Limit(limit).Offset(offset).Find(&ids).Error
        if err != nil {
            return purchaseList, total, err
        }
    } else if info.SupplierId != 0 {
        db = db.Where("supplier_id = ?", info.SupplierId)
    }
    err = db.Count(&total).Error
    if err != nil || total == 0 {
        return purchaseList, total, err
    }
    if len(ids) != 0 {
        db = global.GVA_DB.Model(&purchase.Purchase{})
        err = db.Where("id in (?)", ids).Preload("Supplier").Order("updated_at desc").Find(&purchaseList).Error
    } else {
        //db = global.GVA_DB.Model(&purchase.Purchase{})
        err = db.Limit(limit).Offset(offset).Preload("Supplier").Order("updated_at desc").Find(&purchaseList).Error
    }
 
    return purchaseList, total, err
}
 
//@function: GetPurchaseProductList
//@description: 分页获取采购单产品列表
//@param: purchaseId int
//@return: list interface{},  err error
 
func (slf *PurchaseService) GetPurchaseProductList(purchaseId uint) (list []*purchase.PurchaseProducts, err error) {
    db := global.GVA_DB.Model(&purchase.PurchaseProducts{})
    list = make([]*purchase.PurchaseProducts, 0)
    err = db.Where("purchase_id = ?", purchaseId).Preload("Product").Find(&list).Error
    return list, err
}
 
//@function: Submit
//@description: 提交采购单
//@param: id uint
//@return: err error
 
func (slf *PurchaseService) Submit(id int, status purchase.OrderStatus, warehouse string) (err error) {
 
    //purchaseData, err := slf.GetPurchase(id)
    //if err != nil {
    //    return err
    //}
    //var targetStatus purchase.OrderStatus
    //switch purchaseData.Status {
    //case purchase.OrderStatusConfirmed:
    //    targetStatus = purchase.OrderStatusReceived
    //case purchase.OrderStatusReceived:
    //    targetStatus = purchase.OrderStatusStored
    //case purchase.OrderStatusStored:
    //    targetStatus = purchase.OrderStatusCompleted
    //}
    err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
        m := make(map[string]interface{})
        m["status"] = status
        if warehouse != "" {
            m["warehouse"] = warehouse
        }
        err = tx.Where("id = ?", id).Model(&purchase.Purchase{}).Updates(m).Error
        if err != nil {
            return err
        }
 
        //switch targetStatus {
        //case purchase.OrderStatusReceived:
        //    return SendInspect(purchaseData)
        //case purchase.OrderStatusStored:
        //case purchase.OrderStatusCompleted:
        //}
        return nil
    })
    return err
}
 
func SendInspect(record purchase.Purchase) error {
    productList, err := NewPurchaseService().GetPurchaseProductList(record.ID)
    if err != nil {
        return err
    }
    productIds := make([]uint, 0, len(productList))
    for _, product := range productList {
        productIds = append(productIds, product.ID)
    }
    productService := &test.ProductService{}
    _, productMap, err := productService.GetProducts(productIds)
    if err != nil {
        return err
    }
    inspectOrders := make([]*qualityinspect.QualityInspect, 0, len(productList))
    for _, productItem := range productList {
        product := productMap[productItem.ID]
        if product == nil {
            continue
        }
        inspectOrder := &qualityinspect.QualityInspect{
            InspectType:     qualityinspect.InspectType_InspectTypePurchase,
            MaterialType:    qualityinspect.MaterialType_MaterialTypeRaw,
            MaterialName:    product.Name,
            MaterialId:      product.Number,
            MaterialTp:      product.ModelNumber,
            MaterialUnit:    product.Unit,
            Supplier:        record.Supplier.Name,
            WarehouseName:   "采购总仓",
            ReportAmount:    productItem.Amount.InexactFloat64(),
            InspectMethod:   qualityinspect.InspectMethod_InspectMethodAll,
            InspectAmount:   productItem.Amount.InexactFloat64(),
            PurchaseOrderId: record.Number,
        }
        inspectOrders = append(inspectOrders, inspectOrder)
    }
    if len(inspectOrders) == 0 {
        return nil
    }
    inspectRequest := qualityinspect.SendPurchaseInspectRequest{List: inspectOrders}
    _, err = qualityinspect.NewQualityInspectServiceClient(qualityinspect.Conn).SendPurchaseInspect(context.Background(), &inspectRequest)
    return err
}
 
func (slf *PurchaseService) SavePurchaseType(list []*purchase.PurchaseType) (err error) {
    ids := make([]uint, 0)
    for _, item := range list {
        if item.ID != 0 {
            ids = append(ids, item.ID)
            item.ID = 0
        }
    }
    err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
        err = tx.Where("id in (?)", ids).Delete(&purchase.PurchaseType{}).Error
        if err != nil {
            return err
        }
 
        err = tx.Create(list).Error
        if err != nil {
            return err
        }
        return nil
    })
    return err
}
 
func (slf *PurchaseService) GetPurchaseTypeList() (list []*purchase.PurchaseType, err error) {
    db := global.GVA_DB.Model(&purchase.PurchaseType{})
    list = make([]*purchase.PurchaseType, 0)
    err = db.Order("pin desc, sort desc, id asc").Find(&list).Error
    return list, err
}
 
func (slf *PurchaseService) MaxAutoIncr() (int, error) {
    var total int64
    err := global.GVA_DB.Model(&purchase.Purchase{}).Count(&total).Error
    return int(total), err
}