OrderSendBillsApplicationService.cs 38 KB

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