CommonAppService.cs 41 KB

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