ProductionOrdersApplicationService.cs 126 KB

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