PersonnelModuleController.cs 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615
  1. using Aspose.Cells;
  2. using FluentValidation;
  3. using Microsoft.AspNetCore.SignalR;
  4. using OASystem.API.OAMethodLib;
  5. using OASystem.API.OAMethodLib.Hub.HubClients;
  6. using OASystem.API.OAMethodLib.Hub.Hubs;
  7. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  8. using OASystem.API.OAMethodLib.Quartz.Business;
  9. using OASystem.Domain.Dtos.Groups;
  10. using OASystem.Domain.Dtos.PersonnelModule;
  11. using OASystem.Domain.Entities.Groups;
  12. using OASystem.Domain.Entities.PersonnelModule;
  13. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  14. using OASystem.Domain.ViewModels.PersonnelModule;
  15. using OASystem.Domain.ViewModels.QiYeWeChat;
  16. using OASystem.Infrastructure.Repositories.PersonnelModule;
  17. using System.Collections;
  18. using System.Data;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using static OASystem.API.OAMethodLib.JWTHelper;
  22. namespace OASystem.API.Controllers
  23. {
  24. /// <summary>
  25. /// 人事模块
  26. /// </summary>
  27. [Route("api/[controller]/[action]")]
  28. public class PersonnelModuleController : ControllerBase
  29. {
  30. private Result _result;
  31. private readonly IMapper _mapper;
  32. //private readonly decimal _chengDuMinimumWage = 2100.00M;
  33. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  34. private readonly WageSheetRepository _wageSheetRep;
  35. private readonly UsersRepository _usersRep;
  36. private readonly TaskAllocationRepository _taskAllocationRep;
  37. private readonly SqlSugarClient _sqlSugar;
  38. private readonly IHubContext<ChatHub, IChatClient> _hubContext;
  39. private readonly GoodsRepository _goodsRep;
  40. private string url;
  41. private string path;
  42. /// <summary>
  43. /// 初始化
  44. /// </summary>
  45. /// <param name="qiYeWeChatApiService"></param>
  46. /// <param name="wageSheetRep"></param>
  47. /// <param name="usersRep"></param>
  48. /// <param name="mapper"></param>
  49. /// <param name="taskAllocationRep"></param>
  50. /// <param name="hubContext"></param>
  51. /// <param name="goodsRep"></param>
  52. /// <param name="sqlSugar"></param>
  53. public PersonnelModuleController(
  54. IHubContext<ChatHub, IChatClient> hubContext,
  55. IMapper mapper,
  56. IQiYeWeChatApiService qiYeWeChatApiService,
  57. WageSheetRepository wageSheetRep,
  58. UsersRepository usersRep,
  59. TaskAllocationRepository taskAllocationRep,
  60. GoodsRepository goodsRep,
  61. SqlSugarClient sqlSugar
  62. )
  63. {
  64. _mapper = mapper;
  65. _usersRep = usersRep;
  66. _qiYeWeChatApiService = qiYeWeChatApiService;
  67. _wageSheetRep = wageSheetRep;
  68. _result = new Result();
  69. _sqlSugar = sqlSugar;
  70. url = AppSettingsHelper.Get("ExcelBaseUrl");
  71. path = AppSettingsHelper.Get("ExcelBasePath");
  72. if (!System.IO.Directory.Exists(path))
  73. {
  74. System.IO.Directory.CreateDirectory(path);//不存在就创建文件夹
  75. }
  76. this._taskAllocationRep = taskAllocationRep;
  77. _hubContext = hubContext;
  78. _goodsRep = goodsRep;
  79. }
  80. #region 工资表单
  81. /// <summary>
  82. /// 工资 月列表
  83. /// </summary>
  84. /// <returns></returns>
  85. [HttpPost]
  86. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  87. public async Task<IActionResult> GetWageSheetMonth()
  88. {
  89. string sql = string.Format("Select * From Pm_WageIssueWorkingDay Where IsDel = 0 Order By YearMonth Desc");
  90. var data = await _wageSheetRep._sqlSugar.SqlQueryable<WageSheetMonthView>(sql).ToListAsync();
  91. return Ok(JsonView(true, "查询成功!", data));
  92. }
  93. /// <summary>
  94. /// 工资 工作日信息
  95. /// 查询
  96. /// </summary>
  97. /// <returns></returns>
  98. [HttpPost]
  99. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  100. public async Task<IActionResult> GetWageSheetMonthWorkdays(string startDt, string endDt)
  101. {
  102. //参数处理
  103. var dtFormat = "yyyy-MM-dd";
  104. DateTime startDt1, endDt1;
  105. var startDtIsValid = DateTime.TryParseExact(startDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt1);
  106. var endDtIsValid = DateTime.TryParseExact(endDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt1);
  107. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  108. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  109. var sql = string.Format(@"Select * From Sys_Calendar
  110. Where Isdel = 0 And Dt between '{0}' And '{1}'", startDt, endDt);
  111. var data = await _wageSheetRep._sqlSugar.SqlQueryable<CalendarInfoView>(sql).ToListAsync();
  112. return Ok(JsonView(true, "查询成功!", data));
  113. }
  114. /// <summary>
  115. /// 工资 工作日信息
  116. /// 编辑
  117. /// </summary>
  118. /// <returns></returns>
  119. [HttpPost]
  120. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  121. public async Task<IActionResult> GetWageSheetMonthWorkdaysAddOrEdit(WageSheetMonthWorkdaysAddOrEditDto dto)
  122. {
  123. //参数处理
  124. string yearFormat = "yyyy-MM";
  125. string dtFormat = "yyyy-MM-dd";
  126. DateTime yearDt, startDt1, endDt1;
  127. bool yearDtIsValid = DateTime.TryParseExact(dto.YearMonth, yearFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearDt);
  128. bool startDtIsValid = DateTime.TryParseExact(dto.StartDate, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt1);
  129. bool endDtIsValid = DateTime.TryParseExact(dto.EndDate, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt1);
  130. if (!yearDtIsValid) return Ok(JsonView(false, "年月日期格式错误!正确时间格式:yyyy-MM "));
  131. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  132. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  133. #region 处理数据
  134. Pm_WageIssueWorkingDay pm_WageIssueWorkingDay1 = new Pm_WageIssueWorkingDay();
  135. pm_WageIssueWorkingDay1 = _mapper.Map<Pm_WageIssueWorkingDay>(dto);
  136. List<Sys_Calendar> sys_Calendars = new List<Sys_Calendar>();
  137. sys_Calendars = _mapper.Map<List<Sys_Calendar>>(dto.CalendarInfos);
  138. if (sys_Calendars.Count > 0)
  139. {
  140. sys_Calendars = sys_Calendars.OrderBy(it => it.Dt).ToList();
  141. }
  142. pm_WageIssueWorkingDay1.Workdays = sys_Calendars.Where(it => it.IsWorkDay == true).ToList().Count;
  143. foreach (var item in sys_Calendars)
  144. {
  145. item.Remark = pm_WageIssueWorkingDay1.Remark;
  146. item.CreateUserId = pm_WageIssueWorkingDay1.CreateUserId;
  147. item.CreateTime = pm_WageIssueWorkingDay1.CreateTime;
  148. }
  149. #endregion
  150. var _sqlSugar = _wageSheetRep._sqlSugar;
  151. _sqlSugar.BeginTran();
  152. try
  153. {
  154. List<Sys_Calendar> sys_Calendars_add = new List<Sys_Calendar>();
  155. List<Sys_Calendar> sys_Calendars_update = new List<Sys_Calendar>();
  156. sys_Calendars_add = sys_Calendars.Where(it => it.Id == 0).OrderBy(it => it.Dt).ToList();
  157. sys_Calendars_update = sys_Calendars.Where(it => it.Id != 0).OrderBy(it => it.Dt).ToList();
  158. //int add1 = 0;
  159. //int upd = 0;
  160. if (sys_Calendars_add.Count > 0)
  161. {
  162. var calendarsAdd = await _sqlSugar.Insertable(sys_Calendars_add).ExecuteReturnIdentityAsync();
  163. if (calendarsAdd < 0)
  164. {
  165. _sqlSugar.RollbackTran();
  166. return Ok(JsonView(false, "工作日/节假日/休息日添加失败!"));
  167. }
  168. }
  169. if (sys_Calendars_update.Count > 0)
  170. {
  171. var calendarsUpdate = await _sqlSugar.Updateable<Sys_Calendar>(sys_Calendars)
  172. .UpdateColumns(it => new { it.Dt, it.IsWorkDay, it.IsHoliDay, it.HoliName })
  173. .WhereColumns(it => it.Id)
  174. .ExecuteCommandAsync();
  175. if (calendarsUpdate < 0)
  176. {
  177. _sqlSugar.RollbackTran();
  178. return Ok(JsonView(false, "工作日/节假日/休息日编辑失败!"));
  179. }
  180. }
  181. var calendarsDatas = await _sqlSugar.Queryable<Sys_Calendar>()
  182. .Where(it => Convert.ToDateTime(it.Dt) >= Convert.ToDateTime(dto.StartDate) && Convert.ToDateTime(it.Dt) <= Convert.ToDateTime(dto.EndDate)).ToListAsync();
  183. if (calendarsDatas.Count < 0)
  184. {
  185. _sqlSugar.RollbackTran();
  186. return Ok(JsonView(false, "日期包暂无工作日/节假日/休息日的信息!"));
  187. }
  188. //月份表是否存在
  189. Pm_WageIssueWorkingDay pm_WageIssueWorkingDay = new Pm_WageIssueWorkingDay()
  190. {
  191. YearMonth = dto.YearMonth,
  192. StartDate = dto.StartDate,
  193. EndDate = dto.EndDate,
  194. Workdays = calendarsDatas.Where(it => it.IsWorkDay == true).ToList().Count
  195. };
  196. string sql = string.Format("Select * From Pm_WageIssueWorkingDay Where Isdel = 0 And YearMonth='{0}'", dto.YearMonth);
  197. var workdsys = await _sqlSugar.SqlQueryable<Pm_WageIssueWorkingDay>(sql).FirstAsync();
  198. pm_WageIssueWorkingDay.CreateUserId = dto.UserId;
  199. pm_WageIssueWorkingDay.IsDel = 0;
  200. if (workdsys == null) //添加
  201. {
  202. int addId = await _sqlSugar.Insertable(pm_WageIssueWorkingDay).ExecuteReturnIdentityAsync();
  203. if (addId < 0)
  204. {
  205. _sqlSugar.RollbackTran();
  206. return Ok(JsonView(false, "工作日设置添加失败!"));
  207. }
  208. }
  209. else //更新
  210. {
  211. int updCount = await _sqlSugar.Updateable(pm_WageIssueWorkingDay)
  212. .IgnoreColumns(z => new { z.CreateUserId, z.CreateTime, z.DeleteUserId, z.DeleteTime, z.IsDel })
  213. .WhereColumns(it => it.YearMonth)
  214. .ExecuteCommandAsync();
  215. if (updCount < 0)
  216. {
  217. _sqlSugar.RollbackTran();
  218. return Ok(JsonView(false, "工作日设置编辑失败!"));
  219. }
  220. }
  221. _sqlSugar.CommitTran();
  222. return Ok(JsonView(true, "操作成功!"));
  223. }
  224. catch (Exception ex)
  225. {
  226. _sqlSugar.RollbackTran();
  227. return Ok(JsonView(false, ex.Message));
  228. }
  229. }
  230. /// <summary>
  231. /// 工资表单 基础数据源
  232. /// </summary>
  233. /// <returns></returns>
  234. [HttpPost]
  235. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  236. public async Task<IActionResult> GetWageSheetBasicsDataSource()
  237. {
  238. string companySql = string.Format("Select * From Sys_Company Where IsDel = 0");
  239. var compnayData = await _wageSheetRep._sqlSugar.SqlQueryable<CompanyNameView>(companySql).ToListAsync();
  240. string depSql = string.Format("Select * From Sys_Department Where IsDel = 0");
  241. var depData = await _wageSheetRep._sqlSugar.SqlQueryable<Domain.ViewModels.System.DepartmentView>(depSql).ToListAsync();
  242. //获取OA系统内所有用户
  243. var nameData = await _usersRep.GetUserNameList(1);
  244. if (nameData.Code != 0)
  245. {
  246. return Ok(JsonView(false, nameData.Msg));
  247. }
  248. var data = new
  249. {
  250. compnayData = compnayData,
  251. depData = depData,
  252. userNames = nameData.Data
  253. };
  254. return Ok(JsonView(true, "查询成功!", data));
  255. }
  256. /// <summary>
  257. /// 获取工资发放月份
  258. /// </summary>
  259. /// <param name="dto"></param>
  260. /// <returns></returns>
  261. [HttpPost]
  262. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  263. public async Task<IActionResult> GetWageYaerMonths(WageYearDto dto)
  264. {
  265. string sql = string.Format(@"Select * From Pm_WageIssueWorkingDay
  266. Where Isdel = 0 And YearMonth Like '%{0}%'
  267. Order By YearMonth Asc", dto.Year);
  268. var data = await _wageSheetRep._sqlSugar.SqlQueryable<WageYearMonthView>(sql).ToListAsync();
  269. return Ok(JsonView(true, "操作成功!", data));
  270. }
  271. /// <summary>
  272. /// 获取工资表单
  273. /// </summary>
  274. /// <param name="dto"></param>
  275. /// <returns></returns>
  276. [HttpPost]
  277. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  278. public async Task<IActionResult> GetWageSheetList(WageSheetListDto dto)
  279. {
  280. //参数处理
  281. string ymFormat = "yyyy-MM";
  282. DateTime yearMonthDt;
  283. bool yearMonthDttIsValid = DateTime.TryParseExact(dto.YearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  284. if (!yearMonthDttIsValid)
  285. {
  286. _result.Msg = "年月格式错误!正确时间格式:yyyy-MM ";
  287. return Ok(JsonView(false, _result.Msg));
  288. }
  289. //获取月工资数据
  290. string yearMonth = yearMonthDt.ToString("yyyy-MM");
  291. if (dto.PortType == 1)
  292. {
  293. _result = await _wageSheetRep.Get_WageSheet_ListByYearMonthAsync(yearMonth);
  294. if (_result.Code != 0)
  295. {
  296. return Ok(JsonView(false, _result.Msg));
  297. }
  298. }
  299. else if (dto.PortType == 2)
  300. { }
  301. else if (dto.PortType == 3)
  302. { }
  303. else
  304. {
  305. return Ok(JsonView(false, "请选择正确的端口参数"));
  306. }
  307. return Ok(JsonView(true, _result.Msg, _result.Data));
  308. }
  309. /// <summary>
  310. /// 获取工资 详情
  311. /// </summary>
  312. /// <param name="dto"></param>
  313. /// <returns></returns>
  314. [HttpPost]
  315. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  316. public async Task<IActionResult> GetWageSheetById(WageSheetInfoDto dto)
  317. {
  318. if (dto.PortType == 1)
  319. {
  320. _result = await _wageSheetRep.Get_WageSheet_InfoByIdAsync(dto.Id);
  321. if (_result.Code != 0)
  322. {
  323. return Ok(JsonView(false, _result.Msg));
  324. }
  325. }
  326. else if (dto.PortType == 2)
  327. { }
  328. else if (dto.PortType == 3)
  329. { }
  330. else
  331. {
  332. return Ok(JsonView(false, "请选择正确的端口参数"));
  333. }
  334. return Ok(JsonView(true, _result.Msg, _result.Data));
  335. }
  336. /// <summary>
  337. /// 人事模块 工资表单 删除
  338. /// </summary>
  339. /// <param name="dto"></param>
  340. /// <returns></returns>
  341. [HttpPost]
  342. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  343. public async Task<IActionResult> PostWageSheetDel(WageDelDto dto)
  344. {
  345. try
  346. {
  347. _result = await _wageSheetRep.Post_WageSheet_DelAsync(dto);
  348. if (_result.Code != 0)
  349. {
  350. return Ok(JsonView(false, _result.Msg));
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. return Ok(JsonView(false, ex.Message));
  356. }
  357. return Ok(JsonView(true, _result.Msg, _result.Data));
  358. }
  359. /// <summary>
  360. /// 人事模块 工资表单 添加 Or 修改
  361. /// </summary>
  362. /// <param name="dto"></param>
  363. /// <returns></returns>
  364. [HttpPost]
  365. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  366. public async Task<IActionResult> PostWageSheetAddOrEdit(WageAddOrEditDto dto)
  367. {
  368. try
  369. {
  370. Pm_WageSheet pm_WageSheet = new Pm_WageSheet();
  371. pm_WageSheet = _mapper.Map<Pm_WageSheet>(dto);
  372. pm_WageSheet.LastUpdateUserId = dto.CreateUserId;
  373. #region 计算工资
  374. //月工资
  375. decimal salary = pm_WageSheet.Basic + pm_WageSheet.Floats + pm_WageSheet.PostAllowance + pm_WageSheet.InformationSecurityFee + pm_WageSheet.OtherSubsidies;
  376. //扣款合计
  377. decimal totalDeduction = pm_WageSheet.SickLeave + pm_WageSheet.SomethingFalse + pm_WageSheet.LateTo + pm_WageSheet.LeaveEarly + pm_WageSheet.Absenteeism + pm_WageSheet.NotPunch +
  378. pm_WageSheet.ReservedFunds + pm_WageSheet.WithholdingInsurance + pm_WageSheet.OtherDeductions + pm_WageSheet.OtherDeductions;
  379. //实发合计 不含个税
  380. if (pm_WageSheet.RegularDays >= pm_WageSheet.WorkDays)
  381. {
  382. pm_WageSheet.RegularDays = pm_WageSheet.WorkDays;
  383. salary = salary + pm_WageSheet.Mealsupplement + pm_WageSheet.OtherHandle;
  384. }
  385. else
  386. {
  387. if (dto.UserId == 21) //21==张海麟
  388. {
  389. salary = salary + pm_WageSheet.Mealsupplement + pm_WageSheet.OtherHandle;
  390. }
  391. else
  392. {
  393. salary = PayrollComputation.ConvertToDecimal(salary / pm_WageSheet.WorkDays * pm_WageSheet.RegularDays + pm_WageSheet.Mealsupplement + pm_WageSheet.OtherHandle);
  394. }
  395. }
  396. decimal actualTotal = salary - totalDeduction;
  397. pm_WageSheet.Should = salary;
  398. pm_WageSheet.TotalDeductions = totalDeduction;
  399. pm_WageSheet.TotalRealHair = actualTotal - pm_WageSheet.WithholdingTax;
  400. pm_WageSheet.AfterTax = actualTotal - pm_WageSheet.WithholdingTax;
  401. #endregion
  402. _result = await _wageSheetRep.Post_WageSheet_AddOrEditAsync(dto, pm_WageSheet);
  403. if (_result.Code != 0)
  404. {
  405. return Ok(JsonView(false, _result.Msg));
  406. }
  407. }
  408. catch (Exception ex)
  409. {
  410. return Ok(JsonView(false, ex.Message));
  411. }
  412. return Ok(JsonView(true, _result.Msg, _result.Data));
  413. }
  414. /// <summary>
  415. /// 计算工资
  416. /// </summary>
  417. /// <returns></returns>
  418. [HttpPost]
  419. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  420. public async Task<IActionResult> SalaryCalculatorAsync(SalaryCalculatorDto dto)
  421. {
  422. Result result = new Result();
  423. Stopwatch sw = new Stopwatch();
  424. sw.Start();
  425. //参数处理
  426. string ymFormat = "yyyy-MM";
  427. string dtFormat = "yyyy-MM-dd";
  428. DateTime yearMonthDt, startDt, endDt;
  429. bool yearMonthDtIsValid = DateTime.TryParseExact(dto.yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  430. bool startDtIsValid = DateTime.TryParseExact(dto.startDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt);
  431. bool endDtIsValid = DateTime.TryParseExact(dto.endDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt);
  432. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  433. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  434. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  435. string thisYearMonth = dto.yearMonth;
  436. string preYearMonth = yearMonthDt.AddMonths(-1).ToString("yyyy-MM");
  437. //计算本月工资起止时间 比如是2月的1号-28号,那就是2月1号的零点到3月1号的零点
  438. DateTime thisStartDt = startDt;
  439. DateTime thisEndDt = endDt; //
  440. //本月工资是否有数据 有数据则不计算
  441. result = await _wageSheetRep.Get_WageSheet_ListByYearMonthAsync(thisYearMonth);
  442. if (result.Code == 0)
  443. {
  444. return Ok(JsonView(false, thisYearMonth + " 工资数据已存在,若无人员工资请手动添加!"));
  445. }
  446. //获取上个月工资信息
  447. List<Pm_WageSheet> preWageSheetItems = await _wageSheetRep._sqlSugar.Queryable<Pm_WageSheet>().Where(it => it.IsDel == 0 && it.YearMonth == preYearMonth).ToListAsync();
  448. preWageSheetItems = preWageSheetItems.OrderBy(it => it.UserId).ToList();
  449. if (preWageSheetItems.Count <= 0)
  450. {
  451. return Ok(JsonView(false, thisYearMonth + " 上月工资数据不存在,请手动添加!"));
  452. }
  453. //处理上个月同月同人 多条数据
  454. List<Pm_WageSheet> preWageSheetItems1 = new List<Pm_WageSheet>();
  455. //preWageSheetItems1 = preWageSheetItems.GroupBy(it => new { it.YearMonth, it.UserId })
  456. // .Select(it => it.FirstOrDefault(item => item.Basic != 0))
  457. // .ToList();
  458. preWageSheetItems1 = preWageSheetItems
  459. .GroupBy(it => new { it.YearMonth, it.UserId })
  460. .Select(it => it.FirstOrDefault(item => item.Basic != 0))
  461. .Where(it => it != null)
  462. .ToList()!;
  463. //获取OA系统内所有用户
  464. List<UserNameView> userNames = _usersRep._sqlSugar.SqlQueryable<UserNameView>("Select Id,CnName From Sys_Users").ToList();
  465. List<Pm_WageSheet> wageSheets = new List<Pm_WageSheet>();
  466. _result = await PayrollComputation.SalaryCalculatorAsync(preWageSheetItems1, userNames, dto.UserId, thisYearMonth, thisStartDt, thisEndDt);
  467. #region 批量添加
  468. if (_result.Code != 0)
  469. {
  470. return Ok(JsonView(false, _result.Msg));
  471. }
  472. wageSheets = _result.Data;
  473. var add = await _wageSheetRep._sqlSugar.Insertable(wageSheets).ExecuteCommandAsync();
  474. if (add <= 0)
  475. {
  476. return Ok(JsonView(false, "操作失败!"));
  477. }
  478. #endregion
  479. #region 处理返回数据
  480. //List <WageSheetItemInfoView> wageSheetItems = new List<WageSheetItemInfoView>();
  481. //wageSheetItems = _mapper.Map<List<WageSheetItemInfoView>>(wageSheets);
  482. //wageSheetItems = wageSheetItems.Select(it =>
  483. // {
  484. // UserNameView? uName1 = new UserNameView();
  485. // UserNameView? uName2 = new UserNameView();
  486. // uName1 = userNames.Where(it1 => it.UserId == it1.Id).FirstOrDefault();
  487. // if (uName1 != null) it.Name = uName1.CnName;
  488. // uName2 = userNames.Where(it1 => it.LastUpdateUserId == it1.Id).FirstOrDefault();
  489. // if (uName2 != null) it.LastUpdateUserName = uName2.CnName;
  490. // return it; }
  491. // ).ToList();
  492. #endregion
  493. sw.Stop();
  494. return Ok(JsonView(true, "操作成功! 耗时:" + (sw.ElapsedMilliseconds / 1000) + "s"));
  495. }
  496. /// <summary>
  497. /// 计算工资 By YearMonth And UserId
  498. /// </summary>
  499. /// <returns></returns>
  500. [HttpPost]
  501. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  502. public async Task<IActionResult> SalaryCalculatorSingleAsync(SalaryCalculatorSingleDto dto)
  503. {
  504. Result result = new Result();
  505. Stopwatch sw = new Stopwatch();
  506. sw.Start();
  507. //参数处理
  508. string ymFormat = "yyyy-MM";
  509. string ymdFormat = "yyyy-MM-dd";
  510. DateTime yearMonthDt, startDt, endDt;
  511. bool yearMonthDtIsValid = DateTime.TryParseExact(dto.YearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  512. bool startDtIsValid = DateTime.TryParseExact(dto.StartDate, ymdFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt);
  513. bool endDtIsValid = DateTime.TryParseExact(dto.EndDate, ymdFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt);
  514. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  515. if (!startDtIsValid) return Ok(JsonView(false, "开始时间格式错误!正确时间格式:yyyy-MM-dd "));
  516. if (!yearMonthDtIsValid) return Ok(JsonView(false, "结束时间格式错误!正确时间格式:yyyy-MM-dd "));
  517. List<Pm_WageSheet> wageSheets = new List<Pm_WageSheet>();
  518. Pm_WageSheet wageSheet = _mapper.Map<Pm_WageSheet>(dto);
  519. Pm_WageSheet wageSheet1 = await _wageSheetRep._sqlSugar.Queryable<Pm_WageSheet>().Where(it => it.UserId == dto.UserId && it.YearMonth == dto.YearMonth && it.StartDate == dto.StartDate && it.EndDate == dto.EndDate).FirstAsync();
  520. if (wageSheet1 != null)
  521. {
  522. wageSheet.Id = wageSheet1.Id;
  523. }
  524. wageSheets.Add(wageSheet);
  525. //获取OA系统内所有用户
  526. List<UserNameView> userNames = _usersRep._sqlSugar.SqlQueryable<UserNameView>("Select Id,CnName From Sys_Users").ToList();
  527. _result = await PayrollComputation.SalaryCalculatorAsync(wageSheets, userNames, dto.UserId, dto.YearMonth, startDt, endDt);
  528. if (_result.Code != 0)
  529. {
  530. return Ok(JsonView(false, _result.Msg));
  531. }
  532. List<Pm_WageSheet> wageSheets1 = new List<Pm_WageSheet>();
  533. wageSheets1 = _result.Data;
  534. #region 处理返回数据
  535. List<WageSheetInfoView> wageSheetItems = new List<WageSheetInfoView>();
  536. wageSheetItems = _mapper.Map<List<WageSheetInfoView>>(wageSheets1);
  537. wageSheetItems = wageSheetItems.Select(it =>
  538. {
  539. UserNameView? uName1 = new UserNameView();
  540. UserNameView? uName2 = new UserNameView();
  541. uName1 = userNames.Where(it1 => it.UserId == it1.Id).FirstOrDefault();
  542. if (uName1 != null) it.Name = uName1.CnName;
  543. uName2 = userNames.Where(it1 => it.LastUpdateUserId == it1.Id).FirstOrDefault();
  544. if (uName2 != null) it.LastUpdateUserName = uName2.CnName;
  545. return it;
  546. }
  547. ).ToList();
  548. #endregion
  549. sw.Stop();
  550. return Ok(JsonView(true, "操作成功!耗时:" + (sw.ElapsedMilliseconds / 1000) + "s", wageSheetItems[0]));
  551. }
  552. /// <summary>
  553. /// 导出工资单
  554. /// </summary>
  555. /// <returns></returns>
  556. [HttpPost]
  557. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  558. public async Task<IActionResult> ExportWageCard(string yearMonth)
  559. {
  560. Result result = new Result();
  561. Stopwatch sw = new Stopwatch();
  562. sw.Start();
  563. //参数处理
  564. string ymFormat = "yyyy-MM";
  565. DateTime yearMonthDt;
  566. bool yearMonthDtIsValid = DateTime.TryParseExact(yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  567. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  568. //公司部门
  569. string sql = string.Format(@"Select row_number() over(order by pm_ws.Id) as Row_Number,
  570. sc.Id as CompanyId,sc.CompanyName,sd.Id as DepId,sd.DepName,
  571. sys_u1.CnName Name,sys_u2.CnName LastUpdateUserName,pm_ws.*
  572. From Pm_WageSheet pm_ws
  573. Left Join Sys_Users sys_u1 On pm_ws.UserId = sys_u1.Id
  574. Left Join Sys_Users sys_u2 On pm_ws.LastUpdateUserId = sys_u2.Id
  575. Left Join Sys_Company sc On sys_u1.companyId = sc.Id
  576. Left Join Sys_Department sd On sys_u1.DepId = sd.Id
  577. Where pm_ws.IsDel = 0 And pm_ws.YearMonth = '{0}'", yearMonth);
  578. var wageSheetList = await _wageSheetRep._sqlSugar.SqlQueryable<ExportWageSheetItemView>(sql).ToListAsync();
  579. if (wageSheetList.Count <= 0)
  580. {
  581. return Ok(JsonView(false, yearMonth + "暂无工资数据!"));
  582. }
  583. decimal SumPrice = 0.00M;
  584. foreach (var item in wageSheetList)
  585. {
  586. SumPrice += item.AfterTax;
  587. }
  588. WorkbookDesigner designer = new WorkbookDesigner();
  589. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/工资详细清单.xlsx");
  590. designer.Workbook.Worksheets[0].Name = yearMonth + " 工资单";
  591. designer.SetDataSource("WageSheet", wageSheetList);
  592. designer.SetDataSource("YearMonth", yearMonth);
  593. designer.SetDataSource("StartEndDt", wageSheetList[0].StartDate + " - " + wageSheetList[0].EndDate);
  594. designer.SetDataSource("WorkDays", wageSheetList[0].WorkDays);
  595. designer.SetDataSource("SumPrice", SumPrice);
  596. designer.SetDataSource("WageSheetTitle", "工资单");//
  597. designer.Process();
  598. string fileName = "WageCard/" + yearMonth + "_工资单_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  599. string path = AppSettingsHelper.Get("ExcelBasePath");
  600. designer.Workbook.Save(path + fileName);
  601. designer = null;
  602. string excelPath = AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  603. string url = AppSettingsHelper.Get("ExcelBaseUrl");
  604. string fileUrl = url + excelPath;
  605. sw.Stop();
  606. return Ok(JsonView(true, "操作成功!耗时:" + (sw.ElapsedMilliseconds / 1000) + "s", new { FileUrl = fileUrl }));
  607. }
  608. /// <summary>
  609. /// 下载个税模板
  610. /// </summary>
  611. /// <returns></returns>
  612. [HttpPost]
  613. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  614. public async Task<IActionResult> WageSheetTaxTemplate()
  615. {
  616. string serverUrl = AppSettingsHelper.Get("WageSheetExcelBaseUrl");
  617. var userData = await _usersRep.GetUserNameList(1);
  618. if (userData.Code == 0)
  619. {
  620. var userNames = userData.Data;
  621. List<string> names = new List<string>();
  622. List<UserNameView> users = new List<UserNameView>();
  623. names.Add("管理员");
  624. names.Add("国交共享号");
  625. names.Add("人事审核号");
  626. names.Add("国交主管号");
  627. List<TaxTemlateViuw> taxs = new List<TaxTemlateViuw>();
  628. users = JsonConvert.DeserializeObject<List<UserNameView>>(JsonConvert.SerializeObject(userNames));
  629. foreach (UserNameView item in users)
  630. {
  631. string uName = item.CnName;
  632. if (!names.Contains(uName))
  633. {
  634. taxs.Add(new TaxTemlateViuw { UserName = item.CnName });
  635. }
  636. }
  637. if (taxs.Count > 0)
  638. {
  639. WorkbookDesigner designer = new WorkbookDesigner();
  640. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/个税导入模板.xlsx");
  641. designer.Workbook.Worksheets[0].Name = "个税模板";
  642. designer.SetDataSource("TaxTemp", taxs);
  643. designer.Process();
  644. string fileName = "WageSheetTaxFile/个税模板" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  645. string path = AppSettingsHelper.Get("ExcelBasePath");
  646. designer.Workbook.Save(path + fileName);
  647. designer = null;
  648. string excelPath = AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  649. string url = AppSettingsHelper.Get("ExcelBaseUrl");
  650. string fileUrl = url + excelPath;
  651. return Ok(JsonView(true, "操作成功!", new { FileUrl = fileUrl }));
  652. }
  653. }
  654. return Ok(JsonView(false, "操作失败!"));
  655. }
  656. /// <summary>
  657. /// 上传个税
  658. /// </summary>
  659. /// <returns></returns>
  660. [HttpPost]
  661. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  662. public async Task<IActionResult> UploadTax(IFormFile file)
  663. {
  664. try
  665. {
  666. var yearMonth = Request.Headers["YearMonth"].ToString();
  667. //string yearMonth = "2023-10";
  668. string ymFormat = "yyyy-MM";
  669. DateTime yearMonthDt;
  670. bool yearMonthDtIsValid = DateTime.TryParseExact(yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  671. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  672. if (file != null)
  673. {
  674. var fileDir = AppSettingsHelper.Get("WageSheetExcelFptPath");
  675. //文件名称
  676. string projectFileName = file.FileName;
  677. //上传的文件的路径
  678. string filePath = "";
  679. if (!Directory.Exists(fileDir))
  680. {
  681. Directory.CreateDirectory(fileDir);
  682. }
  683. //上传的文件的路径
  684. filePath = fileDir + $@"\{projectFileName}";
  685. if (System.IO.File.Exists(filePath))
  686. {
  687. //删除文件
  688. System.IO.File.Delete(filePath);
  689. }
  690. using (FileStream fs = System.IO.File.Create(filePath))
  691. {
  692. file.CopyTo(fs);
  693. fs.Flush();
  694. }
  695. if (System.IO.File.Exists(filePath))
  696. {
  697. Workbook book = new Workbook(filePath);
  698. DataSet dataSet = new DataSet();
  699. if (book.Worksheets.Count > 0)
  700. {
  701. var sheet = book.Worksheets[0];
  702. if (sheet != null)
  703. {
  704. // sheets 中的数据必须存在
  705. if (sheet.Cells.MaxDataRow != -1 && sheet.Cells.MaxDataColumn != -1)
  706. {
  707. // 方法 ExportDataTable 的参数说明
  708. // 要导出的第一个单元格的行号。
  709. // 要导出的第一个单元格的列号。
  710. // 要导入的行数。
  711. // 要导入的列数。
  712. // 指示第一行的数据是否导出到DataTable的列名。
  713. DataTable dataTable = sheet.Cells.ExportDataTable(0, 0, sheet.Cells.MaxDataRow + 1, sheet.Cells.MaxDataColumn + 1, true);
  714. dataSet.Tables.Add(dataTable);
  715. DataTable taxData = dataSet.Tables[0];
  716. //公司部门
  717. string sql = string.Format(@"Select row_number() over(order by pm_ws.Id) as Row_Number,
  718. sc.Id as CompanyId,sc.CompanyName,sd.Id as DepId,sd.DepName,
  719. sys_u1.CnName Name,sys_u2.CnName LastUpdateUserName,pm_ws.*
  720. From Pm_WageSheet pm_ws
  721. Left Join Sys_Users sys_u1 On pm_ws.UserId = sys_u1.Id
  722. Left Join Sys_Users sys_u2 On pm_ws.LastUpdateUserId = sys_u2.Id
  723. Left Join Sys_Company sc On sys_u1.companyId = sc.Id
  724. Left Join Sys_Department sd On sys_u1.DepId = sd.Id
  725. Where pm_ws.IsDel = 0 And pm_ws.YearMonth = '{0}'
  726. Order By UserId Asc ", yearMonth);
  727. var wageSheetList = await _wageSheetRep._sqlSugar.SqlQueryable<WageSheetInfoView>(sql).ToListAsync();
  728. if (wageSheetList.Count <= 0)
  729. {
  730. return Ok(JsonView(false, yearMonth + "工资数据不存在,请先添加工资数据!"));
  731. }
  732. for (int i = 0; i < taxData.Rows.Count; i++)
  733. {
  734. string name = taxData.Rows[i][0].ToString().Trim();
  735. List<WageSheetInfoView> wageSheets = new List<WageSheetInfoView>();
  736. wageSheets = wageSheetList.Where(it => it.Name.Equals(name)).ToList();
  737. if (wageSheets.Count > 0)
  738. {
  739. wageSheetList.Where(it => it.Name.Equals(name))
  740. .Select(it =>
  741. {
  742. //修改 绩效不等于0.00M的数据
  743. //decimal oldTax = it.WithholdingTax;
  744. var newTax = Convert.ToDecimal(taxData.Rows[i][1].ToString());
  745. it.WithholdingTax = newTax;
  746. it.TotalRealHair = it.Should - it.TotalDeductions - newTax;
  747. return it;
  748. })
  749. .ToList();
  750. }
  751. }
  752. List<Pm_WageSheet> wageSheets1 = new List<Pm_WageSheet>();
  753. wageSheets1 = _mapper.Map<List<Pm_WageSheet>>(wageSheetList);
  754. var updateStatus = _wageSheetRep._sqlSugar
  755. .Updateable(wageSheets1)
  756. .UpdateColumns(it => new { it.WithholdingTax, it.TotalRealHair })
  757. .ExecuteCommand();
  758. if (updateStatus < 0)
  759. {
  760. return Ok(JsonView(false, "操作失败!"));
  761. }
  762. if (System.IO.File.Exists(filePath))
  763. {
  764. //删除文件
  765. System.IO.File.Delete(filePath);
  766. }
  767. return Ok(JsonView(true, "操作成功!"));
  768. }
  769. }
  770. else
  771. {
  772. return Ok(JsonView(false, "工作薄没有数据!"));
  773. }
  774. }
  775. }
  776. return Ok(JsonView(true, "上传成功!", projectFileName));
  777. }
  778. else
  779. {
  780. return Ok(JsonView(false, "上传失败!"));
  781. }
  782. }
  783. catch (Exception ex)
  784. {
  785. return Ok(JsonView(false, "程序错误!"));
  786. throw;
  787. }
  788. //return Ok(JsonView(true, "操作成功!"));
  789. }
  790. /// <summary>
  791. /// 打卡记录测试
  792. /// </summary>
  793. /// <returns></returns>
  794. [HttpPost]
  795. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  796. public async Task<IActionResult> Test(string startDt, string endDt, int code)
  797. {
  798. UserIdListView userIdListView = await _qiYeWeChatApiService.GetUserIdListAsync();
  799. if (userIdListView.errcode != 0)
  800. {
  801. _result.Msg = "【企业微信】【打卡】【获取员工ID】【Msg】" + userIdListView.errmsg;
  802. return Ok(JsonView(false, _result.Msg));
  803. }
  804. List<string> qyWhchatIdList = new List<string>();
  805. //qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid).ToList();
  806. qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid!).ToList();
  807. var data = await _qiYeWeChatApiService.GetCheckinDataAsync(qyWhchatIdList, code, Convert.ToDateTime(startDt), Convert.ToDateTime(endDt));
  808. return Ok(JsonView(true, "操作成功!", data.checkindata));
  809. }
  810. /// <summary>
  811. /// 审批详情
  812. /// </summary>
  813. /// <returns></returns>
  814. [HttpPost]
  815. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  816. public async Task<IActionResult> PostApprovalDetailAsync(string spNo)
  817. {
  818. if (string.IsNullOrEmpty(spNo))
  819. {
  820. return Ok(JsonView(false, "审批单号不能为空!!"));
  821. }
  822. var data = await _qiYeWeChatApiService.GetApprovalDetailAsync(spNo);
  823. return Ok(JsonView(true, "操作成功!", data));
  824. }
  825. #endregion
  826. #region 任务单
  827. /// <summary>
  828. /// 任务分配
  829. /// 基础数据源
  830. /// </summary>
  831. /// <returns></returns>
  832. [HttpPost]
  833. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  834. public async Task<IActionResult> PostTaskAllocationInit(TaskAllocationInitDto dto)
  835. {
  836. #region 参数验证
  837. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  838. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  839. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  840. #region 页面操作权限验证
  841. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  842. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  843. #endregion
  844. #endregion
  845. var _view = await _taskAllocationRep._Init(dto.PortType, dto.UserId);
  846. if (_view.Code == 0)
  847. {
  848. return Ok(JsonView(true, "查询成功!", _view.Data));
  849. }
  850. return Ok(JsonView(false, _view.Msg));
  851. }
  852. /// <summary>
  853. /// 任务分配
  854. /// page
  855. /// </summary>
  856. /// <returns></returns>
  857. [HttpPost]
  858. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  859. public async Task<IActionResult> PostTaskAllocationPage(TaskAllocationPageDto dto)
  860. {
  861. #region 参数验证
  862. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  863. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  864. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  865. #region 页面操作权限验证
  866. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  867. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  868. #endregion
  869. #endregion
  870. string whereSql = "" ,currUserName = "";
  871. #region 分页参数处理
  872. //类型处理
  873. if (dto.Type == 0) whereSql = "";
  874. else if (dto.Type == 1) //1 由我指派
  875. {
  876. whereSql = string.Format(@" And ta.CreateUserId = {0} Or (Select COUNT(1) As PeopleNumber From Pm_TaskRelevanceUser Where IsDel = 0 And ta.Id = TAId And UserId = {0}) > 0", dto.UserId);
  877. }
  878. else if (dto.Type == 2)// 2 指派给我
  879. {
  880. whereSql = string.Format(@" And (Select COUNT(1) As PeopleNumber From Pm_TaskRelevanceUser Where IsDel = 0 And ta.Id = TAId And UserId = {0}) > 0", dto.UserId);
  881. }
  882. //状态 -1 全部 0 未开始 1 进行中 2 待审核 3 未完成 4 已完成
  883. if (dto.Status == -1) //全部
  884. {
  885. whereSql += "";
  886. }
  887. else
  888. {
  889. whereSql += string.Format(@" And ta.Status = {0} ", dto.Status);
  890. }
  891. //任务名称
  892. if (!string.IsNullOrEmpty(dto.TaskName))
  893. {
  894. whereSql += string.Format(@" And ta.TaskName Like '%{0}%' ", dto.TaskName);
  895. }
  896. #endregion
  897. var currUserInfo = await _sqlSugar.Queryable<Sys_Users>().FirstAsync(x => x.Id == dto.UserId);
  898. if (currUserInfo != null) currUserName = currUserInfo.CnName;
  899. string pageSql = string.Format(@"Select
  900. ROW_NUMBER() OVER(
  901. ORDER BY
  902. CreateTime Desc
  903. ) AS RowNumber,
  904. *
  905. From
  906. (
  907. Select
  908. ta.Id,
  909. ta.TaskName,
  910. ta.TaskPriority,
  911. d.DepName,
  912. di.TeamName,
  913. ta.Status,
  914. ta.PredictBeginTime,
  915. ta.PredictEndTime,
  916. u.CnName As CreateUserName,
  917. ta.CreateTime,
  918. (
  919. SELECT
  920. STUFF(
  921. (
  922. Select
  923. ',' + u.CnName
  924. From
  925. Pm_TaskRelevanceUser tra
  926. Left Join Sys_Users u On tra.UserId = u.Id
  927. Where
  928. tra.Isdel = 0
  929. And tra.TAId = ta.Id FOR XML PATH('')
  930. ),
  931. 1,
  932. 1,
  933. ''
  934. )
  935. ) As Participant,
  936. (
  937. SELECT
  938. STUFF(
  939. (
  940. Select
  941. ',' + u.CnName
  942. From
  943. Pm_TaskRelevanceUser tra
  944. Left Join Sys_Users u On tra.UserId = u.Id
  945. Where
  946. tra.Isdel = 0
  947. And tra.TAId = ta.Id
  948. And tra.TaskStatus = 4 FOR XML PATH('')
  949. ),
  950. 1,
  951. 1,
  952. ''
  953. )
  954. ) As Consummator
  955. From
  956. Pm_TaskAllocation ta
  957. Left Join Sys_Department d On ta.DepId = d.Id
  958. Left Join Grp_DelegationInfo di On ta.DiId = di.Id
  959. Left Join Sys_Users u On ta.CreateUserId = u.Id
  960. Where
  961. ta.IsDel = 0 {0}
  962. ) As temp
  963. WHERE
  964. [CreateUserName] like '%{1}%'
  965. OR [Participant] like '%{2}%' ", whereSql, currUserName, currUserName);
  966. RefAsync<int> total = 0;
  967. var _view = await _taskAllocationRep._sqlSugar.SqlQueryable<TaskListView>(pageSql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);//ToPageAsync
  968. List<int> taskIds = new List<int>();
  969. taskIds = _view.Select(it => it.Id).ToList();
  970. string taskerSql = string.Format(@"Select tau.TAId,tau.Id,tau.UserId,u.CnName As UserName,tau.BeginTime,tau.OverTime,tau.TaskStatus,
  971. tau.Cause,tau.Score,tau.Remark As ScoreRemark,tau.CreateUserId As TaskCreateUserId
  972. From Pm_TaskRelevanceUser tau
  973. Left Join Sys_Users u On tau.UserId = u.Id
  974. Where tau.IsDel = 0");
  975. var taskerData = _taskAllocationRep._sqlSugar.SqlQueryable<TaskerDetailsView>(taskerSql).Where(it => taskIds.Contains(it.TAId)).ToList();
  976. foreach (var item in _view)
  977. {
  978. //任务接收者显示自己任务状态
  979. if (!item.CreateUserName.Equals(currUserName))
  980. {
  981. var subTaskInfo = taskerData.FirstOrDefault(x => item.Id == x.TAId && x.UserId == dto.UserId);
  982. if (subTaskInfo != null) item.Status = subTaskInfo.TaskStatus;
  983. }
  984. else
  985. {
  986. item.TaskerDetails = taskerData.Where(it => it.TAId == item.Id).ToList();
  987. }
  988. ////处理任务总状态 And 任务人状态
  989. //var taskerStatusData = taskerData.Where(it => it.TAId == item.Id && it.TaskCreateUserId != dto.UserId && it.UserId == dto.UserId).FirstOrDefault();
  990. //if (taskerStatusData != null)
  991. //{
  992. // item.Status = taskerStatusData.TaskStatus;
  993. //}
  994. }
  995. return Ok(JsonView(true, "查询成功!", _view, total));
  996. }
  997. /// <summary>
  998. /// 任务分配
  999. /// 详情
  1000. /// </summary>
  1001. /// <returns></returns>
  1002. [HttpPost]
  1003. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1004. public async Task<IActionResult> PostTaskAllocationDetails(TaskAllocationDetailsDto dto)
  1005. {
  1006. #region 参数验证
  1007. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1008. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1009. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1010. #region 页面操作权限验证
  1011. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1012. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  1013. #endregion
  1014. #endregion
  1015. var _view = await _taskAllocationRep._Details(dto.PortType, dto.Id);
  1016. if (_view.Code == 0)
  1017. {
  1018. return Ok(JsonView(true, "查询成功!", _view.Data));
  1019. }
  1020. return Ok(JsonView(false, _view.Msg));
  1021. }
  1022. /// <summary>
  1023. /// 任务分配
  1024. /// Add Or Edit
  1025. /// </summary>
  1026. /// <returns></returns>
  1027. [HttpPost]
  1028. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1029. public async Task<IActionResult> PostTaskAllocationAddOrEdit(TaskAllocationAddOrEditDto dto)
  1030. {
  1031. #region 参数验证
  1032. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1033. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1034. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1035. #region 页面操作权限验证
  1036. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1037. if (dto.Id == 0)
  1038. {
  1039. if (pageFunAuthView.AddAuth == 0) return Ok(JsonView(false, "您没有添加权限!"));
  1040. }
  1041. else if (dto.Id > 0)
  1042. {
  1043. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1044. }
  1045. #endregion
  1046. #endregion
  1047. var _view = await _taskAllocationRep._AddOrEdit(dto);
  1048. if (_view.Code == 0)
  1049. {
  1050. if (dto.Id == 0) //添加提示任务单创建
  1051. {
  1052. string title = $"[{dto.TaskName}] 任务新建成功!";
  1053. string content = $"[{dto.TaskName}] 任务新建成功,请前往任务页面查看详情!";
  1054. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, dto.UserIds);
  1055. }
  1056. return Ok(JsonView(true, "操作成功!"));
  1057. }
  1058. return Ok(JsonView(false, _view.Msg));
  1059. }
  1060. /// <summary>
  1061. /// 任务分配
  1062. /// 状态任务归属人详情
  1063. /// </summary>
  1064. /// <returns></returns>
  1065. [HttpPost]
  1066. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1067. public async Task<IActionResult> PostTaskAllocationTaskerDetails(TaskerDetailsDto dto)
  1068. {
  1069. var _view = await _taskAllocationRep._TaskerDetails(dto.Id);
  1070. if (_view.Code == 0)
  1071. {
  1072. return Ok(JsonView(true, "操作成功!", _view.Data));
  1073. }
  1074. return Ok(JsonView(false, _view.Msg));
  1075. }
  1076. /// <summary>
  1077. /// 任务分配
  1078. /// 状态任务归属人设置开始状态
  1079. /// </summary>
  1080. /// <returns></returns>
  1081. [HttpPost]
  1082. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1083. public async Task<IActionResult> PostTaskAllocationSetStartStatus(TaskerStatusDto dto)
  1084. {
  1085. var _view = await _taskAllocationRep._TaskerSetStartStatus(dto.UserId, dto.Id);
  1086. if (_view.Code == 0)
  1087. {
  1088. //发送消息
  1089. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1090. if (taskData != null)
  1091. {
  1092. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.TAId == dto.Id).Select(it => it.UserId).ToList();
  1093. if (taskUserIds.Count > 0)
  1094. {
  1095. taskUserIds.Remove(dto.UserId);
  1096. }
  1097. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == dto.UserId).Select(it => it.CnName).First();
  1098. string title_createUser = $"[{taskData.TaskName}] 进度更新!";
  1099. string conten_createUser = $"[{UserName}] 已开始任务,请注意该工作人员任务进度!";
  1100. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title_createUser, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1101. string title = $"[{taskData.TaskName}] 进度更新!";
  1102. string content = $"[{UserName}] 已开始任务.若需查看,请前往任务页面查看详情!";
  1103. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //其他人发送消息
  1104. string content1 = $"任务已开始,请在规定时间完成!若需查看,请前往任务页面查看详情!";
  1105. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content1, new List<int>() { dto.UserId }); //设置任务人 发送消息
  1106. }
  1107. return Ok(JsonView(true, "操作成功!"));
  1108. }
  1109. return Ok(JsonView(false, _view.Msg));
  1110. }
  1111. /// <summary>
  1112. /// 任务分配
  1113. /// 状态 任务归属人 设置完成状态
  1114. /// </summary>
  1115. /// <returns></returns>
  1116. [HttpPost]
  1117. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1118. public async Task<IActionResult> PostTaskAllocationSetOverStatus(TaskerStatusDto dto)
  1119. {
  1120. var _view = await _taskAllocationRep._TaskerSetOverStatus(dto.UserId, dto.Id);
  1121. if (_view.Code == 0)
  1122. {
  1123. //发送消息
  1124. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1125. if (taskData != null)
  1126. {
  1127. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.TAId == dto.Id).Select(it => it.UserId).ToList();
  1128. if (taskUserIds.Count > 0)
  1129. {
  1130. taskUserIds.Remove(dto.UserId);
  1131. }
  1132. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == dto.UserId).Select(it => it.CnName).First();
  1133. string title_createUser = $"[{taskData.TaskName}] 进度更新!";
  1134. string conten_createUser = $"[{UserName}] 已完成任务,请前往任务页面进行审核操作!";
  1135. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title_createUser, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1136. string title = $"[{taskData.TaskName}] 进度更新!";
  1137. string content = $"[{UserName}] 已完成任务,请注意在规定时间内完成任务.若需查看,请前往任务页面查看详情!";
  1138. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //其他人发送消息
  1139. string content1 = $"任务已完成,等待任务发布人审核!若需查看,请前往任务页面查看详情!";
  1140. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content1, new List<int>() { dto.UserId }); //设置任务人 发送消息
  1141. }
  1142. return Ok(JsonView(true, "操作成功!"));
  1143. }
  1144. return Ok(JsonView(false, _view.Msg));
  1145. }
  1146. /// <summary>
  1147. /// 任务分配
  1148. /// 状态 任务归属人 设置知晓状态
  1149. /// </summary>
  1150. /// <returns></returns>
  1151. [HttpPost]
  1152. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1153. public async Task<IActionResult> PostTaskAllocationSetHaveStatus(TaskAllocationStatusDto dto)
  1154. {
  1155. var _view = await _taskAllocationRep._TaskSetHaveStatus(dto.SubId);
  1156. if (_view.Code == 0)
  1157. {
  1158. //发送消息
  1159. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1160. if (taskUserData != null)
  1161. {
  1162. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1163. if (taskData != null)
  1164. {
  1165. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == taskData.CreateUserId).Select(it => it.CnName).First();
  1166. string title = $"[{taskData.TaskName}] 进度更新!";
  1167. string conten_createUser = $"[{UserName}] 已知晓任务.若需查看,请前往任务页面查看详情!";
  1168. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1169. string content = $"请注意任务完成时间!若需查看,请前往任务页面查看详情!";
  1170. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1171. }
  1172. }
  1173. return Ok(JsonView(true, "操作成功!"));
  1174. }
  1175. return Ok(JsonView(false, _view.Msg));
  1176. }
  1177. /// <summary>
  1178. /// 任务分配
  1179. /// 任务发布者 单人设置审批状态
  1180. /// </summary>
  1181. /// <returns></returns>
  1182. [HttpPost]
  1183. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1184. public async Task<IActionResult> PostTaskAllocationSetAuditStatus(TaskAllocationStatusDto dto)
  1185. {
  1186. var _view = await _taskAllocationRep._TaskSetAuditStatus(dto.SubId);
  1187. if (_view.Code == 0)
  1188. {
  1189. //发送消息
  1190. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1191. if (taskUserData != null)
  1192. {
  1193. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1194. if (taskData != null)
  1195. {
  1196. string title = $"[{taskData.TaskName}] 进度更新!";
  1197. string content = $"任务已完成!若需查看,请前往任务页面查看详情!";
  1198. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1199. }
  1200. }
  1201. return Ok(JsonView(true, "操作成功!"));
  1202. }
  1203. return Ok(JsonView(false, _view.Msg));
  1204. }
  1205. /// <summary>
  1206. /// 任务分配
  1207. /// 任务发布者 单人设置未完成状态
  1208. /// </summary>
  1209. /// <returns></returns>
  1210. [HttpPost]
  1211. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1212. public async Task<IActionResult> PostTaskAllocationSetUnFinishedStatus(TaskAllocationSetUnFinishedStatusDto dto)
  1213. {
  1214. var _view = await _taskAllocationRep._TaskSetUnFinishedStatus(dto.SubId, dto.Cause);
  1215. if (_view.Code == 0)
  1216. {
  1217. //发送消息
  1218. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1219. if (taskUserData != null)
  1220. {
  1221. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1222. if (taskData != null)
  1223. {
  1224. string title = $"[{taskData.TaskName}] 进度更新!";
  1225. string content = $"任务未完成!若需查看,请前往任务页面查看详情!";
  1226. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1227. }
  1228. }
  1229. return Ok(JsonView(true, "操作成功!"));
  1230. }
  1231. return Ok(JsonView(false, _view.Msg));
  1232. }
  1233. ///// <summary>
  1234. ///// 任务分配
  1235. ///// 确认任务是否可操作完成
  1236. ///// </summary>
  1237. ///// <returns></returns>
  1238. //[HttpPost]
  1239. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1240. //public async Task<IActionResult> PostTaskAllocationIsConfirmCompletion(TaskAllocationScoreDto dto)
  1241. //{
  1242. // try
  1243. // {
  1244. // #region 参数验证
  1245. // if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1246. // if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1247. // PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1248. // #region 页面操作权限验证
  1249. // pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1250. // if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1251. // #endregion
  1252. // #endregion
  1253. // var _view = await _taskAllocationRep._TaskConfirmCompletion(dto.PortType, dto.Id);
  1254. // if (_view.Code == 0)
  1255. // {
  1256. // return Ok(JsonView(true, "操作成功!"));
  1257. // }
  1258. // return Ok(JsonView(false, _view.Msg));
  1259. // }
  1260. // catch (Exception ex)
  1261. // {
  1262. // return Ok(JsonView(false, ex.Message));
  1263. // }
  1264. //}
  1265. ///// <summary>
  1266. ///// 任务分配
  1267. ///// 任务确认完成
  1268. ///// </summary>
  1269. ///// <returns></returns>
  1270. //[HttpPost]
  1271. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1272. //public async Task<IActionResult> PostTaskAllocationConfirmCompletion(TaskAllocationConfirmCompletionDto dto)
  1273. //{
  1274. // try
  1275. // {
  1276. // #region 参数验证
  1277. // if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1278. // if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1279. // PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1280. // #region 页面操作权限验证
  1281. // pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1282. // if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1283. // #endregion
  1284. // #endregion
  1285. // var _view = await _taskAllocationRep._TaskConfirmCompletion(dto.PortType,dto.Id);
  1286. // if (_view.Code == 0)
  1287. // {
  1288. // return Ok(JsonView(true, "操作成功!"));
  1289. // }
  1290. // return Ok(JsonView(false, _view.Msg));
  1291. // }
  1292. // catch (Exception ex)
  1293. // {
  1294. // return Ok(JsonView(false, ex.Message));
  1295. // }
  1296. //}
  1297. /// <summary>
  1298. /// 任务分配
  1299. /// 任务发布者 任务评分
  1300. /// </summary>
  1301. /// <returns></returns>
  1302. [HttpPost]
  1303. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1304. public async Task<IActionResult> PostTaskAllocationScore(TaskAllocationScoreDto dto)
  1305. {
  1306. #region 参数验证
  1307. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1308. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1309. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1310. #region 页面操作权限验证
  1311. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1312. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1313. #endregion
  1314. #endregion
  1315. var _view = await _taskAllocationRep._TaskScore(dto);
  1316. if (_view.Code == 0)
  1317. {
  1318. //发送消息
  1319. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1320. if (taskUserData != null)
  1321. {
  1322. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1323. if (taskData != null)
  1324. {
  1325. string title = $"[{taskData.TaskName}] 进度更新!";
  1326. string content = $"任务评分已完成!若需查看,请前往任务页面查看详情!";
  1327. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1328. }
  1329. }
  1330. return Ok(JsonView(true, "操作成功!"));
  1331. }
  1332. return Ok(JsonView(false, _view.Msg));
  1333. }
  1334. /// <summary>
  1335. /// 任务分配
  1336. /// 任务发布者 任务终止
  1337. /// </summary>
  1338. /// <returns></returns>
  1339. [HttpPost]
  1340. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1341. public async Task<IActionResult> PostTaskAllocationTermination(TaskAllocationConfirmCompletionDto dto)
  1342. {
  1343. #region 参数验证
  1344. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1345. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1346. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1347. #region 页面操作权限验证
  1348. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1349. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1350. #endregion
  1351. #endregion
  1352. var _view = await _taskAllocationRep._TaskTermination(dto.Id);
  1353. if (_view.Code == 0)
  1354. {
  1355. //发送消息
  1356. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1357. if (taskData != null)
  1358. {
  1359. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.Id).Select(it => it.UserId).ToList();
  1360. taskUserIds.Add(taskData.CreateUserId);
  1361. string title = $"[{taskData.TaskName}] 进度更新!";
  1362. string content = $"任务已终止!若需查看,请前往任务页面查看详情!";
  1363. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //设置任务人 发送消息
  1364. }
  1365. return Ok(JsonView(true, "操作成功!"));
  1366. }
  1367. return Ok(JsonView(false, _view.Msg));
  1368. }
  1369. /// <summary>
  1370. /// 任务分配
  1371. /// 任务发布者 任务删除
  1372. /// </summary>
  1373. /// <returns></returns>
  1374. [HttpPost]
  1375. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1376. public async Task<IActionResult> PostTaskAllocationDel(TaskAllocationConfirmCompletionDto dto)
  1377. {
  1378. #region 参数验证
  1379. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1380. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1381. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1382. #region 页面操作权限验证
  1383. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1384. if (pageFunAuthView.DeleteAuth == 0) return Ok(JsonView(false, "您没有删除权限!"));
  1385. #endregion
  1386. #endregion
  1387. var _view = await _taskAllocationRep._TaskDel(dto.Id);
  1388. if (_view.Code == 0)
  1389. {
  1390. return Ok(JsonView(true, "操作成功!"));
  1391. }
  1392. return Ok(JsonView(false, _view.Msg));
  1393. }
  1394. #endregion
  1395. #region 团组状态通知
  1396. /// <summary>
  1397. /// 测试
  1398. /// </summary>
  1399. /// <param name="dto"></param>
  1400. /// <returns></returns>
  1401. [HttpPost]
  1402. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1403. public async Task<IActionResult> Test_QIYEWX(PostTourClientListDownloadFile dto)
  1404. {
  1405. //List<string> templist = new List<string>() { 234.ToString() };
  1406. //await AppNoticeLibrary.SendUserMsg_GroupStatus_AuditFee(14090, templist, QiyeWeChatEnum.TestChat);
  1407. //await AppNoticeLibrary.SendUserMsg_GroupShare_ToJob(dto.DiId); ;
  1408. //DeleReminderMessage.PostMessageByWebhook();
  1409. //GroupStatus_UserSimplelistView list = await _qiYeWeChatApiService.GroupStatus_GetUserList();
  1410. //创建群聊
  1411. //List<string> userList1 = new List<string>() { "Feint", "amy.zhu@pan-american-intl.com", "judy.zeng@pan-american-intl.com", "FuHongJin" };
  1412. //List<string> userList2 = new List<string>() { "Feint", "ZhaoYaQi", "LiaoWenYa" };
  1413. //List<string> userList3 = new List<string>() { "Feint", "amy.zhu@pan-american-intl.com", "judy.zeng@pan-american-intl.com", "FuHongJin", "ZhaoYaQi", "LiaoWenYa" };
  1414. //GroupStatus_CreateChatView rst1 = await _qiYeWeChatApiService.GroupStatus_CreateChat("团组通知", "Feint", userList1, "CaiWuChat01");
  1415. //GroupStatus_CreateChatView rst2 = await _qiYeWeChatApiService.GroupStatus_CreateChat("OA通知-国交部", "Feint", userList2, "GuoJiaoLeader01");
  1416. //GroupStatus_CreateChatView rst3 = await _qiYeWeChatApiService.GroupStatus_CreateChat("OA通知-团组(公司客户)", "Feint", userList3, "CompanyCRMChat01");
  1417. //推送消息(模板)
  1418. //List<string> userList = new List<string>() { "Feint", "huaju.liu", "johnny.yang@pan-american-intl.com" };
  1419. //List<string> userList = new List<string>() { "Feint", "johnny.yang@pan-american-intl.com" };
  1420. //GroupStatus_CreateChatView rst1 = await _qiYeWeChatApiService.GroupStatus_CreateChat("团组费用提示", "Feint", userList, "GuoJiaoChat01");
  1421. //团组出发
  1422. //AppNoticeLibrary.SendUserMsg_GroupStatus_Create(2358, userList);
  1423. //费用审核
  1424. //AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(dto.DiId, QiyeWeChatEnum.TestChat);
  1425. //费用审核结果通知(通过情况下发送财务群)
  1426. //List<string> userList = new List<string>() { "234" };
  1427. //AppNoticeLibrary.SendUserMsg_GroupStatus_AuditFee(dto.DiId, userList, QiyeWeChatEnum.CaiWuChat02);
  1428. //4、财务付款时:(1)对应版块人员【单独发,状态为已付款才发】
  1429. //AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(dto.DiId, userList);
  1430. //团组提醒财务群
  1431. //DateTime dtNow = DateTime.Now;
  1432. //List<Grp_DelegationInfo> listSource = _usersRep.Query<Grp_DelegationInfo>(s => s.IsDel == 0 && s.VisitStartDate >= dtNow).Take(3).ToList();
  1433. //List<Grp_DelegationInfo> listAdd7day = _usersRep.Query<Grp_DelegationInfo>(s => s.IsDel == 0 && s.VisitStartDate >= dtNow).Take(3).ToList();
  1434. //List<Grp_DelegationInfo> listAdd3day = new List<Grp_DelegationInfo>() { };
  1435. //AppNoticeLibrary.SendChatMsg_GroupRemindersToCaiwu(listAdd7day, listAdd3day, QiyeWeChatEnum.TestChat);
  1436. //日付申请提醒财务群
  1437. //AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dto.DiId, QiyeWeChatEnum.CaiWuChat02);
  1438. //日付申请结果推送用户、成功通知财务群
  1439. //AppNoticeLibrary.DailyPayReminder_Audit_ToUser(dto.DiId, userList, QiyeWeChatEnum.TestChat);
  1440. //AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dto.DiId, userList);
  1441. //string q = "";
  1442. DeleReminderMessage.PostMessageByWebhook_CRMStatistics();
  1443. return Ok(JsonView(true, "操作成功!"));
  1444. }
  1445. #endregion
  1446. #region 物资进销存
  1447. /// <summary>
  1448. /// 物资进销存
  1449. /// 基础数据类型
  1450. /// </summary>
  1451. /// <returns></returns>
  1452. [HttpGet]
  1453. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1454. public async Task<IActionResult> GoodsInitDataSource()
  1455. {
  1456. return Ok(await _goodsRep.InitDataSource());
  1457. }
  1458. /// <summary>
  1459. /// 物资进销存
  1460. /// 基础数据类型 --> 团组名称列表 分页
  1461. /// </summary>
  1462. /// <returns></returns>
  1463. [HttpPost]
  1464. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1465. public async Task<IActionResult> GoodsGroupNameInit(QueryGroupListOffsetDto dto)
  1466. {
  1467. var watch = new Stopwatch();
  1468. watch.Start();
  1469. var countyDatas = await _sqlSugar
  1470. .Queryable<Grp_DelegationInfo>()
  1471. .Where((di) => di.IsDel == 0 && !string.IsNullOrWhiteSpace(di.TeamName))
  1472. .OrderBy((di) => new { id = SqlFunc.Desc(di.Id) })
  1473. .Select((di) => new { id = di.Id, name = di.TeamName})
  1474. .ToListAsync();
  1475. countyDatas.Insert(0, new { id = 0, name = "其他物资(公司内部物资)"});
  1476. countyDatas.Insert(0, new { id = -1, name = "拜访客户所使用的物资" });
  1477. countyDatas.Insert(0, new { id = -2, name = "库存调整" });
  1478. var total = countyDatas.Count;
  1479. countyDatas = countyDatas.WhereIF(!string.IsNullOrEmpty(dto.Search), x => x.name.Contains(dto.Search)).ToList();
  1480. countyDatas = countyDatas
  1481. .Skip((dto.PageIndex - 1) * dto.PageSize)
  1482. .Take(dto.PageSize)
  1483. .ToList();
  1484. watch.Stop();
  1485. return Ok(JsonView(true, $"{MsgTips.Succeed},耗时 {watch.ElapsedMilliseconds} ms", countyDatas, total));
  1486. }
  1487. /// <summary>
  1488. /// 物资进销存
  1489. /// 物品 列表
  1490. /// </summary>
  1491. /// <returns></returns>
  1492. [HttpPost]
  1493. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1494. public async Task<IActionResult> GoodsList(GoodsListDto dto)
  1495. {
  1496. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1497. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1498. return Ok(await _goodsRep.GoodsList(dto));
  1499. }
  1500. /// <summary>
  1501. /// 物资进销存
  1502. /// 物品 详情
  1503. /// </summary>
  1504. /// <returns></returns>
  1505. [HttpGet()]
  1506. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1507. public async Task<IActionResult> GoodsInfo(int portType, int id)
  1508. {
  1509. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1510. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1511. return Ok(await _goodsRep.GoodsInfo(portType, id));
  1512. }
  1513. /// <summary>
  1514. /// 物资进销存
  1515. /// 物品 OP(Add OR Edit)
  1516. /// </summary>
  1517. /// <returns></returns>
  1518. [HttpPost]
  1519. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1520. public async Task<IActionResult> GoodsOP(GoodsOpDto dto)
  1521. {
  1522. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1523. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1524. var validator = new GoodsOPDTOValidator();
  1525. var validatorRes = await validator.ValidateAsync(dto);
  1526. if (!validatorRes.IsValid)
  1527. {
  1528. var sb = new StringBuilder();
  1529. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1530. return Ok(JsonView(false, sb.ToString()));
  1531. }
  1532. return Ok(await _goodsRep.GoodsOp(dto, currUserInfo.UserId));
  1533. }
  1534. /// <summary>
  1535. /// 物资进销存
  1536. /// 物品 Del
  1537. /// </summary>
  1538. /// <returns></returns>
  1539. [HttpDelete("{id}")]
  1540. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1541. public async Task<IActionResult> GoodsDel(int id)
  1542. {
  1543. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1544. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1545. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1546. return Ok(await _goodsRep.GoodsDel(id, currUserInfo.UserId));
  1547. }
  1548. /// <summary>
  1549. /// 物资进销存
  1550. /// 入库 列表
  1551. /// </summary>
  1552. /// <returns></returns>
  1553. [HttpPost]
  1554. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1555. public async Task<IActionResult> GoodsStorageList(GoodsStorageListDto dto)
  1556. {
  1557. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1558. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1559. return Ok(await _goodsRep.GoodsStorageList(dto));
  1560. }
  1561. /// <summary>
  1562. /// 物资进销存
  1563. /// 入库 详情
  1564. /// </summary>
  1565. /// <returns></returns>
  1566. [HttpGet("{id}")]
  1567. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1568. public async Task<IActionResult> GoodsStorageInfo([FromQuery] int portType, int id)
  1569. {
  1570. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1571. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1572. return Ok(await _goodsRep.GoodsStorageInfo(portType, id));
  1573. }
  1574. /// <summary>
  1575. /// 物资进销存
  1576. /// 入库 OP(Add OR Edit)
  1577. /// </summary>
  1578. /// <returns></returns>
  1579. [HttpPost]
  1580. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1581. public async Task<IActionResult> GoodsStorageOp(GoodsStorageOpDto dto)
  1582. {
  1583. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1584. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1585. var validator = new GoodsStorageOpDtoValidator();
  1586. var validatorRes = await validator.ValidateAsync(dto);
  1587. if (!validatorRes.IsValid)
  1588. {
  1589. var sb = new StringBuilder();
  1590. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1591. return Ok(JsonView(false, sb.ToString()));
  1592. }
  1593. return Ok(await _goodsRep.GoodsStorageOp(dto, currUserInfo.UserId));
  1594. }
  1595. /// <summary>
  1596. /// 物资进销存
  1597. /// 入库 Del
  1598. /// </summary>
  1599. /// <returns></returns>
  1600. [HttpDelete("{id}")]
  1601. //[Authorize]
  1602. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1603. public async Task<IActionResult> GoodsStorageDel(int id)
  1604. {
  1605. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1606. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1607. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1608. return Ok(await _goodsRep.GoodsStorageDel(id, currUserInfo.UserId));
  1609. }
  1610. /// <summary>
  1611. /// 物资进销存
  1612. /// 入库 excelDownload
  1613. /// </summary>
  1614. /// <returns></returns>
  1615. [HttpPost]
  1616. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1617. public async Task<IActionResult> GoodsStorageExcelDownload()
  1618. {
  1619. //token验证
  1620. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1621. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1622. //文件下载权限验证
  1623. int userId = currUserInfo.UserId,
  1624. pageId = 191;
  1625. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1626. #region 页面操作权限验证
  1627. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  1628. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您未分配文件下载权限!"));
  1629. #endregion
  1630. return Ok(await _goodsRep.GoodsStorageExcelDownload());
  1631. }
  1632. /// <summary>
  1633. /// 物资进销存
  1634. /// 领用 List
  1635. /// </summary>
  1636. /// <returns></returns>
  1637. [HttpPost]
  1638. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1639. public async Task<IActionResult> GoodsReceiveList(GoodsReceiveListDTO dto)
  1640. {
  1641. //token验证
  1642. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1643. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1644. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1645. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1646. //文件下载权限验证
  1647. int userId = currUserInfo.UserId,
  1648. pageId = 191;
  1649. if (dto.IsExcelDownload )
  1650. {
  1651. if (userId < 1) return Ok(JsonView(false, "excel导出时,需传入正确的当前操作人UserId!"));
  1652. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1653. #region 页面操作权限验证
  1654. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  1655. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您未分配文件下载权限!"));
  1656. #endregion
  1657. }
  1658. return Ok(await _goodsRep.GoodsReceiveList(dto));
  1659. }
  1660. /// <summary>
  1661. /// 物资进销存
  1662. /// 领用详情
  1663. /// </summary>
  1664. /// <returns></returns>
  1665. [HttpGet("{id}")]
  1666. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1667. public async Task<IActionResult> GoodsReceiveInfo([FromQuery] int portType, int id)
  1668. {
  1669. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1670. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1671. return Ok(await _goodsRep.GoodsReceiveInfo(portType, id));
  1672. }
  1673. /// <summary>
  1674. /// 物资进销存
  1675. /// 领用 OP
  1676. /// </summary>
  1677. /// <returns></returns>
  1678. [HttpPost]
  1679. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1680. public async Task<IActionResult> GoodsReceiveOP(GoodsReceiveOpDto dto)
  1681. {
  1682. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1683. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1684. var validator = new GoodsReceiveOpDtoValidator();
  1685. var validatorRes = await validator.ValidateAsync(dto);
  1686. if (!validatorRes.IsValid)
  1687. {
  1688. var sb = new StringBuilder();
  1689. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1690. return Ok(JsonView(false, sb.ToString()));
  1691. }
  1692. return Ok(await _goodsRep.GoodsReceiveOp(dto, currUserInfo.UserId));
  1693. }
  1694. /// <summary>
  1695. /// 物资进销存
  1696. /// 领用 审核
  1697. /// </summary>
  1698. /// <param name="dto"></param>
  1699. /// <returns></returns>
  1700. [HttpPost]
  1701. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1702. public async Task<IActionResult> GoodsReceiveAudit(GoodsReceiveAuditDTO dto)
  1703. {
  1704. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1705. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1706. var validator = new GoodsReceiveAuditDTOValidator();
  1707. var validatorRes = await validator.ValidateAsync(dto);
  1708. if (!validatorRes.IsValid)
  1709. {
  1710. var sb = new StringBuilder();
  1711. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1712. return Ok(JsonView(false, sb.ToString()));
  1713. }
  1714. int[] idArray = dto.Label
  1715. .Split(',')
  1716. .Select(x =>
  1717. {
  1718. if (int.TryParse(x, out var id)) return id;
  1719. return id;
  1720. })
  1721. .ToArray();
  1722. return Ok(await _goodsRep.GoodsReceiveAudit(idArray, currUserInfo.UserId, dto.AuditEnum));
  1723. }
  1724. /// <summary>
  1725. /// 物资进销存
  1726. /// 领用 Del
  1727. /// </summary>
  1728. /// <returns></returns>
  1729. [HttpDelete("{id}")]
  1730. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1731. public async Task<IActionResult> GoodsReceiveDel(int id)
  1732. {
  1733. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1734. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1735. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1736. return Ok(await _goodsRep.GoodsReceiveDel(id, currUserInfo.UserId));
  1737. }
  1738. #endregion
  1739. #region 员工绩效
  1740. /// <summary>
  1741. /// 员工绩效组成结构获取
  1742. /// </summary>
  1743. /// <param name="userid"></param>
  1744. /// <param name="date"></param>
  1745. /// <returns></returns>
  1746. [HttpGet]
  1747. public IActionResult GetPerformanceList(int userid,string date, int loginUser)
  1748. {
  1749. var jw = JsonView(false);
  1750. if (!DateTime.TryParse(date,out DateTime date_Dt))
  1751. {
  1752. jw.Msg = "日期格式有误!";
  1753. return Ok(jw);
  1754. }
  1755. string sql_CTE = $@"-- 定义递归查询的CTE
  1756. WITH PerAssessmentSettingsCTE AS (
  1757. -- 选择指定ID的记录作为起点
  1758. SELECT
  1759. pac.Id,
  1760. pac.Name,
  1761. pac.AssessmentProportion,
  1762. pac.AssessmentStandard,
  1763. pac.ParentId,
  1764. 1 AS Depth
  1765. FROM
  1766. Per_AssessmentSetting pac
  1767. INNER JOIN
  1768. Per_AssessmentContentSetting pacs
  1769. ON
  1770. pac.id = pacs.assessmentSettingid AND pacs.isdel = 0
  1771. WHERE
  1772. pacs.userid = {userid}
  1773. AND
  1774. pac.isdel = 0
  1775. UNION ALL
  1776. -- 递归部分,选择所有子级记录
  1777. SELECT
  1778. ps.Id,
  1779. ps.Name,
  1780. ps.AssessmentProportion,
  1781. ps.AssessmentStandard,
  1782. ps.ParentId,
  1783. CAST(caste.Depth as int) + 1
  1784. FROM
  1785. Per_AssessmentSetting ps
  1786. INNER JOIN PerAssessmentSettingsCTE caste ON ps.Id = caste.ParentId)
  1787. -- 从CTE中选择最终结果
  1788. SELECT * FROM PerAssessmentSettingsCTE
  1789. OPTION (MAXRECURSION 0); -- 允许无限递归 ";
  1790. var result_CTE = _sqlSugar.Ado.SqlQuery<Per_AssessmentSetting>(sql_CTE);
  1791. var ids = result_CTE.Select(x => x.Id);
  1792. var List = _sqlSugar.Queryable<Per_AssessmentSetting>()
  1793. .LeftJoin<Per_AssessmentContentSetting>((a, b) => a.Id == b.AssessmentSettingId && b.IsDel == 0 && b.UserId == userid)
  1794. .LeftJoin<Per_AssessmentScore>((a, b,c) => b.Id == c.AssessmentContentSettingId && c.IsDel == 0 && c.YearMonth.Year == date_Dt.Year && c.YearMonth.Month == date_Dt.Month)
  1795. .Where((a, b) => a.IsDel == 0 && ids.Contains(a.Id))
  1796. .Select((a, b, c) => new TreeNode
  1797. {
  1798. Id = a.Id,
  1799. ContentId = b.Id,
  1800. Name = a.Name,
  1801. ParentId = a.ParentId,
  1802. AssessmentProportion = a.AssessmentProportion, //占比
  1803. AssessmentStandard = a.AssessmentStandard, //描述
  1804. AssessmentProportionChi = b.AssessmentProportionChi, //占比
  1805. UserId = b.UserId,
  1806. JobId = b.JobId,
  1807. AssessmentSettingId = b.AssessmentSettingId,
  1808. Fixed = b.Fixed,
  1809. TargetValue = b.TargetValue,
  1810. AssessmentProportion_Percentage = a.AssessmentProportion * 100,
  1811. HigherUpAssessment = c.HigherUpAssessment,
  1812. HigherUpConfig = c.HigherUpConfig,
  1813. HigherUpUserId = c.HigherUpUserId,
  1814. Score = c.Score,
  1815. ScoreTotal = c.ScoreTotal,
  1816. SelfAssessment = c.SelfAssessment,
  1817. Status = c.Status,
  1818. YearMonth = c.YearMonth,
  1819. })
  1820. .ToList();
  1821. var rootNodeList = List.Where(x => x.ParentId == 0);
  1822. var rootResult = rootNodeList.Select(x => BuildSubTree(x, List));
  1823. jw.Data = new
  1824. {
  1825. Root = rootResult,
  1826. IsLeader = IsLeader(userid,loginUser)
  1827. };
  1828. jw.Code = 200;
  1829. jw.Msg = "成功";
  1830. return Ok(jw);
  1831. }
  1832. private TreeNode BuildSubTree(TreeNode parent, List<TreeNode> nodes)
  1833. {
  1834. var children = nodes
  1835. .Where(n => n.ParentId == parent.Id)
  1836. .Select(n => BuildSubTree(n, nodes))
  1837. .ToList();
  1838. parent.Children = children;
  1839. return parent;
  1840. }
  1841. /// <summary>
  1842. /// 绩效项增改
  1843. /// </summary>
  1844. /// <param name="dto"></param>
  1845. /// <returns></returns>
  1846. [HttpPost]
  1847. public async Task<IActionResult> AssessmentSettingOperationAsync(PerAssessmentSettingOperationDto dto)
  1848. {
  1849. var jw = JsonView(false);
  1850. if (!ModelState.IsValid)
  1851. {
  1852. jw.Msg = "参数错误";
  1853. jw.Data = ModelState;
  1854. return Ok(jw);
  1855. }
  1856. try
  1857. {
  1858. if (dto.ParentId != 0)
  1859. {
  1860. var parent = await _sqlSugar.Queryable<Per_AssessmentSetting>().FirstAsync(x=>x.IsDel == 0 && x.Id == dto.ParentId);
  1861. if (parent == null)
  1862. {
  1863. jw.Msg = "父级节点不存在";
  1864. return Ok(jw);
  1865. }
  1866. }
  1867. var entity = new Per_AssessmentSetting
  1868. {
  1869. Name = dto.Name,
  1870. AssessmentProportion = dto.AssessmentProportion,
  1871. AssessmentStandard = dto.AssessmentStandard,
  1872. ParentId = dto.ParentId,
  1873. Id = dto.Id,
  1874. Remark = dto.Remark,
  1875. };
  1876. jw.Code = 200;
  1877. if (dto.Id == 0)
  1878. {
  1879. entity.CreateUserId = dto.CreateId;
  1880. entity.CreateTime = DateTime.Now;
  1881. await _sqlSugar.Insertable(entity).ExecuteCommandAsync();
  1882. jw.Msg = "添加成功!";
  1883. }
  1884. else
  1885. {
  1886. await _sqlSugar.Updateable(entity).ExecuteCommandAsync();
  1887. jw.Msg = "修改成功!";
  1888. }
  1889. }
  1890. catch (Exception ex)
  1891. {
  1892. jw.Msg = "Api error " + ex.Message;
  1893. jw.Code = 400;
  1894. }
  1895. return Ok(jw);
  1896. }
  1897. /// <summary>
  1898. /// 绩效内容增改
  1899. /// </summary>
  1900. /// <param name="dto"></param>
  1901. /// <returns></returns>
  1902. [HttpPost]
  1903. public IActionResult AssessmentSettingOperationContentAsync(AssessmentSettingOperationContenDto dto)
  1904. {
  1905. var jw = JsonView(false, "", "");
  1906. var entity = new Per_AssessmentContentSetting
  1907. {
  1908. AssessmentProportionChi = dto.AssessmentProportionChi,
  1909. AssessmentSettingId = dto.AssessmentSettingId,
  1910. CreateTime = DateTime.Now,
  1911. CreateUserId = dto.CreateUserId,
  1912. Fixed = dto.Fixed,
  1913. Id = dto.Id,
  1914. JobId = dto.JobId,
  1915. TargetValue = dto.TargetValue,
  1916. UserId = dto.UserId,
  1917. Remark = dto.Remark,
  1918. };
  1919. var entity_Fk = _sqlSugar.Queryable<Per_AssessmentSetting>().First(x => x.Id == dto.AssessmentSettingId && x.IsDel == 0);
  1920. if (entity_Fk == null)
  1921. {
  1922. jw.Msg = "考核设置不存在";
  1923. return Ok(jw);
  1924. }
  1925. try
  1926. {
  1927. if (dto.Id == 0)
  1928. {
  1929. //add
  1930. var insertCount = _sqlSugar.Insertable(entity).ExecuteCommand();
  1931. jw.Msg = "添加成功!";
  1932. }
  1933. else
  1934. {
  1935. //update
  1936. var updateCount = _sqlSugar.Updateable(entity).ExecuteCommand();
  1937. jw.Msg = "修改成功!";
  1938. }
  1939. jw.Code = 200;
  1940. }
  1941. catch (Exception ex)
  1942. {
  1943. jw.Msg = "Api error " + ex.Message;
  1944. jw.Code = 400;
  1945. }
  1946. return Ok(jw);
  1947. }
  1948. /// <summary>
  1949. /// 绩效项查询
  1950. /// </summary>
  1951. /// <param name="dto"></param>
  1952. /// <returns></returns>
  1953. [HttpPost]
  1954. public async Task<IActionResult> QueryAssessmentSettingListOffsetAsync(QueryAssessmentSettingListOffsetAsyncDto dto)
  1955. {
  1956. var jw = JsonView(false);
  1957. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  1958. var entities = await _sqlSugar.Queryable<Per_AssessmentSetting>()
  1959. .Where(x=>x.IsDel == 0)
  1960. .WhereIF(!string.IsNullOrEmpty(dto.SearchValue), e => e.Name.Contains(dto.SearchValue))
  1961. .ToPageListAsync(dto.pageIndex, dto.pageSize, total);
  1962. var DtoResult = entities.Select(e => new
  1963. {
  1964. e.Id,
  1965. Name = e.Name,
  1966. AssessmentProportion = e.AssessmentProportion,
  1967. AssessmentStandard = e.AssessmentStandard,
  1968. ParentId = e.ParentId,
  1969. Remark = e.Remark
  1970. }).ToList();
  1971. jw.Data = new
  1972. {
  1973. total = total.Value,
  1974. dto.pageIndex,
  1975. dto.pageSize,
  1976. List = DtoResult
  1977. };
  1978. jw.Code = 200;
  1979. jw.Msg = "查询成功!";
  1980. return Ok(jw);
  1981. }
  1982. /// <summary>
  1983. /// 绩效分数保存
  1984. /// </summary>
  1985. /// <param name="dto"></param>
  1986. /// <returns></returns>
  1987. [HttpPost]
  1988. public IActionResult SaveUserAssessmen(SaveUserAssessmenDto dto)
  1989. {
  1990. var jw = JsonView(false,"请传入正确的数据!");
  1991. if (dto.Data.Any()) {
  1992. if (!DateTime.TryParse(dto.AssessmenData, out DateTime yearMonth_Dt))
  1993. {
  1994. jw.Data = "月份参数有误!";
  1995. return Ok(jw);
  1996. }
  1997. try
  1998. {
  1999. var ids = dto.Data.Select(x => x.AssessmentContentSettingId).ToList();
  2000. var QueryContent_DB = _sqlSugar.Queryable<Per_AssessmentContentSetting>()
  2001. .InnerJoin<Per_AssessmentSetting>((a, b) => b.IsDel == 0 && a.AssessmentSettingId == b.Id)
  2002. .Where((a, b) => a.IsDel == 0 && ids.Contains(a.Id))
  2003. .Select((a, b) => new
  2004. {
  2005. ContentSettingId = a.Id,
  2006. SettingId = b.Id,
  2007. a.TargetValue,
  2008. b.AssessmentStandard,
  2009. MergeStr = $"【项名称:{b.Name}/目标值:{a.TargetValue}/评估标准:{b.AssessmentStandard}】",
  2010. a.AssessmentProportionChi,
  2011. b.Name
  2012. })
  2013. .ToList()
  2014. .ToDictionary(x => x.ContentSettingId);
  2015. //删除上级未确认数据
  2016. var expressionWhere = Expressionable
  2017. .Create<Per_AssessmentScore>()
  2018. .And(x => x.YearMonth.Year == yearMonth_Dt.Year && x.YearMonth.Month == yearMonth_Dt.Month)
  2019. .And(x => ids.Contains(x.AssessmentContentSettingId))
  2020. .And(x => x.HigherUpConfig == 0)
  2021. .ToExpression();
  2022. if (IsLeader(dto.AssessmenUserId, dto.CreateUserId))
  2023. {
  2024. expressionWhere = Expressionable
  2025. .Create<Per_AssessmentScore>()
  2026. .And(x => x.YearMonth.Year == yearMonth_Dt.Year && x.YearMonth.Month == yearMonth_Dt.Month)
  2027. .And(x => ids.Contains(x.AssessmentContentSettingId))
  2028. .ToExpression();
  2029. }
  2030. _sqlSugar.BeginTran();
  2031. _sqlSugar.Updateable<Per_AssessmentScore>()
  2032. .Where(expressionWhere)
  2033. .SetColumns(x => new Per_AssessmentScore { IsDel = 1, DeleteUserId = dto.CreateUserId, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })
  2034. .ExecuteCommand();
  2035. var entityList = new List<Per_AssessmentScore>();
  2036. foreach (var x in dto.Data)
  2037. {
  2038. if (x.HigherUpAssessment > 100 || x.SelfAssessment > 100)
  2039. {
  2040. jw.Msg = QueryContent_DB[x.AssessmentContentSettingId].Name + "项分数不能超过100。";
  2041. return Ok(jw);
  2042. }
  2043. Per_AssessmentScore item = new Per_AssessmentScore
  2044. {
  2045. AssessmentContentSettingId = x.AssessmentContentSettingId,
  2046. CreateTime = DateTime.Now,
  2047. CreateUserId = dto.CreateUserId,
  2048. Details = QueryContent_DB[x.AssessmentContentSettingId].MergeStr,
  2049. HigherUpAssessment = x.HigherUpAssessment,
  2050. HigherUpUserId = x.LeadersId,
  2051. HigherUpConfig = x.HigherUpAssessment > 0 ? 1 : 0,
  2052. SelfAssessment = x.SelfAssessment,
  2053. IsDel = 0,
  2054. Status = x.Status,
  2055. YearMonth = yearMonth_Dt,
  2056. Score = x.SelfAssessment * 0.3M + x.HigherUpAssessment * 0.7M,
  2057. ScoreTotal = (x.SelfAssessment * 0.3M + x.HigherUpAssessment * 0.7M) * QueryContent_DB[x.AssessmentContentSettingId].AssessmentProportionChi,
  2058. };
  2059. entityList.Add(item);
  2060. }
  2061. var influenceRow = _sqlSugar.Insertable(entityList).ExecuteCommand();
  2062. _sqlSugar.CommitTran();
  2063. jw.Code = 200;
  2064. jw.Msg = "保存成功!";
  2065. jw.Data = $"{influenceRow}条数据操作成功!";
  2066. }
  2067. catch (Exception ex)
  2068. {
  2069. _sqlSugar.RollbackTran();
  2070. jw.Code = 500;
  2071. jw.Data = $"API ERROR ({ex.Message})";
  2072. }
  2073. }
  2074. return Ok(jw);
  2075. }
  2076. /// <summary>
  2077. /// 绩效项删除
  2078. /// </summary>
  2079. /// <param name="dto"></param>
  2080. /// <returns></returns>
  2081. [HttpPost]
  2082. public IActionResult DeleteAssessmentSetting(DeleteAssessmentSettingDto dto)
  2083. {
  2084. var jw = JsonView(false, "删除失败!");
  2085. if (!dto.IdArr.Any())
  2086. {
  2087. jw.Msg = "id不能为空!";
  2088. return Ok(jw);
  2089. }
  2090. var rowCount = _sqlSugar.Updateable<Per_AssessmentSetting>()
  2091. .Where(x => dto.IdArr.Contains(x.Id) && x.IsDel == 0)
  2092. .SetColumns(x => new Per_AssessmentSetting
  2093. {
  2094. IsDel = 1,
  2095. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
  2096. DeleteUserId = dto.UserId,
  2097. })
  2098. .ExecuteCommand();
  2099. jw.Code = 200;
  2100. jw.Msg = $"修改成功!,修改数量{rowCount}";
  2101. return Ok(jw);
  2102. }
  2103. /// <summary>
  2104. /// 绩效内容删除
  2105. /// </summary>
  2106. /// <param name="dto"></param>
  2107. /// <returns></returns>
  2108. [HttpPost]
  2109. public IActionResult DeleteAssessmentContentSetting(DeleteAssessmentSettingDto dto)
  2110. {
  2111. var jw = JsonView(false, "删除失败!");
  2112. if (!dto.IdArr.Any())
  2113. {
  2114. jw.Msg = "id不能为空!";
  2115. return Ok(jw);
  2116. }
  2117. var rowCount = _sqlSugar.Updateable<Per_AssessmentContentSetting>()
  2118. .Where(x => dto.IdArr.Contains(x.Id) && x.IsDel == 0)
  2119. .SetColumns(x => new Per_AssessmentContentSetting
  2120. {
  2121. IsDel = 1,
  2122. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
  2123. DeleteUserId = dto.UserId,
  2124. })
  2125. .ExecuteCommand();
  2126. jw.Code = 200;
  2127. jw.Msg = $"修改成功!,修改数量{rowCount}";
  2128. return Ok(jw);
  2129. }
  2130. private bool IsLeader(int userId, int higherUserId)
  2131. {
  2132. Dictionary <int,List<int>> keyValues = new Dictionary<int, List<int>>()
  2133. {
  2134. { 5 , new List<int>{ 258 , 235, 234, 233, 208 } }
  2135. };
  2136. if (keyValues.ContainsKey(higherUserId))
  2137. {
  2138. return keyValues[higherUserId].Contains(userId);
  2139. }
  2140. return false;
  2141. }
  2142. #endregion
  2143. #region 企微Api测试
  2144. [HttpPost]
  2145. public async Task<IActionResult> GetCheckin_MonthDataAsync(DateTime start, DateTime end)
  2146. {
  2147. var jw = JsonView(false);
  2148. jw.Data = await _qiYeWeChatApiService.GetCheckin_MonthDataAsync1(start,end);
  2149. return Ok(jw);
  2150. }
  2151. [HttpPost]
  2152. public async Task<IActionResult> QueryAssessmentByUser(QueryAssessmentByUser Dto)
  2153. {
  2154. var jw = JsonView(false);
  2155. var user_entity = _sqlSugar.Queryable<Sys_Users>()
  2156. .First(e => e.Id == Dto.UserId && e.IsDel == 0);
  2157. var start_Bool = DateTime.TryParse(Dto.Start, out DateTime start);
  2158. var end_Bool = DateTime.TryParse(Dto.End, out DateTime end);
  2159. if (!start_Bool || !end_Bool)
  2160. {
  2161. jw.Msg = "时间格式不正确!";
  2162. return Ok(jw);
  2163. }
  2164. jw.Msg = "用户企业微信Id未绑定!";
  2165. if (user_entity != null && !string.IsNullOrEmpty(user_entity.QiyeChatUserId))
  2166. {
  2167. var data = await _qiYeWeChatApiService.QueryAssessmentByUser(start, end, new List<string> { user_entity.QiyeChatUserId });
  2168. jw.Data = data;
  2169. jw.Msg = "查询成功!";
  2170. jw.Code = 200;
  2171. }
  2172. return Ok(jw);
  2173. }
  2174. [HttpPost]
  2175. public IActionResult TempTest(QueryAssessmentSettingListOffsetAsyncDto Dto)
  2176. {
  2177. var jw = JsonView(false);
  2178. return Ok(jw);
  2179. }
  2180. #endregion
  2181. }
  2182. }