PersonnelModuleController.cs 106 KB

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