CommonAppService.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.Entity;
  5. using System.Data.SqlClient;
  6. using System.Linq;
  7. using System.Linq.Dynamic.Core;
  8. using System.Net.Http.Headers;
  9. using System.Net.Mail;
  10. using System.Text.RegularExpressions;
  11. using System.Threading.Tasks;
  12. using System.Web.Mvc;
  13. using System.Xml.Linq;
  14. using Abp.Application.Services;
  15. using Abp.Application.Services.Dto;
  16. using Abp.Auditing;
  17. using Abp.Domain.Repositories;
  18. using Abp.Domain.Uow;
  19. using Abp.Extensions;
  20. using Abp.Json;
  21. using Abp.Net.Mail;
  22. using Abp.Net.Mail.Smtp;
  23. using Abp.Runtime.Caching;
  24. using Abp.Runtime.Session;
  25. using Abp.Timing;
  26. using IwbZero.AppServiceBase;
  27. using IwbZero.Helper;
  28. using IwbZero.IdentityFramework;
  29. using IwbZero.Session;
  30. using MailKit;
  31. using Microsoft.AspNet.Identity;
  32. using Microsoft.AspNet.SignalR;
  33. using Newtonsoft.Json;
  34. using Newtonsoft.Json.Linq;
  35. using NPOI.SS.Formula.Functions;
  36. using Org.BouncyCastle.Asn1.Ocsp;
  37. using ShwasherSys.Authorization.Users;
  38. using ShwasherSys.BaseSysInfo;
  39. using ShwasherSys.BaseSysInfo.States;
  40. using ShwasherSys.BaseSysInfo.SysAttachFiles.Dto;
  41. using ShwasherSys.BasicInfo;
  42. using ShwasherSys.Common.Dto;
  43. using ShwasherSys.Common.Dto.HomeChartDto;
  44. using ShwasherSys.Common.Dto.Wx;
  45. using ShwasherSys.CompanyInfo;
  46. using ShwasherSys.CompanyInfo.DeviceInfo.Dto;
  47. using ShwasherSys.CustomerInfo;
  48. using ShwasherSys.EntityFramework;
  49. using ShwasherSys.Hubs;
  50. using ShwasherSys.Inspection;
  51. using ShwasherSys.NotificationInfo;
  52. using ShwasherSys.Order;
  53. using ShwasherSys.Order.Dto;
  54. using ShwasherSys.OrderSendInfo;
  55. using ShwasherSys.PackageInfo;
  56. using ShwasherSys.PackageInfo.Dto;
  57. using ShwasherSys.ProductInfo;
  58. using ShwasherSys.ProductInfo.Dto;
  59. using ShwasherSys.ProductionOrderInfo;
  60. using ShwasherSys.ProductionOrderInfo.Dto;
  61. using ShwasherSys.ProductStoreInfo;
  62. using ShwasherSys.ProductStoreInfo.Dto;
  63. using ShwasherSys.SemiProductStoreInfo;
  64. namespace ShwasherSys.Common
  65. {
  66. [DisableAuditing]
  67. public class CommonAppService : ApplicationService,ICommonAppService
  68. {
  69. protected IRepository<ProductionOrder> ProductionOrderRepository { get; }
  70. protected IRepository<CustomerDisabledProduct> CdpRepository;
  71. protected IRepository<ShortMessage> ShortMsgRepository;
  72. protected IRepository<OrderHeader,string> OrderHeaderRepository;
  73. protected IRepository<ViewOrderSend> ViewOrderSendRepository;
  74. protected IRepository<ShortMsgDetail> ShortMsgDetailRepository;
  75. protected IRepository<SysUser,long> SysUserRepository;
  76. protected IRepository<SemiEnterStore> SemiEnterStoreRepository;
  77. protected IUnitOfWorkManager _UnitOfWorkManager;
  78. protected IRepository<SysAttachFile> SysAttachFileRepository;
  79. protected IRepository<Product,string> ProductRepository;
  80. protected IRepository<SemiProducts,string> SemiProductRepository;
  81. protected IRepository<ProductMapper> ProductMapperRepository;
  82. protected ISqlExecuter SqlExecuter;
  83. protected IEmailSender EmailSender;
  84. protected IRepository<CurrentProductStoreHouse> CurrentProductStoreHouseRepository { get; }
  85. protected IRepository<CurrentSemiStoreHouse> CurrentSemiStoreHouseRepository { get; }
  86. protected IRepository<StoreHouseLocation> StoreHouseLocationRepository { get; }
  87. protected IRepository<Customer,string> CustomerRepository { get; }
  88. protected IRepository<CustomerDisabledProduct> CustomerDisabledProductRepository { get; }
  89. protected IRepository<Department,string> DepartmentRepository { get; }
  90. public IHubContext IwbHub { get; }
  91. public EmailMsgSendHandler EmailMsgSendHandler { get; }
  92. public IStatesAppService StatesAppService { get; }
  93. public IRepository<Employee> EmployeeRepository { get; }
  94. public IRepository<ViewPackageApply> ViewPackageApplyRepository { get; }
  95. public IRepository<SemiProducts, string> SemiProductsRepository { get; }
  96. public IRepository<DeviceMgPlan> DeviceMgPlanRepository { get; }
  97. public IRepository<OrderBookStore,long> OrderBookStoreRepository { get; }
  98. protected IRepository<BusinessLog> BusinessLogRepository { get; }
  99. protected IRepository<ProductProperty> ProductPropertyRepository { get; }
  100. protected IRepository<WxUser> WxUserRepository { get; }
  101. public static string WxAppId = "wx55c6a1a085db1601";
  102. public static string WxSecret = "c84deba11907d084ec2962707b208c12";
  103. public static string WxLoginReqUrl = "https://api.weixin.qq.com/sns/jscode2session";
  104. public CommonAppService(ICacheManager cacheManager, IRepository<ShortMsgDetail> shortMsgDetailRepository, IRepository<ShortMessage> shortMsgRepository, IRepository<SysUser, long> sysUserRepository, IUnitOfWorkManager unitOfWorkManager, IRepository<SysAttachFile> sysAttachFileRepository, IRepository<OrderHeader, string> orderHeaderRepository, IRepository<ViewOrderSend> viewOrderSendRepository, ISqlExecuter sqlExecuter, IEmailSender emailSender, IRepository<CurrentProductStoreHouse> currentProductStoreHouseRepository, IRepository<CurrentSemiStoreHouse> currentSemiStoreHouseRepository, IRepository<StoreHouseLocation> storeHouseLocationRepository, IRepository<CustomerDisabledProduct> cdpRepository, IRepository<ProductionOrder> productionOrderRepository, ISmtpEmailSenderConfiguration smtpEmailSenderConfiguration, IRepository<Customer, string> customerRepository, IRepository<CustomerDisabledProduct> customerDisabledProductRepository, IRepository<SemiEnterStore> semiEnterStoreRepository, IRepository<Department, string> departmentRepository, IRepository<SemiProducts, string> semiProductRepository, IRepository<Product, string> productRepository, IRepository<ProductMapper> productMapperRepository, EmailMsgSendHandler emailMsgSendHandler, IStatesAppService statesAppService, IRepository<Employee> employeeRepository,IRepository<ViewPackageApply> viewPackageApplyRepository, IRepository<SemiProducts, string> semiProductsRepository, IRepository<DeviceMgPlan> deviceMgPlanRepository, IRepository<OrderBookStore, long> orderBookStorerepository, IRepository<BusinessLog> businessLogRepository,IRepository<WxUser> wxUserRepository, IRepository<ProductProperty> productPropertyRepository)
  105. {
  106. ShortMsgDetailRepository = shortMsgDetailRepository;
  107. ShortMsgRepository = shortMsgRepository;
  108. SysUserRepository = sysUserRepository;
  109. _UnitOfWorkManager = unitOfWorkManager;
  110. SysAttachFileRepository = sysAttachFileRepository;
  111. OrderHeaderRepository = orderHeaderRepository;
  112. ViewOrderSendRepository = viewOrderSendRepository;
  113. SqlExecuter = sqlExecuter;
  114. IwbHub = GlobalHost.ConnectionManager.GetHubContext<IwbHub>();
  115. EmailSender = emailSender;
  116. CurrentProductStoreHouseRepository = currentProductStoreHouseRepository;
  117. CurrentSemiStoreHouseRepository = currentSemiStoreHouseRepository;
  118. StoreHouseLocationRepository = storeHouseLocationRepository;
  119. CdpRepository = cdpRepository;
  120. ProductionOrderRepository = productionOrderRepository;
  121. SmtpEmailSenderConfiguration = smtpEmailSenderConfiguration;
  122. CustomerRepository = customerRepository;
  123. CustomerDisabledProductRepository = customerDisabledProductRepository;
  124. SemiEnterStoreRepository = semiEnterStoreRepository;
  125. DepartmentRepository = departmentRepository;
  126. SemiProductRepository = semiProductRepository;
  127. ProductMapperRepository = productMapperRepository;
  128. ProductRepository = productRepository;
  129. EmailMsgSendHandler = emailMsgSendHandler;
  130. StatesAppService = statesAppService;
  131. EmployeeRepository = employeeRepository;
  132. ViewPackageApplyRepository = viewPackageApplyRepository;
  133. SemiProductsRepository = semiProductsRepository;
  134. DeviceMgPlanRepository = deviceMgPlanRepository;
  135. OrderBookStoreRepository = orderBookStorerepository;
  136. BusinessLogRepository = businessLogRepository;
  137. WxUserRepository = wxUserRepository;
  138. ProductPropertyRepository = productPropertyRepository;
  139. }
  140. public string KeepClock()
  141. {
  142. return Clock.Now.ToString("yyyy-MM-dd HH:mm:ss");
  143. }
  144. private Action<ISqlExecuter,DateTime> CloseProductionOrder = (sqlExecuter, date) =>
  145. {
  146. //var list = repository.GetAllList(a => a.PlanProduceDate < date && a.ProductionOrderStatus != 5);
  147. //if (list.Any())
  148. //{
  149. // foreach (var l in list)
  150. // {
  151. // l.ProductionOrderStatus = 5;
  152. // repository.Update(l);
  153. // }
  154. //}
  155. string sql =
  156. $"UPDATE [dbo].[ProductionOrders] SET ProductionOrderStatus=5 WHERE EnterDate < '{date:yyyy-MM-dd}' AND ProductionOrderStatus=4 AND IsChecked=1 ";
  157. sqlExecuter.Execute(sql);
  158. };
  159. private readonly IRepository<ProductMapper, int> _productMapperRepository;
  160. /// <summary>
  161. /// 关闭三个月前的排产单
  162. /// </summary>
  163. public async Task CloseProductOrder()
  164. {
  165. var date = DateTime.Now.AddMonths(-3);
  166. date= new DateTime(date.Year,date.Month,date.Day);
  167. if (await ProductionOrderRepository.CountAsync(a=>a.IsChecked==1 && a.EnterDate<date && a.ProductionOrderStatus==4)>0)
  168. {
  169. string sql =
  170. $"update [dbo].[ProductionOrders] set ProductionOrderStatus=5 where PlanProduceDate < '{date:yyyy-MM-dd}'";
  171. await SqlExecuter.ExecuteAsync(sql);
  172. }
  173. }
  174. public async Task WriteShortMessageByDep(string sendman,string departments,string title="",string content="",bool isSendMail = true)
  175. {
  176. string lcRecieveIds = "";
  177. var loArr = departments.Split(',');
  178. var ds = DepartmentRepository.GetAllList(i => loArr.Contains(i.DepartmentName));
  179. var dsIds = ds.Select(i => i.Id);
  180. var users = SysUserRepository.GetAllList(i => dsIds.Contains(i.DepartmentID));
  181. if (users.Any())
  182. {
  183. lcRecieveIds = string.Join(",", users.Select(i => i.UserName).ToArray());
  184. await WriteShortMessage(sendman, lcRecieveIds, title, content, isSendMail);
  185. }
  186. }
  187. /// <summary>
  188. /// 写入短消息
  189. /// </summary>
  190. /// <param name="sendman">发送人</param>
  191. /// <param name="recieveIds">接收用户名 eg:shenjianfang,menghanming,jiangjingeng</param>
  192. /// <param name="title"></param>
  193. /// <param name="content"></param>
  194. public async Task WriteShortMessage(string sendman, string recieveIds, string title = "", string content = "", bool isSendMail = false)
  195. {
  196. ShortMessage shortMessage = new ShortMessage()
  197. {
  198. SendUserID = sendman,
  199. SendTime = Clock.Now,
  200. Title = title,
  201. Content = content,
  202. RecieveUserIds = recieveIds,
  203. IsDelete = "N"
  204. };
  205. var shortMsg = await ShortMsgRepository.InsertAsync(shortMessage);
  206. await CurrentUnitOfWork.SaveChangesAsync();
  207. IwbHub.Clients.All.getShortMsg(shortMessage.ToJsonString());
  208. if (!recieveIds.IsNullOrEmpty())
  209. {
  210. var loArr = recieveIds.Split(',');
  211. if (loArr.Any())
  212. {
  213. //MailMessage mail = new MailMessage();
  214. foreach (var u in loArr)
  215. {
  216. ShortMsgDetail shortMsgDetail = new ShortMsgDetail()
  217. {
  218. IsRead = "N",
  219. MsgID = shortMsg.Id,
  220. RecvUserID = u,
  221. };
  222. //var user = SysUserRepository.FirstOrDefault(i => i.UserName == u);
  223. //mail.To.Add(user.EmailAddress);
  224. //await EmailSender.SendAsync(user.EmailAddress, "系统订单变动", content);
  225. await ShortMsgDetailRepository.InsertAsync(shortMsgDetail);
  226. }
  227. }
  228. if (isSendMail)
  229. {
  230. WriteShortMessage2(sendman, recieveIds, title, content);
  231. }
  232. }
  233. }
  234. public void WriteShortMessage2(string sendman, string recieveIds, string title = "", string content = "")
  235. {
  236. if (!recieveIds.IsNullOrEmpty())
  237. {
  238. var loArr = recieveIds.Split(',');
  239. if (loArr.Any())
  240. {
  241. //MailMessage mail = new MailMessage();
  242. //foreach (var u in loArr)
  243. //{
  244. // var user = SysUserRepository.FirstOrDefault(i => i.UserName == u);
  245. // var emailPattern = @"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$";
  246. // if (user != null && !string.IsNullOrEmpty(user.EmailAddress) && Regex.IsMatch(user.EmailAddress, emailPattern))
  247. // {
  248. // mail.To.Add(user.EmailAddress);
  249. // mail.Body = content;
  250. // mail.IsBodyHtml = true;
  251. // mail.Subject = title;
  252. // }
  253. //}
  254. //if (mail.To.Any())
  255. //{
  256. // await EmailSender.SendAsync(mail);
  257. //}
  258. List<string> receiveEmails = new List<string>();
  259. foreach (var u in loArr)
  260. {
  261. var user = SysUserRepository.FirstOrDefault(i => i.UserName == u);
  262. var emailPattern = @"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$";
  263. if (user != null && !string.IsNullOrEmpty(user.EmailAddress) &&
  264. Regex.IsMatch(user.EmailAddress, emailPattern))
  265. {
  266. receiveEmails.Add(user.EmailAddress);
  267. }
  268. }
  269. if (receiveEmails.Count > 0)
  270. {
  271. EmailMsg mailMsg = new EmailMsg(true, receiveEmails:string.Join(",", receiveEmails) , title, content);
  272. EmailMsgSendHandler.SendEmailMsg(mailMsg);
  273. }
  274. }
  275. }
  276. }
  277. protected virtual void CheckErrors(IdentityResult identityResult)
  278. {
  279. identityResult.CheckErrors(LocalizationManager);
  280. }
  281. public List<SysAttachFile> GetAttachFile(QueryAttachDto input)
  282. {
  283. var query = SysAttachFileRepository.GetAll().Where(i =>
  284. i.TableName == input.TableName && i.ColumnName == input.ColName && i.SourceKey == input.Key);
  285. return query.ToList();
  286. }
  287. /// <summary>
  288. /// 判断订单是否有发货记录
  289. /// </summary>
  290. /// <param name="pcOrderNo"></param>
  291. /// <returns></returns>
  292. public async Task<bool> CheckOrderHasSend(string pcOrderNo)
  293. {
  294. var orderSends = await ViewOrderSendRepository.GetAllListAsync(i => i.OrderNo == pcOrderNo);
  295. return orderSends.Any();
  296. }
  297. /// <summary>
  298. /// 检查改批次产品能否发货给某客户
  299. /// </summary>
  300. /// <param name="productOrderNo"></param>
  301. /// <param name="customerNo"></param>
  302. /// <returns></returns>
  303. public async Task<bool> CheckProductCanSendToCustomer(string productOrderNo,string customerNo)
  304. {
  305. return await CdpRepository.CountAsync(a=>a.CustomerNo==customerNo&&a.ProductOrderNo==productOrderNo)>0;
  306. }
  307. /// <summary>
  308. /// 检查改批次产品能否发货给某客户
  309. /// </summary>
  310. /// <param name="productOrderNos"></param>
  311. /// <param name="customerNo"></param>
  312. /// <returns></returns>
  313. public async Task<bool> CheckProductCanSendToCustomer(List<string> productOrderNos,string customerNo)
  314. {
  315. return await CdpRepository.CountAsync(a=>a.CustomerNo==customerNo&&productOrderNos.Contains(a.ProductOrderNo))>0;
  316. }
  317. public Task PreMonth()
  318. {
  319. return SqlExecuter.ExecuteAsync("update CurrentProductStoreHouse set PreMonthQuantity = Quantity;update CurrentSemiStoreHouse set PreMonthQuantity = ActualQuantity;");
  320. }
  321. [UnitOfWork]
  322. [DisableAuditing]
  323. public int? GetAppGuid(AppGuidType type)
  324. {
  325. var sqlParms = new object[3];
  326. sqlParms[0] = new SqlParameter("@idtype", (int)type);
  327. sqlParms[1] = new SqlParameter("@nextid", SqlDbType.Int) { Direction = ParameterDirection.Output };
  328. sqlParms[2] = new SqlParameter("@maxid", SqlDbType.Int) { Direction = ParameterDirection.Output };
  329. SqlExecuter.Execute(@"exec [dbo].[Sp_AppGuid] @idtype,@nextid out,@maxid out", sqlParms);
  330. int guid = (int)((SqlParameter)sqlParms[2]).Value;
  331. return guid;
  332. }
  333. /// <summary>
  334. /// 检查库存记录是否可以更新
  335. /// </summary>
  336. /// <param name="houseType">仓库类型(1:成品 2:半成品)</param>
  337. /// <param name="houseStoreNo">库存记录编号</param>
  338. /// <returns></returns>
  339. [UnitOfWork]
  340. [DisableAuditing]
  341. public bool CheckStoreRecordCanUpdate(string houseStoreNo,int houseType=1)
  342. {
  343. if (houseType == 1)
  344. {
  345. var houseRecord =
  346. CurrentProductStoreHouseRepository.FirstOrDefault(i =>
  347. i.CurrentProductStoreHouseNo == houseStoreNo);
  348. if (houseRecord != null&&houseRecord.InventoryCheckState==2&&houseRecord.ReturnState==2)
  349. {
  350. return false;
  351. }
  352. }
  353. if (houseType == 2)
  354. {
  355. var houseRecord =
  356. CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  357. i.CurrentSemiStoreHouseNo == houseStoreNo);
  358. if (houseRecord != null && houseRecord.InventoryCheckState == 2 && houseRecord.ReturnState == 2)
  359. {
  360. return false;
  361. }
  362. }
  363. return true;
  364. }
  365. /// <summary>
  366. /// 检查库存记录是否可以更新
  367. /// </summary>
  368. /// <param name="houseType">仓库类型(1:成品 2:半成品)</param>
  369. /// <param name="locationNo">库位编号</param>
  370. /// <returns></returns>
  371. [UnitOfWork]
  372. [DisableAuditing]
  373. public bool CheckStoreCanUpdateByLocationNo(string locationNo,int houseType=1)
  374. {
  375. if (houseType == 1)
  376. {
  377. if (CurrentProductStoreHouseRepository.Count(a => a.StoreLocationNo == locationNo&& (a.InventoryCheckState==2 || a.ReturnState==2))>0)
  378. {
  379. return false;
  380. }
  381. }else if (houseType == 2)
  382. {
  383. if (CurrentSemiStoreHouseRepository.Count(a => a.StoreLocationNo == locationNo&& (a.InventoryCheckState==2 || a.ReturnState==2))>0)
  384. {
  385. return false;
  386. }
  387. }
  388. return true;
  389. }
  390. /// <summary>
  391. /// 查询库区/货架/排(排可以多选)
  392. /// </summary>
  393. /// <param name="storeId"></param>
  394. /// <param name="areaNo"></param>
  395. /// <param name="shelfNo"></param>
  396. /// <returns></returns>
  397. public List<SelectListItem> FilterLocationInfo(int storeId,string areaNo="",string shelfNo="", string levelNo = "")
  398. {
  399. var query = StoreHouseLocationRepository.GetAll().Where(i => i.StoreHouseId == storeId);
  400. if (areaNo.IsNullOrEmpty())
  401. {
  402. var result = query.Select(i => i.StoreAreaCode).Distinct();
  403. return result.Select(i=>new SelectListItem(){Text = i.ToString(),Value = i.ToString()}).ToList();
  404. }
  405. query = query.Where(i => i.StoreAreaCode == areaNo);
  406. if (shelfNo.IsNullOrEmpty())
  407. {
  408. var result = query.Select(i => i.ShelfNumber).Distinct();
  409. return result.Select(i => new SelectListItem() { Text = i.ToString(), Value = i.ToString() }).ToList();
  410. }
  411. query = query.Where(i => i.ShelfNumber == shelfNo);
  412. if (levelNo.IsNullOrEmpty())
  413. {
  414. var result = query.Select(i => i.ShelfLevel).Distinct();
  415. return result.Select(i => new SelectListItem() { Text = i.ToString(), Value = i.ToString() }).ToList();
  416. }
  417. query = query.Where(i => i.ShelfLevel == levelNo);
  418. return query.Select(i => i.SequenceNo).Distinct().Select(i => new SelectListItem() { Text = i.ToString(), Value = i.ToString() }).ToList();
  419. }
  420. public List<ProductionOrderDisCustomerDto> GetDisCustomerInfo(EntityDto<string> input)
  421. {
  422. return CustomerDisabledProductRepository.GetAll().Where(i => i.ProductOrderNo == input.Id).Join(CustomerRepository.GetAll(), p => p.CustomerNo, c => c.Id,
  423. (p, c) =>
  424. new ProductionOrderDisCustomerDto()
  425. {
  426. ProductionOrderNo = p.ProductOrderNo,
  427. CustomerName = c.CustomerName,
  428. CustomerId = p.CustomerNo
  429. }).ToList();
  430. }
  431. #region 发送邮件
  432. public ISmtpEmailSenderConfiguration SmtpEmailSenderConfiguration { get; }
  433. public void SendEmail(string toEmail,string title,string msg,bool isHtml)
  434. {
  435. //SmtpEmailSender emailSender = new SmtpEmailSender(SmtpEmailSenderConfiguration);
  436. //emailSender.Send("zhangwy@iwbnet.com",toEmail , title, msg,isHtml);
  437. //EmailSendHelper.SendEmail(toEmail,title,msg,"","",isHtml);
  438. EmailHelper.SendEmail(toEmail,title,msg,isHtml);
  439. }
  440. #endregion
  441. #region 创建排产单号
  442. public async Task<string> GetProductionOrderNo(string createType = "", string preOrderNo = "", int isOutsourcing = 0)
  443. {
  444. if (string.IsNullOrEmpty(createType))
  445. {
  446. return await NormalGetProductionOrderNo(isOutsourcing);
  447. }
  448. return await SpecialGetProductionOrderNo(createType, preOrderNo);
  449. }
  450. /// <summary>
  451. /// 常规获取批次号
  452. /// </summary>
  453. /// <param name="isOutsourcing">1是外购</param>
  454. /// <returns></returns>
  455. private async Task<string> NormalGetProductionOrderNo(int isOutsourcing)
  456. {
  457. string lcRetVal;
  458. DateTime loTiem = DateTime.Parse(DateTime.Now.Year + "-" + DateTime.Now.Month + "-01");
  459. //loTiem = loTiem.AddSeconds(-1);
  460. var orders = (await ProductionOrderRepository.GetAllListAsync(i => i.TimeCreated >= loTiem && i.ProcessingLevel == "1")).OrderByDescending(i => i.Id).ToList();
  461. var orderNo = orders.FirstOrDefault()?.ProductionOrderNo;
  462. if (!string.IsNullOrEmpty(orderNo))
  463. {
  464. var liTempNo = Convert.ToInt32(orderNo.Substring(3, 4));
  465. liTempNo++;
  466. lcRetVal = liTempNo.ToString();
  467. while (lcRetVal.Length < 4)
  468. {
  469. lcRetVal = "0" + lcRetVal;
  470. }
  471. }
  472. else
  473. {
  474. lcRetVal = "0001";
  475. }
  476. DateTime loDate = DateTime.Today;
  477. //string lcMonth = liMonth < 10 ? liMonth + "" : Convert.ToString(liMonth, 16);
  478. lcRetVal = loDate.Date.Year + GetMonthString(isOutsourcing) + lcRetVal;
  479. lcRetVal = lcRetVal.Substring(2, lcRetVal.Length - 2);
  480. return lcRetVal;
  481. }
  482. /// <summary>
  483. /// 转换月份
  484. /// </summary>
  485. /// <param name="isOutsourcing"></param>
  486. /// <returns></returns>
  487. private string GetMonthString(int isOutsourcing)
  488. {
  489. DateTime loDate = DateTime.Today;
  490. int liMonth = loDate.Date.Month;
  491. if (isOutsourcing == 0)
  492. {
  493. return liMonth < 10 ? liMonth + "" : Convert.ToString(liMonth, 16).ToUpper();
  494. }
  495. string[] scource = { "", "G", "H", "W", "J", "K", "L", "M", "N", "T", "P", "Q", "R" };
  496. return scource[liMonth];
  497. }
  498. private string GetLastFourChar(string preOrderNo)
  499. {
  500. if (!string.IsNullOrEmpty(preOrderNo) && preOrderNo.Length == 11)
  501. {
  502. return preOrderNo.Substring(7, 4);
  503. }
  504. return "";
  505. }
  506. private async Task<string> SpecialGetProductionOrderNo(string createType, string preOrderNo = "")
  507. {
  508. string lcRetVal;
  509. DateTime loTiem = DateTime.Parse(DateTime.Now.Year + "-" + DateTime.Now.Month + "-01");
  510. string reg = @"/^[A-Za-z0-9]{3}" + createType + @"\w{3,7}$/";
  511. string orderNo = "";
  512. if (createType == "T")
  513. {
  514. var orders = (await SemiEnterStoreRepository
  515. .GetAllListAsync(i => i.TimeCreated >= loTiem && Regex.IsMatch(i.ProductionOrderNo, @"/^[A-Za-z0-9]{3}T\w{3,7}$/"))).OrderByDescending(i => i.Id).ToList();
  516. orderNo = orders.FirstOrDefault()?.ProductionOrderNo;
  517. }else if (createType == "G")
  518. {
  519. var orders = (await ProductionOrderRepository
  520. .GetAllListAsync(i => i.TimeCreated >= loTiem && Regex.IsMatch(i.ProductionOrderNo, @"/^[A-Za-z0-9]{3}T\w{3,7}$/"))).OrderByDescending(i => i.Id).ToList();
  521. orderNo = orders.FirstOrDefault()?.ProductionOrderNo;
  522. }
  523. if (!string.IsNullOrEmpty(orderNo))
  524. {
  525. var liTempNo = Convert.ToInt32(orderNo.Substring(4, 3));
  526. liTempNo++;
  527. lcRetVal = liTempNo.ToString();
  528. while (lcRetVal.Length < 3)
  529. {
  530. lcRetVal = "0" + lcRetVal;
  531. }
  532. }
  533. else
  534. {
  535. lcRetVal = "T001";
  536. }
  537. DateTime loDate = DateTime.Today;
  538. //string lcMonth = liMonth < 10 ? liMonth + "" : Convert.ToString(liMonth, 16);
  539. lcRetVal = loDate.Date.Year + GetMonthString(0) + lcRetVal;
  540. lcRetVal = lcRetVal.Substring(2, lcRetVal.Length - 2);
  541. lcRetVal += GetLastFourChar(preOrderNo);
  542. return lcRetVal;
  543. }
  544. #endregion
  545. /// <summary>
  546. /// 根据对照表搜到新的成品编码
  547. /// </summary>
  548. /// <param name="productNo"></param>
  549. /// <returns></returns>
  550. [HttpGet]
  551. public async Task<ProductDto> GetNewProductInfo(string productNo)
  552. {
  553. var productMapper =
  554. await ProductMapperRepository.FirstOrDefaultAsync(i =>
  555. i.PreProductNo == productNo && i.PreProductType == 1);
  556. if (productMapper != null)
  557. {
  558. productNo = productMapper.ProductNo;
  559. }
  560. var pEntity = ProductRepository.Get(productNo);
  561. var po = ObjectMapper.Map<ProductDto>(pEntity);
  562. var materialType = ProductProperty.ProductMaterial + "";
  563. //查询下产品的材料海关编码(绑定在产品属性中的)
  564. if (!string.IsNullOrEmpty(pEntity.MaterialNo))
  565. {
  566. var pp = await ProductPropertyRepository.FirstOrDefaultAsync(i =>
  567. i.PropertyType == materialType && i.PropertyNo == pEntity.MaterialNo);
  568. po.MaterialHsCode = pp?.HsCode;
  569. }
  570. return po;
  571. }
  572. /// <summary>
  573. /// 根据对照表搜到新的半成品编码
  574. /// </summary>
  575. /// <param name="productNo"></param>
  576. /// <returns></returns>
  577. public async Task<SemiProductDto> GetNewSemiProductInfo(string productNo)
  578. {
  579. var productMapper =
  580. await ProductMapperRepository.FirstOrDefaultAsync(i =>
  581. i.PreProductNo == productNo && i.PreProductType == 2);
  582. if (productMapper != null)
  583. {
  584. //CheckErrors(new IdentityResult("未查询到替换信息!"));
  585. productNo = productMapper.ProductNo;
  586. }
  587. var pEntity = SemiProductRepository.Get(productNo);
  588. return ObjectMapper.Map<SemiProductDto>(pEntity);
  589. }
  590. #region 首页提示查询信息
  591. public async Task<List<IndexAlertSumDto>> GetIndexAlertSum()
  592. {
  593. List<IndexAlertSumDto> result = new List<IndexAlertSumDto>();
  594. var user = SysUserRepository.Get(AbpSession.UserId ?? 0);
  595. //销售部和超级管理员可以查看
  596. if (user.UserType == 1 || user.DepartmentID== "002")
  597. {
  598. int notCompleteStatus = OrderStatusEnum.Completed.ToInt();
  599. int deleteStatus = OrderStatusEnum.Delete.ToInt();
  600. var query = OrderHeaderRepository.GetAll().Where(i =>
  601. i.OrderStatusId != notCompleteStatus && i.OrderStatusId != deleteStatus);
  602. int c = await query.CountAsync();
  603. result.Add(new IndexAlertSumDto() { Quantity = c, SumName = "未完成的订单", SumType = "1", TipName = "订单" });
  604. }
  605. if (user.UserType == 1 || user.DepartmentID == "003")
  606. {
  607. int startStatus = ProductionOrderStatusEnum.Start.ToInt();
  608. int auditedStatus = ProductionOrderStatusEnum.Audited.ToInt();
  609. int productingStatus = ProductionOrderStatusEnum.Producting.ToInt();
  610. int storeingStatus = ProductionOrderStatusEnum.Storeing.ToInt();
  611. var query1 = ProductionOrderRepository.GetAll().Where(i =>
  612. i.ProductionOrderStatus == startStatus || i.ProductionOrderStatus == auditedStatus || i.ProductionOrderStatus == productingStatus || i.ProductionOrderStatus == storeingStatus);
  613. int c1 = await query1.CountAsync();
  614. result.Add(new IndexAlertSumDto() { Quantity = c1, SumName = "未完成的排查单", SumType = "2", TipName = "生产" });
  615. }
  616. if (user.UserType == 1 || user.DepartmentID == "005")
  617. {
  618. int applyStatus = PackageApplyStatusEnum.Applying.ToInt();
  619. var query2 = ViewPackageApplyRepository.GetAll().Where(i =>
  620. i.ApplyStatus == applyStatus + "");
  621. int c2 = await query2.CountAsync();
  622. result.Add(new IndexAlertSumDto() { Quantity = c2, SumName = "未审核的包装申请", SumType = "3", TipName = "包装" });
  623. }
  624. if (user.UserType == 1 )
  625. {
  626. var overAndComingSoon = await DeviceMgPlanRepository.GetAllListAsync(i => i.PlanType == 1
  627. && (
  628. i.NumberOfUsers >= i.MaintenanceCycle || (
  629. i.MaintenanceCycle > i.NumberOfUsers
  630. && ((i.MaintenanceCycle - i.NumberOfUsers) <= 10000))
  631. )
  632. );
  633. //var overDtos = ObjectMapper.Map<List<DeviceMgPlanDto>>(over);
  634. var overAndComingSoonDtos = ObjectMapper.Map<List<DeviceMgPlanDto>>(overAndComingSoon);
  635. result.Add(new IndexAlertSumDto() { Quantity = overAndComingSoonDtos.Count, SumName = "模具待维护计划", SumType = "4", TipName = "pro2" });
  636. }
  637. return result;
  638. }
  639. public async Task<List<OrderHeaderDto>> GetOrderHeaderForAlert()
  640. {
  641. int notCompleteStatus = OrderStatusEnum.Completed.ToInt();
  642. int deleteStatus = OrderStatusEnum.Delete.ToInt();
  643. var query = OrderHeaderRepository.GetAll().Where(i =>
  644. i.OrderStatusId != notCompleteStatus && i.OrderStatusId != deleteStatus);
  645. var employeeList = EmployeeRepository.GetAllList();
  646. query = query.OrderByDescending(i => i.TimeCreated);
  647. var entityList = await query.Take(20).ToListAsync();
  648. var r = entityList.Select(i => new OrderHeaderDto()
  649. {
  650. CustomerId = i.CustomerId,
  651. CustomerSendId = i.CustomerSendId,
  652. Fax = i.Fax,
  653. LinkName = i.LinkName,
  654. Id = i.Id,
  655. OrderDate = i.OrderDate,
  656. OrderStatusId = i.OrderStatusId,
  657. OrderStatusName =
  658. StatesAppService.GetDisplayValue("OrderHeader", "OrderStatusId", i.OrderStatusId + ""),
  659. StockNo = i.StockNo,
  660. Telephone = i.Telephone,
  661. TimeLastMod = i.TimeLastMod,
  662. UserIDLastMod = i.UserIDLastMod,
  663. TimeCreated = i.TimeCreated,
  664. SaleType = i.SaleType,
  665. SaleTypeName = StatesAppService.GetDisplayValue("OrderHeader", "SaleType", i.SaleType + ""),
  666. SaleMan = i.SaleMan,
  667. SaleManName = employeeList.FirstOrDefault(a => a.No == i.SaleMan)?.Name,
  668. IsLock = i.IsLock
  669. });
  670. return r.ToList();
  671. }
  672. public async Task<List<ProductionOrderDto>> GetProductionOrderForAlert()
  673. {
  674. int startStatus = ProductionOrderStatusEnum.Start.ToInt();
  675. int auditedStatus = ProductionOrderStatusEnum.Audited.ToInt();
  676. int productingStatus = ProductionOrderStatusEnum.Producting.ToInt();
  677. int storeingStatus = ProductionOrderStatusEnum.Storeing.ToInt();
  678. var query = ProductionOrderRepository.GetAll().Where(i =>
  679. i.ProductionOrderStatus == startStatus || i.ProductionOrderStatus == auditedStatus || i.ProductionOrderStatus == productingStatus || i.ProductionOrderStatus == storeingStatus);
  680. query = query.OrderByDescending(i => i.TimeCreated);
  681. var entityList = await query.Take(20).ToListAsync();
  682. return ObjectMapper.Map<List<ProductionOrderDto>>(entityList);
  683. }
  684. public async Task<List<ViewPackageApply>> GetPackageApplyForAlert()
  685. {
  686. int applyStatus = PackageApplyStatusEnum.Applying.ToInt();
  687. var query = ViewPackageApplyRepository.GetAll().Where(i =>
  688. i.ApplyStatus == applyStatus+"");
  689. query = query.OrderByDescending(i => i.TimeCreated);
  690. var entityList = await query.Take(20).ToListAsync();
  691. return entityList;
  692. }
  693. /// <summary>
  694. /// 首页查询图表
  695. /// </summary>
  696. /// <param name="ct">查询数据表 1:订单明细 2:排产单</param>
  697. /// <param name="qt">汇总分类 1:按季度 0:按年</param>
  698. /// <returns></returns>
  699. public List<StatusChartDto> GetHomeStatusCharts(int ct,int qt)
  700. {
  701. int deleteStatus = OrderItemStatusEnum.Delete.ToInt();
  702. DateTime dt = DateTime.Now;
  703. string startYear = dt.AddYears(-4).Year + "-01-01";
  704. DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初
  705. DateTime endQuarter = startQuarter.AddMonths(3);//.AddDays(-1); //本季度末
  706. string endTime = endQuarter.ToString("yyyy-MM-dd");
  707. var startTime = dt.AddYears(-2).Year + "-01-01";//startQuarter.AddMonths(-21).ToString("yyyy-MM-dd");
  708. string sqlStr = "";
  709. if (ct == 1)
  710. {
  711. sqlStr = $"select sum(1) as Count,OrderItemStatusId as StatusId,datename(year,TimeCreated) as Year from OrderItems where TimeCreated>='{startYear}' GROUP BY OrderItemStatusId,datename(year,TimeCreated) HAVING OrderItemStatusId<>{deleteStatus};";
  712. }else if (ct == 2)
  713. {
  714. sqlStr = $"select sum(1) as Count,ProductionOrderStatus as StatusId,datename(year,TimeCreated) as Year from ProductionOrders where TimeCreated >= '{startYear}' GROUP BY ProductionOrderStatus,datename(year,TimeCreated)";
  715. }
  716. //按季度,默认显示最近5个季度
  717. if (ct == 1&&qt == 1)
  718. {
  719. sqlStr =
  720. $"select sum(1) as Count,OrderItemStatusId as StatusId,datepart(qq,TimeCreated) as Quarterly,datename(year,TimeCreated) as Year from OrderItems where TimeCreated>='{startTime}' and TimeCreated<'{endTime}' GROUP BY OrderItemStatusId,datepart(qq,TimeCreated),datename(year,TimeCreated) HAVING OrderItemStatusId<>{deleteStatus};";
  721. }else if (ct == 2 && qt == 1)
  722. {
  723. sqlStr = $"select sum(1) as Count,ProductionOrderStatus as StatusId,datepart(qq,TimeCreated) as Quarterly,datename(year,TimeCreated) as Year from ProductionOrders where TimeCreated >= '{startTime}' and TimeCreated<'{endTime}' GROUP BY ProductionOrderStatus,datepart(qq,TimeCreated),datename(year,TimeCreated)";
  724. }
  725. var statusChartDtos = SqlExecuter.SqlQuery<StatusChartDto>(sqlStr);
  726. statusChartDtos = statusChartDtos.OrderBy(i => i.Year);
  727. if (qt == 1)
  728. {
  729. statusChartDtos = statusChartDtos.OrderBy(i => i.Year).ThenBy(i=>i.Quarterly);
  730. }
  731. return statusChartDtos.ToList();
  732. }
  733. public List<OrderStatusChartDto> GetOrderStatusCharts(int qt)
  734. {
  735. int deleteStatus = OrderItemStatusEnum.Delete.ToInt();
  736. DateTime dt = DateTime.Now;
  737. string startYear = dt.AddYears(-4).Year +"-01-01";
  738. string sqlStr =
  739. $"select sum(1) as Count,OrderItemStatusId,datename(year,TimeCreated) as Year from OrderItems where TimeCreated>='{startYear}' GROUP BY OrderItemStatusId,datename(year,TimeCreated) HAVING OrderItemStatusId<>{deleteStatus};";
  740. //按季度,默认显示最近5个季度
  741. if (qt==1)
  742. {
  743. DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初
  744. DateTime endQuarter = startQuarter.AddMonths(3);//.AddDays(-1); //本季度末
  745. string endTime = endQuarter.ToString("yyyy-MM-dd");
  746. var startTime = startQuarter.AddMonths(-12).ToString("yyyy-MM-dd");
  747. sqlStr =
  748. $"select sum(1) as Count,OrderItemStatusId,datepart(qq,TimeCreated) as Quarterly,datename(year,TimeCreated) as Year from OrderItems where TimeCreated>='{startTime}' and TimeCreated<'{endTime}' GROUP BY OrderItemStatusId,datepart(qq,TimeCreated),datename(year,TimeCreated) HAVING OrderItemStatusId<>{deleteStatus};";
  749. }
  750. var orderStatusChartDtos = SqlExecuter.SqlQuery<OrderStatusChartDto>(sqlStr);
  751. orderStatusChartDtos = orderStatusChartDtos.OrderBy(i => i.Year);
  752. return orderStatusChartDtos.ToList();
  753. }
  754. public List<ProductionOrderStatusChartDto> GetProductionOrderStatusCharts()
  755. {
  756. // int deleteStatus = OrderStatusEnum.Delete.ToInt();
  757. string startYear = DateTime.Now.AddYears(-4).Year + "-01-01";
  758. string sqlStr =
  759. $"select sum(1) as Count,ProductionOrderStatus,datename(year,TimeCreated) as Year from ProductionOrders where TimeCreated >= '{startYear}' GROUP BY ProductionOrderStatus,datename(year,TimeCreated)";
  760. var orderStatusChartDtos = SqlExecuter.SqlQuery<ProductionOrderStatusChartDto>(sqlStr);
  761. orderStatusChartDtos = orderStatusChartDtos.OrderBy(i => i.Year);
  762. return orderStatusChartDtos.ToList();
  763. }
  764. #endregion
  765. public async Task<List<CurrentProductStoreHouseDto>> GetProductStoreInfoByProductNo(string productNo)
  766. {
  767. var cs = await CurrentProductStoreHouseRepository.GetAllListAsync(i =>
  768. i.ProductNo == productNo && i.Quantity > 0);
  769. return ObjectMapper.Map<List<CurrentProductStoreHouseDto>>(cs);
  770. }
  771. /// <summary>
  772. /// 去除已被替换的产品
  773. /// </summary>
  774. /// <param name="input"></param>
  775. /// <returns></returns>
  776. public async Task<PagedResultDto<ProductDto>> GetProductNotContainOld(IwbPagedRequestDto input)
  777. {
  778. var productNoExts =
  779. (await ProductMapperRepository.GetAllListAsync(i =>i.PreProductType == 1)).Select(i=>i.PreProductNo);
  780. var query = ProductRepository.GetAll().Where(a => a.IsLock == "N"&& !productNoExts.Contains(a.Id));
  781. if (input.SearchList != null && input.SearchList.Count > 0)
  782. {
  783. List<LambdaObject> objList = new List<LambdaObject>();
  784. foreach (var o in input.SearchList)
  785. {
  786. if (o.KeyWords.IsNullOrEmpty())
  787. continue;
  788. object keyWords = o.KeyWords;
  789. objList.Add(new LambdaObject
  790. {
  791. FieldType = (LambdaFieldType)o.FieldType,
  792. FieldName = o.KeyField,
  793. FieldValue = keyWords,
  794. ExpType = (LambdaExpType)o.ExpType
  795. });
  796. }
  797. var exp = objList.GetExp<Product>();
  798. query = query.Where(exp);
  799. }
  800. var totalCount = await query.CountAsync();
  801. query = !input.Sorting.IsNullOrWhiteSpace() ? query.OrderBy(input.Sorting) : query.OrderByDescending(i => i.TimeCreated);
  802. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  803. var entities = await query.ToListAsync();
  804. var dtos = new PagedResultDto<ProductDto>(
  805. totalCount,
  806. entities.Select(ObjectMapper.Map<ProductDto>).ToList()
  807. );
  808. return dtos;
  809. }
  810. /// <summary>
  811. /// 查询半成品信息
  812. /// </summary>
  813. /// <param name="input"></param>
  814. /// <returns></returns>
  815. public async Task<PagedResultDto<SemiProductDto>> GetSemiProductNotContainOld(IwbPagedRequestDto input)
  816. {
  817. var productNoExts =
  818. (await ProductMapperRepository.GetAllListAsync(i => i.PreProductType == 2)).Select(i => i.PreProductNo);
  819. var query = SemiProductRepository.GetAll().Where(a => a.IsLock == "N" && !productNoExts.Contains(a.Id));
  820. if (input.SearchList != null && input.SearchList.Count > 0)
  821. {
  822. List<LambdaObject> objList = new List<LambdaObject>();
  823. foreach (var o in input.SearchList)
  824. {
  825. if (o.KeyWords.IsNullOrEmpty())
  826. continue;
  827. object keyWords = o.KeyWords;
  828. //检查查询条件中带有规格且多个分割条件的
  829. ProductModelSearch.CheckModelGreaterOneFilter(o, ref keyWords);
  830. objList.Add(new LambdaObject
  831. {
  832. FieldType = (LambdaFieldType)o.FieldType,
  833. FieldName = o.KeyField,
  834. FieldValue = keyWords,
  835. ExpType = (LambdaExpType)o.ExpType
  836. });
  837. }
  838. var exp = objList.GetExp<SemiProducts>();
  839. query = exp!=null? query.Where(exp): query;
  840. }
  841. var totalCount = await query.CountAsync();
  842. query = query.OrderByDescending(i => i.TimeCreated);
  843. string pattern = ProductModelSearch.GetModelGreaterOneReg(input.SearchList);
  844. List<SemiProducts> entities;
  845. //检查查询条件中带有规格且多个分割条件的
  846. if (!pattern.IsNullOrEmpty())
  847. {
  848. var es = query.ToList();
  849. es = es.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  850. totalCount = es.Count;
  851. entities = es.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
  852. }
  853. else
  854. {
  855. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  856. entities = await query.ToListAsync();
  857. }
  858. //query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  859. //var entities = await query.ToListAsync();
  860. var dtos = new PagedResultDto<SemiProductDto>(
  861. totalCount,
  862. entities.Select(ObjectMapper.Map<SemiProductDto>).ToList()
  863. );
  864. return dtos;
  865. }
  866. /**
  867. * 解除订单冻结的库存数量
  868. */
  869. public async Task UnLockOrderStore(OrderItem orderItem)
  870. {
  871. var orderBookStores = await OrderBookStoreRepository.GetAllListAsync(i => i.OrderItemId == orderItem.Id);
  872. foreach (var orderBookStore in orderBookStores)
  873. {
  874. var currentProductStore = await CurrentProductStoreHouseRepository.FirstOrDefaultAsync(i => i.CurrentProductStoreHouseNo ==
  875. orderBookStore.CurrentProductStoreHouseNo);
  876. if (currentProductStore.FreezeQuantity < (orderBookStore.Quantity ?? 0))
  877. {
  878. CheckErrors(IdentityResult.Failed("解除仓库冻结库存异常!解除冻结后结果小于0"));
  879. }
  880. currentProductStore.FreezeQuantity -= orderBookStore.Quantity ?? 0;
  881. currentProductStore.TimeLastMod = Clock.Now;
  882. currentProductStore.UserIDLastMod = AbpSession.UserId.ToString();
  883. await CurrentProductStoreHouseRepository.UpdateAsync(currentProductStore);
  884. //orderBookStore.Status = OrderBookStoreStatusEnum.UnLock.ToInt();
  885. //await OrderBookStoreRepository.UpdateAsync(orderBookStore);//先解锁库存
  886. await OrderBookStoreRepository.DeleteAsync(orderBookStore);//软删除掉锁定的记录
  887. }
  888. BusinessLogTypeEnum.OrderLog.WriteLog(BusinessLogRepository, "订单明细删除解除冻结仓库库存", $"仓库库存解除冻结成功!orderItem:{orderItem.Id},UserId:{AbpSession.UserId}", logExt1: $"{orderBookStores.ToJsonString()}");
  889. }
  890. #region 2025
  891. //wxLogin
  892. public Object WxLogin(string code)
  893. {
  894. string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={WxAppId}&secret={WxSecret}&js_code={code}&grant_type=authorization_code";
  895. //{ "session_key":"w7AXdN4VVYjd47ysgQjF0w==","expires_in":7200,"openid":"o_-Xy0Fb2SkcaoQ2OZuLqYsJn7uA"}
  896. try
  897. {
  898. var result = url.HttpGet();
  899. var jObject = JObject.Parse(result);
  900. return jObject.TryGetValue("openid", out JToken openid) ? jObject:null;
  901. }
  902. catch(Exception ex)
  903. {
  904. return ex.Message;
  905. }
  906. }
  907. //获取微信用户解密信息
  908. public Object GetWxUserDecryptInfo(WxUserDecryptDto input)
  909. {
  910. try
  911. {
  912. var decryptedData = WxDecryptHelper.Decrypt(
  913. input.EncryptedData,
  914. input.SessionKey,
  915. input.Iv);
  916. return JsonConvert.DeserializeObject(decryptedData);
  917. }
  918. catch (Exception ex)
  919. {
  920. CheckErrors(IdentityResult.Failed("处置失败!"+ ex.Message));
  921. return null;
  922. }
  923. }
  924. public async Task<WxUser> SaveWxUserInfo(WxUser input)
  925. {
  926. if (!string.IsNullOrEmpty(input.OpenId))
  927. {
  928. CheckErrors(IdentityResult.Failed("传入参数有误差!为传入openid!"));
  929. }
  930. var openid = input.OpenId;
  931. var wxUser = await WxUserRepository.FirstOrDefaultAsync(i => i.OpenId == openid.ToString());
  932. wxUser = wxUser == null? new WxUser() : wxUser;
  933. wxUser.UserId = input.UserId;
  934. wxUser.UserName = input.UserName;
  935. wxUser.RealName = input.RealName;
  936. wxUser.AvatarUrl = input.AvatarUrl;
  937. wxUser.Gender = input.Gender ?? "";
  938. wxUser.Country = input.Country ?? "";
  939. wxUser.Province = input.Province ?? "";
  940. wxUser.City = input.City ?? "";
  941. wxUser.Language = input.Language ?? "";
  942. wxUser.UnionId = input.UnionId ?? "";
  943. await WxUserRepository.InsertOrUpdateAsync(wxUser);
  944. return wxUser;
  945. }
  946. #endregion
  947. }
  948. }