OrderSendBillsApplicationService.cs 40 KB

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