pan
2025-11-24 02f675371094a80ccfebf2e8a2debc6054efe793
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
using AutoMapper;
using SqlSugar;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Stock;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_IRecordService;
using WIDESEA_IStockService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_StockService
{
    public partial class StockInfoService : ServiceBase<Dt_StockInfo, IRepository<Dt_StockInfo>>, IStockInfoService
    {
        private readonly IMapper _mapper;
 
        private readonly IRecordService _recordService;
        public IRepository<Dt_StockInfo> Repository => BaseDal;
        private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
        private readonly IOutboundOrderService _outboundOrderService;
        private readonly ILocationInfoService _locationInfoService;
        public StockInfoService(IRepository<Dt_StockInfo> BaseDal, IMapper mapper, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRecordService recordService, ILocationInfoService locationInfoService, IOutboundOrderService outboundOrderService) : base(BaseDal)
        {
            _mapper = mapper;
            _stockInfoDetailRepository = stockInfoDetailRepository;
            _recordService = recordService;
            _locationInfoService = locationInfoService;
            _outboundOrderService = outboundOrderService;
        }
 
        /// <summary>
        /// 根据托盘号查询库存
        /// </summary>
        /// <param name="palletCode"></param>
        /// <returns></returns>
        public Dt_StockInfo? GetStockByPalletCode(string palletCode)
        {
            Dt_StockInfo stockInfo = BaseDal.QueryFirst(x => x.PalletCode == palletCode);
            if (stockInfo != null)
            {
                stockInfo.Details = _stockInfoDetailRepository.QueryData(x => x.StockId == stockInfo.Id);
            }
            return stockInfo;
        }
 
 
        public void AddMaterielGroup(Dt_StockInfo stockInfo)
        {
            decimal beforeQuantity = 0;
            List<Dt_StockInfoDetail> details = new List<Dt_StockInfoDetail>();
            if (stockInfo.Id == 0)
            {
                if (stockInfo.Details != null && stockInfo.Details.Any())
                {
                    BaseDal.Db.InsertNav(stockInfo).Include(x => x.Details).ExecuteCommand();
                }
                else
                {
                    BaseDal.AddData(stockInfo);
                }
                details = stockInfo.Details;
            }
            else
            {
                beforeQuantity = stockInfo.Details.Where(x => x.Id != 0).Sum(x => x.StockQuantity);
 
                for (int i = 0; i < stockInfo.Details.Count; i++)
                {
                    if (stockInfo.Details[i].Id == 0)
                    {
                        details.Add(_stockInfoDetailRepository.Db.Insertable(stockInfo.Details[i]).ExecuteReturnEntity());
                    }
 
                }
 
            }
            stockInfo.Details = details;
            _recordService.StockQuantityChangeRecordService.AddStockChangeRecord(stockInfo, stockInfo.Details, beforeQuantity, stockInfo.Details.Sum(x => x.StockQuantity) + beforeQuantity, WIDESEA_Common.StockEnum.StockChangeType.MaterielGroup);
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="stockInfos"></param>
        /// <param name="materielCode"></param>
        /// <param name="needQuantity"></param>
        /// <param name="residueQuantity"></param>
        /// <returns></returns>
        public (List<Dt_StockInfo>, Dictionary<int, decimal>) GetOutboundStocks(List<Dt_StockInfo> stockInfos, string materielCode, decimal needQuantity, out decimal residueQuantity)
        {
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            Dictionary<int, decimal> stockAllocations = new Dictionary<int, decimal>(); // 记录每个库存明细的分配数量
 
            // 按先进先出排序所有相关的库存明细
            var sortedStockDetails = stockInfos
                .SelectMany(x => x.Details)
                .Where(x => x.MaterielCode == materielCode &&
                           x.StockQuantity > x.OutboundQuantity) // 有可用库存
                .OrderBy(x => x.CreateDate) // 按日期排序,先进先出
                .ThenBy(x => x.StockId)         // 相同生产日期按库存ID排序
                .ToList();
 
            if (!sortedStockDetails.Any())
            {
                residueQuantity = needQuantity;
                return (outStocks, stockAllocations);
            }
 
            // 计算总可用库存
            var stockTotalQuantity = sortedStockDetails.Sum(x => x.StockQuantity - x.OutboundQuantity);
 
            if (stockTotalQuantity < needQuantity)
            {
                residueQuantity = needQuantity - stockTotalQuantity;
               
            }
            else
            {
                residueQuantity = 0;
            }
 
            decimal remainingNeed = needQuantity;
 
            // 按先进先出顺序分配库存
            foreach (var detail in sortedStockDetails)
            {
                if (remainingNeed <= 0) break;
 
                decimal availableQuantity = detail.StockQuantity - detail.OutboundQuantity;
                if (availableQuantity <= 0) continue;
 
                decimal allocateQuantity = Math.Min(availableQuantity, remainingNeed);
 
                // 更新出库数量
                detail.OutboundQuantity += allocateQuantity;
                remainingNeed -= allocateQuantity;
 
                // 记录分配数量
                stockAllocations[detail.Id] = allocateQuantity;
 
                // 如果这个库存还没添加到出库列表中,就添加
                var stockInfo = stockInfos.First(x => x.Id == detail.StockId);
                if (!outStocks.Contains(stockInfo))
                {
                    outStocks.Add(stockInfo);
                }
            }
 
            residueQuantity = remainingNeed;
            return (outStocks, stockAllocations);
        }
        
        /// <summary>
        /// 根据条码获取库存信息
        /// </summary>
        public async Task<Dt_StockInfoDetail> GetStockDetailByBarcode(string barcode, string materielCode)
        {
            return await Db.Queryable<Dt_StockInfoDetail>()
                .Includes(x => x.StockInfo)
                .Where(x => x.Barcode == barcode && x.MaterielCode == materielCode)
                .FirstAsync();
        }
 
        /// <summary>
        /// 获取物料的所有条码信息
        /// </summary>
        public async Task<List<Dt_StockInfoDetail>> GetMaterialBarcodes(string materielCode, string batchNo = null)
        {
            var query = Db.Queryable<Dt_StockInfoDetail>()
                .Includes(x => x.StockInfo)
                .Where(x => x.MaterielCode == materielCode && x.StockQuantity > x.OutboundQuantity);
 
            if (!string.IsNullOrEmpty(batchNo))
            {
                query = query.Where(x => x.BatchNo == batchNo);
            }
 
            return await query.OrderBy(x => x.CreateDate).ToListAsync();
        }
        public List<Dt_StockInfo> GetStockInfos(string materielCode, string lotNo, string supplyCode, List<string> locationCodes)
        {
            var query = Db.Queryable<Dt_StockInfo>()
             .Where(x => locationCodes.Contains(x.LocationCode)
             //  && x.StockStatus == (int)StockStatusEmun.正常)
             ).Includes(x => x.Details);
 
            if (!string.IsNullOrEmpty(materielCode))
            {
                query = query.Where(x => x.Details.Any(d => d.MaterielCode == materielCode));
            }
 
            if (!string.IsNullOrEmpty(lotNo))
            {
                query = query.Where(x => x.Details.Any(d => d.BatchNo == lotNo));
            }
 
            if (!string.IsNullOrEmpty(supplyCode))
            {
                query = query.Where(x => x.Details.Any(d => d.SupplyCode == supplyCode));
            }
 
            var stocks = query.ToList();
 
            return stocks.OrderBy(x => x.Details.Where(d => d.MaterielCode == materielCode && (string.IsNullOrEmpty(supplyCode) || d.SupplyCode == supplyCode) &&
                           (string.IsNullOrEmpty(lotNo) || d.BatchNo == lotNo)).Min(d => d.CreateDate)).ToList();  
            //ISugarQueryable<Dt_LocationInfo> sugarQueryable = Db.Queryable<Dt_LocationInfo>().Where(x => locationCodes.Contains(x.LocationCode));
            //ISugarQueryable<Dt_StockInfo> sugarQueryable1 = Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.Details.Any(v => v.MaterielCode == materielCode));
            //return sugarQueryable.InnerJoin(sugarQueryable1, (a, b) => a.LocationCode == b.LocationCode).Select((a, b) => b).OrderBy(a => a.CreateDate).Includes(a => a.Details).ToList();
        }
 
        public List<Dt_StockInfo> GetUseableStocks(string materielCode, string batchNo, string supplyCode)
        {
            List<string> locationCodes = _locationInfoService.GetCanOutLocationCodes();
 
            return GetStockInfos(materielCode, batchNo,supplyCode, locationCodes);
        }
 
        public Dt_StockInfo GetPalletStockInfo(int locationType)
        {
 
            return Db.Queryable<Dt_StockInfo>().Where(x => x.StockStatus == StockStatusEmun.入库完成.ObjToInt() && SqlFunc.Subqueryable<Dt_LocationInfo>().Where(v => v.LocationCode == x.LocationCode && v.LocationType == locationType && v.LocationStatus == LocationStatusEnum.Pallet.ObjToInt() && (v.EnableStatus == EnableStatusEnum.OnlyOut.ObjToInt() || EnableStatusEnum.Normal.ObjToInt() == v.EnableStatus)).Any()).OrderBy(x => x.ModifyDate).First();
        }
 
        public List<Dt_StockInfo> GetStockInfosByPalletCodes(List<string> palletCodes)
        {
            return Db.Queryable<Dt_StockInfo>().Where(x => palletCodes.Contains(x.PalletCode)).Includes(x => x.Details).ToList();
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="materielCode"></param>
        /// <returns></returns>
        public List<StockSelectViewDTO> GetStockSelectViews(int orderId, string materielCode)
        {
            try
            {
                Dt_OutboundOrder outboundOrder = _outboundOrderService.Repository.QueryFirst(x => x.Id == orderId);
                if (outboundOrder == null)
                {
                    throw new Exception($"未找到出库单信息");
                }
 
                List<string> locationCodes = _locationInfoService.GetCanOutLocationCodes();
 
                return BaseDal.QueryTabs<Dt_StockInfo, Dt_StockInfoDetail, StockSelectViewDTO>((a, b) => a.Id == b.StockId, (a, b) => new StockSelectViewDTO
                {
                    LocationCode = a.LocationCode,
                    MaterielCode = b.MaterielCode,
                    MaterielName = b.MaterielName,
                    Barcode=b.Barcode,
                    PalletCode = a.PalletCode,
                    UseableQuantity = b.StockQuantity - b.OutboundQuantity
                }, a => locationCodes.Contains(a.LocationCode), b => b.StockQuantity > b.OutboundQuantity && b.MaterielCode == materielCode, x => true).GroupBy(x => x.PalletCode).Select(x => new StockSelectViewDTO
                {
                    LocationCode = x.FirstOrDefault()?.LocationCode ?? "",
                    MaterielCode = x.FirstOrDefault()?.MaterielCode ?? "",
                    MaterielName = x.FirstOrDefault()?.MaterielName ?? "",
                    Barcode=x.FirstOrDefault()?.Barcode??"",
                    PalletCode = x.Key,
                    UseableQuantity = x.Sum(x => x.UseableQuantity)
                }).ToList();
            }
            catch (Exception ex)
            {
                return null;
            }
 
        }
    }
}