zhangqian
2024-08-01 fc3313955a083c9480e4ea74398f72f9ba6addcd
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
package service
 
import (
    "fmt"
    "github.com/shopspring/decimal"
    "github.com/xuri/excelize/v2"
    "strconv"
    "time"
    "wms/constvar"
    "wms/models"
    "wms/pkg/logx"
    "wms/request"
)
 
type WarehouseMonthFormsService struct{}
 
func NewWarehouseMonthFormsService() *WarehouseMonthFormsService {
    return &WarehouseMonthFormsService{}
}
 
func (slf *WarehouseMonthFormsService) Query(params request.GetMonthStats) (result []*models.WarehouseMonthStats, err error) {
    search := slf.BuildSearch(params)
    search = search.SetPage(params.Page, params.PageSize)
    return search.FindNotTotal()
}
 
func (slf *WarehouseMonthFormsService) BuildSearch(params request.GetMonthStats) (search *models.WarehouseMonthStatsSearch) {
    search = models.NewWarehouseMonthStatsSearch().
        SetKeyword(params.Keyword).SetDate(params.Date).SetWarehouseId(params.WarehouseID)
    if params.Preload {
        search = search.SetPreload(true)
    }
    return search
}
 
func (slf *WarehouseMonthFormsService) Count(params request.GetMonthStats) (total int64, err error) {
    search := slf.BuildSearch(params)
    return search.Count()
}
 
func (slf *WarehouseMonthFormsService) FetchAll(params request.GetMonthStats) (list []*models.WarehouseMonthStats, err error) {
    total, err := slf.Count(params)
    if err != nil {
        return nil, err
    }
    list = make([]*models.WarehouseMonthStats, 0, total)
    params.PageSize = 500
    page := 1
    for {
        params.Page = page
        data, err := slf.Query(params)
        if err != nil {
            return nil, err
        }
        if len(data) == 0 {
            break
        }
        list = append(list, data...)
        page++
    }
    return
}
 
func (slf *WarehouseMonthFormsService) Export(dataList []*models.WarehouseMonthStats) (filename string, err error) {
    // 创建一个新的 Excel 文件
    f := excelize.NewFile()
 
    if err != nil {
        logx.Errorf("NewSheet err:%v", err)
        return "", err
    }
 
    headers, headerLen, inputTypes, outputTypes := slf.GetHeaders()
    _, err = SetExcelHeaders(headers, f)
    if err != nil {
        logx.Errorf("SetExcelHeader err:%v", err)
        return "", err
    }
 
    //表头样式
    style, err := SetHeaderStyle(f)
    if err != nil {
        return "", err
    }
 
    f.SetCellStyle("Sheet1", "A1", getColumnAlphabet(headerLen)+"2", style)
    // 设置列宽
    f.SetColWidth("Sheet1", "A", "F", 30)
    f.SetColWidth("Sheet1", "G", getColumnAlphabet(headerLen), 15)
 
    inputStart := 6
    outputStart := 6 + len(inputTypes)
    for i, v := range dataList {
        column := strconv.Itoa(i + 3)
        f.SetCellValue("Sheet1", "A"+column, v.ProductId)
        f.SetCellValue("Sheet1", "B"+column, v.ProductName)
        f.SetCellValue("Sheet1", "C"+column, v.EndAmount)
        f.SetCellValue("Sheet1", "D"+column, v.BeginAmount)
        f.SetCellValue("Sheet1", "E"+column, v.Unit)
        f.SetCellValue("Sheet1", "F"+column, v.SalePrice)
 
        slf.FillDealerTypeToExcel(v.InputItems, inputStart, i+3, inputTypes, f, constvar.InputTotalHeader)
        slf.FillDealerTypeToExcel(v.OutputItems, outputStart, i+3, outputTypes, f, constvar.OutPutTotalHeader)
    }
 
    fileName := fmt.Sprintf("%s月度统计报表%s.xlsx", "仓库", time.Now().Format("2006-01-02-1504"))
    if err := f.SaveAs(fileName); err != nil {
        return fileName, err
    }
 
    return fileName, nil
}
 
func (slf *WarehouseMonthFormsService) GetHeaders() (headers []interface{}, headerLen int, inputTypes, outputTypes []string) {
    // 自定义表头
 
    //查询入库类型
    inputTypes = GetDictNameListByType(constvar.StorageType)
    inputTypes = append(inputTypes, constvar.InputTotalHeader)
 
    headerLen += len(inputTypes)
 
    //查询入库类型
    outputTypes = GetDictNameListByType(constvar.StockoutType)
    outputTypes = append(outputTypes, constvar.OutPutTotalHeader)
 
    headerLen += len(inputTypes)
 
    headerLen += 6
 
    headers = []interface{}{"物料编号", "物料编码", "月末结存", "月初结存", "单位", "单价", map[string][]string{"本月入库": inputTypes}, map[string][]string{"本月出库": outputTypes}}
    return headers, headerLen, inputTypes, outputTypes
}
 
func (slf *WarehouseMonthFormsService) SumItems(items []*models.WarehouseStatsItems) (sum decimal.Decimal) {
    for _, v := range items {
        sum = sum.Add(v.Amount)
    }
    return sum
}
 
func (slf *WarehouseMonthFormsService) FillDealerTypeToExcel(items []*models.WarehouseStatsItems, startIndex int, column int, dealerTypes []string, f *excelize.File, totalHeader string) {
    columnStr := strconv.Itoa(column)
    sum := slf.SumItems(items)
    detailMap := models.WarehouseStatsItemMap(items)
    for k := range detailMap {
        if k == "" {
            detailMap["其他"] = detailMap[k]
            delete(detailMap, k)
        }
    }
 
    for i := 0; i < len(dealerTypes); i++ {
        var amount decimal.Decimal
        if detailMap[dealerTypes[i]] != nil {
            amount = detailMap[dealerTypes[i]].Amount
        } else if dealerTypes[i] == totalHeader {
            amount = sum
        }
        f.SetCellValue("Sheet1", getColumnAlphabet(startIndex+i)+columnStr, amount)
    }
    return
}
 
func GetCurrentWarehouseStats(date string, warehouseId int, productIds []string, realTime bool) (statRecords []*models.WarehouseMonthStats, err error) {
    //本月期初数量/上月结余数量
    groupSumList, err := models.NewLocationProductAmountSearch().SetProductIds(productIds).GroupSum("product_id", "amount")
    productIds = make([]string, 0, len(groupSumList))
    for _, groupSum := range groupSumList {
        productIds = append(productIds, groupSum.Class)
    }
    products, err := models.NewMaterialSearch().SetFields("id, name, unit, weight, more_unit, more_unit_value").SetIDs(productIds).FindNotTotal()
    if err != nil {
        logx.Errorf("MonthStats GetCurrentStats get products err:%v", err)
        return
    }
    productMap := models.MaterialMap(products)
 
    //按配置取开始时间和结束时间
    beginTime, endTime, err := NewSystemConfigService().GetInventoryCutOffTime()
    if realTime {
        beginTime = endTime
        endTime = time.Now()
    }
    if err != nil {
        logx.Errorf("MonthStats GetCurrentStats get GetInventoryCutOffTime err:%v", err)
        return
    }
    inputMap, err := GetStatsMulti(beginTime, endTime, constvar.BaseOperationTypeIncoming, warehouseId)
    if err != nil {
        logx.Errorf("MonthStats GetStatsByOperationType input err:%v", err)
        return
    }
 
    outputMap, err := GetStatsMulti(beginTime, endTime, constvar.BaseOperationTypeOutgoing, warehouseId)
    if err != nil {
        logx.Errorf("MonthStats GetStatsByOperationType output err:%v", err)
        return
    }
 
    for _, groupSum := range groupSumList {
        productId := groupSum.Class
        if productMap[productId] == nil {
            continue
        }
        product := productMap[productId]
 
        amount := groupSum.Sum
        record := models.WarehouseMonthStats{
            WarehouseId:  warehouseId,
            ProductId:    productId,
            ProductName:  product.Name,
            Unit:         product.Unit,
            SalePrice:    product.SalePrice,
            EndAmount:    amount,
            InputAmount:  SumMapAmount(inputMap[productId]),
            InputItems:   GetDealerItems(inputMap[productId], models.MonthStatsItemsTypeInput),
            OutputAmount: SumMapAmount(outputMap[productId]),
            OutputItems:  GetDealerItems(outputMap[productId], models.MonthStatsItemsTypeOutput),
            Date:         date,
        }
        statRecords = append(statRecords, &record)
    }
 
    return
}
 
func GetStatsMulti(beginTime, endTime time.Time, operationType constvar.BaseOperationType, warehouseId int) (m map[string]map[string]decimal.Decimal, err error) {
    m = make(map[string]map[string]decimal.Decimal)
    operationIds, err := models.NewOperationSearch().SetBaseOperationType(operationType).
        SetFields("id").SetTimeBetween(beginTime, endTime).
        SetWarehouseId(warehouseId).
        FindIds()
    if err != nil {
        return
    }
    if len(operationIds) == 0 {
        return
    }
    groupSumList, err := models.NewOperationDetailsSearch().SetOperationIds(operationIds).
        SetFields("product_id, dealer_type, amount").
        GroupMultiSumAmount()
    if err != nil {
        return
    }
    m = make(map[string]map[string]decimal.Decimal)
    for _, v := range groupSumList {
        if m[v.ProductID] == nil {
            m[v.ProductID] = make(map[string]decimal.Decimal)
        }
        m[v.ProductID][v.DealerType] = v.Sum
    }
    return
}
 
func SumMapAmount(m map[string]decimal.Decimal) (sum decimal.Decimal) {
    for _, v := range m {
        sum = sum.Add(v)
    }
    return
}
 
func GetDealerItems(m map[string]decimal.Decimal, tp models.MonthStatsItemsType) (items []*models.WarehouseStatsItems) {
    for k, v := range m {
        name := k
        if name == "" {
            name = "其他"
        }
        items = append(items, &models.WarehouseStatsItems{
            Type:   tp,
            Name:   name,
            Amount: v,
        })
    }
    return
}