PersonnelModuleController.cs 107 KB

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