PersonnelModuleController.cs 94 KB

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