ProductionOrdersApplicationService.cs 117 KB

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