OrderSendBillsApplicationService.cs 36 KB

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