Clear code

This commit is contained in:
Ling 2025-10-09 15:46:16 +08:00
parent b484f81694
commit b983ec007f
4 changed files with 50 additions and 94 deletions

View File

@ -1,9 +1,3 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autofac; using Autofac;
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@ -24,6 +18,13 @@ using Newtonsoft.Json;
using Quartz; using Quartz;
using Quartz.Impl; using Quartz.Impl;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VOL.Core.Configuration; using VOL.Core.Configuration;
using VOL.Core.DBManager; using VOL.Core.DBManager;
using VOL.Core.Extensions; using VOL.Core.Extensions;
@ -227,6 +228,20 @@ namespace VOL.WebApi
ServeUnknownFileTypes = true ServeUnknownFileTypes = true
}); });
app.Use(HttpRequestMiddleware.Context); app.Use(HttpRequestMiddleware.Context);
app.Use(async (context, next) =>
{
// 将请求路径中连续的 "//" 替换为单个 "/"
var pathValue = context.Request.Path.Value ?? string.Empty;
if (pathValue.Contains("//"))
{
var normalized = Regex.Replace(pathValue, "/{2,}", "/");
context.Request.Path = new PathString(normalized);
}
// Do work that can write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
});
//2021.06.27增加创建默认upload文件夹 //2021.06.27增加创建默认upload文件夹
string _uploadPath = (env.ContentRootPath + "/Upload").ReplacePath(); string _uploadPath = (env.ContentRootPath + "/Upload").ReplacePath();

View File

@ -21,6 +21,7 @@
//mysql //mysql
"DbConnectionString": " Data Source=127.0.0.1;Database=laservall_data;AllowLoadLocalInfile=true;User ID=root;Password=1a2b3c4d@-=-=-=;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=43306;sslmode=none;", "DbConnectionString": " Data Source=127.0.0.1;Database=laservall_data;AllowLoadLocalInfile=true;User ID=root;Password=1a2b3c4d@-=-=-=;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=43306;sslmode=none;",
//"DbConnectionString": " Data Source=192.168.88.129;Database=laservall_data;AllowLoadLocalInfile=true;User ID=root;Password=rd5ZytWRknEtmjwW;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=43306;sslmode=none;",
//PgSql //PgSql
// "DbConnectionString": "Host=127.0.0.1;Port=5432;User id=postgres;password=jxx_abcd;Database=vol_v3;", // "DbConnectionString": "Host=127.0.0.1;Port=5432;User id=postgres;password=jxx_abcd;Database=vol_v3;",
@ -32,7 +33,7 @@
"RedisConnectionString": "127.0.0.1,SyncTimeout=15000", //redis() "RedisConnectionString": "127.0.0.1,SyncTimeout=15000", //redis()
"UseRedis": "true", //使redis使使Memory "UseRedis": "true", //使redis使使Memory
"UseSignalR": "true" //使SignalRCorsUrls "UseSignalR": "false" //使SignalRCorsUrls
}, },
"Secret": { // "Secret": { //
"JWT": "AA3925441FFA4B5DB4E64A29B53CE413", //jwt "JWT": "AA3925441FFA4B5DB4E64A29B53CE413", //jwt

View File

@ -16,7 +16,7 @@ namespace VOL.YSErp.Models
public class YSConfig public class YSConfig
{ {
public string ApiUrl = "https://c4.yonyoucloud.com"; // 正式环境 -> c4, 测试环境 -> c1 public string ApiUrl = "https://c4.yonyoucloud.com"; // 正式环境 -> c4, 测试环境 -> c1
public string Appkey = "6fe5b0b6163e45c081cc9a40848d5840";//"08f9377fd9ae45219e7dd3fbebb9858a";//"99355863c0ed4363b09f8511d48f67e4"; public string Appkey = "6fe5b0b6163e45c081cc9a40848d5840";
public string AppSecret = "ceeca798e84268a2d59f97c860e4c1223bf786df";//"8f4b0bf535fcdb6fa5b8ce5c630b740ddaa3b3be";//"3ca452060b684ccc982836cd5f0b6116811cb8ce"; public string AppSecret = "ceeca798e84268a2d59f97c860e4c1223bf786df";
} }
} }

View File

@ -25,9 +25,10 @@ namespace VOL.YSErp.Services.Biz
// YS API URLs // YS API URLs
private readonly string _tokenUrl; private readonly string _tokenUrl;
private readonly string _employeeListUrl; private readonly string _employeeListUrl;
private readonly string _updateEmployeeUrl;
private readonly string _deptListUrl; private readonly string _deptListUrl;
private readonly string _empInfoUrl; private readonly string _empInfoUrl;
private static readonly string[] resposeSuccessCodes = ["200", "00000"];
public YSERPService(SystemToken token, YSConfig config) public YSERPService(SystemToken token, YSConfig config)
{ {
_token = token; _token = token;
@ -38,7 +39,7 @@ namespace VOL.YSErp.Services.Biz
_tokenUrl = $"{_apiUrl}/iuap-api-auth/open-auth/selfAppAuth/getAccessToken"; _tokenUrl = $"{_apiUrl}/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
_employeeListUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/staff/listdetailmdd"; _employeeListUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/staff/listdetailmdd";
_updateEmployeeUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/batchInsertOrUpdateDetailNew"; //_updateEmployeeUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/batchInsertOrUpdateDetailNew";
_deptListUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/digitalModel/basedoc/dept/list"; _deptListUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/digitalModel/basedoc/dept/list";
_empInfoUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/HRCloud/getStaffDetail"; _empInfoUrl = $"{_apiUrl}/iuap-api-gateway/yonbip/hrcloud/HRCloud/getStaffDetail";
} }
@ -160,20 +161,20 @@ namespace VOL.YSErp.Services.Biz
var token = await GetValidTokenAsync(); var token = await GetValidTokenAsync();
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
return new List<YSERPEmployee>(); return [];
} }
var allEmployees = new List<YSERPEmployee>(); var allEmployees = new List<YSERPEmployee>();
var pageIndex = 1; var pageIndex = 1;
const int pageSize = 50; const int pageSize = 50;
Logger.Info($"员工信息API: {_employeeListUrl}"); //Logger.Info($"员工信息API: {_employeeListUrl}");
while (true) while (true)
{ {
try try
{ {
Logger.Info($"获取YS员工数据第 {pageIndex} 页..."); //Logger.Info($"获取YS员工数据第 {pageIndex} 页...");
var payload = new var payload = new
{ {
@ -195,24 +196,25 @@ namespace VOL.YSErp.Services.Biz
{ {
Logger.Error("认证失败: 无效的API令牌或权限不足"); Logger.Error("认证失败: 无效的API令牌或权限不足");
_accessToken = null; _accessToken = null;
return []; //return [];
throw new Exception("认证失败: 无效的YS ERP API令牌或权限不足");
} }
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<YSERPPagedResponse<YSERPEmployee>>(content); var data = JsonSerializer.Deserialize<YSERPPagedResponse<YSERPEmployee>>(content);
if (!new[] { "200", "00000" }.Contains(data.code)) if (data == null || !resposeSuccessCodes.Contains(data.code))
{ {
var errorMsg = data.message; var errorMsg = data?.message;
Logger.Error($"API业务错误: {errorMsg}"); Logger.Error($"API业务错误: {errorMsg}");
throw new Exception(errorMsg); throw new Exception($"API业务错误: 【{errorMsg}】");
} }
var recordList = data.data.recordList; var recordList = data.data.recordList;
if (recordList?.Count == 0) if (recordList?.Count == 0)
{ {
Logger.Info("没有更多员工记录"); //Logger.Info("没有更多员工记录");
break; break;
} }
@ -241,67 +243,6 @@ namespace VOL.YSErp.Services.Biz
return allEmployees; return allEmployees;
} }
public async Task<bool> UpdateEmployeesAsync(List<Dictionary<string, string>> employeeUpdates)
{
var token = await GetValidTokenAsync();
if (string.IsNullOrEmpty(token))
{
return false;
}
//_logger.LogInformation($"YS更新内容: {JsonSerializer.Serialize(employeeUpdates)}");
try
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{_updateEmployeeUrl}?access_token={token}")
{
Content = new StringContent(
JsonSerializer.Serialize(new { data = employeeUpdates }),
Encoding.UTF8,
"application/json")
};
var response = await _httpClient.SendAsync(request);
//_logger.LogInformation($"YS更新响应状态: {response.StatusCode}");
var content = await response.Content.ReadAsStringAsync();
//_logger.LogInformation($"YS更新响应内容: {content}");
response.EnsureSuccessStatusCode();
var data = JsonSerializer.Deserialize<JsonElement>(content);
if (data.GetProperty("code").GetString() == "00000")
{
//_logger.LogInformation($"成功更新 {employeeUpdates.Count} 名员工信息");
if (data.TryGetProperty("data", out var resultData))
{
if (resultData.TryGetProperty("messages", out var messages))
{
foreach (var msg in messages.EnumerateArray())
{
//_logger.LogWarning($"失败信息: {msg}");
}
}
}
return true;
}
else
{
var errorMsg = data.GetProperty("message").GetString();
Logger.Error($"更新失败: {errorMsg}");
return false;
}
}
catch (Exception ex)
{
Logger.Error( $"更新员工信息失败,{ex}");
return false;
}
}
public async Task<List<YSERPDepartment>> GetAllDepartmentsAsync() public async Task<List<YSERPDepartment>> GetAllDepartmentsAsync()
{ {
var token = await GetValidTokenAsync(); var token = await GetValidTokenAsync();
@ -311,7 +252,6 @@ namespace VOL.YSErp.Services.Biz
} }
var allDepts = new List<YSERPDepartment>(); var allDepts = new List<YSERPDepartment>();
//Logger.Info($"员工信息API: {_employeeListUrl}");
try try
{ {
@ -344,19 +284,18 @@ namespace VOL.YSErp.Services.Biz
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<YSERPListResponse<YSERPDepartment>>(content); var data = JsonSerializer.Deserialize<YSERPListResponse<YSERPDepartment>>(content);
if (!new[] { "200", "00000" }.Contains(data.code)) if (data == null || !resposeSuccessCodes.Contains(data.code))
{ {
var errorMsg = data.message; var errorMsg = data?.message;
Logger.Error($"API业务错误: {errorMsg}"); Logger.Error($"API业务错误: {errorMsg}");
throw new Exception(errorMsg); throw new Exception($"API业务错误【{errorMsg}】");
} }
var recordList = data.data; var recordList = data.data;
if(recordList?.Count == 0) if(recordList?.Count == 0)
{ {
Logger.Info("没有更多部门记录"); //Logger.Info("没有更多部门记录");
return allDepts; return allDepts;
} }
else else
@ -403,17 +342,18 @@ namespace VOL.YSErp.Services.Biz
{ {
Logger.Error("认证失败: 无效的API令牌或权限不足"); Logger.Error("认证失败: 无效的API令牌或权限不足");
_accessToken = null; _accessToken = null;
return new YSERPEmployeeInfo(); //return new YSERPEmployeeInfo();
throw new Exception("认证失败: 无效的YS ERP API令牌或权限不足");
} }
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
var data = JsonSerializer.Deserialize<YSERPResponse<YSERPEmployeeInfo>>(content); var data = JsonSerializer.Deserialize<YSERPResponse<YSERPEmployeeInfo>>(content);
if (!new[] { "200", "00000" }.Contains(data.code)) if (data==null || !resposeSuccessCodes.Contains(data.code))
{ {
var errorMsg = data.message; var errorMsg = data?.message;
Logger.Error($"API业务错误: {errorMsg}"); Logger.Error($"API业务错误: {errorMsg}");
throw new Exception(errorMsg); throw new Exception($"API业务错误: 【{errorMsg}】");
} }
return data.data; return data.data;