PersonnelModuleController.cs 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  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 = "";
  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. string pageSql = string.Format(@"Select * From(
  898. Select ROW_NUMBER() OVER(ORDER BY ta.CreateTime Desc) AS RowNumber,
  899. ta.Id,ta.TaskName,ta.TaskPriority,d.DepName,di.TeamName,ta.Status,
  900. ta.PredictBeginTime,ta.PredictEndTime,u.CnName As CreateUserName,ta.CreateTime,
  901. (SELECT STUFF(
  902. (Select ',' + u.CnName From Pm_TaskRelevanceUser tra
  903. Left Join Sys_Users u On tra.UserId = u.Id
  904. Where tra.Isdel = 0 And tra.TAId = ta.Id
  905. FOR XML PATH('')),1,1,'')) As Participant,
  906. (SELECT STUFF(
  907. (Select ',' + u.CnName From Pm_TaskRelevanceUser tra
  908. Left Join Sys_Users u On tra.UserId = u.Id
  909. Where tra.Isdel = 0 And tra.TAId = ta.Id And tra.TaskStatus = 4
  910. FOR XML PATH('')),1,1,'')) As Consummator
  911. From Pm_TaskAllocation ta
  912. Left Join Sys_Department d On ta.DepId = d.Id
  913. Left Join Grp_DelegationInfo di On ta.DiId = di.Id
  914. Left Join Sys_Users u On ta.CreateUserId = u.Id
  915. Where ta.IsDel = 0 {0} ) As temp ", whereSql);
  916. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  917. var _view = await _taskAllocationRep._sqlSugar.SqlQueryable<TaskListView>(pageSql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);//ToPageAsync
  918. List<int> taskIds = new List<int>();
  919. taskIds = _view.Select(it => it.Id).ToList();
  920. string taskerSql = string.Format(@"Select tau.TAId,tau.Id,tau.UserId,u.CnName As UserName,tau.BeginTime,tau.OverTime,tau.TaskStatus,
  921. tau.Cause,tau.Score,tau.Remark As ScoreRemark,tau.CreateUserId As TaskCreateUserId
  922. From Pm_TaskRelevanceUser tau
  923. Left Join Sys_Users u On tau.UserId = u.Id
  924. Where tau.IsDel = 0");
  925. var taskerData = _taskAllocationRep._sqlSugar.SqlQueryable<TaskerDetailsView>(taskerSql).Where(it => taskIds.Contains(it.TAId)).ToList();
  926. foreach (var item in _view)
  927. {
  928. item.TaskerDetails = taskerData.Where(it => it.TAId == item.Id).ToList();
  929. ////处理任务总状态 And 任务人状态
  930. //var taskerStatusData = taskerData.Where(it => it.TAId == item.Id && it.TaskCreateUserId != dto.UserId && it.UserId == dto.UserId).FirstOrDefault();
  931. //if (taskerStatusData != null)
  932. //{
  933. // item.Status = taskerStatusData.TaskStatus;
  934. //}
  935. }
  936. return Ok(JsonView(true, "查询成功!", _view, total));
  937. }
  938. /// <summary>
  939. /// 任务分配
  940. /// 详情
  941. /// </summary>
  942. /// <returns></returns>
  943. [HttpPost]
  944. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  945. public async Task<IActionResult> PostTaskAllocationDetails(TaskAllocationDetailsDto dto)
  946. {
  947. #region 参数验证
  948. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  949. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  950. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  951. #region 页面操作权限验证
  952. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  953. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  954. #endregion
  955. #endregion
  956. var _view = await _taskAllocationRep._Details(dto.PortType, dto.Id);
  957. if (_view.Code == 0)
  958. {
  959. return Ok(JsonView(true, "查询成功!", _view.Data));
  960. }
  961. return Ok(JsonView(false, _view.Msg));
  962. }
  963. /// <summary>
  964. /// 任务分配
  965. /// Add Or Edit
  966. /// </summary>
  967. /// <returns></returns>
  968. [HttpPost]
  969. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  970. public async Task<IActionResult> PostTaskAllocationAddOrEdit(TaskAllocationAddOrEditDto dto)
  971. {
  972. #region 参数验证
  973. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  974. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  975. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  976. #region 页面操作权限验证
  977. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  978. if (dto.Id == 0)
  979. {
  980. if (pageFunAuthView.AddAuth == 0) return Ok(JsonView(false, "您没有添加权限!"));
  981. }
  982. else if (dto.Id > 0)
  983. {
  984. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  985. }
  986. #endregion
  987. #endregion
  988. var _view = await _taskAllocationRep._AddOrEdit(dto);
  989. if (_view.Code == 0)
  990. {
  991. if (dto.Id == 0) //添加提示任务单创建
  992. {
  993. string title = $"[{dto.TaskName}] 任务新建成功!";
  994. string content = $"[{dto.TaskName}] 任务新建成功,请前往任务页面查看详情!";
  995. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, dto.UserIds);
  996. }
  997. return Ok(JsonView(true, "操作成功!"));
  998. }
  999. return Ok(JsonView(false, _view.Msg));
  1000. }
  1001. /// <summary>
  1002. /// 任务分配
  1003. /// 状态任务归属人详情
  1004. /// </summary>
  1005. /// <returns></returns>
  1006. [HttpPost]
  1007. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1008. public async Task<IActionResult> PostTaskAllocationTaskerDetails(TaskerDetailsDto dto)
  1009. {
  1010. var _view = await _taskAllocationRep._TaskerDetails(dto.Id);
  1011. if (_view.Code == 0)
  1012. {
  1013. return Ok(JsonView(true, "操作成功!", _view.Data));
  1014. }
  1015. return Ok(JsonView(false, _view.Msg));
  1016. }
  1017. /// <summary>
  1018. /// 任务分配
  1019. /// 状态任务归属人设置开始状态
  1020. /// </summary>
  1021. /// <returns></returns>
  1022. [HttpPost]
  1023. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1024. public async Task<IActionResult> PostTaskAllocationSetStartStatus(TaskerStatusDto dto)
  1025. {
  1026. var _view = await _taskAllocationRep._TaskerSetStartStatus(dto.UserId, dto.Id);
  1027. if (_view.Code == 0)
  1028. {
  1029. //发送消息
  1030. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1031. if (taskData != null)
  1032. {
  1033. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.TAId == dto.Id).Select(it => it.UserId).ToList();
  1034. if (taskUserIds.Count > 0)
  1035. {
  1036. taskUserIds.Remove(dto.UserId);
  1037. }
  1038. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == dto.UserId).Select(it => it.CnName).First();
  1039. string title_createUser = $"[{taskData.TaskName}] 进度更新!";
  1040. string conten_createUser = $"[{UserName}] 已开始任务,请注意该工作人员任务进度!";
  1041. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title_createUser, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1042. string title = $"[{taskData.TaskName}] 进度更新!";
  1043. string content = $"[{UserName}] 已开始任务.若需查看,请前往任务页面查看详情!";
  1044. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //其他人发送消息
  1045. string content1 = $"任务已开始,请在规定时间完成!若需查看,请前往任务页面查看详情!";
  1046. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content1, new List<int>() { dto.UserId }); //设置任务人 发送消息
  1047. }
  1048. return Ok(JsonView(true, "操作成功!"));
  1049. }
  1050. return Ok(JsonView(false, _view.Msg));
  1051. }
  1052. /// <summary>
  1053. /// 任务分配
  1054. /// 状态 任务归属人 设置完成状态
  1055. /// </summary>
  1056. /// <returns></returns>
  1057. [HttpPost]
  1058. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1059. public async Task<IActionResult> PostTaskAllocationSetOverStatus(TaskerStatusDto dto)
  1060. {
  1061. var _view = await _taskAllocationRep._TaskerSetOverStatus(dto.UserId, dto.Id);
  1062. if (_view.Code == 0)
  1063. {
  1064. //发送消息
  1065. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1066. if (taskData != null)
  1067. {
  1068. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.TAId == dto.Id).Select(it => it.UserId).ToList();
  1069. if (taskUserIds.Count > 0)
  1070. {
  1071. taskUserIds.Remove(dto.UserId);
  1072. }
  1073. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == dto.UserId).Select(it => it.CnName).First();
  1074. string title_createUser = $"[{taskData.TaskName}] 进度更新!";
  1075. string conten_createUser = $"[{UserName}] 已完成任务,请前往任务页面进行审核操作!";
  1076. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title_createUser, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1077. string title = $"[{taskData.TaskName}] 进度更新!";
  1078. string content = $"[{UserName}] 已完成任务,请注意在规定时间内完成任务.若需查看,请前往任务页面查看详情!";
  1079. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //其他人发送消息
  1080. string content1 = $"任务已完成,等待任务发布人审核!若需查看,请前往任务页面查看详情!";
  1081. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content1, new List<int>() { dto.UserId }); //设置任务人 发送消息
  1082. }
  1083. return Ok(JsonView(true, "操作成功!"));
  1084. }
  1085. return Ok(JsonView(false, _view.Msg));
  1086. }
  1087. /// <summary>
  1088. /// 任务分配
  1089. /// 状态 任务归属人 设置知晓状态
  1090. /// </summary>
  1091. /// <returns></returns>
  1092. [HttpPost]
  1093. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1094. public async Task<IActionResult> PostTaskAllocationSetHaveStatus(TaskAllocationStatusDto dto)
  1095. {
  1096. var _view = await _taskAllocationRep._TaskSetHaveStatus(dto.SubId);
  1097. if (_view.Code == 0)
  1098. {
  1099. //发送消息
  1100. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1101. if (taskUserData != null)
  1102. {
  1103. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1104. if (taskData != null)
  1105. {
  1106. var UserName = _taskAllocationRep._sqlSugar.Queryable<Sys_Users>().Where(it => it.Id == taskData.CreateUserId).Select(it => it.CnName).First();
  1107. string title = $"[{taskData.TaskName}] 进度更新!";
  1108. string conten_createUser = $"[{UserName}] 已知晓任务.若需查看,请前往任务页面查看详情!";
  1109. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, conten_createUser, new List<int>() { taskData.CreateUserId }); //创建人发送消息
  1110. string content = $"请注意任务完成时间!若需查看,请前往任务页面查看详情!";
  1111. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1112. }
  1113. }
  1114. return Ok(JsonView(true, "操作成功!"));
  1115. }
  1116. return Ok(JsonView(false, _view.Msg));
  1117. }
  1118. /// <summary>
  1119. /// 任务分配
  1120. /// 任务发布者 单人设置审批状态
  1121. /// </summary>
  1122. /// <returns></returns>
  1123. [HttpPost]
  1124. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1125. public async Task<IActionResult> PostTaskAllocationSetAuditStatus(TaskAllocationStatusDto dto)
  1126. {
  1127. var _view = await _taskAllocationRep._TaskSetAuditStatus(dto.SubId);
  1128. if (_view.Code == 0)
  1129. {
  1130. //发送消息
  1131. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1132. if (taskUserData != null)
  1133. {
  1134. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1135. if (taskData != null)
  1136. {
  1137. string title = $"[{taskData.TaskName}] 进度更新!";
  1138. string content = $"任务已完成!若需查看,请前往任务页面查看详情!";
  1139. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1140. }
  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> PostTaskAllocationSetUnFinishedStatus(TaskAllocationSetUnFinishedStatusDto dto)
  1154. {
  1155. var _view = await _taskAllocationRep._TaskSetUnFinishedStatus(dto.SubId, dto.Cause);
  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. string title = $"[{taskData.TaskName}] 进度更新!";
  1166. string content = $"任务未完成!若需查看,请前往任务页面查看详情!";
  1167. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1168. }
  1169. }
  1170. return Ok(JsonView(true, "操作成功!"));
  1171. }
  1172. return Ok(JsonView(false, _view.Msg));
  1173. }
  1174. ///// <summary>
  1175. ///// 任务分配
  1176. ///// 确认任务是否可操作完成
  1177. ///// </summary>
  1178. ///// <returns></returns>
  1179. //[HttpPost]
  1180. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1181. //public async Task<IActionResult> PostTaskAllocationIsConfirmCompletion(TaskAllocationScoreDto dto)
  1182. //{
  1183. // try
  1184. // {
  1185. // #region 参数验证
  1186. // if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1187. // if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1188. // PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1189. // #region 页面操作权限验证
  1190. // pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1191. // if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1192. // #endregion
  1193. // #endregion
  1194. // var _view = await _taskAllocationRep._TaskConfirmCompletion(dto.PortType, dto.Id);
  1195. // if (_view.Code == 0)
  1196. // {
  1197. // return Ok(JsonView(true, "操作成功!"));
  1198. // }
  1199. // return Ok(JsonView(false, _view.Msg));
  1200. // }
  1201. // catch (Exception ex)
  1202. // {
  1203. // return Ok(JsonView(false, ex.Message));
  1204. // }
  1205. //}
  1206. ///// <summary>
  1207. ///// 任务分配
  1208. ///// 任务确认完成
  1209. ///// </summary>
  1210. ///// <returns></returns>
  1211. //[HttpPost]
  1212. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1213. //public async Task<IActionResult> PostTaskAllocationConfirmCompletion(TaskAllocationConfirmCompletionDto dto)
  1214. //{
  1215. // try
  1216. // {
  1217. // #region 参数验证
  1218. // if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1219. // if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1220. // PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1221. // #region 页面操作权限验证
  1222. // pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1223. // if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1224. // #endregion
  1225. // #endregion
  1226. // var _view = await _taskAllocationRep._TaskConfirmCompletion(dto.PortType,dto.Id);
  1227. // if (_view.Code == 0)
  1228. // {
  1229. // return Ok(JsonView(true, "操作成功!"));
  1230. // }
  1231. // return Ok(JsonView(false, _view.Msg));
  1232. // }
  1233. // catch (Exception ex)
  1234. // {
  1235. // return Ok(JsonView(false, ex.Message));
  1236. // }
  1237. //}
  1238. /// <summary>
  1239. /// 任务分配
  1240. /// 任务发布者 任务评分
  1241. /// </summary>
  1242. /// <returns></returns>
  1243. [HttpPost]
  1244. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1245. public async Task<IActionResult> PostTaskAllocationScore(TaskAllocationScoreDto dto)
  1246. {
  1247. #region 参数验证
  1248. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1249. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1250. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1251. #region 页面操作权限验证
  1252. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1253. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1254. #endregion
  1255. #endregion
  1256. var _view = await _taskAllocationRep._TaskScore(dto);
  1257. if (_view.Code == 0)
  1258. {
  1259. //发送消息
  1260. var taskUserData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.SubId).First();
  1261. if (taskUserData != null)
  1262. {
  1263. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == taskUserData.TAId).First();
  1264. if (taskData != null)
  1265. {
  1266. string title = $"[{taskData.TaskName}] 进度更新!";
  1267. string content = $"任务评分已完成!若需查看,请前往任务页面查看详情!";
  1268. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, new List<int>() { taskUserData.UserId }); //设置任务人 发送消息
  1269. }
  1270. }
  1271. return Ok(JsonView(true, "操作成功!"));
  1272. }
  1273. return Ok(JsonView(false, _view.Msg));
  1274. }
  1275. /// <summary>
  1276. /// 任务分配
  1277. /// 任务发布者 任务终止
  1278. /// </summary>
  1279. /// <returns></returns>
  1280. [HttpPost]
  1281. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1282. public async Task<IActionResult> PostTaskAllocationTermination(TaskAllocationConfirmCompletionDto dto)
  1283. {
  1284. #region 参数验证
  1285. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1286. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1287. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1288. #region 页面操作权限验证
  1289. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1290. if (pageFunAuthView.EditAuth == 0) return Ok(JsonView(false, "您没有编辑权限!"));
  1291. #endregion
  1292. #endregion
  1293. var _view = await _taskAllocationRep._TaskTermination(dto.Id);
  1294. if (_view.Code == 0)
  1295. {
  1296. //发送消息
  1297. var taskData = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskAllocation>().Where(it => it.Id == dto.Id).First();
  1298. if (taskData != null)
  1299. {
  1300. var taskUserIds = _taskAllocationRep._sqlSugar.Queryable<Pm_TaskRelevanceUser>().Where(it => it.Id == dto.Id).Select(it => it.UserId).ToList();
  1301. taskUserIds.Add(taskData.CreateUserId);
  1302. string title = $"[{taskData.TaskName}] 进度更新!";
  1303. string content = $"任务已终止!若需查看,请前往任务页面查看详情!";
  1304. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.TaskProgressUpdate, title, content, taskUserIds); //设置任务人 发送消息
  1305. }
  1306. return Ok(JsonView(true, "操作成功!"));
  1307. }
  1308. return Ok(JsonView(false, _view.Msg));
  1309. }
  1310. /// <summary>
  1311. /// 任务分配
  1312. /// 任务发布者 任务删除
  1313. /// </summary>
  1314. /// <returns></returns>
  1315. [HttpPost]
  1316. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1317. public async Task<IActionResult> PostTaskAllocationDel(TaskAllocationConfirmCompletionDto dto)
  1318. {
  1319. #region 参数验证
  1320. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1321. if (dto.PageId < 1) dto.PageId = 172; //任务指派Id
  1322. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1323. #region 页面操作权限验证
  1324. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1325. if (pageFunAuthView.DeleteAuth == 0) return Ok(JsonView(false, "您没有删除权限!"));
  1326. #endregion
  1327. #endregion
  1328. var _view = await _taskAllocationRep._TaskDel(dto.Id);
  1329. if (_view.Code == 0)
  1330. {
  1331. return Ok(JsonView(true, "操作成功!"));
  1332. }
  1333. return Ok(JsonView(false, _view.Msg));
  1334. }
  1335. #endregion
  1336. #region 团组状态通知
  1337. /// <summary>
  1338. /// 测试
  1339. /// </summary>
  1340. /// <param name="dto"></param>
  1341. /// <returns></returns>
  1342. [HttpPost]
  1343. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1344. public async Task<IActionResult> Test_QIYEWX(PostTourClientListDownloadFile dto)
  1345. {
  1346. //List<string> templist = new List<string>() { 234.ToString() };
  1347. //await AppNoticeLibrary.SendUserMsg_GroupStatus_AuditFee(14090, templist, QiyeWeChatEnum.TestChat);
  1348. //await AppNoticeLibrary.SendUserMsg_GroupShare_ToJob(dto.DiId); ;
  1349. //DeleReminderMessage.PostMessageByWebhook();
  1350. //GroupStatus_UserSimplelistView list = await _qiYeWeChatApiService.GroupStatus_GetUserList();
  1351. //创建群聊
  1352. //List<string> userList1 = new List<string>() { "Feint", "amy.zhu@pan-american-intl.com", "judy.zeng@pan-american-intl.com", "FuHongJin" };
  1353. //List<string> userList2 = new List<string>() { "Feint", "ZhaoYaQi", "LiaoWenYa" };
  1354. //List<string> userList3 = new List<string>() { "Feint", "amy.zhu@pan-american-intl.com", "judy.zeng@pan-american-intl.com", "FuHongJin", "ZhaoYaQi", "LiaoWenYa" };
  1355. //GroupStatus_CreateChatView rst1 = await _qiYeWeChatApiService.GroupStatus_CreateChat("团组通知", "Feint", userList1, "CaiWuChat01");
  1356. //GroupStatus_CreateChatView rst2 = await _qiYeWeChatApiService.GroupStatus_CreateChat("OA通知-国交部", "Feint", userList2, "GuoJiaoLeader01");
  1357. //GroupStatus_CreateChatView rst3 = await _qiYeWeChatApiService.GroupStatus_CreateChat("OA通知-团组(公司客户)", "Feint", userList3, "CompanyCRMChat01");
  1358. //推送消息(模板)
  1359. //List<string> userList = new List<string>() { "Feint", "huaju.liu", "johnny.yang@pan-american-intl.com" };
  1360. //List<string> userList = new List<string>() { "Feint", "johnny.yang@pan-american-intl.com" };
  1361. //GroupStatus_CreateChatView rst1 = await _qiYeWeChatApiService.GroupStatus_CreateChat("团组费用提示", "Feint", userList, "GuoJiaoChat01");
  1362. //团组出发
  1363. //AppNoticeLibrary.SendUserMsg_GroupStatus_Create(2358, userList);
  1364. //费用审核
  1365. //AppNoticeLibrary.SendChatMsg_GroupStatus_ApplyFee(dto.DiId, QiyeWeChatEnum.TestChat);
  1366. //费用审核结果通知(通过情况下发送财务群)
  1367. //List<string> userList = new List<string>() { "234" };
  1368. //AppNoticeLibrary.SendUserMsg_GroupStatus_AuditFee(dto.DiId, userList, QiyeWeChatEnum.CaiWuChat02);
  1369. //4、财务付款时:(1)对应版块人员【单独发,状态为已付款才发】
  1370. //AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(dto.DiId, userList);
  1371. //团组提醒财务群
  1372. //DateTime dtNow = DateTime.Now;
  1373. //List<Grp_DelegationInfo> listSource = _usersRep.Query<Grp_DelegationInfo>(s => s.IsDel == 0 && s.VisitStartDate >= dtNow).Take(3).ToList();
  1374. //List<Grp_DelegationInfo> listAdd7day = _usersRep.Query<Grp_DelegationInfo>(s => s.IsDel == 0 && s.VisitStartDate >= dtNow).Take(3).ToList();
  1375. //List<Grp_DelegationInfo> listAdd3day = new List<Grp_DelegationInfo>() { };
  1376. //AppNoticeLibrary.SendChatMsg_GroupRemindersToCaiwu(listAdd7day, listAdd3day, QiyeWeChatEnum.TestChat);
  1377. //日付申请提醒财务群
  1378. //AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dto.DiId, QiyeWeChatEnum.CaiWuChat02);
  1379. //日付申请结果推送用户、成功通知财务群
  1380. //AppNoticeLibrary.DailyPayReminder_Audit_ToUser(dto.DiId, userList, QiyeWeChatEnum.TestChat);
  1381. //AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dto.DiId, userList);
  1382. //string q = "";
  1383. DeleReminderMessage.PostMessageByWebhook_CRMStatistics();
  1384. return Ok(JsonView(true, "操作成功!"));
  1385. }
  1386. #endregion
  1387. #region 物资进销存
  1388. /// <summary>
  1389. /// 物资进销存
  1390. /// 基础数据类型
  1391. /// </summary>
  1392. /// <returns></returns>
  1393. [HttpGet]
  1394. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1395. public async Task<IActionResult> GoodsInitDataSource()
  1396. {
  1397. return Ok(await _goodsRep.InitDataSource());
  1398. }
  1399. /// <summary>
  1400. /// 物资进销存
  1401. /// 基础数据类型 --> 团组名称列表 分页
  1402. /// </summary>
  1403. /// <returns></returns>
  1404. [HttpPost]
  1405. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1406. public async Task<IActionResult> GoodsGroupNameInit(QueryGroupListOffsetDto dto)
  1407. {
  1408. var watch = new Stopwatch();
  1409. watch.Start();
  1410. var countyDatas = await _sqlSugar
  1411. .Queryable<Grp_DelegationInfo>()
  1412. .Where((di) => di.IsDel == 0 && !string.IsNullOrWhiteSpace(di.TeamName))
  1413. .OrderBy((di) => new { id = SqlFunc.Desc(di.Id) })
  1414. .Select((di) => new { id = di.Id, name = di.TeamName})
  1415. .ToListAsync();
  1416. countyDatas.Insert(0, new { id = 0, name = "其他物资(公司内部物资)"});
  1417. countyDatas.Insert(0, new { id = -1, name = "拜访客户所使用的物资" });
  1418. var total = countyDatas.Count;
  1419. countyDatas = countyDatas.WhereIF(!string.IsNullOrEmpty(dto.Search), x => x.name.Contains(dto.Search)).ToList();
  1420. countyDatas = countyDatas
  1421. .Skip((dto.PageIndex - 1) * dto.PageSize)
  1422. .Take(dto.PageSize)
  1423. .ToList();
  1424. watch.Stop();
  1425. return Ok(JsonView(true, $"{MsgTips.Succeed},耗时 {watch.ElapsedMilliseconds} ms", countyDatas, total));
  1426. }
  1427. /// <summary>
  1428. /// 物资进销存
  1429. /// 物品 列表
  1430. /// </summary>
  1431. /// <returns></returns>
  1432. [HttpPost]
  1433. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1434. public async Task<IActionResult> GoodsList(GoodsListDto dto)
  1435. {
  1436. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1437. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1438. return Ok(await _goodsRep.GoodsList(dto));
  1439. }
  1440. /// <summary>
  1441. /// 物资进销存
  1442. /// 物品 详情
  1443. /// </summary>
  1444. /// <returns></returns>
  1445. [HttpGet()]
  1446. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1447. public async Task<IActionResult> GoodsInfo(int portType, int id)
  1448. {
  1449. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1450. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1451. return Ok(await _goodsRep.GoodsInfo(portType, id));
  1452. }
  1453. /// <summary>
  1454. /// 物资进销存
  1455. /// 物品 OP(Add OR Edit)
  1456. /// </summary>
  1457. /// <returns></returns>
  1458. [HttpPost]
  1459. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1460. public async Task<IActionResult> GoodsOP(GoodsOpDto dto)
  1461. {
  1462. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1463. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1464. var validator = new GoodsOPDTOValidator();
  1465. var validatorRes = await validator.ValidateAsync(dto);
  1466. if (!validatorRes.IsValid)
  1467. {
  1468. var sb = new StringBuilder();
  1469. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1470. return Ok(JsonView(false, sb.ToString()));
  1471. }
  1472. return Ok(await _goodsRep.GoodsOp(dto, currUserInfo.UserId));
  1473. }
  1474. /// <summary>
  1475. /// 物资进销存
  1476. /// 物品 Del
  1477. /// </summary>
  1478. /// <returns></returns>
  1479. [HttpDelete("{id}")]
  1480. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1481. public async Task<IActionResult> GoodsDel(int id)
  1482. {
  1483. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1484. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1485. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1486. return Ok(await _goodsRep.GoodsDel(id, currUserInfo.UserId));
  1487. }
  1488. /// <summary>
  1489. /// 物资进销存
  1490. /// 入库 列表
  1491. /// </summary>
  1492. /// <returns></returns>
  1493. [HttpPost]
  1494. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1495. public async Task<IActionResult> GoodsStorageList(GoodsStorageListDto dto)
  1496. {
  1497. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1498. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1499. return Ok(await _goodsRep.GoodsStorageList(dto));
  1500. }
  1501. /// <summary>
  1502. /// 物资进销存
  1503. /// 入库 详情
  1504. /// </summary>
  1505. /// <returns></returns>
  1506. [HttpGet("{id}")]
  1507. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1508. public async Task<IActionResult> GoodsStorageInfo([FromQuery] int portType, int id)
  1509. {
  1510. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1511. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1512. return Ok(await _goodsRep.GoodsStorageInfo(portType, id));
  1513. }
  1514. /// <summary>
  1515. /// 物资进销存
  1516. /// 入库 OP(Add OR Edit)
  1517. /// </summary>
  1518. /// <returns></returns>
  1519. [HttpPost]
  1520. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1521. public async Task<IActionResult> GoodsStorageOp(GoodsStorageOpDto dto)
  1522. {
  1523. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1524. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1525. var validator = new GoodsStorageOpDtoValidator();
  1526. var validatorRes = await validator.ValidateAsync(dto);
  1527. if (!validatorRes.IsValid)
  1528. {
  1529. var sb = new StringBuilder();
  1530. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1531. return Ok(JsonView(false, sb.ToString()));
  1532. }
  1533. return Ok(await _goodsRep.GoodsStorageOp(dto, currUserInfo.UserId));
  1534. }
  1535. /// <summary>
  1536. /// 物资进销存
  1537. /// 入库 Del
  1538. /// </summary>
  1539. /// <returns></returns>
  1540. [HttpDelete("{id}")]
  1541. //[Authorize]
  1542. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1543. public async Task<IActionResult> GoodsStorageDel(int id)
  1544. {
  1545. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1546. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1547. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1548. return Ok(await _goodsRep.GoodsStorageDel(id, currUserInfo.UserId));
  1549. }
  1550. /// <summary>
  1551. /// 物资进销存
  1552. /// 入库 excelDownload
  1553. /// </summary>
  1554. /// <returns></returns>
  1555. [HttpPost]
  1556. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1557. public async Task<IActionResult> GoodsStorageExcelDownload()
  1558. {
  1559. //token验证
  1560. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1561. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1562. //文件下载权限验证
  1563. int userId = currUserInfo.UserId,
  1564. pageId = 191;
  1565. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1566. #region 页面操作权限验证
  1567. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  1568. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您未分配文件下载权限!"));
  1569. #endregion
  1570. return Ok(await _goodsRep.GoodsStorageExcelDownload());
  1571. }
  1572. /// <summary>
  1573. /// 物资进销存
  1574. /// 领用 List
  1575. /// </summary>
  1576. /// <returns></returns>
  1577. [HttpPost]
  1578. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1579. public async Task<IActionResult> GoodsReceiveList(GoodsReceiveListDTO dto)
  1580. {
  1581. //token验证
  1582. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1583. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1584. if (dto.PortType < 1 || dto.PortType > 3) return Ok(JsonView(false, MsgTips.Port));
  1585. if (dto.PageIndex < 1 || dto.PageSize < 1) return Ok(JsonView(false, MsgTips.PageIndex));
  1586. //文件下载权限验证
  1587. int userId = currUserInfo.UserId,
  1588. pageId = 191;
  1589. if (dto.IsExcelDownload )
  1590. {
  1591. if (userId < 1) return Ok(JsonView(false, "excel导出时,需传入正确的当前操作人UserId!"));
  1592. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1593. #region 页面操作权限验证
  1594. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  1595. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您未分配文件下载权限!"));
  1596. #endregion
  1597. }
  1598. return Ok(await _goodsRep.GoodsReceiveList(dto));
  1599. }
  1600. /// <summary>
  1601. /// 物资进销存
  1602. /// 领用详情
  1603. /// </summary>
  1604. /// <returns></returns>
  1605. [HttpGet("{id}")]
  1606. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1607. public async Task<IActionResult> GoodsReceiveInfo([FromQuery] int portType, int id)
  1608. {
  1609. if (portType < 1 || portType > 3) return Ok(JsonView(false, MsgTips.Port));
  1610. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1611. return Ok(await _goodsRep.GoodsReceiveInfo(portType, id));
  1612. }
  1613. /// <summary>
  1614. /// 物资进销存
  1615. /// 领用 OP
  1616. /// </summary>
  1617. /// <returns></returns>
  1618. [HttpPost]
  1619. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1620. public async Task<IActionResult> GoodsReceiveOP(GoodsReceiveOpDto dto)
  1621. {
  1622. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1623. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1624. var validator = new GoodsReceiveOpDtoValidator();
  1625. var validatorRes = await validator.ValidateAsync(dto);
  1626. if (!validatorRes.IsValid)
  1627. {
  1628. var sb = new StringBuilder();
  1629. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1630. return Ok(JsonView(false, sb.ToString()));
  1631. }
  1632. return Ok(await _goodsRep.GoodsReceiveOp(dto, currUserInfo.UserId));
  1633. }
  1634. /// <summary>
  1635. /// 物资进销存
  1636. /// 领用 审核
  1637. /// </summary>
  1638. /// <param name="dto"></param>
  1639. /// <returns></returns>
  1640. [HttpPost]
  1641. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1642. public async Task<IActionResult> GoodsReceiveAudit(GoodsReceiveAuditDTO dto)
  1643. {
  1644. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1645. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1646. var validator = new GoodsReceiveAuditDTOValidator();
  1647. var validatorRes = await validator.ValidateAsync(dto);
  1648. if (!validatorRes.IsValid)
  1649. {
  1650. var sb = new StringBuilder();
  1651. foreach (var error in validatorRes.Errors) sb.AppendLine(error.ErrorMessage);
  1652. return Ok(JsonView(false, sb.ToString()));
  1653. }
  1654. int[] idArray = dto.Label
  1655. .Split(',')
  1656. .Select(x =>
  1657. {
  1658. if (int.TryParse(x, out var id)) return id;
  1659. return id;
  1660. })
  1661. .ToArray();
  1662. return Ok(await _goodsRep.GoodsReceiveAudit(idArray, currUserInfo.UserId, dto.AuditEnum));
  1663. }
  1664. /// <summary>
  1665. /// 物资进销存
  1666. /// 领用 Del
  1667. /// </summary>
  1668. /// <returns></returns>
  1669. [HttpDelete("{id}")]
  1670. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1671. public async Task<IActionResult> GoodsReceiveDel(int id)
  1672. {
  1673. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  1674. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  1675. if (id < 1) return Ok(JsonView(false, MsgTips.Id));
  1676. return Ok(await _goodsRep.GoodsReceiveDel(id, currUserInfo.UserId));
  1677. }
  1678. #endregion
  1679. #region 员工绩效
  1680. /// <summary>
  1681. /// 员工绩效组成结构获取
  1682. /// </summary>
  1683. /// <param name="userid"></param>
  1684. /// <param name="date"></param>
  1685. /// <returns></returns>
  1686. [HttpGet]
  1687. public IActionResult GetPerformanceList(int userid,string date, int loginUser)
  1688. {
  1689. var jw = JsonView(false);
  1690. if (!DateTime.TryParse(date,out DateTime date_Dt))
  1691. {
  1692. jw.Msg = "日期格式有误!";
  1693. return Ok(jw);
  1694. }
  1695. string sql_CTE = $@"-- 定义递归查询的CTE
  1696. WITH PerAssessmentSettingsCTE AS (
  1697. -- 选择指定ID的记录作为起点
  1698. SELECT
  1699. pac.Id,
  1700. pac.Name,
  1701. pac.AssessmentProportion,
  1702. pac.AssessmentStandard,
  1703. pac.ParentId,
  1704. 1 AS Depth
  1705. FROM
  1706. Per_AssessmentSetting pac
  1707. INNER JOIN
  1708. Per_AssessmentContentSetting pacs
  1709. ON
  1710. pac.id = pacs.assessmentSettingid AND pacs.isdel = 0
  1711. WHERE
  1712. pacs.userid = {userid}
  1713. AND
  1714. pac.isdel = 0
  1715. UNION ALL
  1716. -- 递归部分,选择所有子级记录
  1717. SELECT
  1718. ps.Id,
  1719. ps.Name,
  1720. ps.AssessmentProportion,
  1721. ps.AssessmentStandard,
  1722. ps.ParentId,
  1723. CAST(caste.Depth as int) + 1
  1724. FROM
  1725. Per_AssessmentSetting ps
  1726. INNER JOIN PerAssessmentSettingsCTE caste ON ps.Id = caste.ParentId)
  1727. -- 从CTE中选择最终结果
  1728. SELECT * FROM PerAssessmentSettingsCTE
  1729. OPTION (MAXRECURSION 0); -- 允许无限递归 ";
  1730. var result_CTE = _sqlSugar.Ado.SqlQuery<Per_AssessmentSetting>(sql_CTE);
  1731. var ids = result_CTE.Select(x => x.Id);
  1732. var List = _sqlSugar.Queryable<Per_AssessmentSetting>()
  1733. .LeftJoin<Per_AssessmentContentSetting>((a, b) => a.Id == b.AssessmentSettingId && b.IsDel == 0 && b.UserId == userid)
  1734. .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)
  1735. .Where((a, b) => a.IsDel == 0 && ids.Contains(a.Id))
  1736. .Select((a, b, c) => new TreeNode
  1737. {
  1738. Id = a.Id,
  1739. ContentId = b.Id,
  1740. Name = a.Name,
  1741. ParentId = a.ParentId,
  1742. AssessmentProportion = a.AssessmentProportion, //占比
  1743. AssessmentStandard = a.AssessmentStandard, //描述
  1744. AssessmentProportionChi = b.AssessmentProportionChi, //占比
  1745. UserId = b.UserId,
  1746. JobId = b.JobId,
  1747. AssessmentSettingId = b.AssessmentSettingId,
  1748. Fixed = b.Fixed,
  1749. TargetValue = b.TargetValue,
  1750. AssessmentProportion_Percentage = a.AssessmentProportion * 100,
  1751. HigherUpAssessment = c.HigherUpAssessment,
  1752. HigherUpConfig = c.HigherUpConfig,
  1753. HigherUpUserId = c.HigherUpUserId,
  1754. Score = c.Score,
  1755. ScoreTotal = c.ScoreTotal,
  1756. SelfAssessment = c.SelfAssessment,
  1757. Status = c.Status,
  1758. YearMonth = c.YearMonth,
  1759. })
  1760. .ToList();
  1761. var rootNodeList = List.Where(x => x.ParentId == 0);
  1762. var rootResult = rootNodeList.Select(x => BuildSubTree(x, List));
  1763. jw.Data = new
  1764. {
  1765. Root = rootResult,
  1766. IsLeader = IsLeader(userid,loginUser)
  1767. };
  1768. jw.Code = 200;
  1769. jw.Msg = "成功";
  1770. return Ok(jw);
  1771. }
  1772. private TreeNode BuildSubTree(TreeNode parent, List<TreeNode> nodes)
  1773. {
  1774. var children = nodes
  1775. .Where(n => n.ParentId == parent.Id)
  1776. .Select(n => BuildSubTree(n, nodes))
  1777. .ToList();
  1778. parent.Children = children;
  1779. return parent;
  1780. }
  1781. /// <summary>
  1782. /// 绩效项增改
  1783. /// </summary>
  1784. /// <param name="dto"></param>
  1785. /// <returns></returns>
  1786. [HttpPost]
  1787. public async Task<IActionResult> AssessmentSettingOperationAsync(PerAssessmentSettingOperationDto dto)
  1788. {
  1789. var jw = JsonView(false);
  1790. if (!ModelState.IsValid)
  1791. {
  1792. jw.Msg = "参数错误";
  1793. jw.Data = ModelState;
  1794. return Ok(jw);
  1795. }
  1796. try
  1797. {
  1798. if (dto.ParentId != 0)
  1799. {
  1800. var parent = await _sqlSugar.Queryable<Per_AssessmentSetting>().FirstAsync(x=>x.IsDel == 0 && x.Id == dto.ParentId);
  1801. if (parent == null)
  1802. {
  1803. jw.Msg = "父级节点不存在";
  1804. return Ok(jw);
  1805. }
  1806. }
  1807. var entity = new Per_AssessmentSetting
  1808. {
  1809. Name = dto.Name,
  1810. AssessmentProportion = dto.AssessmentProportion,
  1811. AssessmentStandard = dto.AssessmentStandard,
  1812. ParentId = dto.ParentId,
  1813. Id = dto.Id,
  1814. Remark = dto.Remark,
  1815. };
  1816. jw.Code = 200;
  1817. if (dto.Id == 0)
  1818. {
  1819. entity.CreateUserId = dto.CreateId;
  1820. entity.CreateTime = DateTime.Now;
  1821. await _sqlSugar.Insertable(entity).ExecuteCommandAsync();
  1822. jw.Msg = "添加成功!";
  1823. }
  1824. else
  1825. {
  1826. await _sqlSugar.Updateable(entity).ExecuteCommandAsync();
  1827. jw.Msg = "修改成功!";
  1828. }
  1829. }
  1830. catch (Exception ex)
  1831. {
  1832. jw.Msg = "Api error " + ex.Message;
  1833. jw.Code = 400;
  1834. }
  1835. return Ok(jw);
  1836. }
  1837. /// <summary>
  1838. /// 绩效内容增改
  1839. /// </summary>
  1840. /// <param name="dto"></param>
  1841. /// <returns></returns>
  1842. [HttpPost]
  1843. public IActionResult AssessmentSettingOperationContentAsync(AssessmentSettingOperationContenDto dto)
  1844. {
  1845. var jw = JsonView(false, "", "");
  1846. var entity = new Per_AssessmentContentSetting
  1847. {
  1848. AssessmentProportionChi = dto.AssessmentProportionChi,
  1849. AssessmentSettingId = dto.AssessmentSettingId,
  1850. CreateTime = DateTime.Now,
  1851. CreateUserId = dto.CreateUserId,
  1852. Fixed = dto.Fixed,
  1853. Id = dto.Id,
  1854. JobId = dto.JobId,
  1855. TargetValue = dto.TargetValue,
  1856. UserId = dto.UserId,
  1857. Remark = dto.Remark,
  1858. };
  1859. var entity_Fk = _sqlSugar.Queryable<Per_AssessmentSetting>().First(x => x.Id == dto.AssessmentSettingId && x.IsDel == 0);
  1860. if (entity_Fk == null)
  1861. {
  1862. jw.Msg = "考核设置不存在";
  1863. return Ok(jw);
  1864. }
  1865. try
  1866. {
  1867. if (dto.Id == 0)
  1868. {
  1869. //add
  1870. var insertCount = _sqlSugar.Insertable(entity).ExecuteCommand();
  1871. jw.Msg = "添加成功!";
  1872. }
  1873. else
  1874. {
  1875. //update
  1876. var updateCount = _sqlSugar.Updateable(entity).ExecuteCommand();
  1877. jw.Msg = "修改成功!";
  1878. }
  1879. jw.Code = 200;
  1880. }
  1881. catch (Exception ex)
  1882. {
  1883. jw.Msg = "Api error " + ex.Message;
  1884. jw.Code = 400;
  1885. }
  1886. return Ok(jw);
  1887. }
  1888. /// <summary>
  1889. /// 绩效项查询
  1890. /// </summary>
  1891. /// <param name="dto"></param>
  1892. /// <returns></returns>
  1893. [HttpPost]
  1894. public async Task<IActionResult> QueryAssessmentSettingListOffsetAsync(QueryAssessmentSettingListOffsetAsyncDto dto)
  1895. {
  1896. var jw = JsonView(false);
  1897. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  1898. var entities = await _sqlSugar.Queryable<Per_AssessmentSetting>()
  1899. .Where(x=>x.IsDel == 0)
  1900. .WhereIF(!string.IsNullOrEmpty(dto.SearchValue), e => e.Name.Contains(dto.SearchValue))
  1901. .ToPageListAsync(dto.pageIndex, dto.pageSize, total);
  1902. var DtoResult = entities.Select(e => new
  1903. {
  1904. e.Id,
  1905. Name = e.Name,
  1906. AssessmentProportion = e.AssessmentProportion,
  1907. AssessmentStandard = e.AssessmentStandard,
  1908. ParentId = e.ParentId,
  1909. Remark = e.Remark
  1910. }).ToList();
  1911. jw.Data = new
  1912. {
  1913. total = total.Value,
  1914. dto.pageIndex,
  1915. dto.pageSize,
  1916. List = DtoResult
  1917. };
  1918. jw.Code = 200;
  1919. jw.Msg = "查询成功!";
  1920. return Ok(jw);
  1921. }
  1922. /// <summary>
  1923. /// 绩效分数保存
  1924. /// </summary>
  1925. /// <param name="dto"></param>
  1926. /// <returns></returns>
  1927. [HttpPost]
  1928. public IActionResult SaveUserAssessmen(SaveUserAssessmenDto dto)
  1929. {
  1930. var jw = JsonView(false,"请传入正确的数据!");
  1931. if (dto.Data.Any()) {
  1932. if (!DateTime.TryParse(dto.AssessmenData, out DateTime yearMonth_Dt))
  1933. {
  1934. jw.Data = "月份参数有误!";
  1935. return Ok(jw);
  1936. }
  1937. try
  1938. {
  1939. var ids = dto.Data.Select(x => x.AssessmentContentSettingId).ToList();
  1940. var QueryContent_DB = _sqlSugar.Queryable<Per_AssessmentContentSetting>()
  1941. .InnerJoin<Per_AssessmentSetting>((a, b) => b.IsDel == 0 && a.AssessmentSettingId == b.Id)
  1942. .Where((a, b) => a.IsDel == 0 && ids.Contains(a.Id))
  1943. .Select((a, b) => new
  1944. {
  1945. ContentSettingId = a.Id,
  1946. SettingId = b.Id,
  1947. a.TargetValue,
  1948. b.AssessmentStandard,
  1949. MergeStr = $"【项名称:{b.Name}/目标值:{a.TargetValue}/评估标准:{b.AssessmentStandard}】",
  1950. a.AssessmentProportionChi,
  1951. b.Name
  1952. })
  1953. .ToList()
  1954. .ToDictionary(x => x.ContentSettingId);
  1955. //删除上级未确认数据
  1956. var expressionWhere = Expressionable
  1957. .Create<Per_AssessmentScore>()
  1958. .And(x => x.YearMonth.Year == yearMonth_Dt.Year && x.YearMonth.Month == yearMonth_Dt.Month)
  1959. .And(x => ids.Contains(x.AssessmentContentSettingId))
  1960. .And(x => x.HigherUpConfig == 0)
  1961. .ToExpression();
  1962. if (IsLeader(dto.AssessmenUserId, dto.CreateUserId))
  1963. {
  1964. expressionWhere = Expressionable
  1965. .Create<Per_AssessmentScore>()
  1966. .And(x => x.YearMonth.Year == yearMonth_Dt.Year && x.YearMonth.Month == yearMonth_Dt.Month)
  1967. .And(x => ids.Contains(x.AssessmentContentSettingId))
  1968. .ToExpression();
  1969. }
  1970. _sqlSugar.BeginTran();
  1971. _sqlSugar.Updateable<Per_AssessmentScore>()
  1972. .Where(expressionWhere)
  1973. .SetColumns(x => new Per_AssessmentScore { IsDel = 1, DeleteUserId = dto.CreateUserId, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") })
  1974. .ExecuteCommand();
  1975. var entityList = new List<Per_AssessmentScore>();
  1976. foreach (var x in dto.Data)
  1977. {
  1978. if (x.HigherUpAssessment > 100 || x.SelfAssessment > 100)
  1979. {
  1980. jw.Msg = QueryContent_DB[x.AssessmentContentSettingId].Name + "项分数不能超过100。";
  1981. return Ok(jw);
  1982. }
  1983. Per_AssessmentScore item = new Per_AssessmentScore
  1984. {
  1985. AssessmentContentSettingId = x.AssessmentContentSettingId,
  1986. CreateTime = DateTime.Now,
  1987. CreateUserId = dto.CreateUserId,
  1988. Details = QueryContent_DB[x.AssessmentContentSettingId].MergeStr,
  1989. HigherUpAssessment = x.HigherUpAssessment,
  1990. HigherUpUserId = x.LeadersId,
  1991. HigherUpConfig = x.HigherUpAssessment > 0 ? 1 : 0,
  1992. SelfAssessment = x.SelfAssessment,
  1993. IsDel = 0,
  1994. Status = x.Status,
  1995. YearMonth = yearMonth_Dt,
  1996. Score = x.SelfAssessment * 0.3M + x.HigherUpAssessment * 0.7M,
  1997. ScoreTotal = (x.SelfAssessment * 0.3M + x.HigherUpAssessment * 0.7M) * QueryContent_DB[x.AssessmentContentSettingId].AssessmentProportionChi,
  1998. };
  1999. entityList.Add(item);
  2000. }
  2001. var influenceRow = _sqlSugar.Insertable(entityList).ExecuteCommand();
  2002. _sqlSugar.CommitTran();
  2003. jw.Code = 200;
  2004. jw.Msg = "保存成功!";
  2005. jw.Data = $"{influenceRow}条数据操作成功!";
  2006. }
  2007. catch (Exception ex)
  2008. {
  2009. _sqlSugar.RollbackTran();
  2010. jw.Code = 500;
  2011. jw.Data = $"API ERROR ({ex.Message})";
  2012. }
  2013. }
  2014. return Ok(jw);
  2015. }
  2016. /// <summary>
  2017. /// 绩效项删除
  2018. /// </summary>
  2019. /// <param name="dto"></param>
  2020. /// <returns></returns>
  2021. [HttpPost]
  2022. public IActionResult DeleteAssessmentSetting(DeleteAssessmentSettingDto dto)
  2023. {
  2024. var jw = JsonView(false, "删除失败!");
  2025. if (!dto.IdArr.Any())
  2026. {
  2027. jw.Msg = "id不能为空!";
  2028. return Ok(jw);
  2029. }
  2030. var rowCount = _sqlSugar.Updateable<Per_AssessmentSetting>()
  2031. .Where(x => dto.IdArr.Contains(x.Id) && x.IsDel == 0)
  2032. .SetColumns(x => new Per_AssessmentSetting
  2033. {
  2034. IsDel = 1,
  2035. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
  2036. DeleteUserId = dto.UserId,
  2037. })
  2038. .ExecuteCommand();
  2039. jw.Code = 200;
  2040. jw.Msg = $"修改成功!,修改数量{rowCount}";
  2041. return Ok(jw);
  2042. }
  2043. /// <summary>
  2044. /// 绩效内容删除
  2045. /// </summary>
  2046. /// <param name="dto"></param>
  2047. /// <returns></returns>
  2048. [HttpPost]
  2049. public IActionResult DeleteAssessmentContentSetting(DeleteAssessmentSettingDto dto)
  2050. {
  2051. var jw = JsonView(false, "删除失败!");
  2052. if (!dto.IdArr.Any())
  2053. {
  2054. jw.Msg = "id不能为空!";
  2055. return Ok(jw);
  2056. }
  2057. var rowCount = _sqlSugar.Updateable<Per_AssessmentContentSetting>()
  2058. .Where(x => dto.IdArr.Contains(x.Id) && x.IsDel == 0)
  2059. .SetColumns(x => new Per_AssessmentContentSetting
  2060. {
  2061. IsDel = 1,
  2062. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
  2063. DeleteUserId = dto.UserId,
  2064. })
  2065. .ExecuteCommand();
  2066. jw.Code = 200;
  2067. jw.Msg = $"修改成功!,修改数量{rowCount}";
  2068. return Ok(jw);
  2069. }
  2070. private bool IsLeader(int userId, int higherUserId)
  2071. {
  2072. Dictionary <int,List<int>> keyValues = new Dictionary<int, List<int>>()
  2073. {
  2074. { 5 , new List<int>{ 258 , 235, 234, 233, 208 } }
  2075. };
  2076. if (keyValues.ContainsKey(higherUserId))
  2077. {
  2078. return keyValues[higherUserId].Contains(userId);
  2079. }
  2080. return false;
  2081. }
  2082. #endregion
  2083. #region 企微Api测试
  2084. [HttpPost]
  2085. public async Task<IActionResult> GetCheckin_MonthDataAsync(DateTime start, DateTime end)
  2086. {
  2087. var jw = JsonView(false);
  2088. jw.Data = await _qiYeWeChatApiService.GetCheckin_MonthDataAsync1(start,end);
  2089. return Ok(jw);
  2090. }
  2091. [HttpPost]
  2092. public async Task<IActionResult> QueryAssessmentByUser(QueryAssessmentByUser Dto)
  2093. {
  2094. var jw = JsonView(false);
  2095. var user_entity = _sqlSugar.Queryable<Sys_Users>()
  2096. .First(e => e.Id == Dto.UserId && e.IsDel == 0);
  2097. var start_Bool = DateTime.TryParse(Dto.Start, out DateTime start);
  2098. var end_Bool = DateTime.TryParse(Dto.End, out DateTime end);
  2099. if (!start_Bool || !end_Bool)
  2100. {
  2101. jw.Msg = "时间格式不正确!";
  2102. return Ok(jw);
  2103. }
  2104. jw.Msg = "用户企业微信Id未绑定!";
  2105. if (user_entity != null && !string.IsNullOrEmpty(user_entity.QiyeChatUserId))
  2106. {
  2107. var data = await _qiYeWeChatApiService.QueryAssessmentByUser(start, end, new List<string> { user_entity.QiyeChatUserId });
  2108. jw.Data = data;
  2109. jw.Msg = "查询成功!";
  2110. jw.Code = 200;
  2111. }
  2112. return Ok(jw);
  2113. }
  2114. [HttpPost]
  2115. public IActionResult TempTest(QueryAssessmentSettingListOffsetAsyncDto Dto)
  2116. {
  2117. var jw = JsonView(false);
  2118. return Ok(jw);
  2119. }
  2120. #endregion
  2121. }
  2122. }