PersonnelModuleController.cs 41 KB

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