PersonnelModuleController.cs 103 KB

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