OrderSendBillsApplicationService.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using System.Web.Mvc;
  9. using Abp.Application.Services.Dto;
  10. using Abp.Authorization;
  11. using Abp.Domain.Repositories;
  12. using Abp.Extensions;
  13. using Abp.Json;
  14. using Abp.Timing;
  15. using Castle.MicroKernel.Registration.Interceptor;
  16. using IwbZero.AppServiceBase;
  17. using IwbZero.Auditing;
  18. using IwbZero.IdentityFramework;
  19. using Microsoft.AspNet.Identity;
  20. using ShwasherSys.Authorization.Permissions;
  21. using ShwasherSys.BaseSysInfo;
  22. using ShwasherSys.Common;
  23. using ShwasherSys.CustomerInfo;
  24. using ShwasherSys.EntityFramework;
  25. using ShwasherSys.Lambda;
  26. using ShwasherSys.Order;
  27. using ShwasherSys.OrderSendInfo.Dto;
  28. using ShwasherSys.ProductStoreInfo;
  29. namespace ShwasherSys.OrderSendInfo
  30. {
  31. [AbpAuthorize]
  32. public class OrderSendBillAppService : ShwasherAsyncCrudAppService<OrderSendBill, OrderSendBillDto, string, PagedRequestDto, OrderSendBillCreateDto, OrderSendBillUpdateDto >, IOrderSendBillAppService
  33. {
  34. protected IRepository<OrderSend> OrderSendRepository;
  35. protected IRepository<OrderItem> OrderItemRepository;
  36. protected IRepository<ViewOrderSend> ViewOrderSendRepository;
  37. protected IRepository<ViewOrderSendBill,string> ViewOrderSendBillRepository;
  38. protected IRepository<FinshedEnterStore> FinshedEnterStoreRepository;
  39. protected IRepository<CurrentProductStoreHouse> CurrentProductStoreHouseRepository;
  40. protected IRepository<ProductOutStore> ProductOutStoreRepository;
  41. protected IQueryAppService QueryAppService { get; }
  42. protected ICommonAppService CommonAppService { get; }
  43. protected IRepository<BusinessLog> BusinessLogRepository { get; }
  44. protected IRepository<Customer,string> CustomerRepository { get; }
  45. protected ISqlExecuter SqlExecuter;
  46. public OrderSendBillAppService(IRepository<OrderSendBill, string> repository, IRepository<OrderSend> orderSendRepository, ISqlExecuter sqlExecuter, IRepository<OrderItem> orderItemRepository, IRepository<ViewOrderSend> viewOrderSendRepository, IRepository<ViewOrderSendBill,string> viewOrderSendBillRepository, IRepository<FinshedEnterStore> finshedEnterStoreRepository, IRepository<CurrentProductStoreHouse> currentProductStoreHouseRepository, IRepository<ProductOutStore> productOutStoreRepository, IRepository<BusinessLog> businessLogRepository, IRepository<Customer, string> customerRepository, IQueryAppService queryAppService, ICommonAppService commonAppService) : base(repository)
  47. {
  48. OrderSendRepository = orderSendRepository;
  49. SqlExecuter = sqlExecuter;
  50. OrderItemRepository = orderItemRepository;
  51. ViewOrderSendRepository = viewOrderSendRepository;
  52. ViewOrderSendBillRepository = viewOrderSendBillRepository;
  53. FinshedEnterStoreRepository = finshedEnterStoreRepository;
  54. CurrentProductStoreHouseRepository = currentProductStoreHouseRepository;
  55. ProductOutStoreRepository = productOutStoreRepository;
  56. BusinessLogRepository = businessLogRepository;
  57. CustomerRepository = customerRepository;
  58. QueryAppService = queryAppService;
  59. CommonAppService = commonAppService;
  60. }
  61. protected override string GetPermissionName { get; set; } = PermissionNames.PagesSendGoodsOrderSendBillCreate;
  62. protected override string GetAllPermissionName { get; set; } = PermissionNames.PagesSendGoodsOrderSendBillCreate;
  63. protected override string CreatePermissionName { get; set; } = PermissionNames.PagesSendGoodsOrderSendBillCreateCreate;
  64. protected override string DeletePermissionName { get; set; } = PermissionNames.PagesSendGoodsOrderSendBillCreateDelete;
  65. #region 发货管理
  66. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillCreateDelete),AuditLog("撤销发货")]
  67. public bool CancelOrderSend(EntityDto<string> input)
  68. {
  69. bool lbRetval = false;
  70. string orderSendIds = input.Id;
  71. try
  72. {
  73. var arrOrderSendIds = orderSendIds.Split(',');
  74. foreach (var orderSendId in arrOrderSendIds)
  75. {
  76. OrderSend loSendInfo = OrderSendRepository.Get(Convert.ToInt32(orderSendId));
  77. OrderItem loOrderItem = OrderItemRepository.Get(loSendInfo.OrderItemId);
  78. //-------------- 添加订单发货撤销后入库申请逻辑 ---------------
  79. var productOutStore = ProductOutStoreRepository.FirstOrDefault(i => i.OrderSendId == loSendInfo.Id);
  80. if (productOutStore == null)
  81. {
  82. CheckErrors(IwbIdentityResult.Failed("未发现出库记录!"));
  83. return false;
  84. }
  85. if (productOutStore.ApplyStatus==FinshedOutStoreApplyStatusEnum.OutStored.ToInt())
  86. {
  87. CheckErrors(IwbIdentityResult.Failed("发货记录:"+loSendInfo.Id+"的出库申请已确认出库,发货明细不可撤销!"));
  88. return false;
  89. }
  90. productOutStore.IsClose = true;//关闭出库申请记录
  91. ProductOutStoreRepository.UpdateAsync(productOutStore);
  92. CurrentProductStoreHouse currentStore = CurrentProductStoreHouseRepository.FirstOrDefault(i =>
  93. i.CurrentProductStoreHouseNo == loSendInfo.CurrentProductStoreHouseNo);
  94. if (currentStore == null)
  95. {
  96. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  97. return false;
  98. }
  99. currentStore.FreezeQuantity -= loSendInfo.SendQuantity;//恢复冻结库存
  100. currentStore.TimeLastMod = Clock.Now;
  101. CurrentProductStoreHouseRepository.UpdateAsync(currentStore);
  102. loOrderItem.OrderItemStatusId = OrderItemStatusEnum.Audited.ToInt();//更新订单明细状态
  103. OrderSendRepository.DeleteAsync(loSendInfo);//删除发货明细
  104. loOrderItem.TimeLastMod = Clock.Now;
  105. loOrderItem.UserIDLastMod = AbpSession.UserName;
  106. OrderItemRepository.UpdateAsync(loOrderItem);
  107. BusinessLogTypeEnum.OrderSend.WriteLog(BusinessLogRepository,"撤销发货",$"发货单{loSendInfo.ToJsonString()}取消发货,库存编码为:{currentStore.CurrentProductStoreHouseNo}的库存冻结数量减少{loSendInfo.SendQuantity}!订单明细状态变更为发货中..{loOrderItem.ToJsonString()}");
  108. }
  109. this.LogInfo("撤销发货明细:" + input.Id + " 成功!");
  110. lbRetval = true;
  111. }
  112. catch (Exception e)
  113. {
  114. this.LogError("撤销发货明细:" + input.Id + " 失败!" + e);
  115. throw;
  116. }
  117. return lbRetval;
  118. }
  119. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillCreate),AuditLog("根据客户编号,查询出待生成发货单的发货明细")]
  120. public async Task<List<ViewOrderSend>> GetOrderSendByCustomerId(QuerySendDto input)
  121. {
  122. var queryAllList = ViewOrderSendRepository.GetAll().Where(i =>
  123. i.CustomerId == input.CustomerId && (i.OrderSendBillNo == null || i.OrderSendBillNo == "") &&
  124. i.CustomerSendId == input.CustomerSendId).OrderByDescending(i=>i.SendDate);
  125. var query = await AsyncQueryableExecuter.ToListAsync(queryAllList);
  126. if (input.SendDateStart != null)
  127. {
  128. query= query.Where(i => i.SendDate >= input.SendDateStart).ToList();
  129. }
  130. if (input.SendDateEnd != null)
  131. {
  132. query = query.Where(i => i.SendDate < input.SendDateEnd).ToList();
  133. }
  134. return query;
  135. }
  136. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillCreate),AuditLog("查询出待生成发货单的客户列表记录")]
  137. public List<SelectListItem> GetHasSendOrderCustomer()
  138. {
  139. List<SelectListItem> listItems = new List<SelectListItem>();
  140. var queryAllList = ViewOrderSendRepository.GetAll().Where(i => (i.OrderSendBillNo == null || i.OrderSendBillNo == "") && i.CustomerId != null).Select(i => i.CustomerId).Distinct();
  141. foreach (var send in queryAllList)
  142. {
  143. listItems.Add(new SelectListItem()
  144. {
  145. Text = send,
  146. Value = send
  147. });
  148. }
  149. return listItems;
  150. }
  151. #endregion
  152. #region 发货单管理
  153. /// <summary>
  154. /// 生成发货单号
  155. /// </summary>
  156. /// <returns></returns>
  157. public string GetNewOrderSendBillNo()
  158. {
  159. string lcRetVal = "";
  160. DateTime loTiem = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-01");
  161. loTiem = loTiem.AddSeconds(-1);
  162. var bills = Repository.GetAll().Where(i => i.TimeCreated > loTiem).OrderByDescending(i => i.Id);
  163. if (bills.Any())
  164. {
  165. int liTempNo = 0;
  166. string lcTempNo = bills.First().Id;
  167. lcTempNo = lcTempNo.Remove(0, 1);
  168. liTempNo = Convert.ToInt32(lcTempNo);
  169. liTempNo++;
  170. lcRetVal = "B" + liTempNo;
  171. if (lcRetVal.Length < 10)
  172. {
  173. lcRetVal = "0" + lcRetVal;
  174. }
  175. }
  176. else
  177. {
  178. DateTime loDate = DateTime.Today;
  179. string month = loDate.Date.Month < 10 ? "0" + loDate.Date.Month : loDate.Date.Month.ToString();
  180. lcRetVal = "B" + loDate.Date.Year + month + "0001";
  181. }
  182. return lcRetVal;
  183. }
  184. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillCreateCreate),AuditLog("发货单生成")]
  185. public override async Task<OrderSendBillDto> Create(OrderSendBillCreateDto input)
  186. {
  187. string orderSendIds = input.OrderSendIds;
  188. input.Id = GetNewOrderSendBillNo();
  189. input.SendDate = Clock.Now;
  190. input.TimeCreated = input.SendDate;
  191. input.TimeLastMod = input.SendDate;
  192. input.UserIDLastMod = AbpSession.UserName;
  193. input.IsDoBill = "N";
  194. //string lcSql = "update OrderSend set OrderSendBillNo='" + input.Id + "' ";
  195. //lcSql += " where OrderSendId in(" + orderSendIds + ")";
  196. //var sCount = SqlExecuter.Execute(lcSql);
  197. string lcSql = "";
  198. var osi = Array.ConvertAll<string, int>(orderSendIds.Split(','), int.Parse);
  199. for (int i = 0; i < osi.Length; i++)
  200. {
  201. lcSql += $"update OrderSend set OrderSendBillNo='{input.Id}',SendBillSort=${i+1} where OrderSendId = ${osi[i]};\r\n ";
  202. }
  203. var sCount = SqlExecuter.Execute(lcSql);
  204. //var oss =await OrderSendRepository.GetAllListAsync(i => osi.Contains(i.Id));
  205. //for (int i =0; i < oss.Count; i++)
  206. //{
  207. // oss[i].SendBillSort = i + 1;
  208. // await OrderSendRepository.UpdateAsync(oss[i]);
  209. //}
  210. var dto = await CreateEntity(input);
  211. var customer = await CustomerRepository.FirstOrDefaultAsync(a => a.Id == dto.CustomerId);
  212. if (string.IsNullOrEmpty(customer.Email))
  213. {
  214. return dto;
  215. }
  216. var orders = await ViewOrderSendRepository.GetAllListAsync(a => (orderSendIds + ",").Contains(a.Id + ","));
  217. if (orders.Any())
  218. {
  219. var expressName =await QueryAppService.GetExpressNameById(input.ExpressId ?? 0);
  220. string msg = $"发货快递:{expressName },快递单号:{input.ExpressBillNo}\r\n\r\n";
  221. foreach (var os in orders)
  222. {
  223. msg += $"订单号:{os.StockNo},产品名称:{os.ProductName},发货数量:{os.SendQuantity}\r\n";
  224. }
  225. CommonAppService.SendEmail(customer.Email,"您有订单已发货",msg,false);
  226. }
  227. return dto;
  228. }
  229. private (int, int) GetStatementCount(IQueryable<OrderSend> query,string orderSendBillNo)
  230. {
  231. var all = query.Where(i => i.OrderSendBillNo == orderSendBillNo);
  232. var has= all.Where(i => !string.IsNullOrEmpty(i.StatementBillNo));
  233. return (all.Count(), has.Count());
  234. }
  235. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillMg),AuditLog("发货单管理查询")]
  236. public async Task<PagedResultDto<ViewOrderSendBill>> GetAllView(PagedRequestDto input)
  237. {
  238. var actionStopwatch = Stopwatch.StartNew();
  239. var query = FilterGetOrderSendBills(input);
  240. var totalCount = await AsyncQueryableExecuter.CountAsync(query);
  241. query = query.OrderByDescending(a => a.SendDate);
  242. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  243. var entities = await AsyncQueryableExecuter.ToListAsync(query);
  244. var dtos = new PagedResultDto<ViewOrderSendBill>(
  245. totalCount,
  246. entities
  247. );
  248. actionStopwatch.Stop();
  249. Debug.WriteLine(actionStopwatch.ElapsedMilliseconds);
  250. return dtos;
  251. }
  252. private IQueryable<ViewOrderSendBill> FilterGetOrderSendBills(PagedRequestDto input)
  253. {
  254. var query = ViewOrderSendBillRepository.GetAll();
  255. if (input.SearchList != null && input.SearchList.Count > 0)
  256. {
  257. List<LambdaObject> objList = new List<LambdaObject>();
  258. foreach (var o in input.SearchList)
  259. {
  260. if (o.KeyWords.IsNullOrEmpty())
  261. continue;
  262. object keyWords = o.KeyWords;
  263. if (o.KeyField == "sendDate" && (LambdaExpType)o.ExpType == LambdaExpType.LessOrEqual)
  264. {
  265. keyWords = Convert.ToDateTime(keyWords).AddDays(1);
  266. }
  267. if (o.KeyField == "isbill")
  268. {
  269. if (keyWords.ToString() == "1")
  270. {
  271. query = query.Where(i => i.OrderSendCount >= 0 && i.StatementCount == 0);
  272. }
  273. else if (keyWords.ToString() == "2")
  274. {
  275. query = query.Where(i => i.OrderSendCount > 0 && i.StatementCount == i.OrderSendCount);
  276. }
  277. else if (keyWords.ToString() == "3")
  278. {
  279. query = query.Where(i => i.StatementCount > 0 && i.StatementCount < i.OrderSendCount);
  280. }
  281. continue;
  282. }
  283. objList.Add(new LambdaObject
  284. {
  285. FieldType = (LambdaFieldType)o.FieldType,
  286. FieldName = o.KeyField,
  287. FieldValue = keyWords,
  288. ExpType = (LambdaExpType)o.ExpType
  289. });
  290. }
  291. if (objList.Any())
  292. {
  293. var exp = objList.GetExp<ViewOrderSendBill>();
  294. query = query.Where(exp);
  295. }
  296. }
  297. return query;
  298. }
  299. public async Task<decimal[]> GetAllPrice(PagedRequestDto input)
  300. {
  301. var query = FilterGetOrderSendBills(input);
  302. var totalPrice = await query.SumAsync(i => i.TotalPrice);
  303. var afterTaxTotalPrice = await query.SumAsync(i => i.AfterTaxTotalPrice);
  304. decimal[] result = new[] {totalPrice ?? 0, afterTaxTotalPrice ?? 0};
  305. return result;
  306. }
  307. //#region MyRegion
  308. //[AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillMg), AuditLog("发货单管理查询")]
  309. //public async Task<PagedResultDto<ViewOrderSendBill>> GetAllView1(PagedRequestDto input)
  310. //{
  311. // string sqlWhere = "";
  312. // string isBill = "";
  313. // if (input.SearchList != null && input.SearchList.Count > 0)
  314. // {
  315. // foreach (var o in input.SearchList)
  316. // {
  317. // if (o.KeyWords.IsNullOrEmpty())
  318. // continue;
  319. // object keyWords = o.KeyWords;
  320. // if (o.KeyField == "id" )
  321. // {
  322. // sqlWhere += $" and OrderSendBillNo like '%{keyWords}%' ";
  323. // }
  324. // if (o.KeyField == "customerId")
  325. // {
  326. // sqlWhere += $" and CustomerId like '%{keyWords}%' ";
  327. // }
  328. // if (o.KeyField == "sendDate" && (LambdaExpType)o.ExpType == LambdaExpType.LessOrEqual)
  329. // {
  330. // keyWords = Convert.ToDateTime(keyWords).AddDays(1);
  331. // sqlWhere += $" and SendDate <= '{keyWords:yyyy-MM-dd}' ";
  332. // }
  333. // if (o.KeyField == "sendDate" && (LambdaExpType)o.ExpType == LambdaExpType.GreaterOrEqual)
  334. // {
  335. // keyWords = Convert.ToDateTime(keyWords);
  336. // sqlWhere += $" and SendDate >= '{keyWords:yyyy-MM-dd}' ";
  337. // }
  338. // if (o.KeyField == "isbill")
  339. // {
  340. // isBill = keyWords.ToString();
  341. // }
  342. // }
  343. // }
  344. // string sql = "select OrderSendBillNo as Id,CustomerId,SendDate,ContactTels,ExpressName,ExpressId,ExpressBillNo,ContactMan, TotalPrice,AfterTaxTotalPrice,CurrencyId,OrderSendCount,StatementCount,SendAddress,TimeCreated,TimeLastMod,UserIDLastMod,IsDoBill,CreatorUserId from v_OrderSendBill where 1=1 " + sqlWhere;
  345. // var query = SqlExecuter.SqlQuery<ViewOrderSendBill>(sql);
  346. // var stQuery = OrderSendRepository.GetAll().Where(i => !string.IsNullOrEmpty(i.OrderSendBillNo));
  347. // foreach (var viewOrderSendBill in query)
  348. // {
  349. // var t = GetStatementCount(stQuery, viewOrderSendBill.Id);
  350. // viewOrderSendBill.StatementCount = t.Item2;
  351. // viewOrderSendBill.OrderSendCount = t.Item1;
  352. // }
  353. // if (!string.IsNullOrEmpty(isBill))
  354. // {
  355. // if (isBill == "1")
  356. // {
  357. // query = query.Where(i => i.OrderSendCount >= 0 && i.StatementCount == 0);
  358. // }
  359. // else if (isBill == "2")
  360. // {
  361. // query = query.Where(i => i.OrderSendCount > 0 && i.StatementCount == i.OrderSendCount);
  362. // }
  363. // else if (isBill == "3")
  364. // {
  365. // query = query.Where(i => i.StatementCount > 0 && i.StatementCount < i.OrderSendCount);
  366. // }
  367. // }
  368. // int totalCount = query.Count();
  369. // query = query.OrderByDescending(a => a.SendDate);
  370. // query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  371. // var entities =query.ToList();
  372. // var dtos = new PagedResultDto<ViewOrderSendBill>(
  373. // totalCount,
  374. // entities
  375. // );
  376. // return dtos;
  377. //}
  378. //#endregion
  379. [AbpAuthorize(PermissionNames.PagesSendGoodsOrderSendBillMgDelete),AuditLog("发货单撤销")]
  380. public override Task Delete(EntityDto<string> input)
  381. {
  382. CheckDeletePermission();
  383. var entity =Repository.Get(input.Id);
  384. var orderSends = OrderSendRepository.GetAllList(i => i.OrderSendBillNo == entity.Id);
  385. foreach (var send in orderSends)
  386. {
  387. send.OrderSendBillNo = "";
  388. send.OrderStickBillNo = "";
  389. OrderSendRepository.UpdateAsync(send);
  390. }
  391. BusinessLogTypeEnum.OrderSend.WriteLog(BusinessLogRepository, "撤销发货单", $"发货单{entity.ToJsonString()}撤销");
  392. //this.Logger.Info("撤销发货单!"+entity.ToString());
  393. return Repository.DeleteAsync(input.Id);
  394. }
  395. public async Task UpdateExpressInfo(OrderSendBillExpressUpdateDto input)
  396. {
  397. var entity = Repository.Get(input.Id);
  398. entity.ExpressId = input.ExpressId;
  399. entity.ExpressBillNo = input.ExpressBillNo;
  400. await Repository.UpdateAsync(entity);
  401. }
  402. public async Task<string> ExportOrderSend(EntityDto<string> input)
  403. {
  404. var bill = await Repository.FirstOrDefaultAsync(input.Id);
  405. var orderSends =(await ViewOrderSendRepository.GetAllListAsync(i => i.OrderSendBillNo == input.Id)).OrderBy(i => i.SendBillSort).ThenByDescending(i => i.SendDate).ToList();
  406. var customerInfo =await CustomerRepository.FirstOrDefaultAsync(bill.CustomerId);
  407. var templateInfo = await QueryAppService.QueryTemplate(bill.CustomerId, 2);
  408. string[] classPath = templateInfo.ClassPath.Split("@@",StringSplitOptions.RemoveEmptyEntries);
  409. if (!classPath.Any())
  410. {
  411. CheckErrors(IdentityResult.Failed("未查到对应的classPath"));
  412. }
  413. string className = classPath[0];
  414. string methodName = classPath[1];
  415. var tpType = Type.GetType(className);
  416. object obj = Activator.CreateInstance(tpType ?? throw new InvalidOperationException());
  417. Object[] paras = { bill, orderSends, customerInfo, templateInfo };
  418. MethodInfo method = tpType.GetMethod(methodName);
  419. var result = method?.Invoke(obj, paras);
  420. return result?.ToString();
  421. }
  422. public async Task<string> ExportOrderSendCommon(EntityDto<string> input)
  423. {
  424. var bill = await Repository.FirstOrDefaultAsync(input.Id);
  425. //var orderSends = (await ViewOrderSendRepository.GetAllListAsync(i => i.OrderSendBillNo == input.Id)).OrderBy(i=>i.SurfaceColor).ThenBy(i=>i.Rigidity).ToList();
  426. var orderSends =
  427. (await ViewOrderSendRepository.GetAllListAsync(i => i.OrderSendBillNo == input.Id)).OrderBy(i => i.SendBillSort).ThenByDescending(i=>i.SendDate).ToList();
  428. var customerInfo = await CustomerRepository.FirstOrDefaultAsync(bill.CustomerId);
  429. if (orderSends.Any())
  430. {
  431. if (orderSends[0].SaleType == 2)
  432. {
  433. return ExportOutSale(orderSends, bill, customerInfo);
  434. }
  435. }
  436. string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/OrderSendTemplate/送货单模板.xlsx";
  437. var savePath = "Download/Excel/OrderSendBill";
  438. var work = ExcelHelper.CreateWorkBook07(path);
  439. var sheet1 = work.GetSheet("Sheet1");
  440. sheet1.GenerateCell(2, 1).SetCellValue("单号:"+bill.Id);
  441. sheet1.GenerateCell(5, 2).SetCellValue("客户:" + customerInfo.CustomerName);
  442. sheet1.GenerateCell(5, 10).SetCellValue("地址:" + bill.SendAddress);
  443. sheet1.GenerateCell(6, 2).SetCellValue("联系电话:" + bill.ContactTels);
  444. sheet1.GenerateCell(6, 10).SetCellValue("联系人:" + bill.ContactMan);
  445. sheet1.GenerateCell(7, 1).SetCellValue("日期:" + DateTime.Now.ToString("yyyy年MM月dd日"));
  446. sheet1.InsertRows(10, orderSends.Count);
  447. int index = 0;
  448. decimal allPackageCount = 0;
  449. foreach (var send in orderSends)
  450. {
  451. var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  452. var quantityPerPack = send.QuantityPerPack ?? 0;
  453. quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  454. decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  455. var sysl = sendQuantity - quantityPerPack * packageCount;
  456. allPackageCount += packageCount+(sysl>0?1:0);
  457. sheet1.GenerateCell(10 + index, 1).SetValue<int>(index + 1);
  458. sheet1.GenerateCell(10 + index, 2).SetValue(send.StockNo?? send.OrderNo);
  459. sheet1.GenerateCell(10 + index, 3).SetValue(send.PartNo ?? "");
  460. sheet1.GenerateCell(10 + index, 4).SetValue(send.ProductName??"");
  461. sheet1.GenerateCell(10 + index, 5).SetValue(send.Model ?? "");
  462. sheet1.GenerateCell(10 + index, 6).SetValue(send.SurfaceColor ?? "");
  463. sheet1.GenerateCell(10 + index, 7).SetValue(send.Material ?? "");
  464. sheet1.GenerateCell(10 + index, 8).SetValue(send.Rigidity ?? "");
  465. sheet1.GenerateCell(10 + index, 9).SetValue("千件");
  466. sheet1.GenerateCell(10 + index, 10).SetValue<decimal>(sendQuantity);
  467. sheet1.GenerateCell(10 + index, 11).SetValue<decimal>(packageCount);
  468. sheet1.GenerateCell(10 + index, 12).SetValue<decimal>(quantityPerPack);
  469. sheet1.GenerateCell(10 + index, 13).SetValue<decimal>(sysl);
  470. sheet1.GenerateCell(10 + index, 14).SetValue<decimal>(sendQuantity);
  471. sheet1.GenerateCell(10 + index, 15).SetValue(send.ProductBatchNum??"");
  472. index++;
  473. }
  474. index++;
  475. sheet1.GenerateCell(10 + index, 8).SetValue( "合计: 托盘、"+ allPackageCount + "箱、待进仓");
  476. index+=3;
  477. sheet1.GenerateCell(10 + index, 12).SetValue( "送货日期:"+DateTime.Now.ToString("yyyy-MM-dd"));
  478. var fileName = $"送货单-{Clock.Now:yyMMddHHmmss}.xlsx";
  479. var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  480. if (!result.IsNullOrEmpty())
  481. {
  482. //CheckErrors(IwbIdentityResult.Failed(result));
  483. return null;
  484. }
  485. return $"/{savePath}/{fileName}";
  486. }
  487. private string ExportOutSale(List<ViewOrderSend> orderSends, OrderSendBill bill,
  488. Customer customerInfo)
  489. {
  490. string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/OrderSendTemplate/外销送货单模板.xlsx";
  491. var savePath = "Download/Excel/OrderSendBill";
  492. var work = ExcelHelper.CreateWorkBook07(path);
  493. var sheet1 = work.GetSheet("Sheet1");
  494. sheet1.GenerateCell(2, 1).SetCellValue("单号:" + bill.Id);
  495. sheet1.GenerateCell(5, 1).SetCellValue("Buyer Name:" + customerInfo.CustomerName);
  496. sheet1.GenerateCell(6, 1).SetCellValue("Buyer Add: " + bill.SendAddress);
  497. //sheet1.GenerateCell(6, 2).SetCellValue("联系电话:" + bill.ContactTels);
  498. //sheet1.GenerateCell(6, 10).SetCellValue("联系人:" + bill.ContactMan);
  499. //sheet1.GenerateCell(7, 1).SetCellValue("日期:" + DateTime.Now.ToString("yyyy年MM月dd日"));
  500. sheet1.InsertRows(14, orderSends.Count);
  501. int index = 0;
  502. decimal allPackageCount = 0;
  503. decimal allSendQuantity = 0;
  504. decimal allTotalPrice = 0;
  505. foreach (var send in orderSends)
  506. {
  507. var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  508. allSendQuantity += sendQuantity;
  509. var quantityPerPack = send.QuantityPerPack ?? 0;
  510. quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  511. decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  512. var sysl = sendQuantity - quantityPerPack * packageCount;
  513. allPackageCount += packageCount + (sysl > 0 ? 1 : 0);
  514. sheet1.GenerateCell(14 + index, 1).SetValue<int>(index + 1);
  515. sheet1.GenerateCell(14 + index, 2).SetValue(send.StockNo ?? send.OrderNo);
  516. sheet1.GenerateCell(14 + index, 3).SetValue(send.PartNo ?? "");
  517. sheet1.GenerateCell(14 + index, 4).SetValue(send.ProductName ?? "");
  518. sheet1.GenerateCell(14 + index, 5).SetValue(send.Model ?? "");
  519. sheet1.GenerateCell(14 + index, 6).SetValue(send.SurfaceColor ?? "");
  520. sheet1.GenerateCell(14 + index, 7).SetValue(send.Material ?? "");
  521. sheet1.GenerateCell(14 + index, 8).SetValue(send.Rigidity ?? "");
  522. sheet1.GenerateCell(14 + index, 9).SetValue("千件");
  523. sheet1.GenerateCell(14 + index, 10).SetValue<decimal>(sendQuantity);
  524. sheet1.GenerateCell(14 + index, 11).SetValue<decimal>(packageCount);
  525. sheet1.GenerateCell(14 + index, 12).SetValue<decimal>(quantityPerPack);
  526. sheet1.GenerateCell(14 + index, 13).SetValue<decimal>(sysl);
  527. sheet1.GenerateCell(14 + index, 14).SetValue<decimal>(sendQuantity);
  528. sheet1.GenerateCell(14 + index, 15).SetValue(send.ProductBatchNum ?? "");
  529. //sheet1.GenerateCell(14 + index, 16).SetValue<decimal>(send.Price);
  530. //sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(send.TotalPrice);
  531. allTotalPrice += send.TotalPrice;
  532. index++;
  533. }
  534. index += 4;
  535. sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(allSendQuantity);
  536. index += 1;
  537. //sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(allTotalPrice);
  538. index += 3;
  539. sheet1.GenerateCell(14 + index, 12).SetValue("送货日期:" + DateTime.Now.ToString("yyyy-MM-dd"));
  540. var fileName = $"送货单-{Clock.Now:yyMMddHHmmss}.xlsx";
  541. var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  542. if (!result.IsNullOrEmpty())
  543. {
  544. //CheckErrors(IwbIdentityResult.Failed(result));
  545. return null;
  546. }
  547. return $"/{savePath}/{fileName}";
  548. }
  549. #endregion
  550. }
  551. }