ProductionOrdersApplicationService.cs 114 KB

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