PersonnelModuleController.cs 103 KB

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