OrderSendBillsApplicationService.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. if (!templateInfo.ClassPath.IsNullOrEmpty())
  467. {
  468. HandlerMiniDto(miniValue, templateInfo);
  469. }
  470. path = AppDomain.CurrentDomain.BaseDirectory + templateInfo.FilePath;
  471. fileName = templateInfo.Name + fileName;
  472. }
  473. var savePath = "Download/Excel/OrderSendBill";
  474. savePath = Path.Combine($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  475. string resultPath = $"/Download/Excel/OrderSendBill/{fileName}";
  476. //var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  477. try
  478. {
  479. await MiniExcel.SaveAsByTemplateAsync(savePath, path, miniValue);
  480. }
  481. catch (Exception err)
  482. {
  483. CheckErrors(new IdentityResult(err.Message));
  484. }
  485. return resultPath;
  486. }
  487. private async Task<OrderSendMiniExcelDto> ConvertToMiniExcelDto(OrderSendBill bill,Customer customerInfo,List<ViewOrderSend> orderSends)
  488. {
  489. OrderSendMiniExcelDto miniValue = new OrderSendMiniExcelDto()
  490. {
  491. Ex1 = DateTime.Now.ToString("yyyy-MM-dd"),
  492. Ex2 = DateTime.Now.ToString("yyyy年MM月dd日"),
  493. OrderSendBillNo = bill.Id,
  494. SendAddress = bill.SendAddress,
  495. CustomerName = customerInfo.CustomerName,
  496. ContactTels = bill.ContactTels,
  497. ContactMan = bill.ContactMan
  498. };
  499. var customerDefaultProducts = await QueryAppService.GetCustomerDefaultProductByCustomerId(customerInfo.Id);
  500. var productProperties =await QueryAppService.GetProductPropertyEntity(ProductProperty.ProductMaterial+"");
  501. miniValue.SendDate = bill.SendDate;
  502. int index = 0;
  503. decimal allPackageCount = 0;
  504. decimal allSendQuantity = 0;
  505. decimal allTotalPrice = 0;
  506. List<OrderSendItemExcelDto> orderSendItem = new List<OrderSendItemExcelDto>();
  507. foreach (var send in orderSends)
  508. {
  509. OrderSendItemExcelDto item = new OrderSendItemExcelDto();
  510. var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  511. allSendQuantity += sendQuantity;
  512. var quantityPerPack = send.QuantityPerPack ?? 0;
  513. quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  514. decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  515. var sysl = sendQuantity - quantityPerPack * packageCount;
  516. allPackageCount += packageCount + (sysl > 0 ? 1 : 0);
  517. item.Index = index + 1;
  518. item.StockNo = send.StockNo ?? send.OrderNo;
  519. item.PartNo = send.PartNo ?? "";
  520. item.ProductName = send.ProductName ?? "";
  521. item.Model = send.Model ?? "";
  522. item.SurfaceColor = send.SurfaceColor ?? "";
  523. item.Material = send.Material ?? "";
  524. item.Rigidity = send.Rigidity ?? "";
  525. item.Unit = "千件";
  526. item.SendQuantity = sendQuantity;
  527. item.PackageCount = packageCount;
  528. item.QuantityPerPack = quantityPerPack;
  529. item.Sysl = sysl;
  530. item.ProductBatchNum = send.ProductBatchNum ?? "";
  531. item.SendDate = send.SendDate;
  532. item.Remark = send.Remark;
  533. item.Price = send.Price;
  534. item.AfterTaxPrice = send.AfterTaxPrice;
  535. item.ProductHsCode =
  536. CommonQueryService.GetProductHsCode(send.CustomerId, send.ProductNo, customerDefaultProducts);
  537. item.MaterialHsCode =
  538. CommonQueryService.GetMaterialHsCode(send.ProductNo,productProperties);
  539. allTotalPrice += send.TotalPrice;
  540. orderSendItem.Add(item);
  541. index++;
  542. }
  543. miniValue.AllPackageCount = allPackageCount;
  544. miniValue.AllSendQuantity = allSendQuantity;
  545. miniValue.AllTotalPrice = allTotalPrice;
  546. miniValue.send = orderSendItem;
  547. return miniValue;
  548. }
  549. //public async Task<string> ExportOrderSendCommon2(EntityDto<string> input)
  550. // {
  551. // var bill = await Repository.FirstOrDefaultAsync(input.Id);
  552. // //var orderSends = (await ViewOrderSendRepository.GetAllListAsync(i => i.OrderSendBillNo == input.Id)).OrderBy(i=>i.SurfaceColor).ThenBy(i=>i.Rigidity).ToList();
  553. // var orderSends =
  554. // (await ViewOrderSendRepository.GetAllListAsync(i => i.OrderSendBillNo == input.Id)).OrderBy(i => i.SendBillSort).ThenByDescending(i=>i.SendDate).ToList();
  555. // var customerInfo = await CustomerRepository.FirstOrDefaultAsync(bill.CustomerId);
  556. // if (orderSends.Any())
  557. // {
  558. // if (orderSends[0].SaleType == 2)
  559. // {
  560. // return ExportOutSale(orderSends, bill, customerInfo);
  561. // }
  562. // }
  563. // string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/OrderSendTemplate/送货单模板.xlsx";
  564. // var savePath = "Download/Excel/OrderSendBill";
  565. // var work = ExcelHelper.CreateWorkBook07(path);
  566. // var sheet1 = work.GetSheet("Sheet1");
  567. // sheet1.GenerateCell(2, 1).SetCellValue("单号:"+bill.Id);
  568. // sheet1.GenerateCell(5, 2).SetCellValue("客户:" + customerInfo.CustomerName);
  569. // sheet1.GenerateCell(5, 10).SetCellValue("地址:" + bill.SendAddress);
  570. // sheet1.GenerateCell(6, 2).SetCellValue("联系电话:" + bill.ContactTels);
  571. // sheet1.GenerateCell(6, 10).SetCellValue("联系人:" + bill.ContactMan);
  572. // sheet1.GenerateCell(7, 1).SetCellValue("日期:" + DateTime.Now.ToString("yyyy年MM月dd日"));
  573. // sheet1.InsertRows(10, orderSends.Count);
  574. // int index = 0;
  575. // decimal allPackageCount = 0;
  576. // foreach (var send in orderSends)
  577. // {
  578. // var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  579. // var quantityPerPack = send.QuantityPerPack ?? 0;
  580. // quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  581. // decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  582. // var sysl = sendQuantity - quantityPerPack * packageCount;
  583. // allPackageCount += packageCount+(sysl>0?1:0);
  584. // sheet1.GenerateCell(10 + index, 1).SetValue<int>(index + 1);
  585. // sheet1.GenerateCell(10 + index, 2).SetValue(send.StockNo?? send.OrderNo);
  586. // sheet1.GenerateCell(10 + index, 3).SetValue(send.PartNo ?? "");
  587. // sheet1.GenerateCell(10 + index, 4).SetValue(send.ProductName??"");
  588. // sheet1.GenerateCell(10 + index, 5).SetValue(send.Model ?? "");
  589. // sheet1.GenerateCell(10 + index, 6).SetValue(send.SurfaceColor ?? "");
  590. // sheet1.GenerateCell(10 + index, 7).SetValue(send.Material ?? "");
  591. // sheet1.GenerateCell(10 + index, 8).SetValue(send.Rigidity ?? "");
  592. // sheet1.GenerateCell(10 + index, 9).SetValue("千件");
  593. // sheet1.GenerateCell(10 + index, 10).SetValue<decimal>(sendQuantity);
  594. // sheet1.GenerateCell(10 + index, 11).SetValue<decimal>(packageCount);
  595. // sheet1.GenerateCell(10 + index, 12).SetValue<decimal>(quantityPerPack);
  596. // sheet1.GenerateCell(10 + index, 13).SetValue<decimal>(sysl);
  597. // sheet1.GenerateCell(10 + index, 14).SetValue<decimal>(sendQuantity);
  598. // sheet1.GenerateCell(10 + index, 15).SetValue(send.ProductBatchNum??"");
  599. // index++;
  600. // }
  601. // index++;
  602. // sheet1.GenerateCell(10 + index, 8).SetValue( "合计: 托盘、"+ allPackageCount + "箱、待进仓");
  603. // index+=3;
  604. // sheet1.GenerateCell(10 + index, 12).SetValue( "送货日期:"+DateTime.Now.ToString("yyyy-MM-dd"));
  605. // var fileName = $"送货单-{Clock.Now:yyMMddHHmmss}.xlsx";
  606. // var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  607. // if (!result.IsNullOrEmpty())
  608. // {
  609. // //CheckErrors(IwbIdentityResult.Failed(result));
  610. // return null;
  611. // }
  612. // return $"/{savePath}/{fileName}";
  613. // }
  614. //private string ExportOutSale(List<ViewOrderSend> orderSends, OrderSendBill bill,
  615. // Customer customerInfo)
  616. //{
  617. // string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/OrderSendTemplate/外销送货单模板2.xlsx";
  618. // OrderSendMiniExcelDto miniValue = new OrderSendMiniExcelDto()
  619. // {
  620. // Ex1 = DateTime.Now.ToString("yyyy-MM-dd"),
  621. // OrderSendBillNo = bill.Id,
  622. // SendAddress = bill.SendAddress,
  623. // CustomerName = customerInfo.CustomerName
  624. // };
  625. // var savePath = "Download/Excel/OrderSendBill";
  626. // var fileName = $"送货单-{Clock.Now:yyMMddHHmmss}.xlsx";
  627. // int index = 0;
  628. // decimal allPackageCount = 0;
  629. // decimal allSendQuantity = 0;
  630. // decimal allTotalPrice = 0;
  631. // List<OrderSendItemExcelDto> orderSendItem = new List<OrderSendItemExcelDto>();
  632. // foreach (var send in orderSends)
  633. // {
  634. // OrderSendItemExcelDto item = new OrderSendItemExcelDto();
  635. // var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  636. // allSendQuantity += sendQuantity;
  637. // var quantityPerPack = send.QuantityPerPack ?? 0;
  638. // quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  639. // decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  640. // var sysl = sendQuantity - quantityPerPack * packageCount;
  641. // allPackageCount += packageCount + (sysl > 0 ? 1 : 0);
  642. // item.Index = index + 1;
  643. // item.StockNo = send.StockNo ?? send.OrderNo;
  644. // item.PartNo = send.PartNo ?? "";
  645. // item.ProductName = send.ProductName ?? "";
  646. // item.Model = send.Model ?? "";
  647. // item.SurfaceColor = send.SurfaceColor ?? "";
  648. // item.Material = send.Material ?? "";
  649. // item.Rigidity = send.Rigidity ?? "";
  650. // item.Unit = "千件";
  651. // item.SendQuantity = sendQuantity;
  652. // item.PackageCount = packageCount;
  653. // item.QuantityPerPack = quantityPerPack;
  654. // item.Sysl = sysl;
  655. // item.ProductBatchNum = send.ProductBatchNum ?? "";
  656. // allTotalPrice += send.TotalPrice;
  657. // orderSendItem.Add(item);
  658. // index++;
  659. // }
  660. // miniValue.AllPackageCount = allPackageCount;
  661. // miniValue.AllSendQuantity = allSendQuantity;
  662. // miniValue.AllTotalPrice = allTotalPrice;
  663. // miniValue.send=orderSendItem;
  664. // savePath = Path.Combine($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  665. // string resultPath = $"/Download/Excel/OrderSendBill/{fileName}";
  666. // //var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  667. // try
  668. // {
  669. // MiniExcel.SaveAsByTemplate(savePath, path, miniValue);
  670. // }
  671. // catch (Exception err)
  672. // {
  673. // CheckErrors(new IdentityResult(err.Message));
  674. // }
  675. // return resultPath;
  676. //}
  677. //private string ExportOutSale2(List<ViewOrderSend> orderSends, OrderSendBill bill,
  678. //Customer customerInfo)
  679. //{
  680. // string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/OrderSendTemplate/外销送货单模板.xlsx";
  681. // var savePath = "Download/Excel/OrderSendBill";
  682. // var work = ExcelHelper.CreateWorkBook07(path);
  683. // var sheet1 = work.GetSheet("Sheet1");
  684. // sheet1.GenerateCell(2, 1).SetCellValue("单号:" + bill.Id);
  685. // sheet1.GenerateCell(5, 1).SetCellValue("Buyer Name:" + customerInfo.CustomerName);
  686. // sheet1.GenerateCell(6, 1).SetCellValue("Buyer Add: " + bill.SendAddress);
  687. // //sheet1.GenerateCell(6, 2).SetCellValue("联系电话:" + bill.ContactTels);
  688. // //sheet1.GenerateCell(6, 10).SetCellValue("联系人:" + bill.ContactMan);
  689. // //sheet1.GenerateCell(7, 1).SetCellValue("日期:" + DateTime.Now.ToString("yyyy年MM月dd日"));
  690. // sheet1.InsertRows(14, orderSends.Count);
  691. // int index = 0;
  692. // decimal allPackageCount = 0;
  693. // decimal allSendQuantity = 0;
  694. // decimal allTotalPrice = 0;
  695. // foreach (var send in orderSends)
  696. // {
  697. // var sendQuantity = Math.Round(Math.Floor(send.SendQuantity * 1000) / 1000, 3);//发货数量
  698. // allSendQuantity += sendQuantity;
  699. // var quantityPerPack = send.QuantityPerPack ?? 0;
  700. // quantityPerPack = quantityPerPack == 0 ? sendQuantity : quantityPerPack;//每包数量,如果为0则等于发货数量
  701. // decimal packageCount = sendQuantity == 0 ? 0 : (sendQuantity <= quantityPerPack ? 1 : Math.Floor(send.SendQuantity / quantityPerPack));
  702. // var sysl = sendQuantity - quantityPerPack * packageCount;
  703. // allPackageCount += packageCount + (sysl > 0 ? 1 : 0);
  704. // sheet1.GenerateCell(14 + index, 1).SetValue<int>(index + 1);
  705. // sheet1.GenerateCell(14 + index, 2).SetValue(send.StockNo ?? send.OrderNo);
  706. // sheet1.GenerateCell(14 + index, 3).SetValue(send.PartNo ?? "");
  707. // sheet1.GenerateCell(14 + index, 4).SetValue(send.ProductName ?? "");
  708. // sheet1.GenerateCell(14 + index, 5).SetValue(send.Model ?? "");
  709. // sheet1.GenerateCell(14 + index, 6).SetValue(send.SurfaceColor ?? "");
  710. // sheet1.GenerateCell(14 + index, 7).SetValue(send.Material ?? "");
  711. // sheet1.GenerateCell(14 + index, 8).SetValue(send.Rigidity ?? "");
  712. // sheet1.GenerateCell(14 + index, 9).SetValue("千件");
  713. // sheet1.GenerateCell(14 + index, 10).SetValue<decimal>(sendQuantity);
  714. // sheet1.GenerateCell(14 + index, 11).SetValue<decimal>(packageCount);
  715. // sheet1.GenerateCell(14 + index, 12).SetValue<decimal>(quantityPerPack);
  716. // sheet1.GenerateCell(14 + index, 13).SetValue<decimal>(sysl);
  717. // sheet1.GenerateCell(14 + index, 14).SetValue<decimal>(sendQuantity);
  718. // sheet1.GenerateCell(14 + index, 15).SetValue(send.ProductBatchNum ?? "");
  719. // //sheet1.GenerateCell(14 + index, 16).SetValue<decimal>(send.Price);
  720. // //sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(send.TotalPrice);
  721. // allTotalPrice += send.TotalPrice;
  722. // index++;
  723. // }
  724. // index += 4;
  725. // sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(allSendQuantity);
  726. // index += 1;
  727. // //sheet1.GenerateCell(14 + index, 17).SetValue<decimal>(allTotalPrice);
  728. // index += 3;
  729. // sheet1.GenerateCell(14 + index, 12).SetValue("送货日期:" + DateTime.Now.ToString("yyyy-MM-dd"));
  730. // var fileName = $"送货单-{Clock.Now:yyMMddHHmmss}.xlsx";
  731. // var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  732. // if (!result.IsNullOrEmpty())
  733. // {
  734. // //CheckErrors(IwbIdentityResult.Failed(result));
  735. // return null;
  736. // }
  737. // return $"/{savePath}/{fileName}";
  738. //}
  739. #endregion
  740. }
  741. }