CommonAppService.cs 42 KB

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