GoodsRepository.cs 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117
  1. using Aspose.Cells;
  2. using AutoMapper;
  3. using EyeSoft.Collections.Generic;
  4. using EyeSoft.Runtime.InteropServices;
  5. using Newtonsoft.Json;
  6. using Npgsql.Replication.PgOutput.Messages;
  7. using OASystem.Domain;
  8. using OASystem.Domain.Dtos.PersonnelModule;
  9. using OASystem.Domain.Dtos.System;
  10. using OASystem.Domain.Entities.Groups;
  11. using OASystem.Domain.Entities.PersonnelModule;
  12. using OASystem.Domain.ViewModels.PersonnelModule;
  13. using OASystem.Infrastructure.Repositories.System;
  14. using OASystem.Infrastructure.Tools;
  15. using System.Linq;
  16. using System.Text.RegularExpressions;
  17. namespace OASystem.Infrastructure.Repositories.PersonnelModule
  18. {
  19. /// <summary>
  20. /// 物品进销存
  21. /// 仓储
  22. /// </summary>
  23. public class GoodsRepository : BaseRepository<Pm_GoodsInfo, GoodsInfoView>
  24. {
  25. private readonly IMapper _mapper;
  26. private JsonView _jv;
  27. private string _url;
  28. private string _excelPath;
  29. private List<int> _goodsTypeIds; //多部门审核物品类型Id
  30. private readonly ApprovalProcessRepository _approvalProcessRep;
  31. public GoodsRepository(SqlSugarClient sqlSugar, IMapper mapper, ApprovalProcessRepository approvalProcessRep) : base(sqlSugar)
  32. {
  33. _mapper = mapper;
  34. _jv = new JsonView() { Code = StatusCodes.Status400BadRequest, Msg = "操作失败!" };
  35. _url = AppSettingsHelper.Get("ExcelBaseUrl");
  36. _excelPath = $"{AppSettingsHelper.Get("ExcelBasePath")}";
  37. if (!Directory.Exists(_excelPath))
  38. {
  39. Directory.CreateDirectory(_excelPath);
  40. }
  41. _goodsTypeIds = new List<int>() {
  42. 1423, //1423 贵重物品
  43. };
  44. _approvalProcessRep = approvalProcessRep;
  45. }
  46. /// <summary>
  47. /// 基础数据
  48. /// </summary>
  49. /// <returns></returns>
  50. public async Task<JsonView> InitDataSource()
  51. {
  52. var typeData = await _sqlSugar.Queryable<GoodsTypeView>()
  53. .Includes(x => x.SubTypeItems.Where(z => z.IsDel == 0)
  54. //.Select(z => new {
  55. // z.Id,
  56. // z.STid,
  57. // z.Name
  58. //})
  59. .ToList())
  60. .Where(x => x.IsDel == 0 &&
  61. x.Remark.Equals("GoodsType"))
  62. //.Select(x => new {
  63. // x.Id,
  64. // x.Name,
  65. // x.SubTypeItems
  66. //})
  67. .ToListAsync();
  68. var groupData = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  69. .Where(x => x.IsDel == 0)
  70. .Select(x => new
  71. {
  72. id = x.Id,
  73. groupName = x.TeamName
  74. })
  75. .OrderByDescending(x => x.id)
  76. .ToListAsync();
  77. groupData.Insert(0, new { id = 0, groupName = "其他物资(公司内部物资)" });
  78. groupData.Insert(0, new { id = -1, groupName = "拜访客户所使用的物资" });
  79. groupData.Insert(0, new { id = -2, groupName = "库存调整" });
  80. groupData.Insert(0, new { id = -3, groupName = "全部团组" });
  81. var userData = await _sqlSugar.Queryable<Sys_Users>()
  82. .Where(x => x.IsDel == 0)
  83. .Select(x => new
  84. {
  85. x.Id,
  86. UserName = x.CnName,
  87. })
  88. .ToListAsync();
  89. //库存状态
  90. var stockStatus = new List<dynamic>() {
  91. new { Value = -1, Text = "全部" },
  92. new { Value = 0, Text = "待确认" },
  93. new { Value = 1, Text = "部分确认" },
  94. new { Value = 2, Text = "已确认" },
  95. new { Value = 3, Text = "已拒绝" },
  96. };
  97. //领用出库状态
  98. var receiveStatus = new List<dynamic>() {
  99. new { Value = -1, Text = "全部" },
  100. new { Value = GoodsAuditEnum.Pending, Text = GoodsAuditEnum.Pending.GetEnumDescription() },
  101. //new { Value = GoodsAuditEnum.Approved, Text = GoodsAuditEnum.Approved.GetEnumDescription() },
  102. //new { Value = GoodsAuditEnum.UnApproved, Text = GoodsAuditEnum.UnApproved.GetEnumDescription() },
  103. //new { Value = GoodsAuditEnum.OutPending, Text = GoodsAuditEnum.OutPending.GetEnumDescription() },
  104. new { Value = GoodsAuditEnum.OutConfirming, Text = GoodsAuditEnum.OutConfirming.GetEnumDescription() },
  105. new { Value = GoodsAuditEnum.OutConfirmed, Text = GoodsAuditEnum.OutConfirmed.GetEnumDescription() },
  106. new { Value = GoodsAuditEnum.OutRejected, Text = GoodsAuditEnum.OutRejected.GetEnumDescription() },
  107. };
  108. _jv.Code = StatusCodes.Status200OK;
  109. _jv.Data = new { goodsTypeData = typeData, stockStatus = stockStatus, receiveStatus = receiveStatus, groupNameData = groupData, userNameData = userData };
  110. _jv.Msg = $"操作成功";
  111. return _jv;
  112. }
  113. /// <summary>
  114. /// 物品列表
  115. /// </summary>
  116. /// <param name="dto"></param>
  117. /// <returns></returns>
  118. public async Task<JsonView> GoodsList(GoodsListDto dto)
  119. {
  120. var ids = new List<int>();
  121. if (!string.IsNullOrEmpty(dto.TypeIds))
  122. {
  123. var strArray = dto.TypeIds.Split(',');
  124. foreach (var str in strArray)
  125. {
  126. if (int.TryParse(str, out int id))
  127. {
  128. ids.Add(id);
  129. }
  130. }
  131. }
  132. var auditEnums = new List<GoodsAuditEnum>() {
  133. GoodsAuditEnum.Pending,
  134. GoodsAuditEnum.OutPending,
  135. GoodsAuditEnum.OutConfirming
  136. };
  137. RefAsync<int> total = 0;
  138. var data = await _sqlSugar.Queryable<GoodsListView>()
  139. //.Includes(glv => glv.Receives.Where(z1 => z1.IsDel == 0 && z1.AuditStatus == GoodsAuditEnum.Pending).ToList())
  140. .Includes(glv => glv.Receives.Where(z1 => z1.IsDel == 0 && auditEnums.Contains(z1.AuditStatus)).ToList())
  141. .Includes(glv => glv.TypeData)
  142. .Includes(glv => glv.UserData)
  143. .LeftJoin<Sys_SetData>((glv, sd) => glv.Type == sd.Id)
  144. .LeftJoin<Sys_Users>((glv, sd, u) => glv.LastUpdateUserId == u.Id)
  145. .Where(glv => glv.IsDel == 0)
  146. .WhereIF(ids.Count > 0, glv => ids.Contains(glv.Type))
  147. .WhereIF(!string.IsNullOrEmpty(dto.GoodsName), glv => glv.Name.Contains(dto.GoodsName))
  148. .OrderByDescending(glv => glv.LastUpdateTime)
  149. .ToPageListAsync(dto.PageIndex, dto.PageSize, total);
  150. var view = data.Select(x => new
  151. {
  152. x.Id,
  153. x.Name,
  154. x.Type,
  155. TypeName = x.TypeData?.Name ?? string.Empty,
  156. LastUpdateUserName = x.UserData?.CnName ?? string.Empty,
  157. x.LastUpdateTime,
  158. StockQuantity = x.StockQuantity - x.WaitAuditQuantity,
  159. x.Unit,
  160. x.StockQuantityLabel,
  161. x.Remark
  162. }).ToList();
  163. _jv.Code = StatusCodes.Status200OK;
  164. _jv.Data = view;
  165. _jv.Count = total;
  166. _jv.Msg = $"操作成功";
  167. return _jv;
  168. }
  169. /// <summary>
  170. /// 物品Info
  171. /// </summary>
  172. /// <param name="portType"></param>
  173. /// <param name="id"></param>
  174. /// <returns></returns>
  175. public async Task<JsonView> GoodsInfo(int portType, int id)
  176. {
  177. var data = await _sqlSugar.Queryable<Pm_GoodsInfo>()
  178. .LeftJoin<Sys_SetData>((gi, sd) => gi.Type == sd.Id)
  179. .LeftJoin<Sys_Users>((gi, sd, u1) => gi.LastUpdateUserId == u1.Id)
  180. .LeftJoin<Sys_Users>((gi, sd, u1, u2) => gi.CreateUserId == u2.Id)
  181. .Where((gi, sd, u1, u2) => gi.IsDel == 0 && gi.Id == id)
  182. .Select((gi, sd, u1, u2) => new
  183. {
  184. gi.Id,
  185. gi.Name,
  186. ParentType = sd.STid,
  187. gi.Type,
  188. TypeName = sd.Name,
  189. gi.SQ_Total,
  190. gi.OQ_Total,
  191. gi.PriceTotal,
  192. gi.StockQuantity,
  193. gi.Unit,
  194. gi.Remark,
  195. LastUpdateUserName = u1.CnName,
  196. gi.LastUpdateTime,
  197. CreateUserName = u2.CnName,
  198. gi.CreateTime,
  199. })
  200. .FirstAsync();
  201. _jv.Code = StatusCodes.Status200OK;
  202. _jv.Data = data;
  203. _jv.Msg = $"操作成功";
  204. return _jv;
  205. }
  206. /// <summary>
  207. /// 物品 OP(Create Or Edit)
  208. /// </summary>
  209. /// <param name="dto"></param>
  210. /// <param name="currUserId"></param>
  211. /// <returns></returns>
  212. public async Task<JsonView> GoodsOp(GoodsOpDto dto, int currUserId)
  213. {
  214. var info = new Pm_GoodsInfo()
  215. {
  216. Id = dto.Id,
  217. Name = dto.Name,
  218. Type = dto.Type,
  219. SQ_Total = 0,
  220. OQ_Total = 0,
  221. PriceTotal = 0,
  222. StockQuantity = 0,
  223. Unit = dto.Unit,
  224. Remark = dto.Remark,
  225. LastUpdateUserId = currUserId,
  226. LastUpdateTime = DateTime.Now,
  227. CreateUserId = currUserId
  228. };
  229. if (dto.Id > 0) //Edit
  230. {
  231. var upd = await _sqlSugar.Updateable(info)
  232. .UpdateColumns(x => new
  233. {
  234. x.Name,
  235. x.Type,
  236. x.Unit,
  237. x.Remark,
  238. x.LastUpdateUserId,
  239. x.LastUpdateTime,
  240. })
  241. .ExecuteCommandAsync();
  242. if (upd > 0)
  243. {
  244. _jv.Msg = $"修改成功!";
  245. _jv.Code = StatusCodes.Status200OK;
  246. return _jv;
  247. }
  248. }
  249. else if (dto.Id < 1) //添加
  250. {
  251. var selectInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Name.Equals(info.Name));
  252. if (selectInfo != null)
  253. {
  254. _jv.Msg = $"“{info.Name}”该物品已存在,请勿重新添加!";
  255. return _jv;
  256. }
  257. var add = await _sqlSugar.Insertable(info).ExecuteCommandAsync();
  258. if (add > 0)
  259. {
  260. _jv.Msg = $"添加成功!";
  261. _jv.Code = StatusCodes.Status200OK;
  262. return _jv;
  263. }
  264. }
  265. return _jv;
  266. }
  267. /// <summary>
  268. /// 物品 Del
  269. /// </summary>
  270. /// <param name="id"></param>
  271. /// <param name="currUserId"></param>
  272. /// <returns></returns>
  273. public async Task<JsonView> GoodsDel(int id, int currUserId)
  274. {
  275. _sqlSugar.BeginTran();
  276. var goods = await _sqlSugar.Updateable<Pm_GoodsInfo>()
  277. .SetColumns(x => new Pm_GoodsInfo()
  278. {
  279. IsDel = 1,
  280. DeleteUserId = currUserId,
  281. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
  282. })
  283. .Where(x => x.Id == id)
  284. .ExecuteCommandAsync();
  285. if (goods < 1)
  286. {
  287. _sqlSugar.RollbackTran();
  288. _jv.Msg = $"操作失败";
  289. return _jv;
  290. }
  291. var goodsStorage = await _sqlSugar.Updateable<Pm_GoodsStorage>()
  292. .SetColumns(x => new Pm_GoodsStorage()
  293. {
  294. IsDel = 1,
  295. DeleteUserId = currUserId,
  296. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
  297. })
  298. .Where(x => x.Id == id)
  299. .ExecuteCommandAsync();
  300. var goodsReceive = await _sqlSugar.Updateable<Pm_GoodsReceive>()
  301. .SetColumns(x => new Pm_GoodsReceive()
  302. {
  303. IsDel = 1,
  304. DeleteUserId = currUserId,
  305. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
  306. })
  307. .Where(x => x.Id == id)
  308. .ExecuteCommandAsync();
  309. _sqlSugar.CommitTran();
  310. _jv.Code = StatusCodes.Status200OK;
  311. _jv.Msg = $"操作成功!";
  312. return _jv;
  313. }
  314. /// <summary>
  315. /// 入库/出库 审核类型
  316. /// 根据物品类型 处理审核是否需要多部门审核
  317. /// </summary>
  318. /// <param name="goodsTypeId">物品类型Id </param>
  319. /// <returns></returns>
  320. public bool GoodsAuditType(int goodsTypeId)
  321. {
  322. if (_goodsTypeIds.Contains(goodsTypeId))
  323. {
  324. return true;
  325. }
  326. return false;
  327. }
  328. /// <summary>
  329. /// 物品入库列表(带审核)
  330. /// </summary>
  331. /// <param name="dto"></param>
  332. /// <returns></returns>
  333. public async Task<JsonView> GoodsStorageList(GoodsStorageListDto dto)
  334. {
  335. string reqAuditLabel = dto.AuditLabel;
  336. var auditLabel = Array.Empty<int>();
  337. int userId = dto.CurrUserId;
  338. if (!string.IsNullOrEmpty(reqAuditLabel))
  339. {
  340. if (!reqAuditLabel.Contains("-1"))
  341. {
  342. auditLabel = reqAuditLabel
  343. .Split(',')
  344. .Select(x =>
  345. {
  346. if (int.TryParse(x, out var id)) return id;
  347. return id;
  348. })
  349. .ToArray();
  350. }
  351. }
  352. var auditList = GoodsStorageConfirmAuditDep(1);
  353. var hrAuditPer = false;
  354. var finAuditPer = false;
  355. var hrAuditInfo = auditList.FirstOrDefault(x => x.AuditDep == GoodsAuditDepEnum.Hr);
  356. var finAuditInfo = auditList.FirstOrDefault(x => x.AuditDep == GoodsAuditDepEnum.Financial);
  357. if (hrAuditInfo != null)
  358. {
  359. if (hrAuditInfo.AuditorIds.Any(x => x == userId)) hrAuditPer = true;
  360. }
  361. if (finAuditInfo != null)
  362. {
  363. if (finAuditInfo.AuditorIds.Any(x => x == userId)) finAuditPer = true;
  364. }
  365. RefAsync<int> total = 0;
  366. var data = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  367. .LeftJoin<Pm_GoodsInfo>((gs, gi) => gs.GoodsId == gi.Id)
  368. .LeftJoin<Sys_Users>((gs, gi, u) => gs.CreateUserId == u.Id)
  369. .LeftJoin<Sys_Users>((gs, gi, u, u1) => gs.StorageUserId == u1.Id)
  370. .Where((gs, gi, u, u1) => gs.IsDel == 0)
  371. .WhereIF(dto.GoodsId > 0, (gs, gi, u, u1) => gs.GoodsId == dto.GoodsId)
  372. .WhereIF(auditLabel.Length > 0, (gs, gi, u, u1) => auditLabel.Contains((int)gs.ConfirmStatus))
  373. .WhereIF(!string.IsNullOrEmpty(dto.GoodsName), (gs, gi, u, u1) => gi.Name.Contains(dto.GoodsName))
  374. .WhereIF(!string.IsNullOrEmpty(dto.BatchNo), (gs, gi, u, u1) => gs.BatchNo.Contains(dto.BatchNo))
  375. .WhereIF(finAuditPer, (gs, gi, u, u1) => _goodsTypeIds.Contains(gi.Type))
  376. .Select((gs, gi, u, u1) => new GoodsStorageListView()
  377. {
  378. Id = gs.Id,
  379. GoodsId = gs.GoodsId,
  380. GoodsType = gi.Type,
  381. BatchNo = gs.BatchNo,
  382. GoodsName = gi.Name,
  383. Quantity = gs.Quantity,
  384. UnitPrice = gs.UnitPrice,
  385. TotalPrice = gs.TotalPrice,
  386. SupplierName = gs.SupplierName,
  387. SupplierTel = gs.SupplierTel,
  388. SupplierAddress = gs.SupplierAddress,
  389. SupplierSource = gs.SupplierSource,
  390. StorageUserName = u1.CnName,
  391. StorageTime = gs.StorageTime,
  392. CreateUserName = u.CnName,
  393. ConfirmStatus = gs.ConfirmStatus,
  394. StatusDesc = gs.StatusDesc,
  395. CreateTime = gs.CreateTime,
  396. Remark = gs.Remark
  397. })
  398. .OrderByDescending(gs => gs.CreateTime)
  399. .ToPageListAsync(dto.PageIndex, dto.PageSize, total);
  400. foreach (var item in data)
  401. {
  402. var auditDeps = new List<GoodsStorageAuditPerView>();
  403. auditDeps.Add(new() { AuditPer = hrAuditPer, AuditDep = GoodsAuditDepEnum.Hr, ButtonText = GoodsAuditDepEnum.Hr.GetEnumDescription() });
  404. var auditPer = GoodsAuditType(item.GoodsType);
  405. if (auditPer)
  406. {
  407. auditDeps.Add(new() { AuditPer = finAuditPer, AuditDep = GoodsAuditDepEnum.Financial, ButtonText = GoodsAuditDepEnum.Financial.GetEnumDescription() });
  408. }
  409. item.AuditPers = auditDeps.ToArray();
  410. }
  411. _jv.Code = StatusCodes.Status200OK;
  412. _jv.Data = data;
  413. _jv.Count = total;
  414. _jv.Msg = $"操作成功";
  415. return _jv;
  416. }
  417. /// <summary>
  418. /// 物品入库详情
  419. /// </summary>
  420. /// <param name="id"></param>
  421. /// <returns></returns>
  422. public async Task<JsonView> GoodsStorageInfo(int portType, int id)
  423. {
  424. var data = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  425. .LeftJoin<Pm_GoodsInfo>((gs, gi) => gs.GoodsId == gi.Id)
  426. .LeftJoin<Sys_Users>((gs, gi, u) => gs.CreateUserId == u.Id)
  427. .LeftJoin<Sys_Users>((gs, gi, u, u1) => gs.StorageUserId == u1.Id)
  428. .Where((gs, gi, u, u1) => gs.IsDel == 0)
  429. .WhereIF(id > 0, (gs, gi, u, u1) => gs.Id == id)
  430. .Select((gs, gi, u, u1) => new
  431. {
  432. gs.Id,
  433. gs.GoodsId,
  434. GoodsName = gi.Name,
  435. gs.Quantity,
  436. gs.UnitPrice,
  437. gs.TotalPrice,
  438. gs.SupplierName,
  439. gs.SupplierTel,
  440. gs.SupplierAddress,
  441. gs.SupplierSource,
  442. gs.ReceiveQuantity,
  443. gs.StorageUserId,
  444. StorageUser = u1.CnName,
  445. gs.StorageTime,
  446. CreateUserName = u.CnName,
  447. gs.CreateUserId,
  448. gs.CreateTime,
  449. gs.Remark,
  450. //gs.IsInConfirm
  451. })
  452. .FirstAsync();
  453. _jv.Msg = $"操作成功!";
  454. _jv.Code = StatusCodes.Status200OK;
  455. _jv.Data = data;
  456. return _jv;
  457. }
  458. /// <summary>
  459. /// 物品入库 操作(Create Or Edit)
  460. /// </summary>
  461. /// <param name="dto"></param>
  462. /// <param name="currUserId"></param>
  463. /// <returns></returns>
  464. public async Task<JsonView> GoodsStorageOp(GoodsStorageOpDto dto, int currUserId)
  465. {
  466. var info = _mapper.Map<Pm_GoodsStorage>(dto);
  467. info.CreateUserId = currUserId;
  468. info.BatchNo = DateTime.Now.ToString("yyyyMMddHHmmssfff");
  469. _sqlSugar.BeginTran();
  470. if (info.Id > 0) //修改
  471. {
  472. var selectInfo = await _sqlSugar.Queryable<Pm_GoodsStorage>().FirstAsync(x => x.Id == dto.Id);
  473. var auditStatus = selectInfo.ConfirmStatus;
  474. if (auditStatus == GoodsConfirmEnum.Confirmed || auditStatus == GoodsConfirmEnum.PartConfirmed)
  475. {
  476. _sqlSugar.RollbackTran();
  477. _jv.Msg = $"该条入库信息已确认或部分确认审核,不可更改!如若更改请取消已确认或部分确认审核状态!";
  478. return _jv;
  479. }
  480. var storageEdit = await _sqlSugar.Updateable(info)
  481. .UpdateColumns(x => new
  482. {
  483. x.Quantity,
  484. x.UnitPrice,
  485. x.TotalPrice,
  486. x.SupplierName,
  487. x.SupplierTel,
  488. x.SupplierAddress,
  489. x.SupplierSource,
  490. x.StorageUserId,
  491. x.StorageTime
  492. })
  493. .Where(x => x.Id == dto.Id)
  494. .ExecuteCommandAsync();
  495. if (storageEdit < 1)
  496. {
  497. _sqlSugar.RollbackTran();
  498. _jv.Msg = $"修改失败!";
  499. return _jv;
  500. }
  501. //入库确认默认状态 多条 or 单条
  502. var auditInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>().Where(x => x.Type == 1 && x.DataId == dto.Id).ToListAsync();
  503. if (auditInfos.Any())
  504. {
  505. var isAuditPer = false;
  506. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.IsDel == 0 && x.Id == dto.GoodsId);
  507. if (goodsInfo != null)
  508. {
  509. isAuditPer = GoodsAuditType(goodsInfo.Type);
  510. }
  511. if (!isAuditPer && auditInfos.Count == 1)
  512. {
  513. var auditInfo = new Pm_GoodsAudit(1, GoodsAuditDepEnum.Financial, dto.Id, GoodsConfirmEnum.WaitConfirm, currUserId);
  514. await _sqlSugar.Insertable(auditInfo).ExecuteCommandAsync();
  515. }
  516. }
  517. }
  518. else if (info.Id < 1) //添加
  519. {
  520. info.ConfirmStatus = GoodsConfirmEnum.WaitConfirm;
  521. var storageAddId = await _sqlSugar.Insertable(info).ExecuteReturnIdentityAsync();
  522. if (storageAddId < 1)
  523. {
  524. _sqlSugar.RollbackTran();
  525. _jv.Msg = $"添加失败!";
  526. return _jv;
  527. }
  528. //入库确认默认状态
  529. List<Pm_GoodsAudit> auditInfos = GoodsStorageConfirm(1, storageAddId, info.CreateUserId);
  530. if (auditInfos.Any())
  531. {
  532. //验证添加多条或者单条审核状态
  533. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.IsDel == 0 && x.Id == dto.GoodsId);
  534. if (goodsInfo != null)
  535. {
  536. var isAuditPer = GoodsAuditType(goodsInfo.Type);
  537. if (!isAuditPer) auditInfos = auditInfos.Where(x => x.Dep == GoodsAuditDepEnum.Hr).ToList();
  538. }
  539. await _sqlSugar.Insertable(auditInfos).ExecuteCommandAsync();
  540. }
  541. }
  542. _sqlSugar.CommitTran();
  543. _jv.Msg = $"操作成功!";
  544. _jv.Code = StatusCodes.Status200OK;
  545. return _jv;
  546. }
  547. /// <summary>
  548. /// 物品入库 确认操作-默认审核部门
  549. /// </summary>
  550. /// <param name="auditType">
  551. /// 审核类型
  552. /// 1.入库 2.出库
  553. /// </param>
  554. /// <param name="dataId">dataId</param>
  555. /// <param name="currUserId">审核人</param>
  556. /// <returns></returns>
  557. public List<Pm_GoodsAudit> GoodsStorageConfirm(int auditType, int dataId, int currUserId)
  558. {
  559. var goodsAuditList = new List<Pm_GoodsAudit>();
  560. goodsAuditList.Add(new Pm_GoodsAudit(auditType, GoodsAuditDepEnum.Hr, dataId, GoodsConfirmEnum.WaitConfirm, currUserId));
  561. goodsAuditList.Add(new Pm_GoodsAudit(auditType, GoodsAuditDepEnum.Financial, dataId, GoodsConfirmEnum.WaitConfirm, currUserId));
  562. return goodsAuditList;
  563. }
  564. /// <summary>
  565. /// 物品入库 确认操作
  566. /// </summary>
  567. /// <param name="dto"></param>
  568. /// <returns></returns>
  569. public async Task<JsonView> GoodsStorageConfirmStatusChange(GoodsStorageConfirmDto dto, int currUserId)
  570. {
  571. int gsId = dto.Id;
  572. var auditDep = dto.AuditDep;
  573. if (gsId < 1)
  574. {
  575. _jv.Msg = string.Format("{0}", MsgTips.Id);
  576. return _jv;
  577. }
  578. if (currUserId < 1)
  579. {
  580. _jv.Msg = string.Format("{0}", MsgTips.UserId);
  581. return _jv;
  582. }
  583. //验证审核部门
  584. (bool auditPer, GoodsAuditDepEnum goodsAuditDep) = GoodsAuditDep(currUserId, auditDep, 1);
  585. if (!auditPer)
  586. {
  587. _jv.Msg = string.Format("未分配入库确认权限!");
  588. return _jv;
  589. }
  590. //入库确认 更改审核状态
  591. _sqlSugar.BeginTran();
  592. var info = await _sqlSugar.Queryable<Pm_GoodsStorage>().Where(x => x.IsDel == 0 && x.Id == gsId).FirstAsync();
  593. if (info == null)
  594. {
  595. _jv.Msg = string.Format("入库信息不存在!");
  596. return _jv;
  597. }
  598. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().Where(x => x.IsDel == 0 && x.Id == info.GoodsId).FirstAsync();
  599. if (goodsInfo == null)
  600. {
  601. _jv.Msg = string.Format("物品信息不存在!");
  602. return _jv;
  603. }
  604. int goodsTypeId = goodsInfo.Type;
  605. var preChangeStatus = info.ConfirmStatus;
  606. if (preChangeStatus == dto.ConfirmStatus)
  607. {
  608. _jv.Msg = string.Format("“{0}”已操作,请勿重复该操作!", dto.ConfirmStatus.GetEnumDescription());
  609. return _jv;
  610. }
  611. var preInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>().Where(x => x.IsDel == 0 && x.DataId == gsId).ToListAsync();
  612. //验证是否需要多级确认
  613. var isAuditPer = GoodsAuditType(goodsTypeId);
  614. //单部门审核时默认人事部审核
  615. if (!isAuditPer) goodsAuditDep = GoodsAuditDepEnum.Hr;
  616. var auditInfo = preInfos.FirstOrDefault(x => x.Dep == goodsAuditDep);
  617. if (auditInfo != null)
  618. {
  619. //移除部门审核状态
  620. preInfos.Remove(auditInfo);
  621. auditInfo.AuditStatus = dto.ConfirmStatus;
  622. auditInfo.AuditUserId = currUserId;
  623. auditInfo.AuditTime = DateTime.Now;
  624. var updStatus = await _sqlSugar.Updateable(auditInfo)
  625. .UpdateColumns(x => new { x.AuditStatus, x.AuditUserId, x.AuditTime })
  626. .ExecuteCommandAsync();
  627. if (updStatus < 1)
  628. {
  629. _sqlSugar.RollbackTran();
  630. _jv.Msg = string.Format("入库确认失败!");
  631. return _jv;
  632. }
  633. }
  634. else
  635. {
  636. auditInfo = new Pm_GoodsAudit(1, goodsAuditDep, gsId, dto.ConfirmStatus, currUserId, currUserId);
  637. var addStatus = await _sqlSugar.Insertable(auditInfo).ExecuteCommandAsync();
  638. if (addStatus < 1)
  639. {
  640. _sqlSugar.RollbackTran();
  641. _jv.Msg = string.Format("入库确认失败!");
  642. return _jv;
  643. }
  644. }
  645. preInfos.Add(auditInfo);
  646. //入库确认 更改入库状态及扣或增加除库存数、金额
  647. var confirmStatus = GoodsConfirmEnum.WaitConfirm;
  648. if (isAuditPer) //多级审核确认
  649. {
  650. if (preInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() >= 2)
  651. {
  652. confirmStatus = GoodsConfirmEnum.Confirmed;
  653. }
  654. else if (preInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() >= 1)
  655. {
  656. confirmStatus = GoodsConfirmEnum.PartConfirmed;
  657. }
  658. else if (preInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.UnApproved).Count() > 0)
  659. {
  660. confirmStatus = GoodsConfirmEnum.UnApproved;
  661. }
  662. else if (preInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.PartConfirmed).Count() > 0)
  663. {
  664. confirmStatus = GoodsConfirmEnum.PartConfirmed;
  665. }
  666. }
  667. else //人事部审核确认
  668. {
  669. confirmStatus = GoodsConfirmEnum.Confirmed;
  670. confirmStatus = dto.ConfirmStatus;
  671. preInfos = preInfos.Where(x => x.Dep == GoodsAuditDepEnum.Hr).ToList();
  672. }
  673. //入库状态描述
  674. var statusDesc = new StringBuilder();
  675. foreach (var preInfo in preInfos)
  676. {
  677. string depName = preInfo.Dep.GetEnumDescription(),
  678. auditStatus = preInfo.AuditStatus.GetEnumDescription(),
  679. auditUserName = preInfo.AuditUserId > 0 ? _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == preInfo.AuditUserId)?.CnName ?? "-" : "-",
  680. auditTime = preInfo.AuditUserId > 0 ? preInfo.AuditTime.ToString("yyyy-MM-dd HH:mm:ss") : "-";
  681. statusDesc.Append(string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>", depName, auditStatus, auditUserName, auditTime));
  682. }
  683. //更改入库状态及描述
  684. info.ConfirmStatus = confirmStatus;
  685. info.StatusDesc = statusDesc.ToString();
  686. var goodsStorageUpd = await _sqlSugar.Updateable(info)
  687. .UpdateColumns(x => new
  688. {
  689. x.ConfirmStatus,
  690. x.StatusDesc,
  691. })
  692. .Where(x => x.Id == info.Id)
  693. .ExecuteCommandAsync();
  694. if (goodsStorageUpd < 1)
  695. {
  696. _sqlSugar.RollbackTran();
  697. _jv.Msg = $"入库确认状态更改失败!";
  698. return _jv;
  699. }
  700. //入库审核通过数量、金额
  701. decimal auditQuantity = info.Quantity,
  702. auditTotalPrice = info.TotalPrice;
  703. goodsInfo.LastUpdateUserId = currUserId;
  704. goodsInfo.LastUpdateTime = DateTime.Now;
  705. if (confirmStatus == GoodsConfirmEnum.Confirmed) // 确认状态
  706. {
  707. //更改后的状态和更改前的状态不一致时 更改库存数、金额
  708. if (preChangeStatus != confirmStatus) //
  709. {
  710. goodsInfo.SQ_Total += auditQuantity;
  711. goodsInfo.StockQuantity += auditQuantity;
  712. goodsInfo.PriceTotal += auditTotalPrice;
  713. }
  714. }
  715. else //其他状态 拒绝、部分确认、等待确认
  716. {
  717. //更改前状态为确认状态时,减库存数、金额
  718. if (preChangeStatus == GoodsConfirmEnum.Confirmed)
  719. {
  720. goodsInfo.SQ_Total -= auditQuantity;
  721. goodsInfo.StockQuantity -= auditQuantity;
  722. goodsInfo.PriceTotal -= auditTotalPrice;
  723. }
  724. }
  725. var goodsUpd = await _sqlSugar.Updateable(goodsInfo)
  726. .UpdateColumns(x => new
  727. {
  728. x.SQ_Total,
  729. x.StockQuantity,
  730. x.PriceTotal,
  731. x.LastUpdateUserId,
  732. x.LastUpdateTime,
  733. })
  734. .Where(x => x.Id == info.GoodsId)
  735. .ExecuteCommandAsync();
  736. if (goodsUpd > 0)
  737. {
  738. _sqlSugar.CommitTran();
  739. _jv.Msg = $"操作成功!";
  740. _jv.Code = StatusCodes.Status200OK;
  741. return _jv;
  742. }
  743. _sqlSugar.RollbackTran();
  744. _jv.Msg = $"操作失败!";
  745. return _jv;
  746. }
  747. /// <summary>
  748. /// 获取物品审核部门
  749. /// </summary>
  750. /// <param name="userId"> userId </param>
  751. /// <param name="auditDepEnum"> 审核部门枚举 </param>
  752. /// <param name="auditType">
  753. /// 指定审核类型(入库/出库)
  754. /// 1:入库审核
  755. /// 2:出库审核
  756. /// </param>
  757. /// <returns></returns>
  758. public (bool, GoodsAuditDepEnum) GoodsAuditDep(int userId, GoodsAuditDepEnum auditDepEnum, int auditType = 1)
  759. {
  760. if (userId < 1) return (false, GoodsAuditDepEnum.Hr);
  761. var auditList = GoodsStorageConfirmAuditDep(1);
  762. if (auditType == 1)
  763. {
  764. if (auditList.Any(x => x.AuditDep == auditDepEnum && x.AuditorIds.Contains(userId)))
  765. {
  766. return (true, auditDepEnum);
  767. }
  768. }
  769. return (false, GoodsAuditDepEnum.Hr);
  770. }
  771. /// <summary>
  772. /// 物品审核部门列表
  773. /// </summary>
  774. /// <param name="auditType">
  775. /// 指定审核类型(入库/出库)
  776. /// 1:入库审核
  777. /// 2:出库审核
  778. /// </param>
  779. /// <returns></returns>
  780. public List<GoodsAuditDepView> GoodsStorageConfirmAuditDep(int auditType = 1)
  781. {
  782. var auditList = new List<GoodsAuditDepView>();
  783. var hrAuditorIds = new GoodsAuditDepView()
  784. {
  785. AuditDep = GoodsAuditDepEnum.Hr,
  786. AuditorIds = new int[] {
  787. 309, // 赖红燕
  788. 343, // 陈湘
  789. //374, // 罗颖
  790. 208, // 雷怡
  791. }
  792. };
  793. var finAuditorIds = new GoodsAuditDepView()
  794. {
  795. AuditDep = GoodsAuditDepEnum.Financial,
  796. AuditorIds = new int[] {
  797. 187, // 曾艳
  798. 281, // 伏虹瑾
  799. 208, // 雷怡
  800. }
  801. };
  802. if (auditType == 1)//入库
  803. {
  804. hrAuditorIds.AuditorIds = new int[] {
  805. //343, // 陈湘
  806. 374, // 罗颖
  807. 208, // 雷怡
  808. };
  809. auditList.Add(hrAuditorIds);
  810. auditList.Add(finAuditorIds);
  811. }
  812. else if (auditType == 2) //出库
  813. {
  814. auditList.Add(hrAuditorIds);
  815. auditList.Add(finAuditorIds);
  816. }
  817. return auditList;
  818. }
  819. /// <summary>
  820. /// 物品入库 Del
  821. /// </summary>
  822. /// <param name="id"></param>
  823. /// <returns></returns>
  824. public async Task<JsonView> GoodsStorageDel(int id, int userId)
  825. {
  826. var storageInfo = await _sqlSugar
  827. .Queryable<Pm_GoodsStorage>()
  828. .Where(x => x.Id == id)
  829. .FirstAsync();
  830. if (storageInfo == null) return _jv;
  831. var auditStatus = storageInfo.ConfirmStatus;
  832. if (auditStatus == GoodsConfirmEnum.Confirmed || auditStatus == GoodsConfirmEnum.PartConfirmed)
  833. {
  834. _sqlSugar.RollbackTran();
  835. _jv.Msg = $"该条入库信息已确认或部分确认审核,不可删除!如若删除请取消已确认或部分确认审核状态!";
  836. return _jv;
  837. }
  838. decimal delAgoQuantity = storageInfo.Quantity,
  839. delAgoTotalPrice = storageInfo.TotalPrice;
  840. var goodsId = storageInfo.GoodsId;
  841. _sqlSugar.BeginTran();
  842. var storageDel = await _sqlSugar.Updateable<Pm_GoodsStorage>()
  843. .SetColumns(x => new Pm_GoodsStorage
  844. {
  845. DeleteUserId = userId,
  846. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  847. IsDel = 1
  848. })
  849. .Where(x => x.Id == id)
  850. .ExecuteCommandAsync();
  851. if (storageDel < 1)
  852. {
  853. _sqlSugar.RollbackTran();
  854. _jv.Msg = $"操作失败!";
  855. return _jv;
  856. }
  857. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == goodsId);
  858. goodsInfo.SQ_Total = goodsInfo.SQ_Total - delAgoQuantity;
  859. goodsInfo.StockQuantity = goodsInfo.StockQuantity - delAgoQuantity;
  860. goodsInfo.PriceTotal = goodsInfo.PriceTotal - delAgoTotalPrice;
  861. goodsInfo.LastUpdateUserId = userId;
  862. goodsInfo.LastUpdateTime = DateTime.Now;
  863. var goodsEdit = await _sqlSugar.Updateable(goodsInfo)
  864. .UpdateColumns(x => new
  865. {
  866. x.SQ_Total,
  867. x.StockQuantity,
  868. x.PriceTotal,
  869. x.LastUpdateUserId,
  870. x.LastUpdateTime,
  871. })
  872. .Where(x => x.Id == goodsId)
  873. .ExecuteCommandAsync();
  874. if (goodsEdit > 0)
  875. {
  876. _sqlSugar.CommitTran();
  877. _jv.Msg = $"操作成功!";
  878. _jv.Code = StatusCodes.Status200OK;
  879. return _jv;
  880. }
  881. _sqlSugar.RollbackTran();
  882. _jv.Msg = $"操作失败!";
  883. return _jv;
  884. }
  885. /// <summary>
  886. /// 物品入库
  887. /// excelDownload
  888. /// </summary>
  889. /// <param name="dto"></param>
  890. /// <returns></returns>
  891. public async Task<JsonView> GoodsStorageExcelDownload()
  892. {
  893. var fileName = $"物资入库{Guid.NewGuid()}.xlsx";
  894. var excelTempPath = $"{_excelPath}Template/物资入库Temp.xlsx";
  895. if (!File.Exists(excelTempPath))
  896. {
  897. _jv.Code = StatusCodes.Status204NoContent;
  898. _jv.Msg = $"该模板文件不存在!";
  899. return _jv;
  900. }
  901. _url = $"{_url}Office/Excel/GoodsFiles/";
  902. _excelPath = $"{_excelPath}GoodsFiles";
  903. if (!Directory.Exists(_excelPath))
  904. {
  905. Directory.CreateDirectory(_excelPath);
  906. }
  907. //入库记录
  908. var storageData = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  909. .LeftJoin<Sys_Users>((gs, su) => gs.StorageUserId == su.Id)
  910. .Where((gs, su) => gs.IsDel == 0)
  911. .Select((gs, su) => new
  912. {
  913. gs.GoodsId,
  914. gs.Quantity,
  915. su.CnName,
  916. gs.StorageTime
  917. })
  918. .ToListAsync();
  919. //出库记录
  920. var receiveData = await _sqlSugar.Queryable<Pm_GoodsReceive>()
  921. .LeftJoin<Sys_Users>((gr, su) => gr.CreateUserId == su.Id)
  922. .Where((gr, su) => gr.IsDel == 0)
  923. .Select((gr, su) => new
  924. {
  925. gr.GoodsId,
  926. gr.Quantity,
  927. su.CnName,
  928. gr.CreateTime,
  929. gr.Reason
  930. })
  931. .ToListAsync();
  932. var data = await _sqlSugar.Queryable<Pm_GoodsInfo>()
  933. .Where(gi => gi.IsDel == 0)
  934. .Select(gi => new GoodsStorageExcelDownloadView
  935. {
  936. Id = gi.Id,
  937. Name = gi.Name,
  938. SQ_Total = gi.SQ_Total,
  939. OQ_Total = gi.OQ_Total,
  940. StockQuantity = gi.StockQuantity,
  941. Unit = gi.Unit
  942. })
  943. .ToListAsync();
  944. foreach (var item in data)
  945. {
  946. var storageData1 = storageData.Where(x => x.GoodsId == item.Id).ToList();
  947. if (storageData1.Any())
  948. {
  949. item.SQ_Total1 = storageData1.Sum(x => x.Quantity);
  950. item.SQ_Total -= item.SQ_Total1;
  951. item.StorageLabel = string.Join("\r\n", storageData1.Select(x => "数量:【" + x.Quantity.ToString("#0.00") + "】 入库人:【" + x.CnName + "】 入库时间:【" + x.StorageTime + "】").ToList());
  952. }
  953. var receiveData1 = receiveData.Where(x => x.GoodsId == item.Id).ToList();
  954. if (receiveData1.Any())
  955. {
  956. item.ReceiveLabel = string.Join("\r\n", receiveData1.Select(x => "数量:【" + x.Quantity.ToString("#0.00") + "】 申请人:【" + x.CnName + "】 申请时间:【" + x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") + "】 原因:【" + x.Reason + "】").ToList());
  957. }
  958. }
  959. //载入模板
  960. WorkbookDesigner designer = new WorkbookDesigner();
  961. designer.Workbook = new Workbook(excelTempPath);
  962. designer.SetDataSource("Export", data);
  963. designer.Process();
  964. #region 渲染Cell批注
  965. var sheet = designer.Workbook.Worksheets[0];
  966. for (int i = 0; i < data.Count; i++)
  967. {
  968. string storageComment = $"C{i + 2}",
  969. receiveComment = $"D{i + 2}",
  970. storageCommentText = data[i].StorageLabel,
  971. receiveCommentText = data[i].ReceiveLabel;
  972. if (!string.IsNullOrEmpty(storageCommentText))
  973. {
  974. int storageIndex = sheet.Comments.Add(storageComment);
  975. Aspose.Cells.Comment comment = sheet.Comments[storageIndex];
  976. comment.Note = storageCommentText;
  977. comment.Width = 500;
  978. comment.Height = 200;
  979. //comment.Font.Color = Color.Red;
  980. }
  981. if (!string.IsNullOrEmpty(receiveCommentText))
  982. {
  983. int receiveIndex = sheet.Comments.Add(receiveComment);
  984. Aspose.Cells.Comment comment = sheet.Comments[receiveIndex];
  985. comment.Note = receiveCommentText;
  986. comment.Width = 800;
  987. comment.Height = 200;
  988. //comment.Font.Color = Color.Red;
  989. }
  990. }
  991. #endregion
  992. string serverPath = $"{_url}{fileName}";
  993. designer.Workbook.Save($"{_excelPath}/{fileName}");
  994. _jv.Code = StatusCodes.Status200OK;
  995. _jv.Data = new { url = serverPath };
  996. _jv.Msg = $"操作成功";
  997. return _jv;
  998. }
  999. /// <summary>
  1000. /// 物品领用列表
  1001. /// </summary>
  1002. /// <param name="dto"></param>
  1003. /// <returns></returns>
  1004. public async Task<JsonView> GoodsReceiveList(GoodsReceiveListDTO dto)
  1005. {
  1006. //参数处理
  1007. int[] typeLabel = Array.Empty<int>(),
  1008. userLabel = Array.Empty<int>(),
  1009. auditLabel = Array.Empty<int>(),
  1010. groupLabel = Array.Empty<int>();
  1011. string[] userNameLabel = Array.Empty<string>();
  1012. int currUserId = dto.CurrUserId;
  1013. if (!string.IsNullOrEmpty(dto.TypeLabel))
  1014. {
  1015. typeLabel = dto.TypeLabel
  1016. .Split(',')
  1017. .Select(x =>
  1018. {
  1019. if (int.TryParse(x, out var id)) return id;
  1020. return id;
  1021. })
  1022. .ToArray();
  1023. }
  1024. if (!string.IsNullOrEmpty(dto.UserLabel))
  1025. {
  1026. userLabel = dto.UserLabel
  1027. .Split(',')
  1028. .Select(x =>
  1029. {
  1030. if (int.TryParse(x, out var id)) return id;
  1031. return id;
  1032. })
  1033. .ToArray();
  1034. if (userLabel.Any())
  1035. {
  1036. userNameLabel = await _sqlSugar.Queryable<Sys_Users>().Where(x => userLabel.Contains(x.Id)).Select(x => x.CnName).ToArrayAsync();
  1037. }
  1038. }
  1039. if (!string.IsNullOrEmpty(dto.AuditLabel))
  1040. {
  1041. auditLabel = dto.AuditLabel
  1042. .Split(',')
  1043. .Select(x =>
  1044. {
  1045. if (int.TryParse(x, out var id)) return id;
  1046. return id;
  1047. })
  1048. .ToArray();
  1049. if (auditLabel.Any(x => x == -1))
  1050. {
  1051. auditLabel = auditLabel.Where(x => x != -1).ToArray();
  1052. }
  1053. }
  1054. if (!string.IsNullOrEmpty(dto.GroupLabel))
  1055. {
  1056. groupLabel = dto.GroupLabel
  1057. .Split(',')
  1058. .Select(x =>
  1059. {
  1060. if (int.TryParse(x, out var id)) return id;
  1061. return id;
  1062. })
  1063. .ToArray();
  1064. }
  1065. //全部团组
  1066. bool isAllGroups = false;
  1067. if (groupLabel.Contains(-3)) isAllGroups = true;
  1068. //物品ID和物品名称只能传一个
  1069. if (dto.GoodsId > 0) dto.GoodsName = string.Empty;
  1070. if (!string.IsNullOrEmpty(dto.GoodsName)) dto.GoodsId = 0;
  1071. if (currUserId == 343) //陈湘OAId登录 只显示贵重物品审核信息
  1072. {
  1073. if (_goodsTypeIds.Any())
  1074. {
  1075. var newArray = typeLabel.ToList();
  1076. newArray.AddRange(_goodsTypeIds);
  1077. typeLabel = newArray.ToArray();
  1078. }
  1079. }
  1080. var beginBool = DateTime.TryParse(!string.IsNullOrEmpty(dto.BeginDt) ? $"{dto.BeginDt} 00:00:00" : string.Empty, out var begin);
  1081. var endBool = DateTime.TryParse(!string.IsNullOrEmpty(dto.EndDt) ? $"{dto.EndDt} 00:00:00" : string.Empty, out var end);
  1082. //新旧领用数据整合
  1083. var oldDatas = _sqlSugar.Queryable<Pm_GoodsReceive>()
  1084. .InnerJoin<Pm_GoodsInfo>((gr, gi) => gr.GoodsId == gi.Id)
  1085. .LeftJoin<Sys_SetData>((gr, gi, sd) => gi.Type == sd.Id)
  1086. .LeftJoin<Sys_Users>((gr, gi, sd, u1) => gr.AuditUserId == u1.Id)
  1087. .LeftJoin<Sys_Users>((gr, gi, sd, u1, u2) => gr.CreateUserId == u2.Id)
  1088. .LeftJoin<Grp_DelegationInfo>((gr, gi, sd, u1, u2, di) => gr.GroupId == di.Id)
  1089. .Where((gr, gi, sd, u1, u2, di) => gr.IsDel == 0 && gr.GoodsId > 0)
  1090. .Select((gr, gi, sd, u1, u2, di) => new GoodsReceiveListMobileView
  1091. {
  1092. Id = gr.Id,
  1093. GroupId = gr.GroupId,
  1094. GroupName = di.TeamName,
  1095. GoodsId = gr.GoodsId,
  1096. GoodsName = gi.Name,
  1097. GoodsTypeId = gi.Type,
  1098. GoodsType = sd.Name,
  1099. Quantity = gr.Quantity,
  1100. Unit = gi.Unit,
  1101. Reason = gr.Reason,
  1102. Remark = gr.Remark,
  1103. AuditStatus = gr.AuditStatus,
  1104. StatusDesc = gr.StatusDesc,
  1105. AuditUserId = gr.AuditUserId,
  1106. AuditUserName = u1.CnName,
  1107. AuditTime = gr.AuditTime,
  1108. CreateUserName = u2.CnName,
  1109. CreateTime = gr.CreateTime
  1110. });
  1111. var newDatas = _sqlSugar.Queryable<Pm_GoodsReceive>()
  1112. .LeftJoin<Pm_GoodsReceiveDetails>((gr, grd) => gr.Id == grd.GoodsReceiveId)
  1113. .LeftJoin<Pm_GoodsInfo>((gr, grd, gi) => grd.GoodsId == gi.Id)
  1114. .LeftJoin<Sys_SetData>((gr, grd, gi, sd) => gi.Type == sd.Id)
  1115. .LeftJoin<Sys_Users>((gr, grd, gi, sd, u1) => gr.AuditUserId == u1.Id)
  1116. .LeftJoin<Sys_Users>((gr, grd, gi, sd, u1, u2) => gr.CreateUserId == u2.Id)
  1117. .LeftJoin<Grp_DelegationInfo>((gr, grd, gi, sd, u1, u2, di) => gr.GroupId == di.Id)
  1118. .Where((gr, grd, gi, sd, u1, u2, di) => gr.IsDel == 0 && grd.IsDel == 0 && gr.GoodsId < 1)
  1119. .Select((gr, grd, gi, sd, u1, u2, di) => new GoodsReceiveListMobileView
  1120. {
  1121. Id = gr.Id,
  1122. GroupId = gr.GroupId,
  1123. GroupName = di.TeamName,
  1124. GoodsId = gr.GoodsId,
  1125. GoodsName = gi.Name,
  1126. GoodsTypeId = gi.Type,
  1127. GoodsType = sd.Name,
  1128. Quantity = grd.Quantity,
  1129. Unit = gi.Unit,
  1130. Reason = gr.Reason,
  1131. Remark = gr.Remark,
  1132. AuditStatus = gr.AuditStatus,
  1133. StatusDesc = gr.StatusDesc,
  1134. AuditUserId = gr.AuditUserId,
  1135. AuditUserName = u1.CnName,
  1136. AuditTime = gr.AuditTime,
  1137. CreateUserName = u2.CnName,
  1138. CreateTime = gr.CreateTime
  1139. });
  1140. var isIdSelect = false;
  1141. var isNameSelect = false;
  1142. if (dto.GoodsId > 0)
  1143. {
  1144. isIdSelect = true;
  1145. dto.GoodsName = string.Empty;
  1146. }
  1147. if (!string.IsNullOrEmpty(dto.GoodsName))
  1148. {
  1149. isIdSelect = false;
  1150. isNameSelect = true;
  1151. }
  1152. RefAsync<int> total = 0;
  1153. var data = _sqlSugar.UnionAll(oldDatas, newDatas)
  1154. .WhereIF(isIdSelect && !isNameSelect, x => x.GoodsId == dto.GoodsId)
  1155. .WhereIF(!isIdSelect && isNameSelect, x => x.GoodsName.Contains(dto.GoodsName))
  1156. .WhereIF(auditLabel.Length > 0, x => auditLabel.Contains((int)x.AuditStatus))
  1157. .WhereIF(typeLabel.Length > 0, x => typeLabel.Contains(x.GoodsTypeId))
  1158. .WhereIF(userNameLabel.Length > 0, x => userNameLabel.Contains(x.CreateUserName))
  1159. .WhereIF(!isAllGroups && groupLabel.Length > 0, x => groupLabel.Contains(x.GroupId))
  1160. .WhereIF(isAllGroups, x => x.GroupId > 0)
  1161. .WhereIF(beginBool && endBool, x => x.CreateTime >= begin && x.CreateTime <= end)
  1162. .OrderByDescending(x => x.CreateTime);
  1163. //excel导出
  1164. if (dto.IsExcelDownload)
  1165. {
  1166. var fileName = $"物资领用{Guid.NewGuid()}.xlsx";
  1167. var excelTempPath = $"{_excelPath}Template/物资领用Temp.xlsx";
  1168. if (!File.Exists(excelTempPath))
  1169. {
  1170. _jv.Code = StatusCodes.Status204NoContent;
  1171. _jv.Msg = $"该模板文件不存在!";
  1172. return _jv;
  1173. }
  1174. _url = $"{_url}Office/Excel/GoodsFiles/";
  1175. _excelPath = $"{_excelPath}GoodsFiles";
  1176. if (!Directory.Exists(_excelPath))
  1177. {
  1178. Directory.CreateDirectory(_excelPath);
  1179. }
  1180. //载入模板
  1181. WorkbookDesigner designer = new WorkbookDesigner();
  1182. designer.Workbook = new Workbook(excelTempPath);
  1183. var tableData = await data.ToListAsync();
  1184. foreach (var item in tableData)
  1185. {
  1186. var oldGroupName = item.GroupName;
  1187. item.GroupName = item.GroupId switch
  1188. {
  1189. 0 => "其他物资(公司内部物资)",
  1190. -1 => "拜访客户所使用的物资",
  1191. -2 => "库存调整",
  1192. _ => oldGroupName
  1193. };
  1194. //审核相关处理
  1195. if (string.IsNullOrEmpty(item.AuditUserName))
  1196. {
  1197. var oldAuditDatas = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  1198. .LeftJoin<Sys_Users>((x, u) => x.AuditUserId == u.Id)
  1199. .Where((x, u) => x.IsDel == 0 && x.Type == 2 && x.DataId == item.Id)
  1200. .Select((x, u) => new {
  1201. x.AuditTime,
  1202. u.CnName
  1203. })
  1204. .ToListAsync();
  1205. if (oldAuditDatas.Any())
  1206. {
  1207. item.AuditUserName = string.Join("、", oldAuditDatas.Select(x => x.CnName).ToArray());
  1208. if (!string.IsNullOrEmpty(item.AuditUserName))
  1209. {
  1210. item.AuditTime = oldAuditDatas.Last().AuditTime;
  1211. }
  1212. else item.AuditTime = DateTime.Now;
  1213. }
  1214. else
  1215. {
  1216. var newAuditDatas = await _sqlSugar.Queryable<Sys_AuditRecord>()
  1217. .InnerJoin<Sys_AuditFlow>((x,y) => x.FlowId == y.Id)
  1218. .Where((x, y) => x.IsDel == 0 && y.BusinessType == 1 && y.BusinessId == item.Id)
  1219. .Select((x, y) => new {
  1220. x.AuditTime,
  1221. x.AuditorName
  1222. })
  1223. .ToListAsync();
  1224. if (newAuditDatas.Any())
  1225. {
  1226. item.AuditUserName = string.Join("、", newAuditDatas.Select(x => x.AuditorName).Distinct().ToArray());
  1227. if (!string.IsNullOrEmpty(item.AuditUserName))
  1228. {
  1229. item.AuditTime = newAuditDatas.Last().AuditTime;
  1230. }
  1231. else item.AuditTime = DateTime.Now;
  1232. }
  1233. }
  1234. }
  1235. }
  1236. designer.SetDataSource("Export", tableData);
  1237. designer.Process();
  1238. string serverPath = $"{_url}{fileName}";
  1239. designer.Workbook.Save($"{_excelPath}/{fileName}");
  1240. _jv.Code = StatusCodes.Status200OK;
  1241. _jv.Data = new { url = serverPath };
  1242. _jv.Msg = $"操作成功";
  1243. return _jv;
  1244. }
  1245. //返回分页数据
  1246. var view = await data.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
  1247. foreach (var item in view)
  1248. {
  1249. //团组名称处理
  1250. var oldGroupName = item.GroupName;
  1251. item.GroupName = item.GroupId switch
  1252. {
  1253. 0 => "其他物资(公司内部物资)",
  1254. -1 => "拜访客户所使用的物资",
  1255. -2 => "库存调整",
  1256. _ => oldGroupName
  1257. };
  1258. //审核相关处理
  1259. if (string.IsNullOrEmpty(item.AuditUserName))
  1260. {
  1261. var oldAuditDatas = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  1262. .LeftJoin<Sys_Users>((x, u) => x.AuditUserId == u.Id)
  1263. .Where((x, u) => x.IsDel == 0 && x.Type == 2 && x.DataId == item.Id)
  1264. .Select((x, u) => new {
  1265. x.AuditTime,
  1266. u.CnName
  1267. })
  1268. .ToListAsync();
  1269. if (oldAuditDatas.Any())
  1270. {
  1271. item.AuditUserName = string.Join("、", oldAuditDatas.Select(x => x.CnName).ToArray());
  1272. if (!string.IsNullOrEmpty(item.AuditUserName))
  1273. {
  1274. item.AuditTime = oldAuditDatas.Last().AuditTime;
  1275. }
  1276. else item.AuditTime = DateTime.Now;
  1277. }
  1278. else
  1279. {
  1280. var newAuditDatas = await _sqlSugar.Queryable<Sys_AuditRecord>()
  1281. .InnerJoin<Sys_AuditFlow>((x, y) => x.FlowId == y.Id)
  1282. .Where((x, y) => x.IsDel == 0 && y.BusinessType == 1 && y.BusinessId == item.Id)
  1283. .Select((x, y) => new {
  1284. x.AuditTime,
  1285. x.AuditorName
  1286. })
  1287. .ToListAsync();
  1288. if (newAuditDatas.Any())
  1289. {
  1290. item.AuditUserName = string.Join("、", newAuditDatas.Select(x => x.AuditorName).Distinct().ToArray());
  1291. if (!string.IsNullOrEmpty(item.AuditUserName))
  1292. {
  1293. item.AuditTime = newAuditDatas.Last().AuditTime;
  1294. }
  1295. else item.AuditTime = DateTime.Now;
  1296. }
  1297. }
  1298. }
  1299. //权限前台验证
  1300. var auditPers = new List<GoodsStorageAuditPerView>
  1301. {
  1302. new() { AuditPer = true, AuditDep = GoodsAuditDepEnum.Hr, ButtonText = GoodsAuditDepEnum.Hr_Reception.GetDescription() }
  1303. };
  1304. if (_goodsTypeIds.Contains(item.GoodsTypeId))
  1305. {
  1306. auditPers.Add(new() { AuditPer = true, AuditDep = GoodsAuditDepEnum.Hr, ButtonText = GoodsAuditDepEnum.Hr.GetDescription() });
  1307. }
  1308. item.AuditPers = auditPers.ToArray();
  1309. }
  1310. if (dto.PortType == 2 || dto.PortType == 3)
  1311. {
  1312. _jv.Data = view;
  1313. }
  1314. else if (dto.PortType == 1)
  1315. {
  1316. var view1 = _mapper.Map<List<GoodsReceiveListView>>(view);
  1317. _jv.Data = view1;
  1318. }
  1319. _jv.Code = StatusCodes.Status200OK;
  1320. _jv.Count = total;
  1321. _jv.Msg = $"操作成功";
  1322. return _jv;
  1323. }
  1324. /// <summary>
  1325. /// 物品领用详情
  1326. /// </summary>
  1327. /// <param name="portType"></param>
  1328. /// <param name="id"></param>
  1329. /// <returns></returns>
  1330. public async Task<JsonView> GoodsReceiveInfo(int portType, int id)
  1331. {
  1332. var data = await _sqlSugar.Queryable<Pm_GoodsReceive>()
  1333. .LeftJoin<Pm_GoodsInfo>((gr, gi) => gr.GoodsId == gi.Id)
  1334. .LeftJoin<Sys_Users>((gr, gi, u1) => gr.AuditUserId == u1.Id)
  1335. .LeftJoin<Sys_Users>((gr, gi, u1, u2) => gr.CreateUserId == u2.Id)
  1336. .LeftJoin<Grp_DelegationInfo>((gr, gi, u1, u2, di) => gr.GroupId == di.Id)
  1337. .Where((gr, gi, u1, u2, di) => gr.IsDel == 0)
  1338. .WhereIF(id > 0, (gr, gi, u1, u2, di) => gr.Id == id)
  1339. .Select((gr, gi, u1, u2, di) => new GoodsReceiveInfoMobileView
  1340. {
  1341. Id = gr.Id,
  1342. GroupId = gr.GroupId,
  1343. GroupName = di.TeamName,
  1344. GoodsId = gr.GoodsId,
  1345. GoodsName = gi.Name,
  1346. Quantity = gr.Quantity,
  1347. Reason = gr.Reason,
  1348. Remark = gr.Remark,
  1349. GoodsStorageInfo = gr.GoodsStorageInfo,
  1350. AuditStatus = gr.AuditStatus,
  1351. AuditUserId = gr.AuditUserId,
  1352. AuditUserName = u1.CnName,
  1353. AuditTime = gr.AuditTime,
  1354. CreateUserName = u2.CnName,
  1355. CreateTime = gr.CreateTime
  1356. })
  1357. .FirstAsync();
  1358. if (!string.IsNullOrEmpty(data.GoodsStorageInfo))
  1359. {
  1360. var subData = new List<dynamic>();
  1361. try
  1362. {
  1363. var subData1 = JsonConvert.DeserializeObject<List<GoodsReceiveLinkStorageView>>(data.GoodsStorageInfo);
  1364. if (subData1.Count > 0)
  1365. {
  1366. string goodsStorageInfoStr = string.Empty;
  1367. var storageIds = subData1.Select(x => x.StorageId).ToList();
  1368. var storages = await _sqlSugar.Queryable<Pm_GoodsStorage>().Where(x => x.IsDel == 0 && storageIds.Contains(x.Id)).ToListAsync();
  1369. foreach (var item in subData1)
  1370. {
  1371. var storageInfo = storages.Find(x => x.Id == item.StorageId);
  1372. if (storageInfo != null)
  1373. {
  1374. subData.Add(new
  1375. {
  1376. StorageId = item.StorageId,
  1377. BatchNo = storageInfo.BatchNo,
  1378. RecsiveQuantity = item.Quantity
  1379. });
  1380. goodsStorageInfoStr += $"物品名称:{data.GoodsName} 批次号:{storageInfo.BatchNo} 领用数量:{item.Quantity} \r\n";
  1381. }
  1382. }
  1383. data.QuantityInfos = subData;
  1384. data.GoodsStorageInfoStr = goodsStorageInfoStr;
  1385. }
  1386. }
  1387. catch (Exception e)
  1388. {
  1389. Console.WriteLine(e);
  1390. }
  1391. }
  1392. _jv.Code = StatusCodes.Status200OK;
  1393. _jv.Msg = $"操作成功";
  1394. if (portType == 2 || portType == 3) //移动端
  1395. {
  1396. _jv.Data = data;
  1397. }
  1398. else if (portType == 1) //pc端
  1399. {
  1400. _jv.Data = _mapper.Map<GoodsReceiveInfoView>(data);
  1401. }
  1402. return _jv;
  1403. }
  1404. /// <summary>
  1405. /// 物品领用 OP(Add Or Edit)
  1406. /// </summary>
  1407. /// <param name="dto"></param>
  1408. /// <param name="currUserId"></param>
  1409. /// <returns></returns>
  1410. public async Task<JsonView> GoodsReceiveOp(GoodsReceiveOpDto dto, int currUserId)
  1411. {
  1412. var info = _mapper.Map<Pm_GoodsReceive>(dto);
  1413. info.CreateUserId = currUserId;
  1414. var auditEnums = new List<GoodsAuditEnum>() {
  1415. GoodsAuditEnum.Approved, // 1
  1416. GoodsAuditEnum.UnApproved, // 2
  1417. GoodsAuditEnum.OutConfirmed,// 5
  1418. GoodsAuditEnum.OutRejected // 6
  1419. };
  1420. _sqlSugar.BeginTran();
  1421. //物品现有库存
  1422. var goodsInfo = _sqlSugar.Queryable<Pm_GoodsInfo>().First(x => x.Id == info.GoodsId);
  1423. var stockQuantity = goodsInfo?.StockQuantity ?? 0.00M;
  1424. //待审核 该物品数量
  1425. var waitAuditQuantity = await _sqlSugar.Queryable<Pm_GoodsReceive>().Where(x => x.IsDel == 0 &&
  1426. x.GoodsId == dto.GoodsId &&
  1427. !auditEnums.Contains(x.AuditStatus)
  1428. ).SumAsync(x => x.Quantity);
  1429. //验证默认审核 多条 or 单条
  1430. //出库确认默认审核状态
  1431. var isAuditPer = GoodsAuditType(goodsInfo?.Type ?? 0);
  1432. //验证默认审核 多条审核时添加
  1433. var goodsAuditInfo1 = new Pm_GoodsAudit(2, GoodsAuditDepEnum.Hr_Reception, info.Id, GoodsConfirmEnum.WaitConfirm, currUserId);
  1434. var goodsAuditInfo2 = new Pm_GoodsAudit(2, GoodsAuditDepEnum.Hr, info.Id, GoodsConfirmEnum.WaitConfirm, currUserId);
  1435. var goodsAuditInfos = new List<Pm_GoodsAudit>() { goodsAuditInfo1 };
  1436. //状态描述
  1437. StringBuilder stringBuilder = new StringBuilder();
  1438. stringBuilder.Append($"领用确认:状态:待确认 审核人:- 审核时间:-;<br/>");
  1439. if (isAuditPer)
  1440. {
  1441. goodsAuditInfos.Add(goodsAuditInfo2);
  1442. stringBuilder.Append($"人事部:状态:待确认 审核人:- 审核时间:-;<br/>");
  1443. }
  1444. info.StatusDesc = stringBuilder.ToString();
  1445. if (info.Id > 0) //修改
  1446. {
  1447. //审核验证
  1448. var selectInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.Id == info.Id);
  1449. if (auditEnums.Contains(selectInfo.AuditStatus))
  1450. {
  1451. _sqlSugar.RollbackTran();
  1452. _jv.Msg = $"该条数据已执行操作({selectInfo.AuditStatus.GetEnumDescription()}),不可更改!";
  1453. return _jv;
  1454. }
  1455. //物品数量验证
  1456. var editAfterQuantity = waitAuditQuantity - selectInfo.Quantity + info.Quantity;
  1457. if (editAfterQuantity > stockQuantity)
  1458. {
  1459. _sqlSugar.RollbackTran();
  1460. _jv.Msg = $"该物品现有库存不足,不可更改!请联系采购人员购买!";
  1461. return _jv;
  1462. }
  1463. var edit = await _sqlSugar.Updateable(info)
  1464. .UpdateColumns(x => new
  1465. {
  1466. x.GroupId,
  1467. x.Quantity,
  1468. x.Reason,
  1469. x.Remark,
  1470. x.StatusDesc,
  1471. })
  1472. .Where(x => x.Id == info.Id)
  1473. .ExecuteCommandAsync();
  1474. if (edit > 0)
  1475. {
  1476. var auditInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>().Where(x => x.DataId == info.Id).ToListAsync();
  1477. if (!auditInfos.Any()) await _sqlSugar.Insertable(goodsAuditInfos).ExecuteCommandAsync();
  1478. _sqlSugar.CommitTran();
  1479. _jv.Msg = $"操作成功!";
  1480. _jv.Code = StatusCodes.Status200OK;
  1481. return _jv;
  1482. }
  1483. }
  1484. else if (info.Id < 1) //添加
  1485. {
  1486. //物品数量验证
  1487. decimal addAgoQuantity = waitAuditQuantity + info.Quantity;
  1488. if (addAgoQuantity > stockQuantity)
  1489. {
  1490. _sqlSugar.RollbackTran();
  1491. _jv.Msg = $"该物品现有库存不足,不可更改!请联系采购人员购买!";
  1492. return _jv;
  1493. }
  1494. var add = await _sqlSugar.Insertable(info).ExecuteReturnIdentityAsync();
  1495. if (add > 0)
  1496. {
  1497. goodsAuditInfos.ForEach(x => x.DataId = add);
  1498. await _sqlSugar.Insertable(goodsAuditInfos).ExecuteCommandAsync();
  1499. _sqlSugar.CommitTran();
  1500. _jv.Msg = $"操作成功!";
  1501. _jv.Code = StatusCodes.Status200OK;
  1502. return _jv;
  1503. }
  1504. }
  1505. _sqlSugar.RollbackTran();
  1506. return _jv;
  1507. }
  1508. /// <summary>
  1509. /// 物品领用 Audit
  1510. /// </summary>
  1511. /// <param name="idArray"></param>
  1512. /// <param name="userId"></param>
  1513. /// <param name="auditEnum"></param>
  1514. /// <returns></returns>
  1515. public async Task<JsonView> GoodsReceiveAudit(int[] idArray, int userId, GoodsAuditEnum auditEnum)
  1516. {
  1517. if (idArray.Length < 1) return _jv;
  1518. if (!Enum.IsDefined(typeof(GoodsAuditEnum),(int)auditEnum))
  1519. {
  1520. _jv.Msg = $"出库确认状态超出可用范围!";
  1521. return _jv;
  1522. }
  1523. int receiveId = idArray[0];
  1524. var currUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == userId)?.CnName ?? "-";
  1525. _sqlSugar.BeginTran();
  1526. var receiveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.IsDel == 0 && receiveId == x.Id);
  1527. if (receiveInfo == null)
  1528. {
  1529. _sqlSugar.RollbackTran();
  1530. _jv.Msg = $"当前领用信息不存在!";
  1531. return _jv;
  1532. }
  1533. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == receiveInfo.GoodsId);
  1534. int goodTypeId = goodsInfo?.Type ?? 0;
  1535. //审核前状态
  1536. var preChangeStatus = receiveInfo.AuditStatus;
  1537. //状态验证
  1538. //if (preChangeStatus == auditEnum)
  1539. //{
  1540. // _sqlSugar.RollbackTran();
  1541. // _jv.Msg = $"该条数据状态已设置,不可重复设置!";
  1542. // return _jv;
  1543. //}
  1544. var isAuditPer = GoodsAuditType(goodTypeId);
  1545. if (isAuditPer) //多人审核
  1546. {
  1547. var auditDep = GoodsAuditDepEnum.Hr_Reception;
  1548. var auditInfo = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  1549. .FirstAsync(x => x.Type == 2 && x.DataId == receiveInfo.Id && x.Dep == GoodsAuditDepEnum.Hr_Reception);
  1550. if (auditInfo != null && auditInfo.AuditStatus == GoodsConfirmEnum.Confirmed)
  1551. {
  1552. auditDep = GoodsAuditDepEnum.Hr;
  1553. //多人审核的时候验证审核权限
  1554. var auditList = GoodsStorageConfirmAuditDep(2);
  1555. var auditDepInfo = auditList.Find(x => x.AuditorIds.Contains(userId));
  1556. if (auditDepInfo == null)
  1557. {
  1558. _jv.Msg = string.Format("未分配出库确认权限!");
  1559. _sqlSugar.RollbackTran();
  1560. return _jv;
  1561. }
  1562. }
  1563. // 确认中 确认 拒绝
  1564. _jv = await GoodsReceiveOutConfirmingMultiple(receiveInfo, userId, auditDep, auditEnum);
  1565. //switch (auditEnum)
  1566. //{
  1567. // case GoodsAuditEnum.Pending: //领用待确认(取消确认、取消拒绝)
  1568. // _jv = await GoodsReceivePending(preChangeStatus, receiveId, userId, currUserName, auditEnum);
  1569. // break;
  1570. // case GoodsAuditEnum.Approved: //领用确认
  1571. // _jv = await GoodsReceiveApproved(preChangeStatus, receiveId, userId, currUserName, auditEnum);
  1572. // break;
  1573. // case GoodsAuditEnum.UnApproved: //领用拒绝
  1574. // _jv = await GoodsReceiveUnApproved(preChangeStatus, receiveId, userId, currUserName, auditEnum);
  1575. // break;
  1576. // case GoodsAuditEnum.OutPending: //出库待确认(取消出库确认、取消出库拒绝)
  1577. // _jv = await GoodsReceiveOutPending(preChangeStatus, receiveInfo, userId, auditDep, auditEnum);
  1578. // break;
  1579. // case GoodsAuditEnum.OutConfirmed: //出库确认
  1580. // _jv = await GoodsReceiveOutConfirming(receiveInfo, userId, auditDep, auditEnum);
  1581. // break;
  1582. // case GoodsAuditEnum.OutRejected: //出库拒绝
  1583. // _jv = await GoodsReceiveOutConfirming(receiveInfo, userId, auditDep, auditEnum);
  1584. // break;
  1585. //}
  1586. }
  1587. else //单人审核
  1588. {
  1589. //领用确认 --> 已确认 / 领用拒绝 --> 已拒绝
  1590. _jv = await GoodsReceiveOutConfirmingSingle(receiveInfo,userId, currUserName,auditEnum);
  1591. }
  1592. if (_jv.Code == StatusCodes.Status200OK)
  1593. {
  1594. _sqlSugar.CommitTran();
  1595. _jv.Msg = $"操作成功!";
  1596. _jv.Data = auditEnum;
  1597. return _jv;
  1598. }
  1599. _sqlSugar.RollbackTran();
  1600. return _jv;
  1601. }
  1602. #region 多人审核状态变更
  1603. /// <summary>
  1604. /// 物品领用状态 - 领用待确认(取消确认、取消拒绝)
  1605. /// </summary>
  1606. /// <param name="preChangeStatus">更改前状态</param>
  1607. /// <param name="receiveId"></param>
  1608. /// <param name="userId"></param>
  1609. /// <param name="userName"></param>
  1610. /// <param name="auditEnum"></param>
  1611. /// <returns></returns>
  1612. public async Task<JsonView> GoodsReceivePending(GoodsAuditEnum preChangeStatus, int receiveId, int userId, string userName, GoodsAuditEnum auditEnum)
  1613. {
  1614. _jv.Code = StatusCodes.Status400BadRequest;
  1615. //领用待确认 操作范围
  1616. var audirEnumPers = new List<GoodsAuditEnum>() {
  1617. GoodsAuditEnum.Approved,
  1618. GoodsAuditEnum.UnApproved
  1619. };
  1620. if (!audirEnumPers.Contains(preChangeStatus))
  1621. {
  1622. _jv.Msg = $"{GoodsAuditEnum.Approved.GetEnumDescription()}、{GoodsAuditEnum.UnApproved.GetEnumDescription()},状态下可取消操作!";
  1623. return _jv;
  1624. }
  1625. var currUserOpDt = DateTime.Now;
  1626. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  1627. var statusDesc = string.Format(@"领用确认:状态:{0} 审核人:{1} 审核时间:{2};<br/>人事部确认:状态:待确认 审核人:- 审核时间:-;<br/>财务部确认:状态:待确认 审核人:- 审核时间:-;", auditEnum.GetEnumDescription(), userName, currUserOpTime);
  1628. auditEnum = GoodsAuditEnum.Pending;
  1629. var changeStatus = await _sqlSugar
  1630. .Updateable<Pm_GoodsReceive>()
  1631. .SetColumns(x => new Pm_GoodsReceive()
  1632. {
  1633. AuditStatus = auditEnum,
  1634. AuditUserId = userId,
  1635. AuditTime = currUserOpDt,
  1636. StatusDesc = statusDesc
  1637. })
  1638. .Where(x => x.Id == receiveId)
  1639. .ExecuteCommandAsync();
  1640. if (changeStatus > 0)
  1641. {
  1642. _jv.Code = StatusCodes.Status200OK;
  1643. }
  1644. return _jv;
  1645. }
  1646. /// <summary>
  1647. /// 物品领用状态 - 领用确认
  1648. /// </summary>
  1649. /// <param name="preChangeStatus">更改前状态</param>
  1650. /// <param name="receiveId"></param>
  1651. /// <param name="userId"></param>
  1652. /// <param name="userName"></param>
  1653. /// <param name="auditEnum"></param>
  1654. /// <returns></returns>
  1655. public async Task<JsonView> GoodsReceiveApproved(GoodsAuditEnum preChangeStatus, int receiveId, int userId, string userName, GoodsAuditEnum auditEnum)
  1656. {
  1657. _jv.Code = StatusCodes.Status400BadRequest;
  1658. if (preChangeStatus != GoodsAuditEnum.Pending)
  1659. {
  1660. _jv.Msg = $"{GoodsAuditEnum.Pending.GetEnumDescription()},状态下可取消操作!";
  1661. return _jv;
  1662. }
  1663. var currUserOpDt = DateTime.Now;
  1664. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  1665. var statusDesc = string.Format(@"领用确认:状态:{0} 审核人:{1} 审核时间:{2};<br/>人事部确认:状态:待确认 审核人:- 审核时间:-;<br/>财务部确认:状态:待确认 审核人:- 审核时间:-;", auditEnum.GetEnumDescription(), userName, currUserOpTime);
  1666. auditEnum = GoodsAuditEnum.OutPending;
  1667. var changeStatus = await _sqlSugar
  1668. .Updateable<Pm_GoodsReceive>()
  1669. .SetColumns(x => new Pm_GoodsReceive()
  1670. {
  1671. AuditStatus = auditEnum,
  1672. AuditUserId = userId,
  1673. AuditTime = currUserOpDt,
  1674. StatusDesc = statusDesc
  1675. })
  1676. .Where(x => x.Id == receiveId)
  1677. .ExecuteCommandAsync();
  1678. if (changeStatus > 0)
  1679. {
  1680. _jv.Code = StatusCodes.Status200OK;
  1681. }
  1682. return _jv;
  1683. }
  1684. /// <summary>
  1685. /// 物品领用状态 - 领用拒绝
  1686. /// </summary>
  1687. /// <param name="preChangeStatus">更改前状态</param>
  1688. /// <param name="receiveId"></param>
  1689. /// <param name="userId"></param>
  1690. /// <param name="userName"></param>
  1691. /// <param name="auditEnum"></param>
  1692. /// <returns></returns>
  1693. public async Task<JsonView> GoodsReceiveUnApproved(GoodsAuditEnum preChangeStatus, int receiveId, int userId, string userName, GoodsAuditEnum auditEnum)
  1694. {
  1695. _jv.Code = StatusCodes.Status400BadRequest;
  1696. if (preChangeStatus != GoodsAuditEnum.Pending)
  1697. {
  1698. _jv.Msg = $"{GoodsAuditEnum.Pending.GetEnumDescription()},状态下可取消操作!";
  1699. return _jv;
  1700. }
  1701. auditEnum = GoodsAuditEnum.UnApproved;
  1702. var currUserOpDt = DateTime.Now;
  1703. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  1704. var statusDesc = string.Format(@"领用确认:状态:{0} 审核人:{1} 审核时间:{2};<br/>人事部确认:状态:待确认 审核人:- 审核时间:-;<br/>财务部认:状态:待确认 审核人:- 审核时间:-;<br/>", auditEnum.GetEnumDescription(), userName, currUserOpTime);
  1705. var changeStatus = await _sqlSugar
  1706. .Updateable<Pm_GoodsReceive>()
  1707. .SetColumns(x => new Pm_GoodsReceive()
  1708. {
  1709. AuditStatus = auditEnum,
  1710. AuditUserId = userId,
  1711. AuditTime = currUserOpDt,
  1712. StatusDesc = statusDesc
  1713. })
  1714. .Where(x => x.Id == receiveId)
  1715. .ExecuteCommandAsync();
  1716. if (changeStatus > 0)
  1717. {
  1718. _jv.Code = StatusCodes.Status200OK;
  1719. }
  1720. return _jv;
  1721. }
  1722. /// <summary>
  1723. /// 物品领用状态 - 出库待确认(出库确认、出库拒绝)
  1724. /// </summary>
  1725. /// <param name="preChangeStatus">更改前状态</param>
  1726. /// <param name="receiveId"></param>
  1727. /// <param name="userId"></param>
  1728. /// <param name="userName"></param>
  1729. /// <param name="auditEnum"></param>
  1730. /// <returns></returns>
  1731. public async Task<JsonView> GoodsReceiveOutPending(GoodsAuditEnum preChangeStatus, Pm_GoodsReceive receiveInfo, int userId, GoodsAuditDepEnum depEnum, GoodsAuditEnum auditEnum)
  1732. {
  1733. _jv.Code = StatusCodes.Status400BadRequest;
  1734. //出库待确认 操作范围
  1735. var audirEnumPers = new List<GoodsAuditEnum>() {
  1736. GoodsAuditEnum.OutConfirmed,
  1737. GoodsAuditEnum.OutRejected
  1738. };
  1739. if (!audirEnumPers.Contains(preChangeStatus))
  1740. {
  1741. _jv.Msg = $"{GoodsAuditEnum.OutConfirmed.GetEnumDescription()}、{GoodsAuditEnum.OutRejected.GetEnumDescription()},状态下可取消操作!";
  1742. return _jv;
  1743. }
  1744. var currUserOpDt = DateTime.Now;
  1745. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  1746. var auditInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  1747. .Where(x => x.IsDel == 0 && x.DataId == receiveInfo.Id && x.Type == 2)
  1748. .ToListAsync();
  1749. auditEnum = GoodsAuditEnum.OutPending;
  1750. var auditStatus = GoodsConfirmEnum.WaitConfirm;
  1751. var auditInfo = auditInfos.Find(x => x.Dep == depEnum);
  1752. if (auditInfo == null)
  1753. {
  1754. auditInfo = new Pm_GoodsAudit(2, depEnum, receiveInfo.Id, auditStatus, userId);
  1755. var addStatus = await _sqlSugar.Insertable(auditInfo).ExecuteCommandAsync();
  1756. if (addStatus < 1)
  1757. {
  1758. _jv.Msg = $"出库确认取消操作失败!";
  1759. return _jv;
  1760. }
  1761. auditInfos.Add(auditInfo);
  1762. }
  1763. else
  1764. {
  1765. //移除旧数据
  1766. auditInfos.Remove(auditInfo);
  1767. auditInfo.AuditStatus = auditStatus;
  1768. auditInfo.AuditUserId = userId;
  1769. auditInfo.AuditTime = currUserOpDt;
  1770. var updStatus = await _sqlSugar.Updateable<Pm_GoodsAudit>()
  1771. .SetColumns(x => new Pm_GoodsAudit()
  1772. {
  1773. AuditStatus = auditStatus,
  1774. AuditUserId = userId,
  1775. AuditTime = currUserOpDt
  1776. })
  1777. .Where(x => x.Id == auditInfo.Id)
  1778. .ExecuteCommandAsync();
  1779. if (updStatus < 1)
  1780. {
  1781. _jv.Msg = $"出库确认操作失败!";
  1782. return _jv;
  1783. }
  1784. //添加更新后的数据
  1785. auditInfos.Add(auditInfo);
  1786. }
  1787. //处理状态描述
  1788. StringBuilder statusDesc = new StringBuilder();
  1789. var receiveUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == receiveInfo.AuditUserId)?.CnName ?? "-";
  1790. string receiveStatusDesc = string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>",
  1791. "领用确认", GoodsAuditEnum.Approved.GetEnumDescription(), receiveUserName, receiveInfo.AuditTime.ToString("yyyy-MM-dd HH:mm:ss"));
  1792. statusDesc.Append(receiveStatusDesc);
  1793. foreach (var auditInf in auditInfos)
  1794. {
  1795. string userName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == auditInf.AuditUserId)?.CnName ?? "-";
  1796. string userOpTime = !userName.Equals("-") ? auditInf.AuditTime.ToString("yyyy-MM-dd HH:mm:ss") : "-";
  1797. string auditInfStatusDesc = string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>",
  1798. auditInf.Dep.GetEnumDescription(), auditInf.AuditStatus.GetEnumDescription(), userName, currUserOpTime);
  1799. statusDesc.Append(auditInfStatusDesc);
  1800. }
  1801. //批次库存信息
  1802. string goodsStorageInfo = receiveInfo.GoodsStorageInfo;
  1803. //出库确认取消是单独处理
  1804. if (preChangeStatus == GoodsAuditEnum.OutConfirming)
  1805. {
  1806. if (auditInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() == 1)
  1807. {
  1808. auditEnum = GoodsAuditEnum.OutConfirming;
  1809. }
  1810. //2.1 更改库存
  1811. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().Where(x => x.Id == receiveInfo.GoodsId).FirstAsync();
  1812. goodsInfo.StockQuantity -= receiveInfo.Quantity;
  1813. goodsInfo.OQ_Total += receiveInfo.Quantity;
  1814. goodsInfo.LastUpdateTime = DateTime.Now;
  1815. goodsInfo.LastUpdateUserId = userId;
  1816. var editGoods = await _sqlSugar
  1817. .Updateable(goodsInfo)
  1818. .UpdateColumns(x => new
  1819. {
  1820. x.StockQuantity,
  1821. x.OQ_Total,
  1822. x.LastUpdateUserId,
  1823. x.LastUpdateTime,
  1824. })
  1825. .Where(x => x.Id == receiveInfo.GoodsId)
  1826. .ExecuteCommandAsync();
  1827. if (editGoods < 1)
  1828. {
  1829. _jv.Msg = $"库存更新失败!";
  1830. return _jv;
  1831. }
  1832. //2.2 入库批次关联领用人 更改批次库存
  1833. var goodsStorages = await _sqlSugar
  1834. .Queryable<Pm_GoodsStorage>()
  1835. .Where(x => x.IsDel == 0 &&
  1836. x.GoodsId == receiveInfo.GoodsId &&
  1837. (x.Quantity - x.ReceiveQuantity) > 0
  1838. )
  1839. .OrderBy(x => x.CreateTime)
  1840. .ToListAsync();
  1841. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  1842. var batchStorageInfos = new List<Pm_GoodsStorage>();
  1843. var receiveQuantity = 0.00M; //领用总数量
  1844. foreach (var storage in goodsStorages)
  1845. {
  1846. if (receiveInfo.Quantity == receiveQuantity) break;
  1847. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  1848. if (thisBatchSurplusQuantity <= 0.00M) continue;
  1849. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  1850. const decimal unit = 0.50M;
  1851. while (receiveQuantity < receiveInfo.Quantity)
  1852. {
  1853. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  1854. thisBatchReceiveQuantity += unit;
  1855. receiveQuantity += unit;
  1856. }
  1857. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  1858. {
  1859. StorageId = storage.Id,
  1860. Quantity = thisBatchReceiveQuantity
  1861. });
  1862. storage.ReceiveQuantity += thisBatchReceiveQuantity;
  1863. var storageUpd = storage;
  1864. //storageUpd.ReceiveQuantity += thisBatchReceiveQuantity;
  1865. batchStorageInfos.Add(storageUpd);
  1866. }
  1867. //2.2.1 更改批次库存
  1868. if (goodsReceiveInfos.Count > 0)
  1869. {
  1870. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  1871. .UpdateColumns(x => x.ReceiveQuantity)
  1872. .WhereColumns(x => x.Id)
  1873. .ExecuteCommandAsync();
  1874. if (edit1 < 1)
  1875. {
  1876. _jv.Msg = $"批次库存更新失败!";
  1877. return _jv;
  1878. }
  1879. }
  1880. //2.2.2 添加入库批次关联领用人
  1881. if (goodsReceiveInfos.Count > 0)
  1882. {
  1883. goodsStorageInfo = JsonConvert.SerializeObject(goodsReceiveInfos);
  1884. }
  1885. }
  1886. var statusDesc1 = statusDesc.ToString();
  1887. var changeStatus = await _sqlSugar
  1888. .Updateable<Pm_GoodsReceive>()
  1889. .SetColumns(x => new Pm_GoodsReceive()
  1890. {
  1891. AuditStatus = auditEnum,
  1892. StatusDesc = statusDesc1,
  1893. GoodsStorageInfo = goodsStorageInfo
  1894. })
  1895. .Where(x => x.Id == receiveInfo.Id)
  1896. .ExecuteCommandAsync();
  1897. if (changeStatus > 0)
  1898. {
  1899. _jv.Code = StatusCodes.Status200OK;
  1900. }
  1901. return _jv;
  1902. }
  1903. /// <summary>
  1904. /// 物品领用状态 - 出库确认中、出库确认完成、出库确认拒绝
  1905. /// </summary>
  1906. /// <param name="receiveInfo"></param>
  1907. /// <param name="userId"></param>
  1908. /// <param name="depEnum"></param>
  1909. /// <param name="auditEnum"></param>
  1910. /// <returns></returns>
  1911. public async Task<JsonView> GoodsReceiveOutConfirming(Pm_GoodsReceive receiveInfo, int userId, GoodsAuditDepEnum depEnum, GoodsAuditEnum auditEnum)
  1912. {
  1913. _jv.Code = StatusCodes.Status400BadRequest;
  1914. //更改前状态
  1915. var preChangeStatus = receiveInfo.AuditStatus;
  1916. if (preChangeStatus < GoodsAuditEnum.OutPending)
  1917. {
  1918. _jv.Msg = $"领用确认执行成功!才可执行出库确认或出库拒绝操作!";
  1919. return _jv;
  1920. }
  1921. var currUserOpDt = DateTime.Now;
  1922. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  1923. var auditInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  1924. .Where(x => x.IsDel == 0 && x.DataId == receiveInfo.Id && x.Type == 2)
  1925. .ToListAsync();
  1926. var auditStatus = GoodsConfirmEnum.WaitConfirm;
  1927. if (auditEnum == GoodsAuditEnum.OutRejected) auditStatus = GoodsConfirmEnum.UnApproved;
  1928. else if (auditEnum == GoodsAuditEnum.OutConfirmed) auditStatus = GoodsConfirmEnum.Confirmed;
  1929. var auditInfo = auditInfos.Find(x => x.Dep == depEnum);
  1930. if (auditInfo == null)
  1931. {
  1932. auditInfo = new Pm_GoodsAudit(2, depEnum, receiveInfo.Id, auditStatus, userId);
  1933. var addStatus = await _sqlSugar.Insertable(auditInfo).ExecuteCommandAsync();
  1934. if (addStatus < 1)
  1935. {
  1936. _jv.Msg = $"出库确认操作失败!";
  1937. return _jv;
  1938. }
  1939. auditInfos.Add(auditInfo);
  1940. }
  1941. else
  1942. {
  1943. //移除旧数据
  1944. auditInfos.Remove(auditInfo);
  1945. auditInfo.AuditStatus = auditStatus;
  1946. auditInfo.AuditUserId = userId;
  1947. auditInfo.AuditTime = currUserOpDt;
  1948. var updStatus = await _sqlSugar.Updateable<Pm_GoodsAudit>()
  1949. .SetColumns(x => new Pm_GoodsAudit()
  1950. {
  1951. AuditStatus = auditStatus,
  1952. AuditUserId = userId,
  1953. AuditTime = currUserOpDt
  1954. })
  1955. .Where(x => x.Id == auditInfo.Id)
  1956. .ExecuteCommandAsync();
  1957. if (updStatus < 1)
  1958. {
  1959. _jv.Msg = $"出库确认操作失败!";
  1960. return _jv;
  1961. }
  1962. //添加更新后的数据
  1963. auditInfos.Add(auditInfo);
  1964. }
  1965. //处理状态描述
  1966. StringBuilder statusDesc = new StringBuilder();
  1967. var receiveUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == receiveInfo.AuditUserId)?.CnName ?? "-";
  1968. string receiveStatusDesc = string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>",
  1969. "领用确认", GoodsAuditEnum.Approved.GetEnumDescription(), receiveUserName, receiveInfo.AuditTime.ToString("yyyy-MM-dd HH:mm:ss"));
  1970. statusDesc.Append(receiveStatusDesc);
  1971. foreach (var auditInf in auditInfos)
  1972. {
  1973. string userName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == auditInf.AuditUserId)?.CnName ?? "-";
  1974. string userOpTime = !userName.Equals("-") ? auditInf.AuditTime.ToString("yyyy-MM-dd HH:mm:ss") : "-";
  1975. string auditInfStatusDesc = string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>",
  1976. auditInf.Dep.GetEnumDescription(), auditInf.AuditStatus.GetEnumDescription(), userName, currUserOpTime);
  1977. statusDesc.Append(auditInfStatusDesc);
  1978. }
  1979. if (preChangeStatus == auditEnum)
  1980. {
  1981. _jv.Msg = $"此操作已执行,不可重复操作!";
  1982. return _jv;
  1983. }
  1984. //批次库存信息
  1985. string goodsStorageInfo = receiveInfo.GoodsStorageInfo;
  1986. //更改领用状态及库存
  1987. if (auditInfos.Any(x => x.AuditStatus == GoodsConfirmEnum.UnApproved))
  1988. {
  1989. //出库确认拒绝
  1990. auditEnum = GoodsAuditEnum.OutRejected;
  1991. }
  1992. else if (auditInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() == 2)
  1993. {
  1994. //1.出库确认完成
  1995. auditEnum = GoodsAuditEnum.OutConfirmed;
  1996. //2.更改前的状态为出库确认中 且 更改后的状态为出库确认完成 执行库存减操作
  1997. if (preChangeStatus == GoodsAuditEnum.OutConfirming || preChangeStatus == GoodsAuditEnum.OutRejected)
  1998. {
  1999. //2.1 更改库存
  2000. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().Where(x => x.Id == receiveInfo.GoodsId).FirstAsync();
  2001. goodsInfo.StockQuantity -= receiveInfo.Quantity;
  2002. goodsInfo.OQ_Total += receiveInfo.Quantity;
  2003. goodsInfo.LastUpdateTime = DateTime.Now;
  2004. goodsInfo.LastUpdateUserId = userId;
  2005. var editGoods = await _sqlSugar
  2006. .Updateable(goodsInfo)
  2007. .UpdateColumns(x => new
  2008. {
  2009. x.StockQuantity,
  2010. x.OQ_Total,
  2011. x.LastUpdateUserId,
  2012. x.LastUpdateTime,
  2013. })
  2014. .Where(x => x.Id == receiveInfo.GoodsId)
  2015. .ExecuteCommandAsync();
  2016. if (editGoods < 1)
  2017. {
  2018. _jv.Msg = $"库存更新失败!";
  2019. return _jv;
  2020. }
  2021. //2.2 入库批次关联领用人 更改批次库存
  2022. var goodsStorages = await _sqlSugar
  2023. .Queryable<Pm_GoodsStorage>()
  2024. .Where(x => x.IsDel == 0 &&
  2025. x.GoodsId == receiveInfo.GoodsId &&
  2026. (x.Quantity - x.ReceiveQuantity) > 0
  2027. )
  2028. .OrderBy(x => x.CreateTime)
  2029. .ToListAsync();
  2030. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  2031. var batchStorageInfos = new List<Pm_GoodsStorage>();
  2032. var receiveQuantity = 0.00M; //领用总数量
  2033. foreach (var storage in goodsStorages)
  2034. {
  2035. if (receiveInfo.Quantity == receiveQuantity) break;
  2036. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  2037. if (thisBatchSurplusQuantity <= 0.00M) continue;
  2038. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  2039. const decimal unit = 0.50M;
  2040. while (receiveQuantity < receiveInfo.Quantity)
  2041. {
  2042. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  2043. thisBatchReceiveQuantity += unit;
  2044. receiveQuantity += unit;
  2045. }
  2046. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  2047. {
  2048. StorageId = storage.Id,
  2049. Quantity = thisBatchReceiveQuantity
  2050. });
  2051. storage.ReceiveQuantity += thisBatchReceiveQuantity;
  2052. var storageUpd = storage;
  2053. //storageUpd.ReceiveQuantity += thisBatchReceiveQuantity;
  2054. batchStorageInfos.Add(storageUpd);
  2055. }
  2056. //2.2.1 更改批次库存
  2057. if (goodsReceiveInfos.Count > 0)
  2058. {
  2059. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  2060. .UpdateColumns(x => x.ReceiveQuantity)
  2061. .WhereColumns(x => x.Id)
  2062. .ExecuteCommandAsync();
  2063. if (edit1 < 1)
  2064. {
  2065. _jv.Msg = $"批次库存更新失败!";
  2066. return _jv;
  2067. }
  2068. }
  2069. //2.2.2 添加入库批次关联领用人
  2070. if (goodsReceiveInfos.Count > 0)
  2071. {
  2072. goodsStorageInfo = JsonConvert.SerializeObject(goodsReceiveInfos);
  2073. }
  2074. }
  2075. }
  2076. else if (auditInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() == 1)
  2077. {
  2078. //出库确认中
  2079. auditEnum = GoodsAuditEnum.OutConfirming;
  2080. if (preChangeStatus == GoodsAuditEnum.OutConfirmed)
  2081. {
  2082. var goodsStorageInfo1 = receiveInfo.GoodsStorageInfo;
  2083. if (!string.IsNullOrEmpty(goodsStorageInfo))
  2084. {
  2085. var goodsStorageInfos = JsonConvert.DeserializeObject<List<GoodsReceiveLinkStorageView>>(goodsStorageInfo);
  2086. if (goodsStorageInfos.Any())
  2087. {
  2088. foreach (var item in goodsStorageInfos)
  2089. {
  2090. var newStorageInfo = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  2091. .Where(x => x.IsDel == 0 && x.Id == item.StorageId)
  2092. .FirstAsync();
  2093. if (newStorageInfo == null) continue;
  2094. var newEdit = await _sqlSugar.Updateable(newStorageInfo)
  2095. .ReSetValue(x => x.ReceiveQuantity = x.ReceiveQuantity - item.Quantity)
  2096. .ExecuteCommandAsync();
  2097. if (newEdit < 1)
  2098. {
  2099. _jv.Msg = $"批次领用库存更新失败!";
  2100. return _jv;
  2101. }
  2102. }
  2103. }
  2104. }
  2105. }
  2106. }
  2107. else
  2108. {
  2109. auditEnum = GoodsAuditEnum.OutPending;
  2110. }
  2111. var statusDesc1 = statusDesc.ToString();
  2112. var changeStatus = await _sqlSugar
  2113. .Updateable<Pm_GoodsReceive>()
  2114. .SetColumns(x => new Pm_GoodsReceive()
  2115. {
  2116. AuditStatus = auditEnum,
  2117. StatusDesc = statusDesc1,
  2118. GoodsStorageInfo = goodsStorageInfo,
  2119. })
  2120. .Where(x => x.Id == receiveInfo.Id)
  2121. .ExecuteCommandAsync();
  2122. if (changeStatus > 0)
  2123. {
  2124. _jv.Code = StatusCodes.Status200OK;
  2125. }
  2126. return _jv;
  2127. }
  2128. /// <summary>
  2129. ///
  2130. /// </summary>
  2131. /// <param name="receiveInfo"></param>
  2132. /// <param name="userId"></param>
  2133. /// <param name="depEnum"></param>
  2134. /// <param name="auditEnum"></param>
  2135. /// <returns></returns>
  2136. public async Task<JsonView> GoodsReceiveOutConfirmingMultiple(Pm_GoodsReceive receiveInfo, int userId, GoodsAuditDepEnum depEnum, GoodsAuditEnum auditEnum)
  2137. {
  2138. _jv.Code = StatusCodes.Status400BadRequest;
  2139. //更改前状态
  2140. receiveInfo.CreateUserId = userId;
  2141. var preChangeStatus = receiveInfo.AuditStatus;
  2142. var currUserOpDt = DateTime.Now;
  2143. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  2144. var receiveUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == receiveInfo.AuditUserId)?.CnName ?? "-";
  2145. var auditInfos = await _sqlSugar.Queryable<Pm_GoodsAudit>()
  2146. .Where(x => x.IsDel == 0 && x.DataId == receiveInfo.Id && x.Type == 2)
  2147. .ToListAsync();
  2148. var auditStatus = GoodsConfirmEnum.WaitConfirm;
  2149. if (auditEnum == GoodsAuditEnum.UnApproved) auditStatus = GoodsConfirmEnum.UnApproved;
  2150. else if (auditEnum == GoodsAuditEnum.Approved) auditStatus = GoodsConfirmEnum.Confirmed;
  2151. var auditInfo = auditInfos.Find(x => x.Dep == depEnum);
  2152. if (auditInfo == null)
  2153. {
  2154. auditInfo = new Pm_GoodsAudit(2, depEnum, receiveInfo.Id, auditStatus, userId);
  2155. auditInfo.AuditUserId = userId;
  2156. var addStatus = await _sqlSugar.Insertable(auditInfo).ExecuteCommandAsync();
  2157. if (addStatus < 1)
  2158. {
  2159. _jv.Msg = $"出库确认操作失败!";
  2160. return _jv;
  2161. }
  2162. auditInfos.Add(auditInfo);
  2163. }
  2164. else
  2165. {
  2166. //移除旧数据
  2167. auditInfos.Remove(auditInfo);
  2168. auditInfo.AuditStatus = auditStatus;
  2169. auditInfo.AuditUserId = userId;
  2170. auditInfo.AuditTime = currUserOpDt;
  2171. var updStatus = await _sqlSugar.Updateable<Pm_GoodsAudit>()
  2172. .SetColumns(x => new Pm_GoodsAudit()
  2173. {
  2174. AuditStatus = auditStatus,
  2175. AuditUserId = userId,
  2176. AuditTime = currUserOpDt
  2177. })
  2178. .Where(x => x.Id == auditInfo.Id)
  2179. .ExecuteCommandAsync();
  2180. if (updStatus < 1)
  2181. {
  2182. _jv.Msg = $"出库确认操作失败!";
  2183. return _jv;
  2184. }
  2185. //添加更新后的数据
  2186. auditInfos.Add(auditInfo);
  2187. }
  2188. auditInfos = auditInfos.OrderBy(x => x.Dep).ToList();
  2189. //处理状态描述
  2190. StringBuilder statusDesc = new StringBuilder();
  2191. foreach (var auditInf in auditInfos)
  2192. {
  2193. string auditType = auditInf.Dep == GoodsAuditDepEnum.Hr ? "人事部" : "领用确认";
  2194. string userName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == auditInf.AuditUserId)?.CnName ?? "-";
  2195. string userOpTime = !userName.Equals("-") ? auditInf.AuditTime.ToString("yyyy-MM-dd HH:mm:ss") : "-";
  2196. string auditInfStatusDesc = string.Format("{0}:状态:{1} 审核人:{2} 审核时间:{3};<br/>",
  2197. auditType, auditInf.AuditStatus.GetEnumDescription(), userName, currUserOpTime);
  2198. statusDesc.Append(auditInfStatusDesc);
  2199. }
  2200. if (preChangeStatus == auditEnum)
  2201. {
  2202. _jv.Msg = $"此操作已执行,不可重复操作!";
  2203. return _jv;
  2204. }
  2205. //批次库存信息
  2206. string goodsStorageInfo = receiveInfo.GoodsStorageInfo;
  2207. //更改领用状态及库存
  2208. if (auditInfos.Any(x => x.AuditStatus == GoodsConfirmEnum.UnApproved))
  2209. {
  2210. //出库确认拒绝
  2211. auditEnum = GoodsAuditEnum.OutRejected;
  2212. if (preChangeStatus == GoodsAuditEnum.OutConfirmed)
  2213. {
  2214. //回滚库存
  2215. _jv = await GoodsInventoryRollback(receiveInfo);
  2216. if (_jv.Code != StatusCodes.Status200OK) return _jv;
  2217. }
  2218. }
  2219. else if (auditInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() == 2)
  2220. {
  2221. //1.出库确认完成
  2222. auditEnum = GoodsAuditEnum.OutConfirmed;
  2223. //2.更改前的状态为出库确认中 且 更改后的状态为出库确认完成 执行库存减操作
  2224. if (preChangeStatus == GoodsAuditEnum.OutConfirming || preChangeStatus == GoodsAuditEnum.OutRejected)
  2225. {
  2226. //2.1 更改库存
  2227. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().Where(x => x.Id == receiveInfo.GoodsId).FirstAsync();
  2228. goodsInfo.StockQuantity -= receiveInfo.Quantity;
  2229. goodsInfo.OQ_Total += receiveInfo.Quantity;
  2230. goodsInfo.LastUpdateTime = DateTime.Now;
  2231. goodsInfo.LastUpdateUserId = userId;
  2232. var editGoods = await _sqlSugar
  2233. .Updateable(goodsInfo)
  2234. .UpdateColumns(x => new
  2235. {
  2236. x.StockQuantity,
  2237. x.OQ_Total,
  2238. x.LastUpdateUserId,
  2239. x.LastUpdateTime,
  2240. })
  2241. .Where(x => x.Id == receiveInfo.GoodsId)
  2242. .ExecuteCommandAsync();
  2243. if (editGoods < 1)
  2244. {
  2245. _jv.Msg = $"库存更新失败!";
  2246. return _jv;
  2247. }
  2248. //2.2 入库批次关联领用人 更改批次库存
  2249. var goodsStorages = await _sqlSugar
  2250. .Queryable<Pm_GoodsStorage>()
  2251. .Where(x => x.IsDel == 0 &&
  2252. x.GoodsId == receiveInfo.GoodsId &&
  2253. (x.Quantity - x.ReceiveQuantity) > 0
  2254. )
  2255. .OrderBy(x => x.CreateTime)
  2256. .ToListAsync();
  2257. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  2258. var batchStorageInfos = new List<Pm_GoodsStorage>();
  2259. var receiveQuantity = 0.00M; //领用总数量
  2260. foreach (var storage in goodsStorages)
  2261. {
  2262. if (receiveInfo.Quantity == receiveQuantity) break;
  2263. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  2264. if (thisBatchSurplusQuantity <= 0.00M) continue;
  2265. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  2266. const decimal unit = 0.50M;
  2267. while (receiveQuantity < receiveInfo.Quantity)
  2268. {
  2269. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  2270. thisBatchReceiveQuantity += unit;
  2271. receiveQuantity += unit;
  2272. }
  2273. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  2274. {
  2275. StorageId = storage.Id,
  2276. Quantity = thisBatchReceiveQuantity
  2277. });
  2278. storage.ReceiveQuantity += thisBatchReceiveQuantity;
  2279. var storageUpd = storage;
  2280. //storageUpd.ReceiveQuantity += thisBatchReceiveQuantity;
  2281. batchStorageInfos.Add(storageUpd);
  2282. }
  2283. //2.2.1 更改批次库存
  2284. if (goodsReceiveInfos.Count > 0)
  2285. {
  2286. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  2287. .UpdateColumns(x => x.ReceiveQuantity)
  2288. .WhereColumns(x => x.Id)
  2289. .ExecuteCommandAsync();
  2290. if (edit1 < 1)
  2291. {
  2292. _jv.Msg = $"批次库存更新失败!";
  2293. return _jv;
  2294. }
  2295. }
  2296. //2.2.2 添加入库批次关联领用人
  2297. if (goodsReceiveInfos.Count > 0)
  2298. {
  2299. goodsStorageInfo = JsonConvert.SerializeObject(goodsReceiveInfos);
  2300. }
  2301. }
  2302. }
  2303. else if (auditInfos.Where(x => x.AuditStatus == GoodsConfirmEnum.Confirmed).Count() == 1)
  2304. {
  2305. //出库确认中
  2306. auditEnum = GoodsAuditEnum.OutConfirming;
  2307. if (preChangeStatus == GoodsAuditEnum.OutConfirmed)
  2308. {
  2309. //回滚库存
  2310. _jv = await GoodsInventoryRollback(receiveInfo);
  2311. if (_jv.Code != StatusCodes.Status200OK) return _jv;
  2312. }
  2313. }
  2314. else auditEnum = GoodsAuditEnum.OutPending;
  2315. var statusDesc1 = statusDesc.ToString();
  2316. var changeStatus = await _sqlSugar
  2317. .Updateable<Pm_GoodsReceive>()
  2318. .SetColumns(x => new Pm_GoodsReceive()
  2319. {
  2320. AuditStatus = auditEnum,
  2321. StatusDesc = statusDesc1,
  2322. GoodsStorageInfo = goodsStorageInfo,
  2323. })
  2324. .Where(x => x.Id == receiveInfo.Id)
  2325. .ExecuteCommandAsync();
  2326. if (changeStatus > 0)
  2327. {
  2328. _jv.Code = StatusCodes.Status200OK;
  2329. }
  2330. return _jv;
  2331. }
  2332. /// <summary>
  2333. /// 物品库存回滚
  2334. /// </summary>
  2335. /// <param name="receiveInfo"></param>
  2336. /// <returns></returns>
  2337. public async Task<JsonView> GoodsInventoryRollback(Pm_GoodsReceive receiveInfo)
  2338. {
  2339. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == receiveInfo.GoodsId);
  2340. //回滚库存
  2341. var changeGoods = await _sqlSugar
  2342. .Updateable(goodsInfo)
  2343. .ReSetValue(it => {
  2344. it.StockQuantity += receiveInfo.Quantity;
  2345. it.OQ_Total -= receiveInfo.Quantity;
  2346. it.LastUpdateTime = DateTime.Now;
  2347. it.LastUpdateUserId = receiveInfo.CreateUserId;
  2348. })
  2349. .ExecuteCommandAsync();
  2350. if (changeGoods < 1)
  2351. {
  2352. _jv.Msg = $"库存回滚失败!";
  2353. return _jv;
  2354. }
  2355. //批次领用记录
  2356. _jv.Code = StatusCodes.Status200OK;
  2357. var goodsStorageInfo = receiveInfo.GoodsStorageInfo;
  2358. if (string.IsNullOrEmpty(goodsStorageInfo)) return _jv;
  2359. var goodsStorageInfos = JsonConvert.DeserializeObject<List<GoodsReceiveLinkStorageView>>(goodsStorageInfo);
  2360. if (!goodsStorageInfos.Any()) return _jv;
  2361. foreach (var item in goodsStorageInfos)
  2362. {
  2363. var newStorageInfo = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  2364. .Where(x => x.IsDel == 0 && x.Id == item.StorageId)
  2365. .FirstAsync();
  2366. if (newStorageInfo == null) continue;
  2367. var newEdit = await _sqlSugar.Updateable(newStorageInfo)
  2368. .ReSetValue(x => x.ReceiveQuantity = x.ReceiveQuantity - item.Quantity)
  2369. .ExecuteCommandAsync();
  2370. if (newEdit < 1)
  2371. {
  2372. _jv.Code = StatusCodes.Status400BadRequest;
  2373. _jv.Msg = $"批次领用库存更新失败!";
  2374. return _jv;
  2375. }
  2376. }
  2377. _jv.Code = StatusCodes.Status200OK;
  2378. return _jv;
  2379. }
  2380. #endregion
  2381. #region 单人审核状态变更
  2382. /// <summary>
  2383. /// 物品领用状态 - 出库确认完成、出库确认拒绝
  2384. /// </summary>
  2385. /// <param name="receiveInfo"></param>
  2386. /// <param name="userId"></param>
  2387. /// <param name="currUserName"></param>
  2388. /// <param name="auditEnum"></param>
  2389. /// <returns></returns>
  2390. public async Task<JsonView> GoodsReceiveOutConfirmingSingle(Pm_GoodsReceive receiveInfo, int userId,string currUserName,GoodsAuditEnum auditEnum)
  2391. {
  2392. _jv.Code = StatusCodes.Status400BadRequest;
  2393. //状态操作范围验证
  2394. var auditEnums = new List<GoodsAuditEnum>() {
  2395. GoodsAuditEnum.Pending,
  2396. GoodsAuditEnum.Approved,
  2397. GoodsAuditEnum.UnApproved,
  2398. };
  2399. if (!auditEnums.Contains(auditEnum))
  2400. {
  2401. _jv.Msg = $"{GoodsAuditEnum.Pending.GetEnumDescription()}、{GoodsAuditEnum.OutConfirmed.GetEnumDescription()}、{GoodsAuditEnum.OutRejected.GetEnumDescription()},状态下可操作!";
  2402. return _jv;
  2403. }
  2404. var currUserOpDt = DateTime.Now;
  2405. var currUserOpTime = currUserOpDt.ToString("yyyy-MM-dd HH:mm:ss");
  2406. //更改前状态
  2407. var preChangeStatus = receiveInfo.AuditStatus;
  2408. //前台状态验证
  2409. var auditInfo = await _sqlSugar.Queryable<Pm_GoodsAudit>().FirstAsync(x => x.IsDel == 0 && x.Type == 2 && x.DataId == receiveInfo.Id);
  2410. if (auditInfo == null)
  2411. {
  2412. var addInfo = new Pm_GoodsAudit(2, GoodsAuditDepEnum.Hr_Reception, receiveInfo.Id, GoodsConfirmEnum.WaitConfirm, userId);
  2413. auditInfo = await _sqlSugar.Insertable(addInfo).ExecuteReturnEntityAsync();
  2414. if (auditInfo == null)
  2415. {
  2416. _jv.Msg = $"确认操作失败!";
  2417. return _jv;
  2418. }
  2419. }
  2420. if (auditEnum == GoodsAuditEnum.Approved)
  2421. {
  2422. auditInfo.AuditStatus = GoodsConfirmEnum.Confirmed;
  2423. auditEnum = GoodsAuditEnum.OutConfirmed;
  2424. }
  2425. else if (auditEnum == GoodsAuditEnum.UnApproved)
  2426. {
  2427. auditInfo.AuditStatus = GoodsConfirmEnum.UnApproved;
  2428. auditEnum = GoodsAuditEnum.OutRejected;
  2429. }
  2430. if (preChangeStatus == auditEnum)
  2431. {
  2432. _jv.Msg = $"此操作已执行,不可重复操作!";
  2433. return _jv;
  2434. }
  2435. //更新子表审核状态
  2436. var updStatus = await _sqlSugar.Updateable<Pm_GoodsAudit>()
  2437. .SetColumns(x => new Pm_GoodsAudit()
  2438. {
  2439. AuditStatus = auditInfo.AuditStatus,
  2440. AuditUserId = userId,
  2441. AuditTime = currUserOpDt
  2442. })
  2443. .Where(x => x.Id == auditInfo.Id)
  2444. .ExecuteCommandAsync();
  2445. if (updStatus < 1)
  2446. {
  2447. _jv.Msg = $"确认操作失败!";
  2448. return _jv;
  2449. }
  2450. //处理状态描述
  2451. StringBuilder statusDesc = new StringBuilder();
  2452. statusDesc.Append(string.Format("领用确认:状态:{0} 审核人:{1} 审核时间:{2};", auditInfo.AuditStatus.GetEnumDescription(), currUserName, currUserOpTime));
  2453. //批次库存信息
  2454. string goodsStorageInfo = receiveInfo.GoodsStorageInfo;
  2455. if (auditEnum == GoodsAuditEnum.OutConfirmed) //出库确认
  2456. {
  2457. //1 更改库存
  2458. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().Where(x => x.Id == receiveInfo.GoodsId).FirstAsync();
  2459. goodsInfo.StockQuantity -= receiveInfo.Quantity;
  2460. goodsInfo.OQ_Total += receiveInfo.Quantity;
  2461. goodsInfo.LastUpdateTime = DateTime.Now;
  2462. goodsInfo.LastUpdateUserId = userId;
  2463. var editGoods = await _sqlSugar.Updateable(goodsInfo)
  2464. .UpdateColumns(x => new
  2465. {
  2466. x.StockQuantity,
  2467. x.OQ_Total,
  2468. x.LastUpdateUserId,
  2469. x.LastUpdateTime,
  2470. })
  2471. .Where(x => x.Id == receiveInfo.GoodsId)
  2472. .ExecuteCommandAsync();
  2473. if (editGoods < 1)
  2474. {
  2475. _jv.Msg = $"库存更新失败!";
  2476. return _jv;
  2477. }
  2478. //2 入库批次关联领用人 更改批次库存
  2479. var goodsStorages = await _sqlSugar
  2480. .Queryable<Pm_GoodsStorage>()
  2481. .Where(x => x.IsDel == 0 &&
  2482. x.GoodsId == receiveInfo.GoodsId &&
  2483. (x.Quantity - x.ReceiveQuantity) > 0
  2484. )
  2485. .OrderBy(x => x.CreateTime)
  2486. .ToListAsync();
  2487. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  2488. var batchStorageInfos = new List<Pm_GoodsStorage>();
  2489. var receiveQuantity = 0.00M; //领用总数量
  2490. foreach (var storage in goodsStorages)
  2491. {
  2492. if (receiveInfo.Quantity == receiveQuantity) break;
  2493. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  2494. if (thisBatchSurplusQuantity <= 0.00M) continue;
  2495. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  2496. const decimal unit = 0.50M;
  2497. while (receiveQuantity < receiveInfo.Quantity)
  2498. {
  2499. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  2500. thisBatchReceiveQuantity += unit;
  2501. receiveQuantity += unit;
  2502. }
  2503. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  2504. {
  2505. StorageId = storage.Id,
  2506. Quantity = thisBatchReceiveQuantity
  2507. });
  2508. storage.ReceiveQuantity += thisBatchReceiveQuantity;
  2509. var storageUpd = storage;
  2510. //storageUpd.ReceiveQuantity += thisBatchReceiveQuantity;
  2511. batchStorageInfos.Add(storageUpd);
  2512. }
  2513. //3 更改批次库存
  2514. if (goodsReceiveInfos.Count > 0)
  2515. {
  2516. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  2517. .UpdateColumns(x => x.ReceiveQuantity)
  2518. .WhereColumns(x => x.Id)
  2519. .ExecuteCommandAsync();
  2520. if (edit1 < 1)
  2521. {
  2522. _jv.Msg = $"批次库存更新失败!";
  2523. return _jv;
  2524. }
  2525. }
  2526. //4 添加入库批次关联领用人
  2527. if (goodsReceiveInfos.Count > 0)
  2528. {
  2529. goodsStorageInfo = JsonConvert.SerializeObject(goodsReceiveInfos);
  2530. }
  2531. }
  2532. else if (auditEnum == GoodsAuditEnum.OutRejected) //出库拒绝
  2533. {
  2534. //拒绝之前的状态为已完成 回滚库存
  2535. if (preChangeStatus == GoodsAuditEnum.OutConfirmed)
  2536. {
  2537. //回滚库存
  2538. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == receiveInfo.GoodsId);
  2539. var changeGoods = await _sqlSugar
  2540. .Updateable(goodsInfo)
  2541. .ReSetValue(it => {
  2542. it.StockQuantity += receiveInfo.Quantity;
  2543. it.OQ_Total -= receiveInfo.Quantity;
  2544. it.LastUpdateTime = DateTime.Now;
  2545. it.LastUpdateUserId = userId;
  2546. })
  2547. .ExecuteCommandAsync();
  2548. if (changeGoods < 1)
  2549. {
  2550. _jv.Msg = $"库存回滚失败!";
  2551. return _jv;
  2552. }
  2553. //批次号库存 信息更新
  2554. var goodsStorageInfo1 = receiveInfo.GoodsStorageInfo;
  2555. if (!string.IsNullOrEmpty(goodsStorageInfo))
  2556. {
  2557. var goodsStorageInfos = JsonConvert.DeserializeObject<List<GoodsReceiveLinkStorageView>>(goodsStorageInfo);
  2558. if (goodsStorageInfos.Any())
  2559. {
  2560. foreach (var item in goodsStorageInfos)
  2561. {
  2562. var newStorageInfo = await _sqlSugar.Queryable<Pm_GoodsStorage>()
  2563. .Where(x => x.IsDel == 0 && x.Id == item.StorageId)
  2564. .FirstAsync();
  2565. if (newStorageInfo == null) continue;
  2566. var newEdit = await _sqlSugar.Updateable(newStorageInfo)
  2567. .ReSetValue(x => x.ReceiveQuantity = x.ReceiveQuantity - item.Quantity)
  2568. .ExecuteCommandAsync();
  2569. if (newEdit < 1)
  2570. {
  2571. _jv.Msg = $"批次领用库存更新失败!";
  2572. return _jv;
  2573. }
  2574. }
  2575. }
  2576. }
  2577. }
  2578. }
  2579. var statusDesc1 = statusDesc.ToString();
  2580. var changeStatus = await _sqlSugar
  2581. .Updateable<Pm_GoodsReceive>()
  2582. .SetColumns(x => new Pm_GoodsReceive()
  2583. {
  2584. AuditStatus = auditEnum,
  2585. StatusDesc = statusDesc1,
  2586. GoodsStorageInfo = goodsStorageInfo,
  2587. })
  2588. .Where(x => x.Id == receiveInfo.Id)
  2589. .ExecuteCommandAsync();
  2590. if (changeStatus > 0) _jv.Code = StatusCodes.Status200OK;
  2591. return _jv;
  2592. }
  2593. #endregion
  2594. /// <summary>
  2595. /// 物品领用 Del
  2596. /// </summary>
  2597. /// <param name="id"></param>
  2598. /// <param name="currUserId"></param>
  2599. /// <returns></returns>
  2600. public async Task<JsonView> GoodsReceiveDel(int id, int currUserId)
  2601. {
  2602. var receiveInfo = await _sqlSugar
  2603. .Queryable<Pm_GoodsReceive>()
  2604. .Where(x => x.IsDel == 0 && x.Id == id)
  2605. .FirstAsync();
  2606. if (receiveInfo.AuditStatus >= GoodsAuditEnum.Approved)
  2607. {
  2608. _jv.Msg = $"该条数据已进入审批流程,不可删除!";
  2609. return _jv;
  2610. }
  2611. var edit = await _sqlSugar
  2612. .Updateable<Pm_GoodsReceive>()
  2613. .SetColumns(x => new Pm_GoodsReceive()
  2614. {
  2615. IsDel = 1,
  2616. DeleteUserId = currUserId,
  2617. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  2618. })
  2619. .Where(x => x.Id == id)
  2620. .ExecuteCommandAsync();
  2621. if (edit > 0)
  2622. {
  2623. _jv.Msg = $"操作成功!";
  2624. _jv.Code = StatusCodes.Status200OK;
  2625. return _jv;
  2626. }
  2627. return _jv;
  2628. }
  2629. #region New 物品领用、审核
  2630. /// <summary>
  2631. /// 物品领用审核列表
  2632. /// </summary>
  2633. /// <param name="dto"></param>
  2634. /// <returns></returns>
  2635. public async Task<JsonView> GoodsReceiveAuditList(GoodsReceiveAuditListDTO dto)
  2636. {
  2637. var currUserId = dto.CurrUserId;
  2638. var auditStatus = dto.AuditStatus;
  2639. var goodsName = dto.GoodsName;
  2640. var sql = string.Format(@"SELECT
  2641. ROW_NUMBER() OVER (ORDER BY CreateTime DESC) AS RowNumber,
  2642. *
  2643. FROM
  2644. (
  2645. Select
  2646. gr.Id,
  2647. gr.GroupId,
  2648. CASE
  2649. WHEN gr.GroupId = 0 THEN '其他物资(公司内部物资)'
  2650. WHEN gr.GroupId = -1 THEN '拜访客户所使用的物资'
  2651. WHEN gr.GroupId = -2 THEN '库存调整'
  2652. ELSE di.TeamName
  2653. END [GroupName],
  2654. gr.GoodsId,
  2655. CASE
  2656. WHEN gr.GoodsId = 0 THEN gr.GoodsName
  2657. ELSE gi.Name
  2658. END [GoodsName],
  2659. gi.Type [GoodsTypeId],
  2660. sd.Name [GoodsType],
  2661. CASE
  2662. WHEN gi.Type = 0
  2663. OR gi.Type IS NULL THEN CASE
  2664. WHEN af.TemplateId = 3 THEN 1
  2665. ELSE 0
  2666. END
  2667. WHEN gi.Type = 1423 THEN 1
  2668. ELSE 0
  2669. END [IsValuable],
  2670. gr.Quantity,
  2671. gi.Unit,
  2672. gr.Reason,
  2673. gr.Remark,
  2674. gr.AuditStatus,
  2675. gr.StatusDesc,
  2676. gr.AuditUserId,
  2677. u1.CnName [AuditUserName],
  2678. gr.AuditTime,
  2679. u2.CnName [CreateUserName],
  2680. gr.CreateTime
  2681. FROM
  2682. OA2023DB.dbo.Pm_GoodsReceive gr
  2683. LEFT JOIN Pm_GoodsInfo gi ON gr.GoodsId = gi.Id
  2684. LEFT JOIN Grp_DelegationInfo di ON gr.GroupId = di.Id
  2685. LEFT JOIN Sys_Users u1 ON gr.AuditUserId = u1.Id
  2686. LEFT JOIN Sys_Users u2 ON gr.CreateUserId = u2.Id
  2687. LEFT JOIN Sys_AuditFlow af ON gr.Id = af.BusinessId
  2688. LEFT JOIN Sys_SetData sd ON gi.Type = sd.Id
  2689. WHERE
  2690. gr.IsDel = 0
  2691. ) Temp ");
  2692. var isValueable = false;
  2693. if (currUserId == 343) //陈湘OAId登录 只显示贵重物品审核信息
  2694. {
  2695. isValueable = true;
  2696. }
  2697. RefAsync<int> total = 0;
  2698. var view = await _sqlSugar.SqlQueryable<GoodsReceiveListMobileView>(sql)
  2699. .WhereIF(isValueable, x => x.IsValuable == true)
  2700. .WhereIF(!string.IsNullOrEmpty(goodsName), x => x.GoodsName.Contains(goodsName))
  2701. .ToPageListAsync(dto.PageIndex, dto.PageSize, total);
  2702. //普通物品领用审核模板
  2703. var normAuditTemps = await _approvalProcessRep.GetTemplateByBusinessTypeAsync(2); //普通物品
  2704. var normAuditUsers = new List<GoodsStorageAuditPerView>();
  2705. normAuditTemps?.TempNodes.ForEach(x =>
  2706. {
  2707. var auditDep = GoodsAuditDepEnum.Hr_Reception;
  2708. if (x.NodeName.Contains("人事部主管/经理审核")) auditDep = GoodsAuditDepEnum.Hr;
  2709. else if (x.NodeName.Contains("前台审核")) auditDep = GoodsAuditDepEnum.Hr;
  2710. x.NodeUsers.ForEach(y =>
  2711. {
  2712. var userFlang = false;
  2713. if (y.UserId == currUserId) userFlang = true;
  2714. var info = new GoodsStorageAuditPerView() { ButtonText = x.NodeName, AuditDep = auditDep, AuditPer = userFlang };
  2715. normAuditUsers.Add(info);
  2716. });
  2717. });
  2718. //贵重物品领用审核模板
  2719. var valuableAuditTemps = await _approvalProcessRep.GetTemplateByBusinessTypeAsync(3); //贵重物品
  2720. var valuableAuditUsers = new List<GoodsStorageAuditPerView>();
  2721. valuableAuditTemps?.TempNodes.ForEach(x =>
  2722. {
  2723. var auditDep = GoodsAuditDepEnum.Hr_Reception;
  2724. if (x.NodeName.Contains("人事部主管/经理审核")) auditDep = GoodsAuditDepEnum.Hr;
  2725. else if (x.NodeName.Contains("前台审核")) auditDep = GoodsAuditDepEnum.Hr;
  2726. x.NodeUsers.ForEach(y =>
  2727. {
  2728. var userFlang = false;
  2729. if (y.UserId == currUserId) userFlang = true;
  2730. var info = new GoodsStorageAuditPerView() { ButtonText = x.NodeName, AuditDep = auditDep, AuditPer = userFlang };
  2731. valuableAuditUsers.Add(info);
  2732. });
  2733. });
  2734. foreach (var item in view)
  2735. {
  2736. var details = $"暂无物品信息数据";
  2737. //设置领用详情
  2738. if (item.GoodsTypeId < 1)
  2739. {
  2740. var detailsData = await _sqlSugar.Queryable<Pm_GoodsReceiveDetails>()
  2741. .LeftJoin<Pm_GoodsInfo>((grd, gi) => grd.GoodsId == gi.Id)
  2742. .LeftJoin<Sys_SetData>((grd, gi, sd) => gi.Type == sd.Id)
  2743. .Where((grd, gi, sd) => grd.IsDel == 0 && grd.GoodsReceiveId == item.Id)
  2744. .Select((grd, gi, sd) => new
  2745. {
  2746. gi.Name,
  2747. TypeName = sd.Name,
  2748. grd.Quantity,
  2749. grd.Remark
  2750. })
  2751. .ToListAsync();
  2752. if (detailsData.Any())
  2753. {
  2754. //设置领用数量 多个物品 计算领用合计
  2755. item.Quantity = detailsData.Sum(x => x.Quantity);
  2756. var text = new StringBuilder();
  2757. text.Append($"归属团组:{item.GroupName} <br/><br/>");
  2758. detailsData.ForEach(x =>
  2759. {
  2760. var str = $"物品名称:{x.Name} 物品类型:{x.TypeName} 领用数量:{x.Quantity} 备注:{x.Remark}<br/>";
  2761. text.Append(str);
  2762. });
  2763. details = text.ToString();
  2764. }
  2765. }
  2766. else details = $"归属团组/类型:{item.GroupName} <br/><br/>物品名称:{item.GoodsName} 物品类型:{item.GoodsType} 领用数量:{item.Quantity} 备注:{item.Remark}<br/>";
  2767. item.GoodsDetails = details;
  2768. //设置领用状态描述
  2769. var auditRecords = await _sqlSugar.Queryable<Sys_AuditRecord>()
  2770. .InnerJoin<Sys_AuditFlow>((ar,af) => ar.FlowId == af.Id)
  2771. .Where((ar, af) => ar.IsDel == 0 && af.BusinessId == item.Id && af.BusinessType == 1)
  2772. .Select((ar, af) => new {
  2773. NodeId = ar.NodeId,
  2774. ar.NodeName,
  2775. ar.AuditResult,
  2776. ar.AuditorName,
  2777. ar.AuditTime
  2778. })
  2779. //.OrderBy((ar, af) => ar.AuditTime)
  2780. .ToListAsync();
  2781. if (auditRecords.Any())
  2782. {
  2783. var text = new StringBuilder();
  2784. auditRecords.ForEach(x =>
  2785. {
  2786. var statusText = x.AuditResult switch {
  2787. 0 => "待审核",
  2788. 1 => "已审核",
  2789. 2 => "已拒绝",
  2790. 3 => "无需处理",
  2791. _ => "未知"
  2792. };
  2793. var str = $"{x.NodeName}:状态:{statusText} 审核人:{x.AuditorName} 审核时间:{x.AuditTime.ToString("yyyy-MM-dd HH:mm:ss")}<br/>";
  2794. text.Append(str);
  2795. });
  2796. item.StatusDesc = text.ToString();
  2797. }
  2798. //多情况下审核、操作权限验证
  2799. if (item.GoodsTypeId == 0)
  2800. {
  2801. int tempId = 2;
  2802. if (item.IsValuable) tempId = 3;
  2803. item.IsAuditPer = await _approvalProcessRep.VerifyAuditAuthAsync(tempId, 1, item.Id, currUserId);
  2804. }
  2805. else
  2806. {
  2807. if (item.AuditStatus == GoodsAuditEnum.Pending)
  2808. {
  2809. item.IsAuditPer = normAuditTemps?.TempNodes.FirstOrDefault()?.NodeUsers.Any(x => x.UserId == currUserId) ?? false;
  2810. }
  2811. else if (item.AuditStatus == GoodsAuditEnum.OutConfirming)
  2812. {
  2813. item.IsAuditPer = valuableAuditTemps?.TempNodes.FirstOrDefault(x=> x.NodeOrder == 1)?.NodeUsers.Any(x => x.UserId == currUserId) ?? false;
  2814. }
  2815. }
  2816. //前端权限验证
  2817. if (item.IsValuable)
  2818. {
  2819. item.AuditPers = valuableAuditUsers.ToArray();
  2820. }
  2821. else item.AuditPers = normAuditUsers.ToArray();
  2822. }
  2823. if (dto.PortType == 2 || dto.PortType == 3)
  2824. {
  2825. _jv.Data = view;
  2826. }
  2827. else if (dto.PortType == 1)
  2828. {
  2829. var view1 = _mapper.Map<List<GoodsReceiveListView>>(view);
  2830. _jv.Data = view1;
  2831. }
  2832. _jv.Code = StatusCodes.Status200OK;
  2833. _jv.Count = total;
  2834. _jv.Msg = $"操作成功";
  2835. return _jv;
  2836. }
  2837. /// <summary>
  2838. /// 物品领用 可批量 OP(Add Or Edit)
  2839. /// </summary>
  2840. /// <param name="dto"></param>
  2841. /// <param name="currUserId"></param>
  2842. /// <returns></returns>
  2843. public async Task<JsonView> GoodsReceiveBatchOpAsync(GoodsReceiveBatchOpDto dto)
  2844. {
  2845. var goodsReceiveId = dto.Id;
  2846. var currUserId = dto.CurrUserId;
  2847. //请求参数处理
  2848. var receiveInfo = new Pm_GoodsReceive()
  2849. {
  2850. Id = goodsReceiveId,
  2851. GroupId = dto.GroupId,
  2852. Reason = dto.Reason,
  2853. Remark = dto.Remark,
  2854. AuditStatus = GoodsAuditEnum.Pending,
  2855. CreateUserId = currUserId,
  2856. };
  2857. var receiveDetails = _mapper.Map<Pm_GoodsReceiveDetails[]>(dto.ReceiveDetails);
  2858. //receiveDetails.ForEach(x => { x.CreateUserId = dto.CurrUserId; });
  2859. _sqlSugar.BeginTran();
  2860. //审核状态验证 false:其他物品 true:贵重物品
  2861. var isBatchVail = false;
  2862. //物品库存验证
  2863. int goodsIndex = 1;
  2864. var goodsNames = new List<string>();
  2865. foreach (var item in receiveDetails)
  2866. {
  2867. item.CreateUserId = currUserId;
  2868. int goodsId = item.GoodsId;
  2869. //物品验证
  2870. var goodsInfo = _sqlSugar.Queryable<Pm_GoodsInfo>().First(x => x.IsDel == 0 && x.Id == goodsId);
  2871. if (goodsInfo == null)
  2872. {
  2873. _jv.Msg = $"第{goodsIndex}项物品不存在!";
  2874. _sqlSugar.RollbackTran();
  2875. return _jv;
  2876. }
  2877. goodsNames.Add(goodsInfo.Name);
  2878. //物品库存验证
  2879. var stockQuantity = goodsInfo.StockQuantity;
  2880. var awaitAuditQuantity = await GoodsAwaitQuantityAsync(goodsId);
  2881. stockQuantity -= awaitAuditQuantity;
  2882. if (item.Quantity > stockQuantity)
  2883. {
  2884. _jv.Msg = $"“{goodsInfo.Name}”物品库存不足!剩余库存:{stockQuantity} {goodsInfo.Unit}(待审数量:{awaitAuditQuantity});";
  2885. _sqlSugar.RollbackTran();
  2886. return _jv;
  2887. }
  2888. //物品类型验证
  2889. if (_goodsTypeIds.Contains(goodsInfo.Type)) isBatchVail = true;
  2890. goodsIndex++;
  2891. }
  2892. if (goodsNames.Any())
  2893. {
  2894. receiveInfo.GoodsName = string.Join("、", goodsNames);
  2895. }
  2896. //验证领用 添加OR编辑
  2897. var goodsReceiveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.IsDel == 0 && x.Id == goodsReceiveId);
  2898. if (goodsReceiveInfo == null) //添加
  2899. {
  2900. goodsReceiveId = await _sqlSugar.Insertable(receiveInfo).ExecuteReturnIdentityAsync();
  2901. if (goodsReceiveId < 1)
  2902. {
  2903. _jv.Msg = $"领用添加失败!";
  2904. _sqlSugar.RollbackTran();
  2905. return _jv;
  2906. }
  2907. receiveDetails.ForEach(x => { x.GoodsReceiveId = goodsReceiveId; });
  2908. var receiveDetailsStatus = await _sqlSugar.Insertable(receiveDetails).ExecuteCommandAsync();
  2909. if (receiveDetailsStatus < 1)
  2910. {
  2911. _jv.Msg = $"领用明细添加失败!";
  2912. _sqlSugar.RollbackTran();
  2913. return _jv;
  2914. }
  2915. }
  2916. else //修改
  2917. {
  2918. //更改前状态验证
  2919. if (goodsReceiveInfo.AuditStatus != GoodsAuditEnum.Pending)
  2920. {
  2921. _jv.Msg = $"领用状态在“领用待确认”,即可修改!";
  2922. _sqlSugar.RollbackTran();
  2923. return _jv;
  2924. }
  2925. var receiveStatus = await _sqlSugar.Updateable(receiveInfo).ExecuteCommandAsync();
  2926. if (receiveStatus < 1)
  2927. {
  2928. _jv.Msg = $"领用更新失败!";
  2929. _sqlSugar.RollbackTran();
  2930. return _jv;
  2931. }
  2932. //更新子表数据
  2933. if (receiveDetails.Any())
  2934. {
  2935. receiveDetails.ForEach(x => { x.GoodsReceiveId = receiveInfo.Id; });
  2936. var db_receiveDetails = await _sqlSugar.Queryable<Pm_GoodsReceiveDetails>()
  2937. .Where(x => x.IsDel == 0 && x.GoodsReceiveId == goodsReceiveId)
  2938. .ToListAsync();
  2939. var toDelete = db_receiveDetails.Where(p => !receiveDetails.Any(np => np.Id == p.Id)).ToList();
  2940. if (toDelete.Any())
  2941. {
  2942. var delStatus = _sqlSugar.Deleteable(toDelete).ExecuteCommand();
  2943. if (delStatus < 1)
  2944. {
  2945. _jv.Msg = $"领用明细旧数据删除失败!";
  2946. _sqlSugar.RollbackTran();
  2947. return _jv;
  2948. }
  2949. }
  2950. var addOrUpdStatus = await _sqlSugar.Storageable<Pm_GoodsReceiveDetails>(receiveDetails.ToList()).ExecuteCommandAsync();
  2951. if (addOrUpdStatus < 1)
  2952. {
  2953. _jv.Msg = $"领用明细更新失败!";
  2954. _sqlSugar.RollbackTran();
  2955. return _jv;
  2956. }
  2957. }
  2958. }
  2959. #region 审批流程验证、创建
  2960. //审核验证 物品含有贵重物品 使用贵重物品审批流程
  2961. var auditTempInfo = new ApprovalProcessView();
  2962. if (isBatchVail) //贵重物品审核模板
  2963. {
  2964. auditTempInfo = await _approvalProcessRep.GetTemplateByBusinessTypeAsync(3);
  2965. }
  2966. else //其他物品审核模板
  2967. {
  2968. auditTempInfo = await _approvalProcessRep.GetTemplateByBusinessTypeAsync(2);
  2969. }
  2970. if (auditTempInfo == null)
  2971. {
  2972. _jv.Msg = $"未配置审核模板!";
  2973. _sqlSugar.RollbackTran();
  2974. return _jv;
  2975. }
  2976. if (auditTempInfo == null && !auditTempInfo.TempNodes.Any())
  2977. {
  2978. _jv.Msg = $"审核模板未配置节点!";
  2979. _sqlSugar.RollbackTran();
  2980. return _jv;
  2981. }
  2982. //创建审核流程
  2983. var firstNode = auditTempInfo.TempNodes.OrderBy(x => x.NodeOrder).First();
  2984. var flow = await _approvalProcessRep.GetFlowByBusinessAsync(goodsReceiveId, 1);
  2985. int flowId;
  2986. if (flow == null)
  2987. {
  2988. flow = new Sys_AuditFlow()
  2989. {
  2990. BusinessId = goodsReceiveId,
  2991. BusinessType = 1,
  2992. TemplateId = auditTempInfo.Id,
  2993. CurrentNodeId = firstNode.Id,
  2994. Status = 1,
  2995. };
  2996. flowId = await _sqlSugar.Insertable(flow).ExecuteReturnIdentityAsync();
  2997. if (flowId < 1)
  2998. {
  2999. _jv.Msg = $"审核流程添加失败!";
  3000. _sqlSugar.RollbackTran();
  3001. return _jv;
  3002. }
  3003. }
  3004. else flowId = flow.Id;
  3005. #endregion
  3006. //获取第一个节点的审核人员
  3007. var nodeUsers = firstNode.NodeUsers;
  3008. //删除旧的审核记录
  3009. var delRecords = await _sqlSugar.Deleteable<Sys_AuditRecord>()
  3010. .Where(x => x.FlowId == flowId && x.NodeId == firstNode.Id && x.NodeName == firstNode.NodeName)
  3011. .ExecuteCommandHasChangeAsync();
  3012. //创建审核记录
  3013. var records = nodeUsers.Select(user => new Sys_AuditRecord
  3014. {
  3015. FlowId = flowId,
  3016. NodeId = firstNode.Id,
  3017. NodeName = firstNode.NodeName,
  3018. AuditorId = user.UserId,
  3019. AuditorName = user.UserName,
  3020. AuditResult = 0, // 审核中
  3021. AuditTime = DateTime.Now
  3022. }).ToList();
  3023. var recordStatus = await _sqlSugar.Insertable(records).ExecuteCommandAsync();
  3024. if (recordStatus < 1)
  3025. {
  3026. _jv.Msg = $"审核记录创建失败!";
  3027. _sqlSugar.RollbackTran();
  3028. return _jv;
  3029. }
  3030. _sqlSugar.CommitTran();
  3031. _jv.Code = StatusCodes.Status200OK;
  3032. _jv.Msg = $"操作成功!";
  3033. return _jv;
  3034. }
  3035. /// <summary>
  3036. /// 物品领用 批量 List
  3037. /// </summary>
  3038. /// <param name="dto"></param>
  3039. /// <param name="currUserId"></param>
  3040. /// <returns></returns>
  3041. public async Task<JsonView> GoodsReceiveBatchListAsync(GoodsReceiveBatchListDto dto)
  3042. {
  3043. int currUserId = dto.CurrUserId;
  3044. string goodsName = dto.GoodsName;
  3045. var showAllPeopleIds = new List<int>() {
  3046. 374, // 罗颖
  3047. 233, // 刘华举
  3048. 208, // 雷怡
  3049. 343, // 陈湘
  3050. };
  3051. var isShowAllPeople = showAllPeopleIds.Any(x => x == currUserId);
  3052. RefAsync<int> total = 0;
  3053. var receiveList = await _sqlSugar.Queryable<Pm_GoodsReceive>()
  3054. .LeftJoin<Sys_Users>((x,y) => x.CreateUserId == y.Id)
  3055. .Where((x, y) => x.IsDel == 0 && x.GoodsId == 0 )
  3056. .WhereIF(!string.IsNullOrEmpty(goodsName), (x,y) => x.GoodsName.Contains(goodsName))
  3057. .WhereIF(!isShowAllPeople,(x,y) => x.CreateUserId == currUserId)
  3058. .OrderByDescending((x, y) => x.CreateTime)
  3059. .Select((x,y) => new GoodsReceiveBatchListView() {
  3060. Id = x.Id,
  3061. GoodsName = x.GoodsName,
  3062. AccumQty = SqlFunc.Subqueryable<Pm_GoodsReceiveDetails>().Where(z => z.IsDel == 0 && z.GoodsReceiveId == x.Id).Sum(z => z.Quantity),
  3063. Reason = x.Reason,
  3064. Remark = x.Remark,
  3065. Status = x.AuditStatus,
  3066. Applicant = y.CnName,
  3067. ApplyTime = x.CreateTime,
  3068. })
  3069. .ToPageListAsync(dto.PageIndex,dto.PageSize,total);
  3070. foreach (var item in receiveList)
  3071. {
  3072. var detailsText = new StringBuilder();
  3073. if (item.AccumQty > 0)
  3074. {
  3075. var goodsInfos = await _sqlSugar.Queryable<Pm_GoodsReceiveDetails>()
  3076. .InnerJoin<Pm_GoodsInfo>((x, y) => x.GoodsId == y.Id)
  3077. .LeftJoin<Sys_SetData>((x, y, z) => y.Type == z.Id)
  3078. .Where((x, y, z) => x.IsDel == 0 && x.GoodsReceiveId == item.Id)
  3079. .Select((x, y, z) => new
  3080. {
  3081. goodsId = x.GoodsId,
  3082. goodsName = y.Name,
  3083. goodsType = z.Name,
  3084. quantity = x.Quantity,
  3085. remark = x.Remark,
  3086. })
  3087. .ToListAsync();
  3088. if (goodsInfos.Any())
  3089. {
  3090. int index = 1;
  3091. goodsInfos.ForEach(x =>
  3092. {
  3093. detailsText.Append($"{index}.{x.goodsName}({x.goodsType}) 数量:{x.quantity:#0.00} 备注:{x.remark ?? "-"} <br/>");
  3094. index++;
  3095. });
  3096. }
  3097. }
  3098. else detailsText.Append($"暂无数据!");
  3099. item.GoodsDetails = detailsText.ToString();
  3100. }
  3101. _jv.Code = StatusCodes.Status200OK;
  3102. _jv.Msg = $"操作成功!";
  3103. _jv.Data = receiveList;
  3104. _jv.Count = total;
  3105. return _jv;
  3106. }
  3107. /// <summary>
  3108. /// 物品领用 批量 详情
  3109. /// </summary>
  3110. /// <param name="dto"></param>
  3111. /// <param name="currUserId"></param>
  3112. /// <returns></returns>
  3113. public async Task<JsonView> GoodsReceiveBatchInfoAsync(int id)
  3114. {
  3115. var receiveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>()
  3116. .Where(x => x.IsDel == 0 && x.Id == id)
  3117. .FirstAsync();
  3118. if (receiveInfo == null)
  3119. {
  3120. _jv.Msg = "暂无数据!";
  3121. return _jv;
  3122. }
  3123. var info = new GoodsReceiveBatchView();
  3124. info.Id = receiveInfo.Id;
  3125. info.GroupId = receiveInfo.GroupId;
  3126. info.Reason = receiveInfo.Reason;
  3127. info.Remark = receiveInfo.Remark;
  3128. info.ReceiveDetails = await _sqlSugar
  3129. .Queryable<Pm_GoodsReceiveDetails>()
  3130. .LeftJoin<Pm_GoodsInfo>((x, y) => x.GoodsId == y.Id)
  3131. .Where((x, y) => x.IsDel == 0 && x.GoodsReceiveId == receiveInfo.Id)
  3132. .Select((x, y) => new GoodsReceiveDetailsView()
  3133. {
  3134. Id = x.Id,
  3135. GoodsId = x.GoodsId,
  3136. GoodsName = y.Name,
  3137. Quantity = x.Quantity,
  3138. Remark = x.Remark,
  3139. })
  3140. .ToArrayAsync();
  3141. _jv.Code = StatusCodes.Status200OK;
  3142. _jv.Msg = $"操作成功!";
  3143. _jv.Data = info;
  3144. return _jv;
  3145. }
  3146. /// <summary>
  3147. /// 物品领用 审核 通过
  3148. /// </summary>
  3149. /// <param name="id"></param>
  3150. /// <param name="currUserId"></param>
  3151. /// <returns></returns>
  3152. public async Task<JsonView> GoodsReceiveApproveAsync(int id,int currUserId)
  3153. {
  3154. var appId = id;
  3155. //验证审核流程
  3156. var flow = await _approvalProcessRep.GetFlowByBusinessAsync(appId,1);
  3157. if (flow == null)
  3158. {
  3159. _jv.Msg = $"审核流程不存在";
  3160. return _jv;
  3161. }
  3162. if (flow.Status != 1)
  3163. {
  3164. _jv.Msg = $"当前流程不在审核中";
  3165. return _jv;
  3166. }
  3167. //获取当前节点
  3168. var currNode = (await _approvalProcessRep.GetTemplateNodesAsync(flow.TemplateId)).FirstOrDefault(x => x.Id == flow.CurrentNodeId);
  3169. if (currNode == null)
  3170. {
  3171. _jv.Msg = $"当前审核节点不存在";
  3172. return _jv;
  3173. }
  3174. //检查用户是否有权审核
  3175. var canAudit = (await _approvalProcessRep.GetTemplateNodeUsersAsync(currNode.Id))
  3176. .Any(x => x.UserId == currUserId);
  3177. if (!canAudit)
  3178. {
  3179. _jv.Msg = $"您无权审核此领用";
  3180. return _jv;
  3181. }
  3182. //检查是否已审核过
  3183. var existingRecord = await _sqlSugar.Queryable<Sys_AuditRecord>()
  3184. .Where(x => x.FlowId == flow.Id && x.NodeId == currNode.Id && x.AuditorId == currUserId)
  3185. .FirstAsync();
  3186. if (existingRecord != null && existingRecord.AuditResult == 1)
  3187. {
  3188. _jv.Msg = $"您已审核过此领用";
  3189. return _jv;
  3190. }
  3191. // 创建或更新审核记录
  3192. var currUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == currUserId)?.CnName ?? "-";
  3193. var record = existingRecord ?? new Sys_AuditRecord
  3194. {
  3195. FlowId = flow.Id,
  3196. NodeId = currNode.Id,
  3197. NodeName = currNode.NodeName,
  3198. AuditorId = currUserId,
  3199. AuditorName = currUserName,
  3200. AuditResult = 1, // 通过
  3201. AuditTime = DateTime.Now,
  3202. AuditOpinion = "",
  3203. };
  3204. _sqlSugar.BeginTran();
  3205. if (existingRecord == null) await _sqlSugar.Insertable(record).ExecuteCommandAsync();
  3206. else
  3207. {
  3208. record.AuditResult = 1; // 通过
  3209. record.AuditTime = DateTime.Now;
  3210. await _sqlSugar.Updateable(record).ExecuteCommandAsync();
  3211. }
  3212. //检查节点是否完成
  3213. var nodeRecords = await _sqlSugar.Queryable<Sys_AuditRecord>()
  3214. .Where(x => x.FlowId == flow.Id && x.NodeId == currNode.Id)
  3215. .ToListAsync();
  3216. bool isNodeComplete = false;
  3217. if (currNode.ApproveType == 2) // 或签模式
  3218. {
  3219. //或签逻辑:任意一人通过即通过
  3220. if (nodeRecords.Any(x => x.AuditResult == 1))
  3221. {
  3222. isNodeComplete = true;
  3223. // 标记其他未审核的记录为"无需处理"
  3224. var unprocessed = nodeRecords
  3225. .Where(x => x.AuditResult == 0 && x.AuditorId != currUserId)
  3226. .ToList();
  3227. foreach (var r in unprocessed)
  3228. {
  3229. r.AuditResult = 3; // 无需处理
  3230. r.AuditTime = DateTime.Now;
  3231. r.AuditOpinion = "其他审核人已处理";
  3232. }
  3233. if (unprocessed.Any())
  3234. {
  3235. await _sqlSugar.Updateable(unprocessed).ExecuteCommandAsync();
  3236. }
  3237. }
  3238. }
  3239. else // 会签模式
  3240. {
  3241. // 会签逻辑:全部通过才通过
  3242. isNodeComplete = nodeRecords.All(x => x.AuditResult == 1);
  3243. }
  3244. if (isNodeComplete)
  3245. {
  3246. // 查找下一个节点
  3247. var nextNode = (await _approvalProcessRep.GetTemplateNodesAsync(flow.TemplateId))
  3248. .Where(x => x.NodeOrder > currNode.NodeOrder)
  3249. .OrderBy(x => x.NodeOrder)
  3250. .FirstOrDefault();
  3251. if (nextNode == null)
  3252. {
  3253. // 所有节点完成,审核通过
  3254. flow.Status = 2; // 已完成
  3255. flow.CurrentNodeId = 0;
  3256. // 更新业务状态为审核通过
  3257. var auditStatus = await UpdateStatusAsync(appId, GoodsAuditEnum.OutConfirmed);
  3258. if (!auditStatus)
  3259. {
  3260. _jv.Msg = $"审核失败!";
  3261. _sqlSugar.RollbackTran();
  3262. return _jv;
  3263. }
  3264. var deductStatus = await DeductStockAsync(appId);
  3265. if (!deductStatus)
  3266. {
  3267. _jv.Msg = $"库存扣除失败失败!";
  3268. _sqlSugar.RollbackTran();
  3269. return _jv;
  3270. }
  3271. }
  3272. else
  3273. {
  3274. // 进入下一个节点
  3275. flow.CurrentNodeId = nextNode.Id;
  3276. // 更新业务状态为审核中
  3277. var auditStatus = await UpdateStatusAsync(appId, GoodsAuditEnum.OutConfirming);
  3278. if (!auditStatus)
  3279. {
  3280. _jv.Msg = $"审核状态更新失败!";
  3281. _sqlSugar.RollbackTran();
  3282. return _jv;
  3283. }
  3284. // 为下一个节点创建审核记录
  3285. var nextNodeUsers = await _approvalProcessRep.GetTemplateNodeUsersAsync(nextNode.Id);
  3286. var records = nextNodeUsers.Select(user => new Sys_AuditRecord
  3287. {
  3288. FlowId = flow.Id,
  3289. NodeId = nextNode.Id,
  3290. NodeName = nextNode.NodeName,
  3291. AuditorId = user.UserId,
  3292. AuditorName = user.UserName,
  3293. AuditResult = 0,
  3294. AuditTime = DateTime.Now
  3295. }).ToList();
  3296. var recordStatus = await _sqlSugar.Insertable(records).ExecuteCommandAsync();
  3297. if (recordStatus < 1)
  3298. {
  3299. _jv.Msg = $"下一节点审批记录创建失败!";
  3300. _sqlSugar.RollbackTran();
  3301. return _jv;
  3302. }
  3303. }
  3304. var flowStatus = await _sqlSugar.Updateable(flow).ExecuteCommandAsync();
  3305. if (flowStatus < 1)
  3306. {
  3307. _jv.Msg = $"审批流程更新失败!";
  3308. _sqlSugar.RollbackTran();
  3309. return _jv;
  3310. }
  3311. }
  3312. _sqlSugar.CommitTran();
  3313. _jv.Code = StatusCodes.Status200OK;
  3314. _jv.Msg = $"操作成功!";
  3315. return _jv;
  3316. }
  3317. /// <summary>
  3318. /// 物品领用 审核 拒绝
  3319. /// </summary>
  3320. /// <param name="id"></param>
  3321. /// <param name="currUserId"></param>
  3322. /// <returns></returns>
  3323. public async Task<JsonView> GoodsReceiveRejectAsync(int id, int currUserId)
  3324. {
  3325. var appId = id;
  3326. //验证领用单
  3327. var receviveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.Id == appId);
  3328. if (receviveInfo == null)
  3329. {
  3330. _jv.Msg = $"当前领用信息不存在";
  3331. return _jv;
  3332. }
  3333. //验证审核流程
  3334. var flow = await _approvalProcessRep.GetFlowByBusinessAsync(appId, 1);
  3335. if (flow == null)
  3336. {
  3337. _jv.Msg = $"审核流程不存在";
  3338. return _jv;
  3339. }
  3340. //if (flow.Status != 1)
  3341. //{
  3342. // _jv.Msg = $"当前流程不在审核中";
  3343. // return _jv;
  3344. //}
  3345. //获取当前节点
  3346. var currNode = (await _approvalProcessRep.GetTemplateNodesAsync(flow.TemplateId)).FirstOrDefault(x => x.Id == flow.CurrentNodeId);
  3347. if (currNode == null)
  3348. {
  3349. _jv.Msg = $"当前审核节点不存在";
  3350. return _jv;
  3351. }
  3352. //检查用户是否有权审核
  3353. var canAudit = (await _approvalProcessRep.GetTemplateNodeUsersAsync(currNode.Id))
  3354. .Any(x => x.UserId == currUserId);
  3355. if (!canAudit)
  3356. {
  3357. _jv.Msg = $"您无权审核此申请";
  3358. return _jv;
  3359. }
  3360. //检查是否已审核过
  3361. var existingRecord = await _sqlSugar.Queryable<Sys_AuditRecord>()
  3362. .Where(x => x.FlowId == flow.Id && x.NodeId == currNode.Id && x.AuditorId == currUserId)
  3363. .FirstAsync();
  3364. if (existingRecord != null && existingRecord.AuditResult == 2)
  3365. {
  3366. _jv.Msg = $"您已审核过此申请";
  3367. return _jv;
  3368. }
  3369. //验证是否已经审核通过
  3370. bool isApproved = receviveInfo.AuditStatus == GoodsAuditEnum.OutConfirmed;
  3371. _sqlSugar.BeginTran();
  3372. if (isApproved) //审核通过拒绝
  3373. {
  3374. //回滚库存
  3375. var rollbackStatus = await RollbackStockAsync(appId);
  3376. if (!rollbackStatus)
  3377. {
  3378. _jv.Msg = $"物品库存回滚失败!";
  3379. _sqlSugar.RollbackTran();
  3380. return _jv;
  3381. }
  3382. }
  3383. //更新流程状态为已拒绝
  3384. flow.Status = 3; // 已拒绝
  3385. flow.CurrentNodeId = currNode.Id;
  3386. var flowStatus = await _sqlSugar.Updateable(flow).ExecuteCommandAsync();
  3387. if (flowStatus < 1)
  3388. {
  3389. _jv.Msg = $"流程状态更新失败!";
  3390. _sqlSugar.RollbackTran();
  3391. return _jv;
  3392. }
  3393. // 更新领用状态为已拒绝
  3394. var receviveStatus = await UpdateStatusAsync(appId, GoodsAuditEnum.OutRejected); // 已拒绝
  3395. if (!receviveStatus)
  3396. {
  3397. _jv.Msg = $"领用物品状态更新失败!";
  3398. _sqlSugar.RollbackTran();
  3399. return _jv;
  3400. }
  3401. // 创建拒绝记录
  3402. var currUserName = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == currUserId)?.CnName ?? "-";
  3403. var record = new Sys_AuditRecord
  3404. {
  3405. FlowId = flow.Id,
  3406. NodeId = flow.CurrentNodeId,
  3407. NodeName = $"{currNode.NodeName}-撤销",
  3408. AuditorId = currUserId,
  3409. AuditorName = currUserName,
  3410. AuditResult = 2, // 拒绝
  3411. AuditTime = DateTime.Now,
  3412. AuditOpinion = $"用户操作撤销",
  3413. };
  3414. var recordStatus = await _sqlSugar.Insertable(record).ExecuteCommandAsync();
  3415. if (recordStatus < 1)
  3416. {
  3417. _jv.Msg = $"领用物品拒绝记录创建失败!";
  3418. _sqlSugar.RollbackTran();
  3419. return _jv;
  3420. }
  3421. _sqlSugar.CommitTran();
  3422. _jv.Code = StatusCodes.Status200OK;
  3423. _jv.Msg = $"操作成功!";
  3424. return _jv;
  3425. }
  3426. /// <summary>
  3427. /// 物品待审核数量
  3428. /// </summary>
  3429. /// <param name="goodsId"></param>
  3430. /// <returns></returns>
  3431. public async Task<decimal> GoodsAwaitQuantityAsync(int goodsId)
  3432. {
  3433. decimal quantity = 0.00M;
  3434. //单条领用 待审核、确认中 物品数量
  3435. var waitAuditQuantity = await _sqlSugar.Queryable<Pm_GoodsReceive>().Where(x => x.IsDel == 0 &&
  3436. x.GoodsId == goodsId &&
  3437. (x.AuditStatus == GoodsAuditEnum.Pending || x.AuditStatus == GoodsAuditEnum.OutConfirming)
  3438. ).SumAsync(x => x.Quantity);
  3439. //批量领用 待审核、确认中 物品数量
  3440. var waitAuditBatchQuantity = await _sqlSugar.Queryable<Pm_GoodsReceive>()
  3441. .InnerJoin<Pm_GoodsReceiveDetails>((gr, grd) => gr.Id == grd.GoodsReceiveId)
  3442. .Where((gr, grd) => gr.IsDel == 0 &&
  3443. (gr.AuditStatus == GoodsAuditEnum.Pending || gr.AuditStatus == GoodsAuditEnum.OutConfirming) &&
  3444. grd.GoodsId == goodsId
  3445. )
  3446. .Select((gr, grd) => new
  3447. {
  3448. grd.GoodsReceiveId,
  3449. gr.AuditStatus,
  3450. grd.Quantity
  3451. })
  3452. .SumAsync(gr => gr.Quantity);
  3453. quantity = waitAuditQuantity + waitAuditBatchQuantity;
  3454. return quantity;
  3455. }
  3456. /// <summary>
  3457. /// 更改领用状态
  3458. /// </summary>
  3459. /// <param name="id"></param>
  3460. /// <param name="status"></param>
  3461. /// <returns></returns>
  3462. public async Task<bool> UpdateStatusAsync(int id, GoodsAuditEnum status)
  3463. {
  3464. return await _sqlSugar.Updateable<Pm_GoodsReceive>()
  3465. .SetColumns(x => x.AuditStatus == status)
  3466. .Where(x => x.Id == id)
  3467. .ExecuteCommandHasChangeAsync();
  3468. }
  3469. /// <summary>
  3470. /// 领用状态完成扣除库存
  3471. /// </summary>
  3472. /// <param name="id"></param>
  3473. /// <param name="status"></param>
  3474. /// <returns></returns>
  3475. public async Task<bool> DeductStockAsync(int id)
  3476. {
  3477. var receiveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.Id == id);
  3478. if (receiveInfo == null) return false;
  3479. var receiveDetails = await _sqlSugar.Queryable<Pm_GoodsReceiveDetails>()
  3480. .Where(x => x.IsDel == 0 && x.GoodsReceiveId == id)
  3481. .ToListAsync();
  3482. if (!receiveDetails.Any()) return false;
  3483. var goodsInfos = new List<Pm_GoodsInfo>();
  3484. foreach (var item in receiveDetails)
  3485. {
  3486. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == item.GoodsId);
  3487. if (goodsInfo == null) return false;
  3488. //1、物品库存扣除
  3489. var receiveQuantity = item.Quantity;
  3490. goodsInfo.StockQuantity -= receiveQuantity;
  3491. goodsInfo.OQ_Total += receiveQuantity;
  3492. //2、入库批次关联领用人 更改批次库存
  3493. var goodsStorages = await _sqlSugar
  3494. .Queryable<Pm_GoodsStorage>()
  3495. .Where(x => x.IsDel == 0 &&
  3496. x.GoodsId == receiveInfo.GoodsId &&
  3497. (x.Quantity - x.ReceiveQuantity) > 0
  3498. )
  3499. .OrderBy(x => x.CreateTime)
  3500. .ToListAsync();
  3501. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  3502. var batchStorageInfos = new List<Pm_GoodsStorage>();
  3503. foreach (var storage in goodsStorages)
  3504. {
  3505. if (receiveInfo.Quantity == receiveQuantity) break;
  3506. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  3507. if (thisBatchSurplusQuantity <= 0.00M) continue;
  3508. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  3509. const decimal unit = 0.50M;
  3510. while (receiveQuantity < receiveInfo.Quantity)
  3511. {
  3512. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  3513. thisBatchReceiveQuantity += unit;
  3514. receiveQuantity += unit;
  3515. }
  3516. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  3517. {
  3518. StorageId = storage.Id,
  3519. Quantity = thisBatchReceiveQuantity
  3520. });
  3521. storage.ReceiveQuantity += thisBatchReceiveQuantity;
  3522. batchStorageInfos.Add(storage);
  3523. }
  3524. //3 更改批次库存
  3525. if (goodsReceiveInfos.Count > 0)
  3526. {
  3527. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  3528. .UpdateColumns(x => x.ReceiveQuantity)
  3529. .WhereColumns(x => x.Id)
  3530. .ExecuteCommandAsync();
  3531. if (edit1 < 1) return false;
  3532. }
  3533. //4 添加入库批次关联领用人
  3534. if (goodsReceiveInfos.Count > 0)
  3535. {
  3536. item.GoodsStorageInfo = JsonConvert.SerializeObject(goodsReceiveInfos);
  3537. }
  3538. goodsInfos.Add(goodsInfo);
  3539. }
  3540. //库存更改
  3541. var editGoods = await _sqlSugar.Updateable(goodsInfos)
  3542. .UpdateColumns(x => new
  3543. {
  3544. x.StockQuantity,
  3545. x.OQ_Total,
  3546. })
  3547. .Where(x => x.Id == x.Id)
  3548. .ExecuteCommandAsync();
  3549. if (editGoods < 1) return false;
  3550. //领用明细更改
  3551. var editDetails = await _sqlSugar.Updateable(receiveDetails)
  3552. .UpdateColumns(x => new
  3553. {
  3554. x.GoodsStorageInfo,
  3555. })
  3556. .Where(x => x.GoodsReceiveId == x.GoodsReceiveId)
  3557. .ExecuteCommandAsync();
  3558. if (editDetails < 1) return false;
  3559. return true;
  3560. }
  3561. /// <summary>
  3562. /// 领用状态拒绝回滚所有物资的库存
  3563. /// </summary>
  3564. /// <param name="id"></param>
  3565. /// <param name="status"></param>
  3566. /// <returns></returns>
  3567. public async Task<bool> RollbackStockAsync(int id)
  3568. {
  3569. var receiveInfo = await _sqlSugar.Queryable<Pm_GoodsReceive>().FirstAsync(x => x.Id == id);
  3570. if (receiveInfo == null) return false;
  3571. var receiveDetails = await _sqlSugar.Queryable<Pm_GoodsReceiveDetails>()
  3572. .Where(x => x.IsDel == 0 && x.GoodsReceiveId == id)
  3573. .ToListAsync();
  3574. if (!receiveDetails.Any()) return false;
  3575. var goodsInfos = new List<Pm_GoodsInfo>();
  3576. foreach (var item in receiveDetails)
  3577. {
  3578. var goodsInfo = await _sqlSugar.Queryable<Pm_GoodsInfo>().FirstAsync(x => x.Id == item.GoodsId);
  3579. if (goodsInfo == null) return false;
  3580. //1、物品表库存回滚
  3581. var receiveQuantity = item.Quantity;
  3582. goodsInfo.StockQuantity += receiveQuantity;
  3583. goodsInfo.OQ_Total -= receiveQuantity;
  3584. //2、入库批次关联领用人 更改批次库存 回滚
  3585. var goodsStorages = await _sqlSugar
  3586. .Queryable<Pm_GoodsStorage>()
  3587. .Where(x => x.IsDel == 0 &&
  3588. x.GoodsId == receiveInfo.GoodsId &&
  3589. (x.Quantity - x.ReceiveQuantity) > 0
  3590. )
  3591. .OrderBy(x => x.CreateTime)
  3592. .ToListAsync();
  3593. var goodsReceiveInfos = new List<GoodsReceiveLinkStorageView>();
  3594. var batchStorageInfos = new List<Pm_GoodsStorage>();
  3595. foreach (var storage in goodsStorages)
  3596. {
  3597. if (receiveInfo.Quantity == receiveQuantity) break;
  3598. var thisBatchSurplusQuantity = storage.Quantity - storage.ReceiveQuantity;
  3599. if (thisBatchSurplusQuantity <= 0.00M) continue;
  3600. var thisBatchReceiveQuantity = 0.00M; //此批次领用数量
  3601. const decimal unit = 0.50M;
  3602. while (receiveQuantity < receiveInfo.Quantity)
  3603. {
  3604. if (thisBatchSurplusQuantity == thisBatchReceiveQuantity) break;
  3605. thisBatchReceiveQuantity -= unit;
  3606. receiveQuantity -= unit;
  3607. }
  3608. goodsReceiveInfos.Add(new GoodsReceiveLinkStorageView
  3609. {
  3610. StorageId = storage.Id,
  3611. Quantity = thisBatchReceiveQuantity
  3612. });
  3613. storage.ReceiveQuantity -= thisBatchReceiveQuantity;
  3614. batchStorageInfos.Add(storage);
  3615. }
  3616. //3 批次库存 回滚
  3617. if (goodsReceiveInfos.Count > 0)
  3618. {
  3619. var edit1 = await _sqlSugar.Updateable(batchStorageInfos)
  3620. .UpdateColumns(x => x.ReceiveQuantity)
  3621. .WhereColumns(x => x.Id)
  3622. .ExecuteCommandAsync();
  3623. if (edit1 < 1) return false;
  3624. }
  3625. item.GoodsStorageInfo = null;
  3626. goodsInfos.Add(goodsInfo);
  3627. }
  3628. //库存 回滚
  3629. var editGoods = await _sqlSugar.Updateable(goodsInfos)
  3630. .UpdateColumns(x => new
  3631. {
  3632. x.StockQuantity,
  3633. x.OQ_Total,
  3634. })
  3635. .Where(x => x.Id == x.Id)
  3636. .ExecuteCommandAsync();
  3637. if (editGoods < 1) return false;
  3638. //领用明细 回滚
  3639. var editDetails = await _sqlSugar.Updateable(receiveDetails)
  3640. .UpdateColumns(x => new
  3641. {
  3642. x.GoodsStorageInfo,
  3643. })
  3644. .Where(x => x.GoodsReceiveId == x.GoodsReceiveId)
  3645. .ExecuteCommandAsync();
  3646. if (editDetails < 1) return false;
  3647. return true;
  3648. }
  3649. #endregion
  3650. }
  3651. }