PersonnelModuleController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. using Aspose.Cells;
  2. using OASystem.API.OAMethodLib;
  3. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  4. using OASystem.Domain.Dtos.PersonnelModule;
  5. using OASystem.Domain.Entities.PersonnelModule;
  6. using OASystem.Domain.ViewModels.PersonnelModule;
  7. using OASystem.Domain.ViewModels.QiYeWeChat;
  8. using OASystem.Infrastructure.Repositories.PersonnelModule;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Diagnostics;
  12. using System.Globalization;
  13. using System.IO;
  14. namespace OASystem.API.Controllers
  15. {
  16. /// <summary>
  17. /// 人事模块
  18. /// </summary>
  19. [Route("api/[controller]/[action]")]
  20. public class PersonnelModuleController : ControllerBase
  21. {
  22. private Result _result;
  23. private readonly IMapper _mapper;
  24. private readonly decimal _chengDuMinimumWage = 2100.00M;
  25. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  26. private readonly WageSheetRepository _wageSheetRep;
  27. private readonly UsersRepository _usersRep;
  28. private string url;
  29. private string path;
  30. /// <summary>
  31. /// 初始化
  32. /// </summary>
  33. /// <param name="qiYeWeChatApiService"></param>
  34. /// <param name="wageSheetRep"></param>
  35. /// <param name="usersRep"></param>
  36. /// <param name="mapper"></param>
  37. public PersonnelModuleController(IQiYeWeChatApiService qiYeWeChatApiService,WageSheetRepository wageSheetRep, UsersRepository usersRep, IMapper mapper)
  38. {
  39. _mapper = mapper;
  40. _usersRep = usersRep;
  41. _qiYeWeChatApiService = qiYeWeChatApiService;
  42. _wageSheetRep = wageSheetRep;
  43. _result = new Result();
  44. url = AppSettingsHelper.Get("ExcelBaseUrl");
  45. path = AppSettingsHelper.Get("ExcelBasePath");
  46. if (!System.IO.Directory.Exists(path))
  47. {
  48. System.IO.Directory.CreateDirectory(path);//不存在就创建文件夹
  49. }
  50. }
  51. #region 工资表单
  52. /// <summary>
  53. /// 工资 月列表
  54. /// </summary>
  55. /// <returns></returns>
  56. [HttpPost]
  57. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  58. public async Task<IActionResult> GetWageSheetMonth()
  59. {
  60. string sql = string.Format("Select * From Pm_WageIssueWorkingDay Where IsDel = 0 Order By YearMonth Desc");
  61. var data = await _wageSheetRep._sqlSugar.SqlQueryable<WageSheetMonthView>(sql).ToListAsync();
  62. return Ok(JsonView(true, "查询成功!", data));
  63. }
  64. /// <summary>
  65. /// 工资 工作日信息
  66. /// 查询
  67. /// </summary>
  68. /// <returns></returns>
  69. [HttpPost]
  70. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  71. public async Task<IActionResult> GetWageSheetMonthWorkdays(string startDt, string endDt )
  72. {
  73. //参数处理
  74. string dtFormat = "yyyy-MM-dd";
  75. DateTime startDt1, endDt1;
  76. bool startDtIsValid = DateTime.TryParseExact(startDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt1);
  77. bool endDtIsValid = DateTime.TryParseExact(endDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt1);
  78. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  79. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  80. string sql = string.Format(@"Select * From Sys_Calendar
  81. Where Isdel = 0 And Dt between '{0}' And '{1}'", startDt, endDt);
  82. var data = await _wageSheetRep._sqlSugar.SqlQueryable<CalendarInfoView>(sql).ToListAsync();
  83. return Ok(JsonView(true, "查询成功!", data));
  84. }
  85. /// <summary>
  86. /// 工资 工作日信息
  87. /// 编辑
  88. /// </summary>
  89. /// <returns></returns>
  90. [HttpPost]
  91. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  92. public async Task<IActionResult> GetWageSheetMonthWorkdaysAddOrEdit(WageSheetMonthWorkdaysAddOrEditDto dto)
  93. {
  94. //参数处理
  95. string yearFormat = "yyyy-MM";
  96. string dtFormat = "yyyy-MM-dd";
  97. DateTime yearDt, startDt1, endDt1;
  98. bool yearDtIsValid = DateTime.TryParseExact(dto.YearMonth, yearFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearDt);
  99. bool startDtIsValid = DateTime.TryParseExact(dto.StartDate, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt1);
  100. bool endDtIsValid = DateTime.TryParseExact(dto.EndDate, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt1);
  101. if (!yearDtIsValid) return Ok(JsonView(false, "年月日期格式错误!正确时间格式:yyyy-MM "));
  102. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  103. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  104. #region 处理数据
  105. Pm_WageIssueWorkingDay pm_WageIssueWorkingDay1 = new Pm_WageIssueWorkingDay();
  106. pm_WageIssueWorkingDay1 = _mapper.Map<Pm_WageIssueWorkingDay>(dto);
  107. List<Sys_Calendar> sys_Calendars = new List<Sys_Calendar>();
  108. sys_Calendars = _mapper.Map<List<Sys_Calendar>>(dto.CalendarInfos);
  109. pm_WageIssueWorkingDay1.Workdays = sys_Calendars.Where(it => it.IsWorkDay == true).ToList().Count();
  110. foreach (var item in sys_Calendars)
  111. {
  112. item.Remark = pm_WageIssueWorkingDay1.Remark;
  113. item.CreateUserId = pm_WageIssueWorkingDay1.CreateUserId;
  114. item.CreateTime = pm_WageIssueWorkingDay1.CreateTime;
  115. }
  116. #endregion
  117. var _sqlSugar = _wageSheetRep._sqlSugar;
  118. _sqlSugar.BeginTran();
  119. try
  120. {
  121. //月份表是否存在
  122. Pm_WageIssueWorkingDay pm_WageIssueWorkingDay = new Pm_WageIssueWorkingDay()
  123. {
  124. YearMonth = dto.YearMonth,
  125. StartDate = dto.StartDate,
  126. EndDate = dto.EndDate,
  127. Workdays = dto.CalendarInfos.Where(it => it.IsWorkDay == true).ToList().Count()
  128. };
  129. string sql = string.Format("Select * From Pm_WageIssueWorkingDay Where Isdel = 0 And YearMonth='{0}'", dto.YearMonth);
  130. var workdsys = await _sqlSugar.SqlQueryable<Pm_WageIssueWorkingDay>(sql).FirstAsync();
  131. pm_WageIssueWorkingDay.CreateUserId = dto.UserId;
  132. pm_WageIssueWorkingDay.IsDel = 0;
  133. if (workdsys == null) //添加
  134. {
  135. int addId = await _sqlSugar.Insertable(pm_WageIssueWorkingDay).ExecuteReturnIdentityAsync();
  136. }
  137. else //更新
  138. {
  139. int updCount = await _sqlSugar.Updateable(pm_WageIssueWorkingDay)
  140. .IgnoreColumns(z => new { z.CreateUserId, z.CreateTime, z.DeleteUserId, z.DeleteTime, z.IsDel })
  141. .WhereColumns(it => it.YearMonth)
  142. .ExecuteCommandAsync();
  143. }
  144. List<Sys_Calendar> sys_Calendars_add = new List<Sys_Calendar>();
  145. List<Sys_Calendar> sys_Calendars_update = new List<Sys_Calendar>();
  146. sys_Calendars_add = sys_Calendars.Where(it => it.Id == 0).OrderBy(it => it.Dt).ToList();
  147. sys_Calendars_update = sys_Calendars.Where(it => it.Id != 0).OrderBy(it => it.Dt).ToList();
  148. int add1 = 0;
  149. int upd = 0;
  150. if (sys_Calendars_add.Count > 0)
  151. {
  152. await _sqlSugar.Insertable(sys_Calendars_add).ExecuteReturnIdentityAsync();
  153. }
  154. if (sys_Calendars_update.Count > 0)
  155. {
  156. await _sqlSugar.Updateable<Sys_Calendar>(sys_Calendars)
  157. .UpdateColumns(it => new { it.Dt, it.IsWorkDay, it.IsHoliDay, it.HoliName })
  158. .WhereColumns(it => it.Id)
  159. .ExecuteCommandAsync();
  160. }
  161. _sqlSugar.CommitTran();
  162. return Ok(JsonView(true, "操作成功!"));
  163. }
  164. catch (Exception ex)
  165. {
  166. _sqlSugar.RollbackTran();
  167. return Ok(JsonView(false, ex.Message));
  168. }
  169. }
  170. /// <summary>
  171. /// 工资表单 基础数据源
  172. /// </summary>
  173. /// <returns></returns>
  174. [HttpPost]
  175. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  176. public async Task<IActionResult> GetWageSheetBasicsDataSource()
  177. {
  178. string companySql = string.Format("Select * From Sys_Company Where IsDel = 0");
  179. var compnayData = await _wageSheetRep._sqlSugar.SqlQueryable<CompanyNameView>(companySql).ToListAsync();
  180. string depSql = string.Format("Select * From Sys_Department Where IsDel = 0");
  181. var depData = await _wageSheetRep._sqlSugar.SqlQueryable<Domain.ViewModels.System.DepartmentView>(depSql).ToListAsync();
  182. //获取OA系统内所有用户
  183. var nameData = await _usersRep.GetUserNameList(1);
  184. if (nameData.Code != 0)
  185. {
  186. return Ok(JsonView(false, nameData.Msg));
  187. }
  188. var data = new {
  189. compnayData = compnayData,
  190. depData = depData,
  191. userNames = nameData.Data
  192. };
  193. return Ok(JsonView(true, "查询成功!", data));
  194. }
  195. /// <summary>
  196. /// 获取工资发放月份
  197. /// </summary>
  198. /// <param name="dto"></param>
  199. /// <returns></returns>
  200. [HttpPost]
  201. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  202. public async Task<IActionResult> GetWageYaerMonths(WageYearDto dto)
  203. {
  204. string sql = string.Format(@"Select * From Pm_WageIssueWorkingDay
  205. Where Isdel = 0 And YearMonth Like '%{0}%'
  206. Order By YearMonth Asc", dto.Year);
  207. var data = await _wageSheetRep._sqlSugar.SqlQueryable<WageYearMonthView>(sql).ToListAsync();
  208. return Ok(JsonView(true,"操作成功!", data));
  209. }
  210. /// <summary>
  211. /// 获取工资表单
  212. /// </summary>
  213. /// <param name="dto"></param>
  214. /// <returns></returns>
  215. [HttpPost]
  216. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  217. public async Task<IActionResult> GetWageSheetList(WageSheetListDto dto)
  218. {
  219. //参数处理
  220. string ymFormat = "yyyy-MM";
  221. DateTime yearMonthDt;
  222. bool yearMonthDttIsValid = DateTime.TryParseExact(dto.YearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  223. if (!yearMonthDttIsValid)
  224. {
  225. _result.Msg = "年月格式错误!正确时间格式:yyyy-MM ";
  226. return Ok(JsonView(false, _result.Msg));
  227. }
  228. //获取月工资数据
  229. string yearMonth = yearMonthDt.ToString("yyyy-MM");
  230. if (dto.PortType == 1)
  231. {
  232. _result = await _wageSheetRep.Get_WageSheet_ListByYearMonthAsync(yearMonth);
  233. if (_result.Code != 0)
  234. {
  235. return Ok(JsonView(false, _result.Msg));
  236. }
  237. }
  238. else if (dto.PortType == 2)
  239. { }
  240. else if (dto.PortType == 3)
  241. { }
  242. else
  243. {
  244. return Ok(JsonView(false, "请选择正确的端口参数"));
  245. }
  246. return Ok(JsonView(true, _result.Msg, _result.Data));
  247. }
  248. /// <summary>
  249. /// 获取工资 详情
  250. /// </summary>
  251. /// <param name="dto"></param>
  252. /// <returns></returns>
  253. [HttpPost]
  254. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  255. public async Task<IActionResult> GetWageSheetById(WageSheetInfoDto dto)
  256. {
  257. if (dto.PortType == 1)
  258. {
  259. _result = await _wageSheetRep.Get_WageSheet_InfoByIdAsync(dto.Id);
  260. if (_result.Code != 0)
  261. {
  262. return Ok(JsonView(false, _result.Msg));
  263. }
  264. }
  265. else if (dto.PortType == 2)
  266. { }
  267. else if (dto.PortType == 3)
  268. { }
  269. else
  270. {
  271. return Ok(JsonView(false, "请选择正确的端口参数"));
  272. }
  273. return Ok(JsonView(true, _result.Msg, _result.Data));
  274. }
  275. /// <summary>
  276. /// 人事模块 工资表单 删除
  277. /// </summary>
  278. /// <param name="dto"></param>
  279. /// <returns></returns>
  280. [HttpPost]
  281. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  282. public async Task<IActionResult> PostWageSheetDel(WageDelDto dto)
  283. {
  284. try
  285. {
  286. _result = await _wageSheetRep.Post_WageSheet_DelAsync(dto);
  287. if (_result.Code != 0)
  288. {
  289. return Ok(JsonView(false, _result.Msg));
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. return Ok(JsonView(false, ex.Message));
  295. }
  296. return Ok(JsonView(true, _result.Msg, _result.Data));
  297. }
  298. /// <summary>
  299. /// 人事模块 工资表单 添加 Or 修改
  300. /// </summary>
  301. /// <param name="dto"></param>
  302. /// <returns></returns>
  303. [HttpPost]
  304. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  305. public async Task<IActionResult> PostWageSheetAddOrEdit(WageAddOrEditDto dto)
  306. {
  307. try
  308. {
  309. Pm_WageSheet pm_WageSheet = new Pm_WageSheet();
  310. pm_WageSheet = _mapper.Map<Pm_WageSheet>(dto);
  311. pm_WageSheet.LastUpdateUserId = dto.CreateUserId;
  312. #region 计算工资
  313. //月工资
  314. decimal salary = pm_WageSheet.Basic + pm_WageSheet.Floats + pm_WageSheet.PostAllowance + pm_WageSheet.InformationSecurityFee + pm_WageSheet.OtherSubsidies + pm_WageSheet.OtherHandle;
  315. //扣款合计
  316. decimal totalDeduction = pm_WageSheet.SickLeave + pm_WageSheet.SomethingFalse + pm_WageSheet.LateTo + pm_WageSheet.LeaveEarly + pm_WageSheet.Absenteeism + pm_WageSheet.NotPunch +
  317. pm_WageSheet.ReservedFunds + pm_WageSheet.WithholdingInsurance + pm_WageSheet.OtherDeductions + pm_WageSheet.OtherDeductions;
  318. //实发合计 不含个税
  319. if (pm_WageSheet.RegularDays >= pm_WageSheet.WorkDays )
  320. {
  321. pm_WageSheet.RegularDays = pm_WageSheet.WorkDays;
  322. salary = salary + pm_WageSheet.Mealsupplement;
  323. }
  324. else
  325. {
  326. if (dto.UserId == 21) //21==张海麟
  327. {
  328. salary = salary + pm_WageSheet.Mealsupplement;
  329. }
  330. else
  331. {
  332. salary = salary = (PayrollComputation.ConvertToDecimal(salary / pm_WageSheet.WorkDays) * pm_WageSheet.RegularDays) + pm_WageSheet.Mealsupplement;
  333. }
  334. }
  335. decimal actualTotal = salary - totalDeduction;
  336. pm_WageSheet.Should = salary;
  337. pm_WageSheet.TotalDeductions = totalDeduction;
  338. pm_WageSheet.TotalRealHair = actualTotal - pm_WageSheet.WithholdingTax;
  339. pm_WageSheet.AfterTax = actualTotal - pm_WageSheet.WithholdingTax;
  340. #endregion
  341. _result = await _wageSheetRep.Post_WageSheet_AddOrEditAsync(dto, pm_WageSheet);
  342. if (_result.Code != 0)
  343. {
  344. return Ok(JsonView(false, _result.Msg));
  345. }
  346. }
  347. catch (Exception ex)
  348. {
  349. return Ok(JsonView(false, ex.Message));
  350. }
  351. return Ok(JsonView(true, _result.Msg, _result.Data));
  352. }
  353. /// <summary>
  354. /// 计算工资
  355. /// </summary>
  356. /// <returns></returns>
  357. [HttpPost]
  358. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  359. public async Task<IActionResult> SalaryCalculatorAsync(SalaryCalculatorDto dto)
  360. {
  361. Result result = new Result();
  362. Stopwatch sw = new Stopwatch();
  363. sw.Start();
  364. //参数处理
  365. string ymFormat = "yyyy-MM";
  366. string dtFormat = "yyyy-MM-dd";
  367. DateTime yearMonthDt,startDt,endDt;
  368. bool yearMonthDtIsValid = DateTime.TryParseExact(dto.yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  369. bool startDtIsValid = DateTime.TryParseExact(dto.startDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt);
  370. bool endDtIsValid = DateTime.TryParseExact(dto.endDt, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt);
  371. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  372. if (!startDtIsValid) return Ok(JsonView(false, "开始日期格式错误!正确时间格式:yyyy-MM-dd "));
  373. if (!endDtIsValid) return Ok(JsonView(false, "结束格式错误!正确时间格式:yyyy-MM-dd "));
  374. string thisYearMonth = dto.yearMonth;
  375. string preYearMonth = yearMonthDt.AddMonths(-1).ToString("yyyy-MM");
  376. //计算本月工资起止时间 比如是2月的1号-28号,那就是2月1号的零点到3月1号的零点
  377. DateTime thisStartDt = startDt;
  378. DateTime thisEndDt = endDt; //
  379. //本月工资是否有数据 有数据则不计算
  380. result = await _wageSheetRep.Get_WageSheet_ListByYearMonthAsync(thisYearMonth);
  381. if (result.Code == 0 )
  382. {
  383. return Ok(JsonView(false, thisYearMonth + " 工资数据已存在,若无人员工资请手动添加!"));
  384. }
  385. //获取上个月工资信息
  386. List<Pm_WageSheet> preWageSheetItems = await _wageSheetRep._sqlSugar.Queryable<Pm_WageSheet>().Where(it => it.IsDel == 0 && it.YearMonth == preYearMonth).ToListAsync();
  387. preWageSheetItems = preWageSheetItems.OrderBy(it => it.UserId).ToList();
  388. if (preWageSheetItems.Count <= 0)
  389. {
  390. return Ok(JsonView(false, thisYearMonth + " 上月工资数据不存在,请手动添加!"));
  391. }
  392. //处理上个月同月同人 多条数据
  393. List<Pm_WageSheet> preWageSheetItems1 = new List<Pm_WageSheet>();
  394. preWageSheetItems1 = preWageSheetItems.GroupBy(it => new { it.YearMonth,it.UserId })
  395. .Select(it => it.FirstOrDefault(item => item.Basic !=0))
  396. .ToList();
  397. //获取OA系统内所有用户
  398. var nameData = await _usersRep.GetUserNameList(1);
  399. List<UserNameView>? userNames = nameData.Data;
  400. List<Pm_WageSheet> wageSheets = new List<Pm_WageSheet>();
  401. _result = await PayrollComputation.SalaryCalculatorAsync(preWageSheetItems1, userNames,dto.UserId, thisYearMonth, thisStartDt,thisEndDt);
  402. #region 批量添加
  403. if (_result.Code != 0)
  404. {
  405. return Ok(JsonView(false, _result.Msg));
  406. }
  407. wageSheets = _result.Data;
  408. var add = await _wageSheetRep._sqlSugar.Insertable(wageSheets).ExecuteCommandAsync();
  409. if (add <= 0)
  410. {
  411. return Ok(JsonView(false, "操作失败!"));
  412. }
  413. #endregion
  414. #region 处理返回数据
  415. //List <WageSheetItemInfoView> wageSheetItems = new List<WageSheetItemInfoView>();
  416. //wageSheetItems = _mapper.Map<List<WageSheetItemInfoView>>(wageSheets);
  417. //wageSheetItems = wageSheetItems.Select(it =>
  418. // {
  419. // UserNameView? uName1 = new UserNameView();
  420. // UserNameView? uName2 = new UserNameView();
  421. // uName1 = userNames.Where(it1 => it.UserId == it1.Id).FirstOrDefault();
  422. // if (uName1 != null) it.Name = uName1.CnName;
  423. // uName2 = userNames.Where(it1 => it.LastUpdateUserId == it1.Id).FirstOrDefault();
  424. // if (uName2 != null) it.LastUpdateUserName = uName2.CnName;
  425. // return it; }
  426. // ).ToList();
  427. #endregion
  428. sw.Stop();
  429. return Ok(JsonView(true, "操作成功! 耗时:" + (sw.ElapsedMilliseconds/1000) + "s"));
  430. }
  431. /// <summary>
  432. /// 计算工资 By YearMonth And UserId
  433. /// </summary>
  434. /// <returns></returns>
  435. [HttpPost]
  436. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  437. public async Task<IActionResult> SalaryCalculatorSingleAsync(SalaryCalculatorSingleDto dto)
  438. {
  439. Result result = new Result();
  440. Stopwatch sw = new Stopwatch();
  441. sw.Start();
  442. //参数处理
  443. string ymFormat = "yyyy-MM";
  444. string ymdFormat = "yyyy-MM-dd";
  445. DateTime yearMonthDt,startDt,endDt;
  446. bool yearMonthDtIsValid = DateTime.TryParseExact(dto.YearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  447. bool startDtIsValid = DateTime.TryParseExact(dto.StartDate, ymdFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDt);
  448. bool endDtIsValid = DateTime.TryParseExact(dto.EndDate, ymdFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt);
  449. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  450. if (!startDtIsValid) return Ok(JsonView(false, "开始时间格式错误!正确时间格式:yyyy-MM-dd "));
  451. if (!yearMonthDtIsValid) return Ok(JsonView(false, "结束时间格式错误!正确时间格式:yyyy-MM-dd "));
  452. List<Pm_WageSheet> wageSheets = new List<Pm_WageSheet>();
  453. Pm_WageSheet wageSheet = _mapper.Map<Pm_WageSheet>(dto);
  454. wageSheets.Add(wageSheet);
  455. //获取OA系统内所有用户
  456. var nameData = await _usersRep.GetUserNameList(1);
  457. List<UserNameView>? userNames = nameData.Data;
  458. _result = await PayrollComputation.SalaryCalculatorAsync(wageSheets, userNames, dto.UserId, dto.YearMonth, startDt, endDt);
  459. if (_result.Code != 0)
  460. {
  461. return Ok(JsonView(false, _result.Msg));
  462. }
  463. List<Pm_WageSheet> wageSheets1 = new List<Pm_WageSheet>();
  464. wageSheets1 = _result.Data;
  465. #region 处理返回数据
  466. List<WageSheetInfoView> wageSheetItems = new List<WageSheetInfoView>();
  467. wageSheetItems = _mapper.Map<List<WageSheetInfoView>>(wageSheets1);
  468. wageSheetItems = wageSheetItems.Select(it =>
  469. {
  470. UserNameView? uName1 = new UserNameView();
  471. UserNameView? uName2 = new UserNameView();
  472. uName1 = userNames.Where(it1 => it.UserId == it1.Id).FirstOrDefault();
  473. if (uName1 != null) it.Name = uName1.CnName;
  474. uName2 = userNames.Where(it1 => it.LastUpdateUserId == it1.Id).FirstOrDefault();
  475. if (uName2 != null) it.LastUpdateUserName = uName2.CnName;
  476. return it;
  477. }
  478. ).ToList();
  479. #endregion
  480. sw.Stop();
  481. return Ok(JsonView(true, "操作成功!耗时:" + (sw.ElapsedMilliseconds / 1000) + "s", wageSheetItems[0]));
  482. }
  483. /// <summary>
  484. /// 导出工资单
  485. /// </summary>
  486. /// <returns></returns>
  487. [HttpPost]
  488. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  489. public async Task<IActionResult> ExportWageCard(string yearMonth)
  490. {
  491. Result result = new Result();
  492. Stopwatch sw = new Stopwatch();
  493. sw.Start();
  494. //参数处理
  495. string ymFormat = "yyyy-MM";
  496. DateTime yearMonthDt;
  497. bool yearMonthDtIsValid = DateTime.TryParseExact(yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  498. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  499. //公司部门
  500. string sql = string.Format(@"Select row_number() over(order by pm_ws.Id) as Row_Number,
  501. sc.Id as CompanyId,sc.CompanyName,sd.Id as DepId,sd.DepName,
  502. sys_u1.CnName Name,sys_u2.CnName LastUpdateUserName,pm_ws.*
  503. From Pm_WageSheet pm_ws
  504. Left Join Sys_Users sys_u1 On pm_ws.UserId = sys_u1.Id
  505. Left Join Sys_Users sys_u2 On pm_ws.LastUpdateUserId = sys_u2.Id
  506. Left Join Sys_Company sc On sys_u1.companyId = sc.Id
  507. Left Join Sys_Department sd On sys_u1.DepId = sd.Id
  508. Where pm_ws.IsDel = 0 And pm_ws.YearMonth = '{0}'", yearMonth);
  509. var wageSheetList = await _wageSheetRep._sqlSugar.SqlQueryable<ExportWageSheetItemView>(sql).ToListAsync();
  510. if (wageSheetList.Count <= 0)
  511. {
  512. return Ok(JsonView(false, yearMonth + "暂无工资数据!"));
  513. }
  514. decimal SumPrice = 0.00M;
  515. foreach (var item in wageSheetList)
  516. {
  517. SumPrice += item.AfterTax;
  518. }
  519. WorkbookDesigner designer = new WorkbookDesigner();
  520. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/工资详细清单.xlsx");
  521. designer.Workbook.Worksheets[0].Name = yearMonth +" 工资单";
  522. designer.SetDataSource("WageSheet", wageSheetList);
  523. designer.SetDataSource("YearMonth", yearMonth);
  524. designer.SetDataSource("StartEndDt", wageSheetList[0].StartDate +" - "+ wageSheetList[0].EndDate);
  525. designer.SetDataSource("WorkDays", wageSheetList[0].WorkDays);
  526. designer.SetDataSource("SumPrice", SumPrice);
  527. designer.SetDataSource("WageSheetTitle", "工资单");//
  528. designer.Process();
  529. string fileName = "WageCard/" + yearMonth + "_工资单_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  530. string path = AppSettingsHelper.Get("ExcelBasePath");
  531. designer.Workbook.Save(path + fileName);
  532. designer = null;
  533. string excelPath = AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  534. string url = AppSettingsHelper.Get("ExcelBaseUrl");
  535. string fileUrl = url + excelPath;
  536. sw.Stop();
  537. return Ok(JsonView(true, "操作成功!耗时:" + (sw.ElapsedMilliseconds / 1000) + "s", new { FileUrl = fileUrl }));
  538. }
  539. /// <summary>
  540. /// 下载个税模板
  541. /// </summary>
  542. /// <returns></returns>
  543. [HttpPost]
  544. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  545. public async Task<IActionResult> WageSheetTaxTemplate()
  546. {
  547. string serverUrl = AppSettingsHelper.Get("WageSheetExcelBaseUrl");
  548. var userData = await _usersRep.GetUserNameList(1);
  549. if (userData.Code == 0)
  550. {
  551. var userNames = userData.Data;
  552. List<string> names = new List<string>();
  553. List<UserNameView> users = new List<UserNameView>();
  554. names.Add("管理员");
  555. names.Add("国交共享号");
  556. names.Add("人事审核号");
  557. names.Add("国交主管号");
  558. List<TaxTemlateViuw> taxs = new List<TaxTemlateViuw>();
  559. users = JsonConvert.DeserializeObject<List<UserNameView>>(JsonConvert.SerializeObject(userNames));
  560. foreach (UserNameView item in users)
  561. {
  562. string uName = item.CnName;
  563. if (!names.Contains(uName))
  564. {
  565. taxs.Add(new TaxTemlateViuw { UserName = item.CnName });
  566. }
  567. }
  568. if (taxs.Count > 0)
  569. {
  570. WorkbookDesigner designer = new WorkbookDesigner();
  571. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/个税导入模板.xlsx");
  572. designer.Workbook.Worksheets[0].Name = "个税模板";
  573. designer.SetDataSource("TaxTemp", taxs);
  574. designer.Process();
  575. string fileName = "WageSheetTaxFile/个税模板" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  576. string path = AppSettingsHelper.Get("ExcelBasePath");
  577. designer.Workbook.Save(path + fileName);
  578. designer = null;
  579. string excelPath = AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  580. string url = AppSettingsHelper.Get("ExcelBaseUrl");
  581. string fileUrl = url + excelPath;
  582. return Ok(JsonView(true, "操作成功!", new { FileUrl = fileUrl }));
  583. }
  584. }
  585. return Ok(JsonView(false, "操作失败!"));
  586. }
  587. /// <summary>
  588. /// 上传个税
  589. /// </summary>
  590. /// <returns></returns>
  591. [HttpPost]
  592. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  593. public async Task<IActionResult> UploadTax(IFormFile file)
  594. {
  595. try
  596. {
  597. var yearMonth = Request.Headers["YearMonth"].ToString();
  598. //string yearMonth = "2023-10";
  599. string ymFormat = "yyyy-MM";
  600. DateTime yearMonthDt;
  601. bool yearMonthDtIsValid = DateTime.TryParseExact(yearMonth, ymFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out yearMonthDt);
  602. if (!yearMonthDtIsValid) return Ok(JsonView(false, "年月格式错误!正确时间格式:yyyy-MM "));
  603. if (file != null)
  604. {
  605. var fileDir = AppSettingsHelper.Get("WageSheetExcelFptPath");
  606. //文件名称
  607. string projectFileName = file.FileName;
  608. //上传的文件的路径
  609. string filePath = "";
  610. if (!Directory.Exists(fileDir))
  611. {
  612. Directory.CreateDirectory(fileDir);
  613. }
  614. //上传的文件的路径
  615. filePath = fileDir + $@"\{projectFileName}";
  616. if (System.IO.File.Exists(filePath))
  617. {
  618. //删除文件
  619. System.IO.File.Delete(filePath);
  620. }
  621. using (FileStream fs = System.IO.File.Create(filePath))
  622. {
  623. file.CopyTo(fs);
  624. fs.Flush();
  625. }
  626. if (System.IO.File.Exists(filePath))
  627. {
  628. Workbook book = new Workbook(filePath);
  629. DataSet dataSet = new DataSet();
  630. if (book.Worksheets.Count > 0)
  631. {
  632. var sheet = book.Worksheets[0];
  633. if (sheet != null)
  634. {
  635. // sheets 中的数据必须存在
  636. if (sheet.Cells.MaxDataRow != -1 && sheet.Cells.MaxDataColumn != -1)
  637. {
  638. // 方法 ExportDataTable 的参数说明
  639. // 要导出的第一个单元格的行号。
  640. // 要导出的第一个单元格的列号。
  641. // 要导入的行数。
  642. // 要导入的列数。
  643. // 指示第一行的数据是否导出到DataTable的列名。
  644. DataTable dataTable = sheet.Cells.ExportDataTable(0, 0, sheet.Cells.MaxDataRow + 1, sheet.Cells.MaxDataColumn + 1, true);
  645. dataSet.Tables.Add(dataTable);
  646. DataTable taxData = dataSet.Tables[0];
  647. //公司部门
  648. string sql = string.Format(@"Select row_number() over(order by pm_ws.Id) as Row_Number,
  649. sc.Id as CompanyId,sc.CompanyName,sd.Id as DepId,sd.DepName,
  650. sys_u1.CnName Name,sys_u2.CnName LastUpdateUserName,pm_ws.*
  651. From Pm_WageSheet pm_ws
  652. Left Join Sys_Users sys_u1 On pm_ws.UserId = sys_u1.Id
  653. Left Join Sys_Users sys_u2 On pm_ws.LastUpdateUserId = sys_u2.Id
  654. Left Join Sys_Company sc On sys_u1.companyId = sc.Id
  655. Left Join Sys_Department sd On sys_u1.DepId = sd.Id
  656. Where pm_ws.IsDel = 0 And pm_ws.YearMonth = '{0}'
  657. Order By UserId Asc ", yearMonth);
  658. var wageSheetList = await _wageSheetRep._sqlSugar.SqlQueryable<WageSheetInfoView>(sql).ToListAsync();
  659. if (wageSheetList.Count <= 0)
  660. {
  661. return Ok(JsonView(false, yearMonth + "工资数据不存在,请先添加工资数据!"));
  662. }
  663. for (int i = 0; i < taxData.Rows.Count; i++)
  664. {
  665. string name = taxData.Rows[i][0].ToString().Trim();
  666. List<WageSheetInfoView> wageSheets = new List<WageSheetInfoView>();
  667. wageSheets = wageSheetList.Where(it => it.Name.Equals(name)).ToList();
  668. if (wageSheets.Count > 0)
  669. {
  670. wageSheetList.Where(it => it.Name.Equals(name))
  671. .Select(it =>
  672. {
  673. //修改 绩效不等于0.00M的数据
  674. decimal oldTax = it.WithholdingTax;
  675. decimal newTax = Convert.ToDecimal(taxData.Rows[i][1].ToString());
  676. it.WithholdingTax = newTax;
  677. it.TotalRealHair = it.Should - it.TotalDeductions - newTax;
  678. return it;
  679. })
  680. .ToList();
  681. }
  682. }
  683. List<Pm_WageSheet> wageSheets1 = new List<Pm_WageSheet>();
  684. wageSheets1 = _mapper.Map<List<Pm_WageSheet>>(wageSheetList);
  685. var updateStatus = _wageSheetRep._sqlSugar
  686. .Updateable(wageSheets1)
  687. .UpdateColumns(it => new { it.WithholdingTax,it.TotalRealHair})
  688. .ExecuteCommand();
  689. if (updateStatus<0)
  690. {
  691. return Ok(JsonView(false, "操作失败!"));
  692. }
  693. if (System.IO.File.Exists(filePath))
  694. {
  695. //删除文件
  696. System.IO.File.Delete(filePath);
  697. }
  698. return Ok(JsonView(true, "操作成功!"));
  699. }
  700. }
  701. else
  702. {
  703. return Ok(JsonView(false, "工作薄没有数据!"));
  704. }
  705. }
  706. }
  707. return Ok(JsonView(true, "上传成功!", projectFileName));
  708. }
  709. else
  710. {
  711. return Ok(JsonView(false, "上传失败!"));
  712. }
  713. }
  714. catch (Exception ex)
  715. {
  716. return Ok(JsonView(false, "程序错误!"));
  717. throw;
  718. }
  719. return Ok(JsonView(true, "操作成功!"));
  720. }
  721. /// <summary>
  722. /// 打卡记录测试
  723. /// </summary>
  724. /// <returns></returns>
  725. [HttpPost]
  726. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  727. public async Task<IActionResult> Test(string startDt,string endDt)
  728. {
  729. UserIdListView userIdListView = await _qiYeWeChatApiService.GetUserIdListAsync();
  730. if (userIdListView.errcode != 0)
  731. {
  732. _result.Msg = "【企业微信】【打卡】【获取员工ID】【Msg】" + userIdListView.errmsg;
  733. return Ok(JsonView(false, _result.Msg));
  734. }
  735. List<string> qyWhchatIdList = new List<string>();
  736. qyWhchatIdList = userIdListView.dept_user.Select(it => it.userid).ToList();
  737. var data = await _qiYeWeChatApiService.GetCheckinDataAsync(qyWhchatIdList,2,Convert.ToDateTime(startDt), Convert.ToDateTime(endDt));
  738. return Ok(JsonView(true, "操作成功!", data.checkindata));
  739. }
  740. /// <summary>
  741. /// 审批详情
  742. /// </summary>
  743. /// <returns></returns>
  744. [HttpPost]
  745. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  746. public async Task<IActionResult> PostApprovalDetailAsync(string spNo)
  747. {
  748. if (string.IsNullOrEmpty(spNo))
  749. {
  750. return Ok(JsonView(false, "审批单号不能为空!!"));
  751. }
  752. var data = await _qiYeWeChatApiService.GetApprovalDetailAsync(spNo);
  753. return Ok(JsonView(true, "操作成功!", data));
  754. }
  755. #endregion
  756. }
  757. }