ProductionOrdersApplicationService.cs 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. using Abp.Application.Services.Dto;
  10. using Abp.Auditing;
  11. using Abp.Authorization;
  12. using Abp.Domain.Repositories;
  13. using Abp.Domain.Uow;
  14. using Abp.Extensions;
  15. using Abp.Timing;
  16. using Abp.UI;
  17. using Castle.Components.DictionaryAdapter;
  18. using IwbZero.AppServiceBase;
  19. using IwbZero.Auditing;
  20. using IwbZero.Helper;
  21. using IwbZero.IdentityFramework;
  22. using IwbZero.Setting;
  23. using JetBrains.Annotations;
  24. using Microsoft.AspNet.Identity;
  25. using Newtonsoft.Json;
  26. using NPOI.HSSF.UserModel;
  27. using ShwasherSys.Authorization.Permissions;
  28. using ShwasherSys.BaseSysInfo;
  29. using ShwasherSys.BasicInfo.OutFactory;
  30. using ShwasherSys.Common;
  31. using ShwasherSys.CompanyInfo;
  32. using ShwasherSys.Lambda;
  33. using ShwasherSys.ProductionOrderInfo.Dto;
  34. using ShwasherSys.ProductInfo;
  35. using ShwasherSys.ProductStoreInfo;
  36. using ShwasherSys.ProductStoreInfo.Dto;
  37. using ShwasherSys.SemiProductStoreInfo;
  38. using ShwasherSys.SemiProductStoreInfo.Dto;
  39. using ShwasherSys.RmStore;
  40. using LambdaExpType = ShwasherSys.Lambda.LambdaExpType;
  41. using LambdaFieldType = ShwasherSys.Lambda.LambdaFieldType;
  42. using LambdaObject = ShwasherSys.Lambda.LambdaObject;
  43. using ShwasherSys.BaseSysInfo.States;
  44. using ShwasherSys.Common.Dto;
  45. using ShwasherSys.Order;
  46. using ShwasherSys.ProductionOrderInfo.Dto.BindOrder;
  47. namespace ShwasherSys.ProductionOrderInfo
  48. {
  49. [AbpAuthorize, AuditLog("半成品排产出入库维护")]
  50. public class ProductionOrdersAppService : ShwasherAsyncCrudAppService<ProductionOrder, ProductionOrderDto, int, PagedRequestDto, ProductionOrderCreateDto, ProductionOrderUpdateDto>
  51. , IProductionOrdersAppService
  52. {
  53. protected IRepository<CurrentRmStoreHouse,string> CrsRepository { get; }
  54. protected IRepository<RmEnterStore,string> ErsRepository { get; }
  55. protected IRepository<RmOutStore,string> OrsRepository { get; }
  56. protected IRepository<EmployeeWorkPerformance> PerformanceRepository { get; }
  57. protected IRepository<BusinessLog> LogRepository;
  58. protected IRepository<ProductionLog> ProductLogRepository;
  59. protected IRepository<SemiEnterStore> SemiEnterStoreRepository;
  60. protected IRepository<ViewSemiEnterStore> ViewSemiEnterStoreRepository;
  61. protected IRepository<SemiOutStore> SemiOutStoreRepository;
  62. protected IRepository<CurrentSemiStoreHouse> CurrentSemiStoreHouseRepository;
  63. protected IRepository<ViewSemiOutStore> ViewSemiOutStoreRepository;
  64. protected IRepository<SemiProducts, string> SemiProductRepository;
  65. protected IRepository<OutFactory,string> OutFactoryRepository;
  66. protected IRepository<ViewProductOutStore> ViewProductOutStoreRepository { get; }
  67. protected IRepository<ProductOutStore> ProductOutStoreRepository { get; }
  68. protected IRepository<Product,string> ProductRepository { get; }
  69. protected IRepository<CurrentProductStoreHouse> CurrentProductStoreHouseRepository { get; }
  70. protected ICommonAppService CommonAppService { get; }
  71. protected IStatesAppService StatesAppService;
  72. protected IRepository<OrderProduction> OrderProductionRepository { get; }
  73. protected IRepository<ViewOrderItems> ViewOrderItemsRepository { get; }
  74. public ProductionOrdersAppService(IRepository<ProductionOrder, int> repository, IRepository<BusinessLog> logRepository, IRepository<SemiEnterStore> semiEnterStoreRepository, IRepository<SemiOutStore> semiOutStoreRepository, IRepository<ViewSemiEnterStore> viewSemiEnterStoreRepository, IRepository<CurrentSemiStoreHouse> currentSemiStoreHouseRepository, IRepository<ViewSemiOutStore> viewSemiOutStoreRepository, IRepository<SemiProducts, string> semiProductRepository, IRepository<OutFactory, string> outFactoryRepository, IRepository<ProductionLog> productLogRepository, IRepository<EmployeeWorkPerformance> performanceRepository, IRepository<RmOutStore, string> orsRepository, IRepository<RmEnterStore, string> ersRepository, IRepository<CurrentRmStoreHouse, string> crsRepository, ICommonAppService commonAppService, IRepository<ViewProductOutStore> viewProductOutStoreRepository, IRepository<ProductOutStore> productOutStoreRepository, IRepository<CurrentProductStoreHouse> currentProductStoreHouseRepository, IRepository<Product, string> productRepository, IStatesAppService statesAppService, IIwbSettingManager settingManager, IRepository<OrderProduction> orderProductionRepository, IRepository<ViewOrderItems> viewOrderItemsRepository) : base(repository, "ProductionOrderNo")
  75. {
  76. LogRepository = logRepository;
  77. SemiEnterStoreRepository = semiEnterStoreRepository;
  78. SemiOutStoreRepository = semiOutStoreRepository;
  79. ViewSemiEnterStoreRepository = viewSemiEnterStoreRepository;
  80. CurrentSemiStoreHouseRepository = currentSemiStoreHouseRepository;
  81. ViewSemiOutStoreRepository = viewSemiOutStoreRepository;
  82. SemiProductRepository = semiProductRepository;
  83. OutFactoryRepository = outFactoryRepository;
  84. ProductLogRepository = productLogRepository;
  85. PerformanceRepository = performanceRepository;
  86. OrsRepository = orsRepository;
  87. ErsRepository = ersRepository;
  88. CrsRepository = crsRepository;
  89. CommonAppService = commonAppService;
  90. ViewProductOutStoreRepository = viewProductOutStoreRepository;
  91. ProductOutStoreRepository = productOutStoreRepository;
  92. CurrentProductStoreHouseRepository = currentProductStoreHouseRepository;
  93. ProductRepository = productRepository;
  94. StatesAppService = statesAppService;
  95. OrderProductionRepository = orderProductionRepository;
  96. ViewOrderItemsRepository = viewOrderItemsRepository;
  97. SettingManager = settingManager;
  98. }
  99. protected override bool KeyIsAuto { get; set; } = false;
  100. protected override string GetPermissionName { get; set; } = PermissionNames.PagesProductionInfoProductionOrderMg;
  101. protected override string GetAllPermissionName { get; set; } = PermissionNames.PagesProductionInfoProductionOrderMg;
  102. protected override string CreatePermissionName { get; set; } = PermissionNames.PagesProductionInfoProductionOrderMgCreate;
  103. protected override string UpdatePermissionName { get; set; } = PermissionNames.PagesProductionInfoProductionOrderMgUpdate;
  104. protected override string DeletePermissionName { get; set; } = PermissionNames.PagesProductionInfoProductionOrderMgDelete;
  105. #region 排产单
  106. [DisableAuditing]
  107. public override async Task<PagedResultDto<ProductionOrderDto>> GetAll(PagedRequestDto input)
  108. {
  109. var result = GetAllData(input.SearchList);
  110. var totalCount = await AsyncQueryableExecuter.CountAsync(result);
  111. result = result.OrderByDescending(i => i.TimeCreated);
  112. string pattern = ProductModelSearch.GetModelGreaterOneReg(input.SearchList);
  113. List<ProductionOrderDto> entity;
  114. //检查查询条件中带有规格且多个分割条件的
  115. if (!pattern.IsNullOrEmpty())
  116. {
  117. var es = result.ToList();
  118. es = es.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  119. totalCount = es.Count;
  120. entity = es.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
  121. }
  122. else
  123. {
  124. result = result.Skip(input.SkipCount).Take(input.MaxResultCount);
  125. entity = result.ToList();
  126. }
  127. //result = result.Skip(input.SkipCount).Take(input.MaxResultCount);
  128. //var entity = result.ToList();
  129. var dtos = new PagedResultDto<ProductionOrderDto>(
  130. totalCount,
  131. entity
  132. );
  133. return dtos;
  134. }
  135. private IQueryable<ProductionOrderDto> GetAllData(List<MultiSearchDto> input)
  136. {
  137. CheckGetAllPermission();
  138. bool hasEnd = false;
  139. var query = Repository.GetAll();
  140. var outFacQuery = OutFactoryRepository.GetAll();
  141. var result = from u in query
  142. join s in SemiProductRepository.GetAll() on u.SemiProductNo equals s.Id into l
  143. from luq in l.DefaultIfEmpty()
  144. join o in outFacQuery on u.OutsourcingFactory equals o.Id into j
  145. from oj in j.DefaultIfEmpty()
  146. select new ProductionOrderDto
  147. {
  148. Model = luq.Model ?? "",
  149. CarNo = u.CarNo,
  150. EnterQuantity = u.EnterQuantity,
  151. Id = u.Id,
  152. ProductionType = u.ProductionType,
  153. OutsourcingFactory = u.OutsourcingFactory,
  154. CreatorUserId = u.CreatorUserId,
  155. IsChecked = u.IsChecked,
  156. IsLock = u.IsLock,
  157. Material = luq.Material ?? "",
  158. PartNo = luq.PartNo ?? "",
  159. PlanProduceDate = u.PlanProduceDate,
  160. RawMaterials = u.RawMaterials,
  161. SurfaceColor = luq.SurfaceColor ?? "",
  162. Rigidity = luq.Rigidity ?? "",
  163. Remark = u.Remark,
  164. UserIDLastMod = u.UserIDLastMod,
  165. TimeCreated = u.TimeCreated,
  166. TimeLastMod = u.TimeLastMod,
  167. Size = u.Size,
  168. ProcessingType = u.ProcessingType,
  169. ProcessingLevel = u.ProcessingLevel,
  170. SourceProductionOrderNo = u.SourceProductionOrderNo,
  171. StoveNo = u.StoveNo,
  172. Quantity = u.Quantity,
  173. ProductionOrderNo = u.ProductionOrderNo,
  174. ProductionOrderStatus = u.ProductionOrderStatus,
  175. SemiProductNo = u.SemiProductNo,
  176. SemiProductName = luq.SemiProductName,
  177. KgWeight = u.KgWeight,
  178. OutsourcingFactoryName = oj.OutFactoryName,
  179. EnterDate = u.EnterDate,
  180. InspectDate = u.InspectDate,
  181. HasExported = u.HasExported
  182. };
  183. //逻辑删除也同时显示出来
  184. //var property = typeof(ProductionOrder).GetProperty("IsLock");
  185. //if (property != null)
  186. //{
  187. // LambdaObject objLambdaObject = new LambdaObject()
  188. // {
  189. // FieldType = LambdaFieldType.S,
  190. // FieldName = "IsLock",
  191. // FieldValue = "N",
  192. // ExpType = LambdaExpType.Equal
  193. // };
  194. // var expIsLock = objLambdaObject.GetExp<ProductionOrderDto>();
  195. // result = result.Where(expIsLock);
  196. //}
  197. if (input != null && input.Count > 0)
  198. {
  199. List<LambdaObject> objList = new List<LambdaObject>();
  200. foreach (var o in input)
  201. {
  202. if (o.KeyWords.IsNullOrEmpty())
  203. continue;
  204. object keyWords = o.KeyWords;
  205. //检查查询条件中带有规格且多个分割条件的
  206. ProductModelSearch.CheckModelGreaterOneFilter(o, ref keyWords);
  207. objList.Add(new LambdaObject
  208. {
  209. FieldType = (LambdaFieldType)o.FieldType,
  210. FieldName = o.KeyField,
  211. FieldValue = keyWords,
  212. ExpType = (LambdaExpType)o.ExpType
  213. });
  214. if (o.KeyField?.ToLower() == "productionorderstatus" && o.KeyWords == ProductionOrderStatusEnum.End.ToInt() + "")
  215. {
  216. hasEnd = true;
  217. }
  218. }
  219. var exp = objList.GetExp<ProductionOrderDto>();
  220. result = exp!=null? result.Where(exp):result;
  221. }
  222. if (!hasEnd)
  223. {
  224. var endState = ProductionOrderStatusEnum.End.ToInt();
  225. result = result.Where(a => (a.ProductionOrderStatus != endState));
  226. }
  227. return result;
  228. }
  229. private string GetProductionOrderStatus(string p,int? isCheck,bool hasExported=false)
  230. {
  231. var stateDtos = StatesAppService.GetStateList("ProductionOrders", "ProductionOrderStatus",i=>i.CodeValue==p);
  232. var state = stateDtos.First();
  233. string result = state.DisplayValue;
  234. if (p == "4")
  235. {
  236. result += (isCheck??0)>0 ? "-已检验" : "-待检验";
  237. }
  238. result += hasExported ? "-已导出" : "";
  239. return result;
  240. }
  241. public async Task<string> ExportListToExcel(List<MultiSearchDto> input)
  242. {
  243. var result = GetAllData(input);
  244. result = result.OrderByDescending(i => i.TimeCreated);
  245. string pattern = ProductModelSearch.GetModelGreaterOneReg(input);
  246. List<ProductionOrderDto> entity = result.ToList();
  247. //检查查询条件中带有规格且多个分割条件的
  248. if (!pattern.IsNullOrEmpty())
  249. {
  250. entity = entity.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  251. }
  252. // List<ProductionOrderDto> entity = result.ToList();
  253. List<ProductionOrderExcelDto> r = new List<ProductionOrderExcelDto>();
  254. try
  255. {
  256. foreach (var t in entity)
  257. {
  258. ProductionOrderExcelDto e = new ProductionOrderExcelDto();
  259. e.ProductionOrderNo = t.ProductionOrderNo;
  260. e.PartNo = t.PartNo;
  261. e.SemiProductName = t.SemiProductName;
  262. e.Model = t.Model;
  263. e.Quantity = t.Quantity+"";
  264. e.TimeCreated = (t.TimeCreated ?? DateTime.Now).ToString("yyyy-MM-dd");
  265. e.ProductionOrderStatus = GetProductionOrderStatus(t.ProductionOrderStatus + "",
  266. t.IsChecked ?? 0, t.HasExported);
  267. e.Remark = t.Remark;
  268. e.Rigidity = t.Rigidity;
  269. e.SurfaceColor = t.SurfaceColor;
  270. e.Material = t.Material;
  271. e.KgWeight = t.KgWeight+"";
  272. e.PlanProduceDate = (t.PlanProduceDate ?? DateTime.Now).ToString("yyyy-MM-dd");
  273. e.EnterDate = (t.EnterDate ?? DateTime.Now).ToString("yyyy-MM-dd");
  274. e.OutsourcingFactoryName = t.OutsourcingFactoryName;
  275. e.ProcessingType = StatesAppService.GetDisplayValue("ProductionOrders", "ProcessingType",
  276. t.ProcessingType.ToString());
  277. e.SemiProductNo = t.SemiProductNo;
  278. r.Add(e);
  279. }
  280. string downloadUrl =await SettingManager.GetSettingValueAsync("SYSTEMDOWNLOADPATH");
  281. string lcFilePath = System.Web.HttpRuntime.AppDomainAppPath +"\\"+
  282. downloadUrl;
  283. var exportEntity = new Dictionary<string, string>()
  284. {
  285. {"ProductionOrderNo", "订单流水号"},
  286. {"PartNo", "零件号"},
  287. {"SemiProductName", "名称"},
  288. {"Model", "规格"},
  289. {"Quantity", "排产数量"},
  290. {"TimeCreated", "创建时间"},
  291. {"ProductionOrderStatus", "生产状态"},
  292. {"Remark", "备注"},
  293. {"Rigidity", "硬度"},
  294. {"SurfaceColor", "表色"},
  295. {"Material", "材质"},
  296. {"KgWeight", "千件重"},
  297. {"PlanProduceDate", "计划完成时间"},
  298. {"EnterDate", "入库时间"},
  299. {"OutsourcingFactoryName", "外协厂商"},
  300. {"ProcessingType", "加工类型"},
  301. {"SemiProductNo", "产品编码"},
  302. };
  303. string lcResultFileName = ExcelHelper.EntityListToExcel2003(exportEntity, r, "sheet", lcFilePath);
  304. return Path.Combine(downloadUrl, lcResultFileName);
  305. }
  306. catch (Exception ex)
  307. {
  308. Console.WriteLine(ex);
  309. // throw;
  310. }
  311. return "";
  312. }
  313. private ProductionOrderDto TrunProductionOrderDto(ProductionOrder p,SemiProducts s)
  314. {
  315. var productionOrderDto = MapToEntityDto(p);
  316. productionOrderDto.Model = s.Model ?? "";
  317. productionOrderDto.Material = s.Material ?? "";
  318. productionOrderDto.PartNo = s.PartNo ?? "";
  319. productionOrderDto.SurfaceColor = s.SurfaceColor ?? "";
  320. productionOrderDto.Rigidity = s.Rigidity ?? "";
  321. /*var productionOrderDto = new ProductionOrderDto(p)
  322. {
  323. Model = s.Model ?? "",
  324. Material = s.Material ?? "",
  325. PartNo = s.PartNo ?? "",
  326. SurfaceColor = s.SurfaceColor ?? "",
  327. Rigidity = s.Rigidity ?? "",
  328. };*/
  329. return productionOrderDto;
  330. }
  331. /// <summary>
  332. /// 获取新建排产单的编号
  333. /// </summary>
  334. /// <returns></returns>
  335. [DisableAuditing]
  336. public async Task<string> GetNewProductionOrderNo()
  337. {
  338. return await GetNewProductionOrderNo(0);
  339. }
  340. /// <summary>
  341. /// 获取新建排产单(外购单)的编号
  342. /// </summary>
  343. /// <returns></returns>
  344. [DisableAuditing]
  345. public async Task<string> GetNewProductionOrderNo(int isOutsourcing)
  346. {
  347. CheckGetAllPermission();
  348. string lcRetVal;
  349. DateTime loTiem = DateTime.Parse(DateTime.Now.Year + "-" + DateTime.Now.Month + "-01");
  350. //loTiem = loTiem.AddSeconds(-1);
  351. var orders = (await Repository.GetAllListAsync(i => i.TimeCreated >= loTiem && i.ProcessingLevel == "1")).OrderByDescending(i => i.Id).ToList();
  352. var orderNo = orders.FirstOrDefault()?.ProductionOrderNo;
  353. if (!string.IsNullOrEmpty(orderNo))
  354. {
  355. var liTempNo = Convert.ToInt32(orderNo.Substring(3, 4));
  356. liTempNo++;
  357. lcRetVal = liTempNo.ToString();
  358. while (lcRetVal.Length < 4)
  359. {
  360. lcRetVal = "0" + lcRetVal;
  361. }
  362. }
  363. else
  364. {
  365. lcRetVal = "0001";
  366. }
  367. DateTime loDate = DateTime.Today;
  368. //string lcMonth = liMonth < 10 ? liMonth + "" : Convert.ToString(liMonth, 16);
  369. lcRetVal = loDate.Date.Year + GetMonthString(isOutsourcing) + lcRetVal;
  370. lcRetVal = lcRetVal.Substring(2, lcRetVal.Length - 2);
  371. return lcRetVal;
  372. }
  373. /// <summary>
  374. /// 转换月份
  375. /// </summary>
  376. /// <param name="isOutsourcing"></param>
  377. /// <returns></returns>
  378. private string GetMonthString(int isOutsourcing)
  379. {
  380. DateTime loDate = DateTime.Today;
  381. int liMonth = loDate.Date.Month;
  382. if (isOutsourcing == 0)
  383. {
  384. return liMonth < 10 ? liMonth + "" : Convert.ToString(liMonth, 16).ToUpper();
  385. }
  386. string[] scource = {"", "G", "H", "W", "J", "K", "L", "M", "N", "T", "P","Q","R"};
  387. return scource[liMonth];
  388. }
  389. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("变更排产状态")]
  390. public async Task<ProductionOrderDto> ChangeProductionOrderStatus(ChangeProductionOrderStatusDto input)
  391. {
  392. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  393. if (entity.ProductionOrderStatus > ProductionOrderStatusEnum.Producting.ToInt()&&entity.ProductionOrderStatus!= ProductionOrderStatusEnum.HangUp.ToInt() && entity.ProductionOrderStatus != ProductionOrderStatusEnum.Audited.ToInt() && entity.IsChecked==0)
  394. {
  395. CheckErrors(IwbIdentityResult.Failed("排产单已进行入库,不可进行更改!"));
  396. }
  397. //审核时进行绑定订单明细校验
  398. if (input.ProductionOrderStatus == ProductionOrderStatusEnum.Audited.ToInt())
  399. {
  400. var os = QueryOrderItemByPoNo(entity.ProductionOrderNo);
  401. if (!os.Any())
  402. {
  403. CheckErrors(IwbIdentityResult.Failed("排产单未绑定订单明细!"));
  404. }
  405. }
  406. entity.ProductionOrderStatus = input.ProductionOrderStatus;
  407. //ProductionOrderLogs loLogs = new ProductionOrderLogs()
  408. //{
  409. // ProductionOrderNo = loProductionOrder.ProductionOrderNo,
  410. // CreatorUserId = AbpSession.UserName,
  411. // OperatorTitle = $"排产单:{loProductionOrder.ProductionOrderNo} 状态变更",
  412. // OperatorConent = $"排产单:{loProductionOrder.ProductionOrderNo} 状态变更为{input.ProductionOrderStatus}",
  413. // TimeCreated = Clock.Now
  414. //};
  415. //await ProductionOrderLogRepository.InsertAsync(loLogs);
  416. entity = await Repository.UpdateAsync(entity);
  417. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  418. $"排产单状态变更为[{(ProductionOrderStatusEnum)input.ProductionOrderStatus}]",
  419. entity.ProductionOrderNo);
  420. return MapToEntityDto(entity);
  421. }
  422. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("排产进入已入库状态状态")]
  423. public async Task<ProductionOrderDto> ConfirmEnterStore(ConfirmEnterStoreDto input)
  424. {
  425. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  426. if (entity.ProductionOrderStatus != ProductionOrderStatusEnum.Storeing.ToInt())
  427. {
  428. CheckErrors(IwbIdentityResult.Failed("排查单未进行入库操作!"));
  429. }
  430. entity.ProductionOrderStatus = ProductionOrderStatusEnum.EnterStore.ToInt();
  431. //ProductionOrderLogs loLogs = new ProductionOrderLogs()
  432. //{
  433. // ProductionOrderNo = loProductionOrder.ProductionOrderNo,
  434. // CreatorUserId = AbpSession.UserName,
  435. // OperatorTitle = $"排产单:{loProductionOrder.ProductionOrderNo} 状态变更",
  436. // OperatorConent = $"排产单:{loProductionOrder.ProductionOrderNo} 状态变更为{input.ProductionOrderStatus}",
  437. // TimeCreated = Clock.Now
  438. //};
  439. //await ProductionOrderLogRepository.InsertAsync(loLogs);
  440. entity.EnterDate = Clock.Now;
  441. entity = await Repository.UpdateAsync(entity);
  442. if (string.IsNullOrEmpty(input.CurrentRmHouseId))
  443. {
  444. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  445. $"排产单状态变更为[{ProductionOrderStatusEnum.EnterStore}]。");
  446. }
  447. else
  448. {
  449. var rmCurrent= await CreateRwStore(input, entity.ProductionOrderNo);
  450. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产确认入库(车间生产)",$"排产单状态变更为[{ProductionOrderStatusEnum.EnterStore}]。原材料[{rmCurrent.RmProductNo}],领用{input.TotalQuantity}kg,剩余{input.LaveQuantity}kg,使用后库存:{rmCurrent.Quantity}kg",entity.ProductionOrderNo);
  451. }
  452. return MapToEntityDto(entity);
  453. }
  454. /// <summary>
  455. /// 生成原材料出入库记录
  456. /// </summary>
  457. /// <param name="input"></param>
  458. /// <param name="productOrderNo"></param>
  459. /// <returns></returns>
  460. private async Task<CurrentRmStoreHouse> CreateRwStore(ConfirmEnterStoreDto input,string productOrderNo)
  461. {
  462. var current = await CrsRepository.FirstOrDefaultAsync(a => a.Id == input.CurrentRmHouseId);
  463. if (current == null)
  464. {
  465. CheckErrors(IwbIdentityResult.Failed("未查询到库存记录!"));
  466. return null;
  467. }
  468. if (current.Quantity < 0 || (current.Quantity- current.FreezeQuantity - input.TotalQuantity + input.LaveQuantity) < 0)
  469. {
  470. CheckErrors(IwbIdentityResult.Failed("库存不足!"));
  471. return null;
  472. }
  473. current.Quantity = current.Quantity - input.TotalQuantity + input.LaveQuantity;
  474. await CrsRepository.UpdateAsync(current);
  475. var date = DateTime.Now;
  476. var oStore = new RmOutStore
  477. {
  478. Id = Guid.NewGuid().ToString("N"),
  479. CurrentRmStoreHouseNo = current.Id,
  480. IsConfirm= true,
  481. ProductionOrderNo = productOrderNo,
  482. ProductBatchNum = current.ProductBatchNum,
  483. RmProductNo = current.RmProductNo,
  484. ApplyStatus = RmEnterOutStatusEnum.Stored.ToInt(),
  485. CreateSourceType = CreateSourceType.Normal.ToInt(),
  486. StoreHouseId = current.StoreHouseId,
  487. ActualQuantity = input.TotalQuantity,
  488. Quantity = input.TotalQuantity,
  489. ApplyOutDate = date,
  490. AuditUser = AbpSession.UserName,
  491. AuditDate = date,
  492. OutStoreDate = date,
  493. OutStoreUser = AbpSession.UserName,
  494. };
  495. await OrsRepository.InsertAsync(oStore);
  496. if (input.LaveQuantity > 0)
  497. {
  498. var eStore = new RmEnterStore
  499. {
  500. Id = Guid.NewGuid().ToString("N"),
  501. ProductionOrderNo = productOrderNo,
  502. ProductBatchNum = current.ProductBatchNum,
  503. RmProductNo = current.RmProductNo,
  504. ApplyStatus = RmEnterOutStatusEnum.Stored.ToInt(),
  505. CreateSourceType = CreateSourceType.Normal.ToInt(),
  506. StoreHouseId = current.StoreHouseId,
  507. StoreLocationNo = current.StoreLocationNo,
  508. ApplyQuantity = input.LaveQuantity,
  509. Quantity = input.LaveQuantity,
  510. ApplyEnterDate = date,
  511. AuditUser = AbpSession.UserName,
  512. AuditDate = date,
  513. EnterStoreDate = date,
  514. EnterStoreUser = AbpSession.UserName,
  515. };
  516. await ErsRepository.InsertAsync(eStore);
  517. }
  518. return current;
  519. }
  520. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgCreate), AuditLog("创建排产单")]
  521. public override async Task<ProductionOrderDto> Create(ProductionOrderCreateDto input)
  522. {
  523. var entity = await Repository.FirstOrDefaultAsync(a => a.ProductionOrderNo == input.ProductionOrderNo);
  524. if (entity != null)
  525. {
  526. CheckErrors(IwbIdentityResult.Failed("排产单号已存在,请稍后再试!"));
  527. return null;
  528. }
  529. var dto = await base.Create(input);
  530. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  531. $"创建排产单,信息为:[{dto.Obj2String()}]",
  532. dto.ProductionOrderNo);
  533. return dto;
  534. }
  535. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("修改排产单")]
  536. public override async Task<ProductionOrderDto> Update(ProductionOrderUpdateDto input)
  537. {
  538. CheckUpdatePermission();
  539. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  540. if (entity.ProductionOrderStatus > ProductionOrderStatusEnum.Producting.ToInt()&& entity.ProductionOrderStatus != ProductionOrderStatusEnum.Audited.ToInt())
  541. {
  542. CheckErrors(IwbIdentityResult.Failed("排产单已进行入库,不可进行修改!"));
  543. }
  544. MapToEntity(input, entity);
  545. entity.TimeLastMod = Clock.Now;
  546. entity.UserIDLastMod = AbpSession.UserId + "";
  547. entity= await Repository.UpdateAsync(entity);
  548. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  549. $"修改排产单,信息为:[{entity.Obj2String()}]",
  550. entity.ProductionOrderNo);
  551. return MapToEntityDto(entity);
  552. }
  553. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgDelete), AuditLog("删除排产单")]
  554. public override async Task Delete(EntityDto<int> input)
  555. {
  556. CheckDeletePermission();
  557. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  558. if (entity.ProductionOrderStatus > ProductionOrderStatusEnum.Producting.ToInt()&&entity.ProductionOrderStatus!=ProductionOrderStatusEnum.Audited.ToInt())
  559. {
  560. CheckErrors(IwbIdentityResult.Failed("排产单已进行入库,不可进行删除!"));
  561. }
  562. entity.IsLock = "Y";
  563. entity=await Repository.UpdateAsync(entity);
  564. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  565. $"删除排产单,信息为:[{entity.Obj2String()}]",
  566. entity.ProductionOrderNo);
  567. }
  568. /// <summary>
  569. /// 创建外协排产单
  570. /// </summary>
  571. /// <param name="input"></param>
  572. /// <returns></returns>
  573. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgCreate), AuditLog("创建外协排产单")]
  574. public async Task<ProductionOrderDto> CreateOutProductionOrder(CreateOutProductionOrderDto input)
  575. {
  576. string sourceProductionOrderNo = input.SourceProductionOrderNo;
  577. string processType = input.ProcessingType;
  578. string processTypeNo = input.ProcessingTypeNo;
  579. string productionOrderNo = GetOutProductionOrderNo(sourceProductionOrderNo, processType, processTypeNo);
  580. var isExistObj = Repository.FirstOrDefault(i => i.ProductionOrderNo == productionOrderNo);
  581. if (isExistObj != null)
  582. {
  583. throw new UserFriendlyException("该流转单编号已存在!同一批次产品入库分两次外协加工,编号不能重复填写!");
  584. }
  585. if (input.IsReplating == 1)
  586. {
  587. var outStore = await ProductOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.OutStoreId);
  588. outStore.IsClose = true;
  589. outStore.IsConfirm = true;
  590. await ProductOutStoreRepository.UpdateAsync(outStore);
  591. var currentStore = await CurrentProductStoreHouseRepository.FirstOrDefaultAsync(a =>
  592. a.CurrentProductStoreHouseNo == outStore.CurrentProductStoreHouseNo);
  593. currentStore.FreezeQuantity -= outStore.Quantity;
  594. currentStore.Quantity -= outStore.Quantity;
  595. await CurrentProductStoreHouseRepository.UpdateAsync(currentStore);
  596. }
  597. else
  598. {
  599. var semiOutStore = await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.OutStoreId);
  600. semiOutStore.IsClose = true;
  601. await SemiOutStoreRepository.UpdateAsync(semiOutStore);
  602. }
  603. var semiProduct = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == input.SemiProductNo);
  604. ProductionOrderCreateDto objOrderCreateDto = new ProductionOrderCreateDto()
  605. {
  606. Material = semiProduct.Material,
  607. ProductionOrderNo = productionOrderNo,
  608. ProcessingLevel = "2",
  609. OutsourcingFactory = input.OutsourcingFactory,
  610. PlanProduceDate = input.PlanProduceDate,
  611. Model = semiProduct.Model,
  612. Quantity = input.Quantity,
  613. SurfaceColor = semiProduct.SurfaceColor,
  614. ProductionOrderStatus = ProductionOrderStatusEnum.Start.ToInt(),
  615. ProcessingType = processType,
  616. SourceProductionOrderNo = sourceProductionOrderNo,
  617. SemiProductNo = input.SemiProductNo,
  618. Rigidity = semiProduct.Rigidity,
  619. Remark = input.Remark,
  620. };
  621. //返镀标识
  622. if (input.IsReplating == 1)
  623. {
  624. objOrderCreateDto.Remark = $"[返镀]{objOrderCreateDto.Remark}";
  625. }
  626. var dto = await CreateEntity(objOrderCreateDto);
  627. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  628. $"创建外协排产单[{dto.Id}],信息为:[{input.Obj2String()}]",
  629. dto.ProductionOrderNo, dto.SourceProductionOrderNo);
  630. return dto;
  631. }
  632. [AbpAuthorize(PermissionNames.PagesProductionInfoOutProductionOrderMgUpdate), AuditLog("修改外协排产单")]
  633. public async Task<ProductionOrderDto> UpdateOutProductionOrder(UpdateOutProductionOrderDto input)
  634. {
  635. //string productionOrderNo = GetOutProductionOrderNo(input.SourceProductionOrderNo, input.ProcessingType, input.ProcessingTypeNo);
  636. var entity = Repository.FirstOrDefault(i => i.ProductionOrderNo == input.ProductionOrderNo);
  637. if (entity == null)
  638. {
  639. throw new UserFriendlyException("该流转单编号不存在!");
  640. }
  641. //var semiProduct =await SemiProductRepository.FirstOrDefaultAsync(a=>a.Id == input.SemiProductNo);
  642. entity.Quantity = input.Quantity;
  643. entity.PlanProduceDate = input.PlanProduceDate;
  644. entity.TimeLastMod = Clock.Now;
  645. entity.UserIDLastMod = AbpSession.UserName;
  646. entity.Remark = input.Remark;
  647. entity.KgWeight = input.KgWeight??0;
  648. entity.OutsourcingFactory = input.OutsourcingFactory;
  649. entity.SemiProductNo = input.SemiProductNo;
  650. entity = await Repository.UpdateAsync(entity);
  651. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  652. $"修改外协排产单[{entity.Id}],信息为:[{input.Obj2String()}]",
  653. entity.ProductionOrderNo, entity.SourceProductionOrderNo);
  654. return MapToEntityDto(entity);
  655. }
  656. [AbpAuthorize(PermissionNames.PagesProductionInfoOutProductionOrderMgDelete), AuditLog("删除外协排产单")]
  657. public async Task DeleteOutProductionOrder(EntityDto<int> input)
  658. {
  659. //string productionOrderNo = GetOutProductionOrderNo(input.SourceProductionOrderNo, input.ProcessingType, input.ProcessingTypeNo);
  660. var entity = Repository.FirstOrDefault(i => i.Id == input.Id);
  661. if (entity == null)
  662. {
  663. throw new UserFriendlyException("该流转单编号不存在!");
  664. }
  665. if (entity.ProductionOrderStatus >= ProductionOrderStatusEnum.Producting.ToInt()&& entity.ProductionOrderStatus!= ProductionOrderStatusEnum.Audited.ToInt())
  666. {
  667. CheckErrors(IwbIdentityResult.Failed("排产单已进行入库,不可进行删除!"));
  668. }
  669. entity.IsLock = "Y";
  670. await Repository.UpdateAsync(entity);
  671. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半产品排产",
  672. $"删除外协排产单[{entity.Id}]",
  673. entity.ProductionOrderNo, entity.SourceProductionOrderNo);
  674. }
  675. private string GetOutProductionOrderNo(string sourceProductionOrderNo, string processType,
  676. string processTypeNo)
  677. {
  678. string resultNo = sourceProductionOrderNo.Length > 7
  679. ? sourceProductionOrderNo
  680. : sourceProductionOrderNo + "0000";
  681. if (processType == ProductionOrderProcessTypeEnum.HeatTreatment.ToInt() + "")
  682. {
  683. resultNo = resultNo.Substring(0, resultNo.Length - 2) + processTypeNo;
  684. }
  685. else if (processType == ProductionOrderProcessTypeEnum.SurfaceTreatment.ToInt() + "")
  686. {
  687. string lastTwoLength = resultNo.Substring(resultNo.Length - 2, 2);
  688. resultNo = resultNo.Substring(0, resultNo.Length - 4) + processTypeNo + lastTwoLength;
  689. }
  690. return resultNo;
  691. }
  692. //[AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("关联订单明细")]
  693. public async Task BindOrderItems(BindOrdersDto input)
  694. {
  695. string itemIds = input.OrderItemIds;
  696. string[] items = itemIds.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
  697. foreach (string itemId in items)
  698. {
  699. int.TryParse(itemId, out int it);
  700. var isExist = OrderProductionRepository.FirstOrDefault(i =>
  701. i.OrderItemId == it && i.ProductionOrderNo == input.ProductionOrderNo);
  702. if (isExist != null)
  703. {
  704. continue;
  705. }
  706. await OrderProductionRepository.InsertAsync(new OrderProduction()
  707. {OrderItemId = it, ProductionOrderNo = input.ProductionOrderNo});
  708. }
  709. }
  710. // [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("关联订单明细")]
  711. public async Task UnBindOrderItems(BindOrdersDto input)
  712. {
  713. string itemIds = input.OrderItemIds;
  714. string[] items = itemIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  715. foreach (string itemId in items)
  716. {
  717. int.TryParse(itemId, out int it);
  718. var isExist = OrderProductionRepository.FirstOrDefault(i =>
  719. i.OrderItemId == it && i.ProductionOrderNo == input.ProductionOrderNo);
  720. if (isExist != null)
  721. {
  722. await OrderProductionRepository.DeleteAsync(i =>
  723. i.OrderItemId == it && i.ProductionOrderNo == input.ProductionOrderNo);
  724. }
  725. }
  726. }
  727. public List<ViewOrderItems> QueryOrderItemByPoNo(string productionOrderNo)
  728. {
  729. var entities = OrderProductionRepository.GetAllList(i => i.ProductionOrderNo == productionOrderNo);
  730. var its = entities.Select(i => i.OrderItemId);
  731. var rs = ViewOrderItemsRepository.GetAllList(i => its.Contains(i.Id));
  732. return rs;
  733. }
  734. #endregion
  735. #region 半成品入库
  736. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMg), DisableAuditing]
  737. public PagedResultDto<ViewSemiEnterStore> GetSemiEnterStoreApply(PagedRequestDto input)
  738. {
  739. var query = ViewSemiEnterStoreRepository.GetAll();
  740. if (input.SearchList != null && input.SearchList.Count > 0)
  741. {
  742. List<LambdaObject> objList = new List<LambdaObject>();
  743. foreach (var o in input.SearchList)
  744. {
  745. if (o.KeyWords.IsNullOrEmpty())
  746. continue;
  747. object keyWords = o.KeyWords;
  748. //检查查询条件中带有规格且多个分割条件的
  749. ProductModelSearch.CheckModelGreaterOneFilter(o, ref keyWords);
  750. objList.Add(new LambdaObject
  751. {
  752. FieldType = (LambdaFieldType)o.FieldType,
  753. FieldName = o.KeyField,
  754. FieldValue = keyWords,
  755. ExpType = (LambdaExpType)o.ExpType
  756. });
  757. }
  758. var exp = objList.GetExp<ViewSemiEnterStore>();
  759. query = query.Where(exp);
  760. }
  761. var totalCount = query.Count();
  762. query = query.OrderByDescending(i => i.TimeCreated);
  763. string pattern = ProductModelSearch.GetModelGreaterOneReg(input.SearchList);
  764. List<ViewSemiEnterStore> entities;
  765. //检查查询条件中带有规格且多个分割条件的
  766. if (!pattern.IsNullOrEmpty())
  767. {
  768. var es = query.ToList();
  769. es = es.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  770. totalCount = es.Count;
  771. entities = es.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
  772. }
  773. else
  774. {
  775. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  776. entities = query.ToList();
  777. }
  778. //query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  779. //var entities = query.ToList();
  780. var dtos = new PagedResultDto<ViewSemiEnterStore>(
  781. totalCount, entities
  782. );
  783. return dtos;
  784. }
  785. /// <summary>
  786. /// 获取当前排查单申请中数量+成功入库数量(千件数量)
  787. /// </summary>
  788. /// <param name="input"></param>
  789. /// <returns></returns>
  790. private decimal SumEnterStoreQuantity(ProductionOrder input)
  791. {
  792. string applyStatus = EnterStoreApplyStatusEnum.Applying.ToInt() + "",
  793. auditedStatus = EnterStoreApplyStatusEnum.Audited.ToInt() + "",
  794. enterStoredStatus = EnterStoreApplyStatusEnum.EnterStored.ToInt() + "",
  795. checkedStatus = EnterStoreApplyStatusEnum.Checked.ToInt() + "";
  796. var enterLogs = SemiEnterStoreRepository.GetAll().Where(i =>
  797. i.ProductionOrderNo == input.ProductionOrderNo &&
  798. (i.ApplyStatus == applyStatus ||
  799. i.ApplyStatus == auditedStatus ||
  800. i.ApplyStatus == enterStoredStatus ||
  801. i.ApplyStatus == checkedStatus));
  802. decimal result = 0;
  803. if (enterLogs.Any())
  804. {
  805. foreach (var log in enterLogs)
  806. {
  807. result += (log.ApplyStatus == enterStoredStatus ? log.ActualQuantity : log.Quantity) / (input.KgWeight <= 0 ? 1 : input.KgWeight);
  808. }
  809. }
  810. return result;
  811. }
  812. private bool CheckEnterStoreQuantity(ProductionOrder input,decimal enterQuantity,decimal kw)
  813. {
  814. ////已经申请入库数量
  815. //var hasQuantity = SumEnterStoreQuantity(input);
  816. ////最多可入库数量上浮百分之20
  817. //var productQuantity =(double) (input.Quantity * (input.KgWeight <= 0 ? 1 : input.KgWeight)) * 1.2;
  818. //if ((double)(hasQuantity + enterQuantity) > productQuantity)
  819. //{
  820. // return false;
  821. //}
  822. //return true;
  823. //已经申请入库数量
  824. var hasQuantity = SumEnterStoreQuantity(input);
  825. //最多可入库数量上浮百分之20
  826. var productQuantity = (input.MaxQuantity>= input.Quantity)? (double)input.MaxQuantity:(double) (input.Quantity) * 1.2;
  827. if ((double)(hasQuantity + enterQuantity/ (kw <= 0 ? 1 : kw)) > productQuantity)
  828. {
  829. return false;
  830. }
  831. return true;
  832. }
  833. public async Task<bool> CheckEnterStoreQuantity(CreateEnterStoreApplyDto input)
  834. {
  835. var loProductionOrder = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  836. if (!CheckEnterStoreQuantity(loProductionOrder, input.EnterStoreQuantity, input.KgWeight))
  837. {
  838. //CheckErrors(IwbIdentityResult.Failed("申请中数量+成功入库数量, 不能大于等于排产单计划总数量的上限数量!"));
  839. return false;
  840. }
  841. return true;
  842. }
  843. /// <summary>
  844. /// 半成品入库申请
  845. /// </summary>
  846. /// <param name="input"></param>
  847. /// <returns></returns>
  848. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgUpdate), AuditLog("创建入库申请")]
  849. public async Task<SemiEnterStoreDto> CreateEnterStoreApply(CreateEnterStoreApplyDto input)
  850. {
  851. string errMsg = "";
  852. var loProductionOrder = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  853. if (!CheckEnterStoreQuantity(loProductionOrder, input.EnterStoreQuantity, input.KgWeight))
  854. {
  855. //CheckErrors(IwbIdentityResult.Failed("申请中数量+成功入库数量, 不能大于等于排产单计划总数量的上限数量!"));
  856. errMsg = "申请中数量+成功入库数量, 已经大于等于排产单计划总数量的上限数量!";
  857. }
  858. loProductionOrder.ProductionOrderStatus = ProductionOrderStatusEnum.Storeing.ToInt();
  859. loProductionOrder.KgWeight = input.KgWeight;
  860. //loProductionOrder.ProductionOrderStatus = ProductionOrderStatusEnum.Producting.ToInt();
  861. var applySource = loProductionOrder.ProcessingLevel == "1"
  862. ? (loProductionOrder.ProductionType == "0"
  863. ? EnterStoreApplySourceEnum.InnerCar
  864. : EnterStoreApplySourceEnum.Out)
  865. : EnterStoreApplySourceEnum.OutProduct;
  866. SemiEnterStore entity = new SemiEnterStore
  867. {
  868. ApplyEnterDate = Clock.Now,
  869. ApplySource =applySource.ToInt().ToString(),
  870. ApplyStatus = EnterStoreApplyStatusEnum.Applying.ToInt().ToString(),
  871. ProductionOrderNo = loProductionOrder.ProductionOrderNo,
  872. SemiProductNo = loProductionOrder.SemiProductNo,
  873. Quantity = input.EnterStoreQuantity,
  874. ActualQuantity = 0,
  875. AuditDate = Clock.Now,
  876. AuditUser = AbpSession.UserName,
  877. TimeCreated = Clock.Now,
  878. CreatorUserId = AbpSession.UserName,
  879. TimeLastMod = Clock.Now,
  880. UserIDLastMod = AbpSession.UserName,
  881. Remark = input.Remark,
  882. StoreHouseId = input.StoreHouseId,
  883. KgWeight = input.KgWeight,
  884. };
  885. await SemiEnterStoreRepository.InsertAsync(entity);
  886. if (loProductionOrder.ProductionType == "0" &&
  887. input.ProductUser != null && input.ProductUser.Any())
  888. {
  889. if (string.IsNullOrEmpty(input.CarNo))
  890. {
  891. CheckErrors(IwbIdentityResult.Failed("车号不能为空,请检查后再试。"));
  892. }
  893. if (string.IsNullOrEmpty(loProductionOrder.CarNo))
  894. {
  895. loProductionOrder.CarNo = input.CarNo;
  896. }
  897. else if (input.CarNo!=loProductionOrder.CarNo)
  898. {
  899. CheckErrors(IwbIdentityResult.Failed("车号与上一次入库不一致,请检查后再试。"));
  900. }
  901. await CreateProductionLog(input, loProductionOrder.ProductionOrderNo);
  902. }
  903. await Repository.UpdateAsync(loProductionOrder);
  904. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  905. $"创建半成品入库申请[{entity.Id}],信息为:[{input.Obj2String()}]",
  906. entity.ProductionOrderNo);
  907. var result = ObjectMapper.Map<SemiEnterStoreDto>(entity);
  908. result.ErrorMsg = errMsg;
  909. return result;
  910. }
  911. private async Task CreateProductionLog(CreateEnterStoreApplyDto input,string productOrderNo)
  912. {
  913. int index= await GetLogIndex(productOrderNo);
  914. decimal q1 = Math.Round(input.EnterStoreQuantity / input.ProductUser.Count,2),
  915. q2 = Math.Round(input.EnterStoreQuantity2 / input.ProductUser.Count,2);
  916. foreach (var user in input.ProductUser)
  917. {
  918. index++;
  919. string logNo = $"{productOrderNo}-{index}";
  920. var log = new ProductionLog()
  921. {
  922. ProductionNo = logNo,
  923. ProductOrderNo = productOrderNo,
  924. QuantityWeight = q1,
  925. QuantityPcs = q2,
  926. KgWeight = input.KgWeight,
  927. CarNo = input.CarNo,
  928. EmployeeId = user,
  929. };
  930. await ProductLogRepository.InsertAsync(log);
  931. var p = new EmployeeWorkPerformance()
  932. {
  933. PerformanceNo =await WorkTypeDefinition.GetPerformanceNo(PerformanceRepository, WorkTypeDefinition.Product),
  934. ProductOrderNo = productOrderNo,
  935. RelatedNo = logNo,
  936. EmployeeId = user,
  937. WorkType = WorkTypeDefinition.Product,
  938. Performance = q2,
  939. PerformanceUnit = "千件",
  940. PerformanceDesc =
  941. $"{q2}千件,总重:{q1}kg,千件重:{input.KgWeight}",
  942. };
  943. await PerformanceRepository.InsertAsync(p);
  944. await CurrentUnitOfWork.SaveChangesAsync();
  945. }
  946. }
  947. private async Task<int> GetLogIndex(string productOrderNo)
  948. {
  949. var log = await ProductLogRepository.GetAll().Where(a => a.ProductionNo.Contains(productOrderNo + "-")).OrderByDescending(a=>a.CreationTime).FirstOrDefaultAsync();
  950. if (log==null)
  951. {
  952. return 0;
  953. }
  954. var no = log.ProductionNo.Substring(log.ProductionNo.IndexOf("-", StringComparison.Ordinal) + 1);
  955. return Convert.ToInt32(no);
  956. }
  957. /// <summary>
  958. /// 确认入库数量(by yue.)
  959. /// </summary>
  960. /// <param name="input"></param>
  961. /// <returns></returns>
  962. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgConfirm), AuditLog("确认入库申请")]
  963. public async Task<SemiEnterStoreDto> ConfirmSemiEnterStoreQuantity(EntityDto<int> input)
  964. {
  965. var entity = await SemiEnterStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  966. if (entity.ApplyStatus == EnterStoreApplyStatusEnum.EnterStored.ToInt() + "")
  967. {
  968. CheckErrors(IwbIdentityResult.Failed("已入库不能再操作!"));
  969. }
  970. if (entity.ApplyStatus != EnterStoreApplyStatusEnum.Checked.ToInt() + "")
  971. {
  972. CheckErrors(IwbIdentityResult.Failed("还未检验,不能入库!"));
  973. }
  974. entity.ApplyStatus = EnterStoreApplyStatusEnum.EnterStored.ToInt() + "";
  975. var date = Clock.Now;
  976. entity.EnterStoreDate = date;
  977. entity.EnterStoreUser = AbpSession.UserName;
  978. await SemiEnterStoreRepository.UpdateAsync(entity);
  979. var currentStore = CurrentSemiStoreHouseRepository.GetAll().FirstOrDefault(i => i.ProductionOrderNo == entity.ProductionOrderNo&& i.StoreHouseId==entity.StoreHouseId&&i.StoreLocationNo==entity.StoreLocationNo);
  980. if (currentStore != null)
  981. {
  982. var isCanUpdate =
  983. CommonAppService.CheckStoreRecordCanUpdate(currentStore.CurrentSemiStoreHouseNo, 2);
  984. if (!isCanUpdate)
  985. CheckErrors(IwbIdentityResult.Failed("该库存处于退货或者正在盘点状态,不可进行出入库更新!"));
  986. currentStore.ActualQuantity += entity.ActualQuantity;
  987. currentStore.TimeLastMod = date;
  988. currentStore.UserIDLastMod = AbpSession.UserName;
  989. currentStore.KgWeight = entity.KgWeight;
  990. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  991. }
  992. else
  993. {
  994. string lcJson = JsonConvert.SerializeObject(entity);
  995. currentStore = lcJson.GetModel<CurrentSemiStoreHouse>();
  996. var isCanUpdate =
  997. CommonAppService.CheckStoreCanUpdateByLocationNo(currentStore.StoreLocationNo, 2);
  998. if (!isCanUpdate)
  999. CheckErrors(IwbIdentityResult.Failed("该库位正在盘点状态,不可进行出入库更新!"));
  1000. currentStore.CurrentSemiStoreHouseNo = Guid.NewGuid().ToString("N");
  1001. currentStore.TimeCreated = date;
  1002. currentStore.UserIDLastMod = AbpSession.UserName;
  1003. currentStore.ActualQuantity = entity.ActualQuantity;
  1004. currentStore.FreezeQuantity = 0;
  1005. await CurrentSemiStoreHouseRepository.InsertAsync(currentStore);
  1006. }
  1007. //取消确认入库自动变更排查单状态
  1008. /*var productionOrder =
  1009. await Repository.FirstOrDefaultAsync(a => a.ProductionOrderNo == entity.ProductionOrderNo);
  1010. if (productionOrder == null)
  1011. {
  1012. CheckErrors(IwbIdentityResult.Failed("未发现排产单!"));
  1013. return null;
  1014. }
  1015. productionOrder.ProductionOrderStatus = ProductionOrderStatusEnum.EnterStore.ToInt();
  1016. await Repository.UpdateAsync(productionOrder);*/
  1017. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  1018. $"确认半成品入库数量[{entity.Id}],排产单入库信息:[确认数量:{entity.ActualQuantity},库存:{currentStore.ActualQuantity},冻结:{currentStore.FreezeQuantity}]。",
  1019. entity.ProductionOrderNo);
  1020. return ObjectMapper.Map<SemiEnterStoreDto>(entity);
  1021. }
  1022. /// <summary>
  1023. /// 取消入库申请(by yue.)
  1024. /// </summary>
  1025. /// <param name="input"></param>
  1026. /// <returns></returns>
  1027. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgCancel), AuditLog("取消入库申请")]
  1028. public async Task<SemiEnterStoreDto> CancelSemiEnterStoreApplyStatus(EntityDto<int> input)
  1029. {
  1030. var entity = await SemiEnterStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1031. if (entity.ApplyStatus == EnterStoreApplyStatusEnum.EnterStored.ToInt() + "")
  1032. {
  1033. CheckErrors(IwbIdentityResult.Failed("已入库不能再操作!"));
  1034. }
  1035. entity.ApplyStatus = EnterStoreApplyStatusEnum.Canceled.ToInt() + "";
  1036. await SemiEnterStoreRepository.UpdateAsync(entity);
  1037. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  1038. $"取消半成品入库申请[{entity.Id}]",
  1039. entity.ProductionOrderNo);
  1040. return ObjectMapper.Map<SemiEnterStoreDto>(entity);
  1041. }
  1042. /// <summary>
  1043. /// 关闭入库申请 (by yue.)
  1044. /// </summary>
  1045. /// <param name="input"></param>
  1046. /// <returns></returns>
  1047. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgClose), AuditLog("关闭入库申请")]
  1048. public async Task<SemiEnterStoreDto> CloseEnterStoreApply(EntityDto<int> input)
  1049. {
  1050. var entity = await SemiEnterStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1051. entity.IsClose = true;
  1052. //var productionOrder =
  1053. // await Repository.FirstOrDefaultAsync(a => a.ProductionOrderNo == entity.ProductionOrderNo);
  1054. //if (productionOrder == null)
  1055. //{
  1056. // CheckErrors(IwbIdentityResult.Failed("未发现排产单!"));
  1057. // return null;
  1058. //}
  1059. //if (productionOrder.ProductionOrderStatus != ProductionOrderStatusEnum.EnterStore.ToInt()&& productionOrder.ProductionOrderStatus != ProductionOrderStatusEnum.End.ToInt())
  1060. //{
  1061. // productionOrder.ProductionOrderStatus = ProductionOrderStatusEnum.Producting.ToInt();
  1062. //}
  1063. //await Repository.UpdateAsync(productionOrder);
  1064. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  1065. $"关闭半成品入库申请[{entity.Id}]",
  1066. entity.ProductionOrderNo);
  1067. await SemiEnterStoreRepository.UpdateAsync(entity);
  1068. return ObjectMapper.Map<SemiEnterStoreDto>(entity);
  1069. }
  1070. /// <summary>
  1071. /// 恢复入库申请(by yue.)
  1072. /// </summary>
  1073. /// <param name="input"></param>
  1074. /// <returns></returns>
  1075. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgRecovery), AuditLog("恢复入库申请")]
  1076. public async Task<SemiEnterStoreDto> RecoverySemiEnterStoreApplyStatus(EntityDto<int> input)
  1077. {
  1078. var entity = await SemiEnterStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1079. if (entity.ApplyStatus == EnterStoreApplyStatusEnum.EnterStored.ToInt() + "")
  1080. {
  1081. CheckErrors(IwbIdentityResult.Failed("已入库不能再操作!"));
  1082. }
  1083. entity.ApplyStatus = EnterStoreApplyStatusEnum.Applying.ToInt() + "";
  1084. await SemiEnterStoreRepository.UpdateAsync(entity);
  1085. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  1086. $"恢复半成品入库申请[{entity.Id}]",
  1087. entity.ProductionOrderNo);
  1088. return ObjectMapper.Map<SemiEnterStoreDto>(entity);
  1089. }
  1090. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgUpdate), AuditLog("修改入库申请")]
  1091. public async Task<SemiEnterStoreDto> UpdateEnterStoreApply(UpdateSemiEnterStoreDto input)
  1092. {
  1093. var entity = await SemiEnterStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1094. #region 增加入口数量限制检验
  1095. //var productOrder = Repository.FirstOrDefault(i => i.ProductionOrderNo == entity.ProductionOrderNo);
  1096. //if (productOrder != null)
  1097. //{
  1098. // var sumQuantity = SumEnterStoreQuantity(productOrder);
  1099. // sumQuantity = sumQuantity - (entity.Quantity / (entity.KgWeight <= 0 ? 1 : entity.KgWeight)) + (input.Quantity / (input.KgWeight <= 0 ? 1 : input.KgWeight));
  1100. // var maxQuantity = (productOrder.MaxQuantity >= productOrder.Quantity) ? (double)productOrder.MaxQuantity : (double)(productOrder.Quantity) * 1.2;
  1101. // if ((double)sumQuantity > maxQuantity)
  1102. // {
  1103. // CheckErrors(IwbIdentityResult.Failed("申请中数量+成功入库数量, 不能大于等于排产单计划总数量的上限数量!"));
  1104. // }
  1105. //}
  1106. #endregion
  1107. entity.Quantity = input.Quantity;
  1108. entity.KgWeight = input.KgWeight;
  1109. await SemiEnterStoreRepository.UpdateAsync(entity);
  1110. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品入库",
  1111. $"修改半成品入库申请数量[{entity.Id}],数量修改为[{input.Quantity}],千斤重修改为[{input.KgWeight}]",
  1112. entity.ProductionOrderNo);
  1113. return ObjectMapper.Map<SemiEnterStoreDto>(entity);
  1114. }
  1115. #endregion
  1116. #region 半成品出库
  1117. [DisableAuditing,AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMg)]
  1118. public PagedResultDto<ViewSemiOutStore> GetSemiOutStoreApply(PagedRequestDto input)
  1119. {
  1120. int type = OutStoreApplyTypeEnum.OutAssistant.ToInt();
  1121. var query = ViewSemiOutStoreRepository.GetAll().Where(a => a.ApplyTypes== type);
  1122. if (input.SearchList != null && input.SearchList.Count > 0)
  1123. {
  1124. List<LambdaObject> objList = new List<LambdaObject>();
  1125. foreach (var o in input.SearchList)
  1126. {
  1127. if (o.KeyWords.IsNullOrEmpty())
  1128. continue;
  1129. object keyWords = o.KeyWords;
  1130. //检查查询条件中带有规格且多个分割条件的
  1131. ProductModelSearch.CheckModelGreaterOneFilter(o, ref keyWords);
  1132. objList.Add(new LambdaObject
  1133. {
  1134. FieldType = (LambdaFieldType)o.FieldType,
  1135. FieldName = o.KeyField,
  1136. FieldValue = keyWords,
  1137. ExpType = (LambdaExpType)o.ExpType
  1138. });
  1139. }
  1140. var exp = objList.GetExp<ViewSemiOutStore>();
  1141. query = query.Where(exp);
  1142. }
  1143. var totalCount = query.Count();
  1144. query = query.OrderByDescending(i => i.TimeCreated);
  1145. string pattern = ProductModelSearch.GetModelGreaterOneReg(input.SearchList);
  1146. List<ViewSemiOutStore> entities;
  1147. //检查查询条件中带有规格且多个分割条件的
  1148. if (!pattern.IsNullOrEmpty())
  1149. {
  1150. var es = query.ToList();
  1151. es = es.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  1152. totalCount = es.Count;
  1153. entities = es.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
  1154. }
  1155. else
  1156. {
  1157. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  1158. entities = query.ToList();
  1159. }
  1160. //query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  1161. //var entities = query.ToList();
  1162. var dtos = new PagedResultDto<ViewSemiOutStore>(
  1163. totalCount, entities
  1164. );
  1165. return dtos;
  1166. }
  1167. [DisableAuditing,AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMg)]
  1168. public ViewSemiOutStore GetSemiOutStoreApplyById(int id)
  1169. {
  1170. var outStore = ViewSemiOutStoreRepository.Get(id);
  1171. return outStore;
  1172. }
  1173. /// <summary>
  1174. /// 半成品出库申请
  1175. /// </summary>
  1176. /// <param name="input"></param>
  1177. /// <returns></returns>
  1178. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgCreate), AuditLog("创建出库申请")]
  1179. public async Task<SemiOutStoreDto> CreateOutStoreApply(SemiOutStoreCreateDto input)
  1180. {
  1181. var currentStore =
  1182. CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  1183. i.CurrentSemiStoreHouseNo == input.CurrentSemiStoreHouseNo);
  1184. if (currentStore == null)
  1185. {
  1186. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1187. return null;
  1188. }
  1189. #region 检查是否可出入库
  1190. var isCanUpdate =
  1191. CommonAppService.CheckStoreRecordCanUpdate(currentStore.CurrentSemiStoreHouseNo, 2);
  1192. if (!isCanUpdate)
  1193. CheckErrors(IwbIdentityResult.Failed("该库存处于退货或者正在盘点状态,不可进行出入库更新!"));
  1194. #endregion
  1195. var canUseQuantit = currentStore.ActualQuantity - currentStore.FreezeQuantity;
  1196. if (canUseQuantit < input.Quantity)
  1197. {
  1198. CheckErrors(IwbIdentityResult.Failed("可用库存量不够,请检查出库数量!"));
  1199. return null;
  1200. }
  1201. currentStore.ActualQuantity -= input.Quantity;
  1202. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1203. input.ApplyOutDate = Clock.Now;
  1204. var entity = ObjectMapper.Map<SemiOutStore>(input);
  1205. entity.ApplyOutStoreSource = OutStoreApplyTypeEnum.OutAssistant.ToInt() + "";
  1206. entity.ApplyTypes = OutStoreApplyTypeEnum.OutAssistant.ToInt();
  1207. entity.ApplyStatus = OutStoreApplyStatusEnum.OutStored.ToInt() + "";
  1208. entity.IsConfirm = true;
  1209. entity.AuditDate = Clock.Now;
  1210. entity.AuditUser = AbpSession.UserName;
  1211. entity.ActualQuantity = input.Quantity;
  1212. entity.TimeCreated = Clock.Now;
  1213. entity.CreatorUserId = AbpSession.UserName;
  1214. entity.TimeLastMod = Clock.Now;
  1215. entity.UserIDLastMod = AbpSession.UserName;
  1216. int id = await SemiOutStoreRepository.InsertAndGetIdAsync(entity);
  1217. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1218. $"创建出库申请(外协加工)[{entity.Id}],信息为:[{entity.Obj2String()}]",
  1219. entity.ProductionOrderNo);
  1220. var dto=ObjectMapper.Map<SemiOutStoreDto>(entity);
  1221. dto.Id = id;
  1222. return dto;
  1223. }
  1224. ///// <summary>
  1225. ///// 半成品出库申请
  1226. ///// </summary>
  1227. ///// <param name="input"></param>
  1228. ///// <returns></returns>
  1229. //[AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgCreate), AuditLog("创建出库申请")]
  1230. //public async Task<SemiOutStoreDto> CreateOutStoreApply(SemiOutStoreCreateDto input)
  1231. //{
  1232. // var currentStore =
  1233. // CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  1234. // i.CurrentSemiStoreHouseNo == input.CurrentSemiStoreHouseNo);
  1235. // if (currentStore == null)
  1236. // {
  1237. // CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1238. // return null;
  1239. // }
  1240. // var canUseQuantit = currentStore.ActualQuantity - currentStore.FreezeQuantity;
  1241. // if (canUseQuantit < input.Quantity)
  1242. // {
  1243. // CheckErrors(IwbIdentityResult.Failed("可用库存量不够,请检查出库数量!"));
  1244. // return null;
  1245. // }
  1246. // currentStore.FreezeQuantity += input.Quantity;
  1247. // await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1248. // input.ApplyOutDate = Clock.Now;
  1249. // var entity = ObjectMapper.Map<SemiOutStore>(input);
  1250. // entity.ApplyOutStoreSource = OutStoreApplyTypeEnum.OutAssistant.ToInt() + "";
  1251. // entity.ApplyTypes = OutStoreApplyTypeEnum.OutAssistant.ToInt();
  1252. // entity.IsConfirm = false;
  1253. // entity.AuditDate = Clock.Now;
  1254. // entity.AuditUser = AbpSession.UserName;
  1255. // entity.ActualQuantity = 0;
  1256. // entity.TimeCreated = Clock.Now;
  1257. // entity.CreatorUserId = AbpSession.UserName;
  1258. // entity.TimeLastMod = Clock.Now;
  1259. // entity.UserIDLastMod = AbpSession.UserName;
  1260. // entity = await SemiOutStoreRepository.InsertAsync(entity);
  1261. // BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1262. // $"创建出库申请(外协加工)[{entity.Id}],信息为:[{entity.Obj2String()}]",
  1263. // entity.ProductionOrderNo);
  1264. // return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1265. //}
  1266. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgUpdate), AuditLog("修改出库申请")]
  1267. public async Task<SemiOutStoreDto> UpdateOutStoreApply(SemiOutStoreUpdateDto input)
  1268. {
  1269. var entity = await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1270. if (entity.ApplyStatus == OutStoreApplyStatusEnum.Audited + ""|| entity.ApplyStatus == OutStoreApplyStatusEnum.OutStored + "")
  1271. {
  1272. CheckErrors(IwbIdentityResult.Failed("出库申请已处理,不可操作!"));
  1273. return null;
  1274. }
  1275. var currentStore =
  1276. CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  1277. i.CurrentSemiStoreHouseNo == input.CurrentSemiStoreHouseNo);
  1278. if (currentStore == null)
  1279. {
  1280. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1281. return null;
  1282. }
  1283. if (entity.ApplyStatus == OutStoreApplyStatusEnum.Applying.ToInt()+"")
  1284. {
  1285. var canUseQuantit = currentStore.ActualQuantity + entity.Quantity - currentStore.FreezeQuantity;
  1286. if (canUseQuantit < input.Quantity)
  1287. {
  1288. CheckErrors(IwbIdentityResult.Failed("可用库存量不够,请检查出库数量!"));
  1289. return null;
  1290. }
  1291. currentStore.FreezeQuantity -= entity.Quantity;
  1292. currentStore.FreezeQuantity += input.Quantity;
  1293. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1294. entity.Quantity = input.Quantity;
  1295. }
  1296. entity.TimeLastMod = Clock.Now;
  1297. entity.UserIDLastMod = AbpSession.UserName;
  1298. entity.Remark = input.Remark;
  1299. await SemiOutStoreRepository.UpdateAsync(entity);
  1300. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1301. $"修改半成品出库申请数量[{entity.Id}],[数量修改为{input.Quantity},冻结数量:{currentStore.FreezeQuantity},库存数量:{currentStore.ActualQuantity}]",
  1302. entity.ProductionOrderNo);
  1303. return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1304. }
  1305. /// <summary>
  1306. /// 确认出库数量(by yue.)
  1307. /// </summary>
  1308. /// <param name="input"></param>
  1309. /// <returns></returns>
  1310. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionEnterStoreApplyMgConfirm), AuditLog("确认出库申请")]
  1311. public async Task<SemiOutStoreDto> ConfirmSemiOutStoreQuantity(EntityDto<int> input)
  1312. {
  1313. var entity =await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1314. #region 检查是否可出入库
  1315. var isCanUpdate =
  1316. CommonAppService.CheckStoreRecordCanUpdate(entity.CurrentSemiStoreHouseNo, 2);
  1317. if (!isCanUpdate)
  1318. CheckErrors(IwbIdentityResult.Failed("该库存处于退货或者正在盘点状态,不可进行出入库更新!"));
  1319. #endregion
  1320. if (entity.ApplyStatus == OutStoreApplyStatusEnum.OutStored.ToInt() + "")
  1321. {
  1322. CheckErrors(IwbIdentityResult.Failed("已出库不能再操作!"));
  1323. }
  1324. entity.ApplyStatus = OutStoreApplyStatusEnum.OutStored.ToInt() + "";
  1325. entity.IsConfirm = true;
  1326. var date = Clock.Now;
  1327. entity.OutStoreDate = date;
  1328. entity.OutStoreUser = AbpSession.UserName;
  1329. await SemiOutStoreRepository.UpdateAsync(entity);
  1330. var currentStore = await
  1331. CurrentSemiStoreHouseRepository.FirstOrDefaultAsync(i =>
  1332. i.CurrentSemiStoreHouseNo == entity.CurrentSemiStoreHouseNo);
  1333. if (currentStore == null)
  1334. {
  1335. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1336. return null;
  1337. }
  1338. currentStore.FreezeQuantity -= entity.ActualQuantity;
  1339. currentStore.ActualQuantity -= entity.ActualQuantity;
  1340. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1341. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1342. $"确认半成品出库数量[{entity.Id}],[出库数量:{entity.ActualQuantity},冻结数量:{currentStore.FreezeQuantity},库存数量:{currentStore.ActualQuantity}]",
  1343. entity.ProductionOrderNo);
  1344. return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1345. }
  1346. /// <summary>
  1347. /// 取消出库申请(by yue.)
  1348. /// </summary>
  1349. /// <param name="input"></param>
  1350. /// <returns></returns>
  1351. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgCancel), AuditLog("取消出库申请")]
  1352. public async Task<SemiOutStoreDto> CancelSemiOutStoreApplyStatus(EntityDto<int> input)
  1353. {
  1354. var entity = await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1355. var currentStore =
  1356. CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  1357. i.CurrentSemiStoreHouseNo == entity.CurrentSemiStoreHouseNo);
  1358. if (currentStore == null)
  1359. {
  1360. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1361. return null;
  1362. }
  1363. currentStore.FreezeQuantity -= entity.Quantity;
  1364. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1365. entity.ApplyStatus = OutStoreApplyStatusEnum.Canceled.ToInt() + "";
  1366. await SemiOutStoreRepository.UpdateAsync(entity);
  1367. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1368. $"取消半成品出库申请[{entity.Id}]",
  1369. entity.ProductionOrderNo);
  1370. return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1371. }
  1372. /// <summary>
  1373. /// 关闭出库申请 (by yue.)
  1374. /// </summary>
  1375. /// <param name="input"></param>
  1376. /// <returns></returns>
  1377. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgClose), AuditLog("关闭出库申请")]
  1378. public async Task<SemiOutStoreDto> CloseOutStoreApply(EntityDto<int> input)
  1379. {
  1380. var entity = await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1381. entity.IsClose = true;
  1382. await SemiOutStoreRepository.UpdateAsync(entity);
  1383. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1384. $"关闭半成品出库申请[{entity.Id}]",
  1385. entity.ProductionOrderNo);
  1386. return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1387. }
  1388. /// <summary>
  1389. /// 恢复出库申请(by yue.)
  1390. /// </summary>
  1391. /// <param name="input"></param>
  1392. /// <returns></returns>
  1393. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOutStoreApplyMgRecovery),AuditLog("恢复出库申请")]
  1394. public async Task<SemiOutStoreDto> RecoverySemiOutStoreApplyStatus(EntityDto<int> input)
  1395. {
  1396. var entity = await SemiOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1397. var currentStore =
  1398. CurrentSemiStoreHouseRepository.FirstOrDefault(i =>
  1399. i.CurrentSemiStoreHouseNo == entity.CurrentSemiStoreHouseNo);
  1400. if (currentStore == null)
  1401. {
  1402. CheckErrors(IwbIdentityResult.Failed("未发现库存!"));
  1403. return null;
  1404. }
  1405. if (currentStore.ActualQuantity- currentStore.FreezeQuantity < entity.Quantity)
  1406. {
  1407. CheckErrors(IwbIdentityResult.Failed("可用库存量不够,请检查出库数量!"));
  1408. return null;
  1409. }
  1410. currentStore.FreezeQuantity += entity.Quantity;
  1411. await CurrentSemiStoreHouseRepository.UpdateAsync(currentStore);
  1412. entity.ApplyStatus = OutStoreApplyStatusEnum.Applying.ToInt() + "";
  1413. await SemiOutStoreRepository.UpdateAsync(entity);
  1414. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "半成品出库",
  1415. $"恢复半成品出库申请[{entity.Id}]",
  1416. entity.ProductionOrderNo);
  1417. return ObjectMapper.Map<SemiOutStoreDto>(entity);
  1418. }
  1419. #endregion
  1420. #region 成品改镀
  1421. [DisableAuditing, AbpAuthorize(PermissionNames.PagesProductionInfoRePlatingOutStoreApplyMg)]
  1422. public PagedResultDto<ViewProductOutStore> GetRePlatingOutStoreApply(PagedRequestDto input)
  1423. {
  1424. int type = OutStoreApplyTypeEnum.RePlating.ToInt();
  1425. var query = ViewProductOutStoreRepository.GetAll().Where(a => a.ApplyOutStoreSourceType == type);
  1426. if (input.SearchList != null && input.SearchList.Count > 0)
  1427. {
  1428. List<LambdaObject> objList = new List<LambdaObject>();
  1429. foreach (var o in input.SearchList)
  1430. {
  1431. if (o.KeyWords.IsNullOrEmpty())
  1432. continue;
  1433. object keyWords = o.KeyWords;
  1434. //检查查询条件中带有规格且多个分割条件的
  1435. ProductModelSearch.CheckModelGreaterOneFilter(o, ref keyWords);
  1436. objList.Add(new LambdaObject
  1437. {
  1438. FieldType = (LambdaFieldType)o.FieldType,
  1439. FieldName = o.KeyField,
  1440. FieldValue = keyWords,
  1441. ExpType = (LambdaExpType)o.ExpType
  1442. });
  1443. }
  1444. var exp = objList.GetExp<ViewProductOutStore>();
  1445. query = query.Where(exp);
  1446. }
  1447. var totalCount = query.Count();
  1448. query = query.OrderByDescending(i => i.TimeCreated);
  1449. string pattern = ProductModelSearch.GetModelGreaterOneReg(input.SearchList);
  1450. List<ViewProductOutStore> entities;
  1451. //检查查询条件中带有规格且多个分割条件的
  1452. if (!pattern.IsNullOrEmpty())
  1453. {
  1454. var es = query.ToList();
  1455. es = es.Where(f => f.Model != null && Regex.IsMatch(f.Model, pattern)).ToList();
  1456. totalCount = es.Count;
  1457. entities = es.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
  1458. }
  1459. else
  1460. {
  1461. query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  1462. entities = query.ToList();
  1463. }
  1464. //query = query.Skip(input.SkipCount).Take(input.MaxResultCount);
  1465. //var entities = query.ToList();
  1466. var dtos = new PagedResultDto<ViewProductOutStore>(
  1467. totalCount, entities
  1468. );
  1469. return dtos;
  1470. }
  1471. [AbpAuthorize(PermissionNames.PagesProductionInfoRePlatingOutStoreApplyMgCancel), AuditLog("拒绝成品改镀出库申请")]
  1472. public async Task<ProductOutStoreDto> CancelFinishOutStoreApply(EntityDto<int> input)
  1473. {
  1474. var entity = await ProductOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1475. entity.IsClose = true;
  1476. entity.ApplyStatus = OutStoreApplyStatusEnum.Refused.ToInt();
  1477. await ProductOutStoreRepository.UpdateAsync(entity);
  1478. var currentStore = await CurrentProductStoreHouseRepository.FirstOrDefaultAsync(a =>
  1479. a.CurrentProductStoreHouseNo == entity.CurrentProductStoreHouseNo);
  1480. currentStore.FreezeQuantity -= entity.Quantity;//释放冻结
  1481. await CurrentProductStoreHouseRepository.UpdateAsync(currentStore);
  1482. BusinessLogTypeEnum.SStore.WriteLog(LogRepository, "成品出库",
  1483. $"关闭成品出库申请[{entity.Id}]",
  1484. entity.ProductionOrderNo);
  1485. return ObjectMapper.Map<ProductOutStoreDto>(entity);
  1486. }
  1487. [AbpAuthorize(PermissionNames.PagesProductionInfoRePlatingOutStoreApplyMgExport), AuditLog("导出改镀出库申请")]
  1488. public async Task<string> RePlatingExportApply(EntityDto<int> input)
  1489. {
  1490. var entity = await ProductOutStoreRepository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1491. if (entity == null)
  1492. {
  1493. CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息。"));
  1494. return null;
  1495. }
  1496. var productEntity = ProductRepository.Get(entity.ProductNo);
  1497. string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/RePlatingBillTemplate.xls";
  1498. var work = ExcelHelper.CreateWorkBook03(path);
  1499. var sheet1 = work.GetSheet("Sheet1");
  1500. sheet1.GenerateCell(3, 5).SetCellValue(entity.ProductionOrderNo);
  1501. sheet1.GenerateCell(4, 2).SetCellValue($"{productEntity.PartNo}");
  1502. sheet1.GenerateCell(4, 5).SetCellValue(productEntity.ProductName);
  1503. sheet1.GenerateCell(5, 2).SetCellValue(productEntity.Material);
  1504. sheet1.GenerateCell(5, 4).SetCellValue(productEntity.Rigidity);
  1505. sheet1.GenerateCell(5, 6).SetCellValue(productEntity.Model);
  1506. sheet1.GenerateCell(6, 2).SetCellValue(productEntity.SurfaceColor + "");
  1507. sheet1.GenerateCell(9, 1).SetCellValue($"日期:{Clock.Now:yyyy-MM-dd}");
  1508. var savePath = "Download/Excel/ProductionOrder";
  1509. var fileName = $"改镀单[{entity.Id}]-{Clock.Now:yyyyMMddHHmmss}.xls";
  1510. var result = work.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  1511. if (!result.IsNullOrEmpty())
  1512. {
  1513. CheckErrors(IwbIdentityResult.Failed(result));
  1514. return null;
  1515. }
  1516. return $"{savePath}/{fileName}";
  1517. }
  1518. #endregion
  1519. #region 数据统计
  1520. /// <summary>
  1521. /// 统计排查单不合格入库
  1522. /// </summary>
  1523. /// <param name="productionOrderNo"></param>
  1524. /// <returns></returns>
  1525. public async Task<EnterFailureRateDto> QueryEnterFailureRate(string productionOrderNo)
  1526. {
  1527. EnterFailureRateDto result = new EnterFailureRateDto();
  1528. var es = await SemiEnterStoreRepository.GetAllListAsync(a => a.ProductionOrderNo == productionOrderNo);
  1529. if (es.Any())
  1530. {
  1531. decimal total = es.Sum(i => i.Quantity);
  1532. decimal unCheckedQuantity = es.Where(i=>i.ApplyStatus == EnterStoreApplyStatusEnum.UnChecked.ToInt() + "").Sum(i => i.Quantity);
  1533. result.ApplyTotalEnterQuantity = total;
  1534. result.FailureQuantity = unCheckedQuantity;
  1535. }
  1536. return result;
  1537. }
  1538. /// <summary>
  1539. /// 生产统计
  1540. /// </summary>
  1541. /// <param name="input"></param>
  1542. /// <returns></returns>
  1543. public async Task<ProductionReportDto> QueryProductionReport(QueryProductionReportDto input)
  1544. {
  1545. var startDate = input.Year.GetDateByType(input.Month,out var endDate ,out var dateStr);
  1546. //查询指定周期员工生产日志
  1547. var query = ProductLogRepository.GetAllIncluding(a => a.EmployeeInfo)
  1548. .Where(a => a.CreationTime >= startDate && a.CreationTime < endDate).OrderBy(a=>a.CreationTime);
  1549. IQueryable<ProductionReportItem> itemQuery = input.EmployeeId != null
  1550. ?
  1551. //查询指定员工的统计(关联半成品入库视图获取半成品信息)
  1552. query.Where(a => a.EmployeeId == input.EmployeeId)
  1553. .Join(ViewSemiEnterStoreRepository.GetAll(),
  1554. a => a.ProductOrderNo, s => s.ProductionOrderNo, (a, s) => new ProductionReportItem()
  1555. {
  1556. ProductDate = a.CreationTime,
  1557. ProductionOrderNo = a.ProductOrderNo,
  1558. ProductNo = s.SemiProductNo,
  1559. ProductName = s.SemiProductName,
  1560. CarNo = a.CarNo,
  1561. PartNo = s.PartNo,
  1562. Model = s.Model,
  1563. Material = s.Material,
  1564. SurfaceColor = s.SurfaceColor,
  1565. Rigidity = s.Rigidity,
  1566. KgQuantity = a.QuantityWeight,
  1567. PcsQuantity = a.QuantityPcs,
  1568. KgWeight = a.KgWeight,
  1569. EmployeeId = a.EmployeeId,
  1570. EmployeeNo = a.EmployeeInfo.No,
  1571. EmployeeName = a.EmployeeInfo.Name
  1572. }).Distinct()
  1573. :
  1574. // 查询所有员工的统计
  1575. query.Select(a => new ProductionReportItem()
  1576. {
  1577. ProductDate= a.CreationTime,
  1578. ProductionOrderNo = a.ProductOrderNo,
  1579. ProductNo = a.ProductionNo,
  1580. KgQuantity = a.QuantityWeight,
  1581. PcsQuantity = a.QuantityPcs,
  1582. KgWeight = a.KgWeight,
  1583. EmployeeId = a.EmployeeId,
  1584. EmployeeNo = a.EmployeeInfo.No,
  1585. EmployeeName = a.EmployeeInfo.Name
  1586. });
  1587. var items = await itemQuery.ToListAsync();
  1588. var dto = new ProductionReportDto(dateStr, items,input.EmployeeId);
  1589. return dto;
  1590. }
  1591. /// <summary>
  1592. /// 外购统计
  1593. /// </summary>
  1594. /// <param name="input"></param>
  1595. /// <returns></returns>
  1596. public async Task<ProductionReportDto> QueryOutsourcingReport(QueryProductionReportDto input)
  1597. {
  1598. var startDate = input.Year.GetDateByType(input.Month,out var endDate ,out var dateStr);
  1599. //查询外购的排产单进行统计(不是新建状态的)
  1600. var query = Repository.GetAll().Where(a => a.TimeCreated >= startDate && a.TimeCreated < endDate && a.ProductionType=="1" && a.ProductionOrderStatus!=1).OrderBy(a=>a.TimeCreated);
  1601. //联合查询半成品信息
  1602. IQueryable<ProductionReportItem> itemQuery = from a in query
  1603. join sp in SemiProductRepository.GetAll() on a.SemiProductNo equals sp.Id into l
  1604. from s in l.DefaultIfEmpty()
  1605. select new ProductionReportItem()
  1606. {
  1607. ProductDate = a.TimeCreated,
  1608. ProductionOrderNo = a.ProductionOrderNo,
  1609. ProductNo = s.Id,
  1610. ProductName = s.SemiProductName,
  1611. PartNo = s.PartNo,
  1612. Model = s.Model,
  1613. Material = s.Material,
  1614. SurfaceColor = s.SurfaceColor,
  1615. Rigidity = s.Rigidity,
  1616. KgQuantity = a.Quantity * a.KgWeight,
  1617. PcsQuantity = a.Quantity,
  1618. KgWeight = a.KgWeight,
  1619. };
  1620. var items = await itemQuery.ToListAsync();
  1621. var dto = new ProductionReportDto(dateStr, items,0);
  1622. return dto;
  1623. }
  1624. /// <summary>
  1625. /// 导出外购报表
  1626. /// </summary>
  1627. /// <param name="input"></param>
  1628. /// <returns></returns>
  1629. public async Task<string> ExportOutsourcingReport(QueryProductionReportDto input)
  1630. {
  1631. var startDate = input.Year.GetDateByType(input.Month,out var endDate ,out var dateStr);
  1632. var dto = await QueryOutsourcingReport(input);
  1633. if (dto.Items == null || !dto.Items.Any())
  1634. {
  1635. CheckErrors(IwbIdentityResult.Failed("未查询采购信息。"));
  1636. return null;
  1637. }
  1638. string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/OutsourcingReport.xls";
  1639. var work = ExcelHelper.CreateWorkBook03(path);
  1640. var sheet1 = work.GetSheet("Sheet1");
  1641. sheet1.GenerateCell(2, 10).SetCellValue(dateStr);
  1642. int index = 4, count = dto.Items.Count;
  1643. sheet1.InsertRows(index, count-1);
  1644. foreach (var item in dto.Items)
  1645. {
  1646. sheet1.GenerateCell(index, 1).SetValue<int>(index - 3);
  1647. sheet1.GenerateCell(index, 2).SetValue(item.ProductionOrderNo);
  1648. sheet1.GenerateCell(index, 3).SetValue(item.ProductName);
  1649. sheet1.GenerateCell(index, 4).SetValue(item.PartNo);
  1650. sheet1.GenerateCell(index, 5).SetValue(item.Model);
  1651. sheet1.GenerateCell(index, 6).SetValue<decimal>(item.PcsQuantity);
  1652. sheet1.GenerateCell(index, 7).SetValue<decimal>(item.KgWeight);
  1653. sheet1.GenerateCell(index, 8).SetValue<decimal>(item.KgQuantity);
  1654. sheet1.GenerateCell(index, 9).SetValue<DateTime>(item.ProductDate);
  1655. sheet1.GenerateCell(index, 10).SetValue(item.Material);
  1656. sheet1.GenerateCell(index, 11).SetValue(item.SurfaceColor);
  1657. index++;
  1658. }
  1659. sheet1.GenerateCell(index, 2).SetValue($"总重量:{dto.KgTotal} kg");
  1660. sheet1.GenerateCell(index, 4).SetValue($"总件数:{dto.PcsTotal} 千件");
  1661. var savePath = "Download/Excel/ProductionOrder/OutsourcingReport";
  1662. var fileName = $"采购统计-{dateStr}-{Clock.Now:yyMMddHHmmss}.xls";
  1663. var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  1664. if (!result.IsNullOrEmpty())
  1665. {
  1666. //CheckErrors(IwbIdentityResult.Failed(result));
  1667. return null;
  1668. }
  1669. return $"/{savePath}/{fileName}";
  1670. }
  1671. #endregion
  1672. #region ExcelExport
  1673. [AbpAuthorize(PermissionNames.PagesProductionInfoProductionOrderMgExport), AuditLog("导出排产单Excel")]
  1674. public async Task<string> ExcelExport(ExportDto input)
  1675. {
  1676. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == input.Id);
  1677. if (entity == null)
  1678. {
  1679. CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息。"));
  1680. return null;
  1681. }
  1682. var semi = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == entity.SemiProductNo);
  1683. if (semi == null)
  1684. {
  1685. CheckErrors(IwbIdentityResult.Failed("未查询到排产单中半成品信息。"));
  1686. return null;
  1687. }
  1688. string path = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/ProductionOrderTemplate.xls";
  1689. var work = ExcelHelper.CreateWorkBook03(path);
  1690. var sheet1 = work.GetSheet("Template1");
  1691. sheet1.GenerateCell(2, 10).SetCellValue(entity.ProductionOrderNo);
  1692. sheet1.GenerateCell(4, 11).SetCellValue($"{entity.ProductionOrderNo}{Clock.Now:MMdd}");
  1693. sheet1.GenerateCell(5, 4).SetCellValue(semi.PartNo);
  1694. sheet1.GenerateCell(5, 7).SetCellValue(semi.SemiProductName);
  1695. sheet1.GenerateCell(5, 11).SetCellValue(semi.Model);
  1696. sheet1.GenerateCell(6, 4).SetCellValue(semi.Material);
  1697. sheet1.GenerateCell(6, 11).SetCellValue(entity.Quantity + "");
  1698. sheet1.GenerateCell(8, 4).SetCellValue(semi.ProductDesc);
  1699. sheet1.GenerateCell(8, 11).SetCellValue(semi.Rigidity);
  1700. sheet1.GenerateCell(21, 7).SetCellValue(semi.SurfaceColor);
  1701. var sheet2 = work.GetSheet("Template2");
  1702. sheet2.GenerateCell(1, 17).SetCellValue(entity.ProductionOrderNo);
  1703. sheet2.GenerateCell(3, 16).SetCellValue($"{entity.ProductionOrderNo}{Clock.Now:MMdd}");
  1704. sheet2.GenerateCell(4, 3).SetCellValue(semi.PartNo);
  1705. sheet2.GenerateCell(4, 9).SetCellValue(semi.SemiProductName);
  1706. sheet2.GenerateCell(4, 16).SetCellValue(semi.Model);
  1707. sheet2.GenerateCell(5, 3).SetCellValue(semi.Material);
  1708. sheet2.GenerateCell(7, 3).SetCellValue(semi.ProductDesc);
  1709. var sheet3 = work.GetSheet("Template3");
  1710. sheet3.GenerateCell(2, 10).SetCellValue(entity.ProductionOrderNo);
  1711. sheet3.GenerateCell(4, 4).SetCellValue(semi.PartNo);
  1712. sheet3.GenerateCell(4, 11).SetCellValue($"{entity.ProductionOrderNo}{Clock.Now:MMdd}");
  1713. //sheet3.GenerateCell(5, 4).SetCellValue(semi.PartNo);
  1714. sheet3.GenerateCell(5, 7).SetCellValue(semi.SemiProductName);
  1715. sheet3.GenerateCell(5, 11).SetCellValue(semi.Model);
  1716. sheet3.GenerateCell(6, 4).SetCellValue(semi.Material);
  1717. sheet3.GenerateCell(6, 11).SetCellValue(entity.Quantity + "");
  1718. sheet3.GenerateCell(8, 4).SetCellValue(semi.ProductDesc);
  1719. sheet3.GenerateCell(8, 11).SetCellValue(semi.Rigidity);
  1720. var savePath= "Download/Excel/ProductionOrder";
  1721. var fileName = $"排产单[{entity.ProductionOrderNo}]-{Clock.Now:yyyyMMddHHmmss}.xls";
  1722. var result= work.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  1723. if (!result.IsNullOrEmpty())
  1724. {
  1725. CheckErrors(IwbIdentityResult.Failed(result));
  1726. return null;
  1727. }
  1728. entity.HasExported = true;
  1729. await Repository.UpdateAsync(entity);
  1730. return $"/{savePath}/{fileName}";
  1731. }
  1732. //[AbpAuthorize(PermissionNames.PagesProductionInfoOutProductionOrderMgExportOut), AuditLog("导出外协排产单Excel")]
  1733. //public async Task<string> ExcelExportOut(EntityDto<string> input)
  1734. //{
  1735. // string selectIds = input.Id;
  1736. // var ids = selectIds.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
  1737. // if (!ids.Any())
  1738. // {
  1739. // CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息."));
  1740. // return null;
  1741. // }
  1742. // // List<ProductionOrder> sheetProductionOrders = new List<ProductionOrder>();
  1743. // Dictionary<string, List<ProductionOrder>> dicSheet = new Dictionary<string, List<ProductionOrder>>();
  1744. // foreach (var id in ids)
  1745. // {
  1746. // int.TryParse(id, out int enId);
  1747. // var entity = await Repository.FirstOrDefaultAsync(a => a.Id == enId);
  1748. // if (entity == null)
  1749. // {
  1750. // CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息。"));
  1751. // return null;
  1752. // }
  1753. // if (entity.ProcessingLevel == "1" && entity.ProductionOrderStatus == ProductionOrderStatusEnum.Start.ToInt())
  1754. // {
  1755. // CheckErrors(IwbIdentityResult.Failed("存在排产单未确认审核,不可导出!"));
  1756. // return null;
  1757. // }
  1758. // string enKey = entity.OutsourcingFactory + "@@" + entity.ProcessingType;
  1759. // if (dicSheet.ContainsKey(enKey))
  1760. // {
  1761. // dicSheet[enKey].Add(entity);
  1762. // }
  1763. // else
  1764. // {
  1765. // List<ProductionOrder> productionOrders = new List<ProductionOrder>();
  1766. // productionOrders.Add(entity);
  1767. // dicSheet.Add(enKey, productionOrders);
  1768. // }
  1769. // entity.HasExported = true;
  1770. // await Repository.UpdateAsync(entity);
  1771. // }
  1772. // string path3 = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/HotProcess.xls";
  1773. // string path2 = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/SurfaceColorProcess.xls";
  1774. // //List<string> savePathList = new List<string>();
  1775. // string cSavePath = "Download/Excel/ProductionOrder";
  1776. // string fileDir= "Out" + DateTime.Now.ToString("yyMMddHHmmss") + "-" + new Random().Next(1000);
  1777. // var savePath = "Download/Excel/ProductionOrder/"+ fileDir;
  1778. // foreach (var ds in dicSheet)
  1779. // {
  1780. // string[] ot = ds.Key.Split("@@");
  1781. // string type = ot[1];
  1782. // string outFactoryId = ds.Value[0].OutsourcingFactory;
  1783. // var outFactory = await OutFactoryRepository.FirstOrDefaultAsync(a => a.Id == outFactoryId);
  1784. // HSSFWorkbook work = null;
  1785. // if (type == "2")
  1786. // {
  1787. // work = ExcelHelper.CreateWorkBook03(path2);
  1788. // var sheet1 = work.GetSheet("Sheet1");
  1789. // sheet1.GenerateCell(4, 8).SetCellValue("单号:"+DateTime.Now.ToString("yyMMddHHmmss")+new Random().Next(1000));
  1790. // sheet1.GenerateCell(7, 2).SetCellValue(outFactory?.OutFactoryName);
  1791. // sheet1.GenerateCell(7, 9).SetCellValue(outFactory?.Address);
  1792. // sheet1.GenerateCell(8, 2).SetCellValue(outFactory?.Telephone);
  1793. // sheet1.GenerateCell(8, 9).SetCellValue(outFactory?.LinkMan);
  1794. // int index = 1;
  1795. // foreach (var e in ds.Value)
  1796. // {
  1797. // var semi = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == e.SemiProductNo);
  1798. // sheet1.GenerateCell(10+index, 1).SetCellValue(index);
  1799. // sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.PartNo);
  1800. // sheet1.GenerateCell(10 + index, 3).SetCellValue(semi?.SemiProductName);
  1801. // sheet1.GenerateCell(10 + index, 4).SetCellValue(semi?.Model);
  1802. // sheet1.GenerateCell(10 + index, 7).SetCellValue(semi?.SurfaceColor);
  1803. // sheet1.GenerateCell(10 + index, 11).SetCellValue(e?.ProductionOrderNo);
  1804. // index++;
  1805. // }
  1806. // }
  1807. // else if (type == "3")
  1808. // {
  1809. // work = ExcelHelper.CreateWorkBook03(path3);
  1810. // var sheet1 = work.GetSheet("Sheet1");
  1811. // sheet1.GenerateCell(4, 8).SetCellValue("单号:" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(1000));
  1812. // sheet1.GenerateCell(7, 2).SetCellValue(outFactory?.OutFactoryName);
  1813. // sheet1.GenerateCell(7, 9).SetCellValue(outFactory?.Address);
  1814. // sheet1.GenerateCell(8, 2).SetCellValue(outFactory?.Telephone);
  1815. // sheet1.GenerateCell(8, 9).SetCellValue(outFactory?.LinkMan);
  1816. // int index = 1;
  1817. // foreach (var e in ds.Value)
  1818. // {
  1819. // var semi = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == e.SemiProductNo);
  1820. // sheet1.GenerateCell(10 + index, 1).SetCellValue(index);
  1821. // sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.PartNo);
  1822. // sheet1.GenerateCell(10 + index, 3).SetCellValue(semi?.SemiProductName);
  1823. // sheet1.GenerateCell(10 + index, 4).SetCellValue(semi?.Model);
  1824. // sheet1.GenerateCell(10 + index, 6).SetCellValue(semi?.Material);
  1825. // sheet1.GenerateCell(10 + index, 8).SetCellValue(semi?.SurfaceColor);
  1826. // sheet1.GenerateCell(10 + index, 10).SetCellValue(semi?.Rigidity);
  1827. // sheet1.GenerateCell(10 + index, 11).SetCellValue(e?.ProductionOrderNo);
  1828. // index++;
  1829. // }
  1830. // }
  1831. // var fileName = $"外协排产单[{ ds.Value[0].ProductionOrderNo}]-{Clock.Now:HHmmss}.xls";
  1832. // //string lcPath = $"{AppDomain.CurrentDomain.BaseDirectory}{savePath}" + "\\" + fileName;
  1833. // var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  1834. // if (!result.IsNullOrEmpty())
  1835. // {
  1836. // CheckErrors(IwbIdentityResult.Failed(result));
  1837. // return null;
  1838. // }
  1839. // //savePathList.Add(lcPath);
  1840. // }
  1841. // ZipHelper.ZipDirectory($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", $"{AppDomain.CurrentDomain.BaseDirectory}{cSavePath}/{fileDir}.zip" );
  1842. // return $"/{cSavePath}/{fileDir}.zip";
  1843. //}
  1844. [AbpAuthorize(PermissionNames.PagesProductionInfoOutProductionOrderMgExportOut), AuditLog("导出外协排产单Excel")]
  1845. public async Task<string> ExcelExportOut(EntityDto<string> input)
  1846. {
  1847. string selectIds = input.Id;
  1848. var ids = selectIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  1849. if (!ids.Any())
  1850. {
  1851. CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息."));
  1852. return null;
  1853. }
  1854. // List<ProductionOrder> sheetProductionOrders = new List<ProductionOrder>();
  1855. Dictionary<string, List<ProductionOrder>> dicSheet = new Dictionary<string, List<ProductionOrder>>();
  1856. foreach (var id in ids)
  1857. {
  1858. int.TryParse(id, out int enId);
  1859. var entity = await Repository.FirstOrDefaultAsync(a => a.Id == enId);
  1860. if (entity == null)
  1861. {
  1862. CheckErrors(IwbIdentityResult.Failed("未查询到排产单信息。"));
  1863. return null;
  1864. }
  1865. if (entity.ProcessingLevel == "1" && entity.ProductionOrderStatus == ProductionOrderStatusEnum.Start.ToInt())
  1866. {
  1867. CheckErrors(IwbIdentityResult.Failed("存在排产单未确认审核,不可导出!"));
  1868. return null;
  1869. }
  1870. string enKey = entity.OutsourcingFactory + "@@" + entity.ProcessingType;
  1871. if (dicSheet.ContainsKey(enKey))
  1872. {
  1873. dicSheet[enKey].Add(entity);
  1874. }
  1875. else
  1876. {
  1877. List<ProductionOrder> productionOrders = new List<ProductionOrder>();
  1878. productionOrders.Add(entity);
  1879. dicSheet.Add(enKey, productionOrders);
  1880. }
  1881. entity.HasExported = true;
  1882. await Repository.UpdateAsync(entity);
  1883. }
  1884. string path3 = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/HotProcess_v2.xls";
  1885. string path2 = AppDomain.CurrentDomain.BaseDirectory + "Resources/ProductionOrderTemplate/SurfaceColorProcess_v2.xls";
  1886. //List<string> savePathList = new List<string>();
  1887. string cSavePath = "Download/Excel/ProductionOrder";
  1888. string fileDir = "Out" + DateTime.Now.ToString("yyMMddHHmmss") + "-" + new Random().Next(1000);
  1889. var savePath = "Download/Excel/ProductionOrder/" + fileDir;
  1890. foreach (var ds in dicSheet)
  1891. {
  1892. string[] ot = ds.Key.Split("@@");
  1893. string type = ot[1];
  1894. string outFactoryId = ds.Value[0].OutsourcingFactory;
  1895. var outFactory = await OutFactoryRepository.FirstOrDefaultAsync(a => a.Id == outFactoryId);
  1896. HSSFWorkbook work = null;
  1897. if (type == "2")
  1898. {
  1899. work = ExcelHelper.CreateWorkBook03(path2);
  1900. var sheet1 = work.GetSheet("Sheet1");
  1901. sheet1.GenerateCell(2, 8).SetCellValue("单号:" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(1000));
  1902. sheet1.GenerateCell(5, 2).SetCellValue(outFactory?.OutFactoryName);
  1903. sheet1.GenerateCell(5, 8).SetCellValue(outFactory?.Address);
  1904. sheet1.GenerateCell(6, 2).SetCellValue(outFactory?.Telephone);
  1905. sheet1.GenerateCell(6, 8).SetCellValue(outFactory?.LinkMan);
  1906. sheet1.GenerateCell(7, 1).SetCellValue("开单日期:" + DateTime.Now.ToString("yyyy-MM-dd"));
  1907. int index = 0;
  1908. sheet1.InsertRows(10, ds.Value.Count>1 ? ds.Value.Count-1:0);
  1909. foreach (var e in ds.Value)
  1910. {
  1911. var semi = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == e.SemiProductNo);
  1912. sheet1.GenerateCell(10 + index, 1).SetCellValue(index+1);
  1913. //sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.PartNo);
  1914. sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.SemiProductName);
  1915. sheet1.GenerateCell(10 + index, 3).SetCellValue(semi?.Model);
  1916. sheet1.GenerateCell(10 + index, 4).SetCellValue(semi?.Rigidity);
  1917. sheet1.GenerateCell(10 + index, 5).SetCellValue("人工填写");
  1918. sheet1.MergedRegion(10 + index, 10 + index, 7, 9);
  1919. sheet1.GenerateCell(10 + index, 7).SetCellValue(semi?.SurfaceColor);
  1920. sheet1.GenerateCell(10 + index, 10).SetCellValue("人工填写");
  1921. sheet1.GenerateCell(10 + index, 11).SetCellValue(e?.SemiProductNo);
  1922. sheet1.GenerateCell(10 + index, 12).SetCellValue(e?.ProductionOrderNo);
  1923. index++;
  1924. }
  1925. sheet1.GenerateCell(10 + index, 10).SetCellValue("发货日期:" + DateTime.Now.ToString("yyyy-MM-dd"));
  1926. }
  1927. else if (type == "3")
  1928. {
  1929. work = ExcelHelper.CreateWorkBook03(path3);
  1930. var sheet1 = work.GetSheet("Sheet1");
  1931. sheet1.GenerateCell(2, 5).SetCellValue("单号:" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(1000));
  1932. sheet1.GenerateCell(5, 2).SetCellValue(outFactory?.OutFactoryName);
  1933. sheet1.GenerateCell(5, 6).SetCellValue(outFactory?.Address);
  1934. sheet1.GenerateCell(6, 2).SetCellValue(outFactory?.Telephone);
  1935. sheet1.GenerateCell(6, 6).SetCellValue(outFactory?.LinkMan);
  1936. sheet1.GenerateCell(7, 1).SetCellValue("开单日期/热处理批次号:"+ DateTime.Now.ToString("yyyyMMdd"));
  1937. int index = 0;
  1938. sheet1.InsertRows(10, ds.Value.Count > 1 ? ds.Value.Count - 1 : 0);
  1939. foreach (var e in ds.Value)
  1940. {
  1941. var semi = await SemiProductRepository.FirstOrDefaultAsync(a => a.Id == e.SemiProductNo);
  1942. sheet1.GenerateCell(10 + index, 1).SetCellValue(index+1);
  1943. //sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.PartNo);
  1944. sheet1.GenerateCell(10 + index, 2).SetCellValue(semi?.SemiProductName);
  1945. sheet1.GenerateCell(10 + index, 3).SetCellValue(semi?.Model);
  1946. sheet1.GenerateCell(10 + index, 5).SetCellValue(semi?.Material);
  1947. sheet1.GenerateCell(10 + index, 7).SetCellValue(semi?.Rigidity);
  1948. sheet1.GenerateCell(10 + index, 8).SetCellValue("芯部要达到");
  1949. sheet1.GenerateCell(10 + index, 9).SetCellValue(e?.ProductionOrderNo);
  1950. index++;
  1951. }
  1952. sheet1.GenerateCell(10 + index, 8).SetCellValue("发货日期:" + DateTime.Now.ToString("yyyy-MM-dd"));
  1953. }
  1954. var fileName = $"外协排产单[{ ds.Value[0].ProductionOrderNo}]-{Clock.Now:HHmmss}.xls";
  1955. //string lcPath = $"{AppDomain.CurrentDomain.BaseDirectory}{savePath}" + "\\" + fileName;
  1956. var result = work?.SaveWorkBook($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", fileName);
  1957. if (!result.IsNullOrEmpty())
  1958. {
  1959. CheckErrors(IwbIdentityResult.Failed(result));
  1960. return null;
  1961. }
  1962. //savePathList.Add(lcPath);
  1963. }
  1964. ZipHelper.ZipDirectory($"{AppDomain.CurrentDomain.BaseDirectory}{savePath}", $"{AppDomain.CurrentDomain.BaseDirectory}{cSavePath}/{fileDir}.zip");
  1965. return $"/{cSavePath}/{fileDir}.zip";
  1966. }
  1967. #endregion
  1968. }
  1969. }