完成评查点分组的增删改
This commit is contained in:
+82
-13
@@ -156,7 +156,26 @@ export async function apiRequest<T>(
|
||||
headers.set('Accept', 'application/json');
|
||||
}
|
||||
|
||||
// 发送请求,5秒超时
|
||||
// 针对 PostgREST 的额外处理
|
||||
if (endpoint.includes('evaluation_point_groups') && (options.method === 'POST' || options.method === 'PATCH')) {
|
||||
console.log('使用 PostgREST 特定配置处理请求');
|
||||
// 确保请求体是有效的 JSON 对象
|
||||
if (options.body && typeof options.body === 'string') {
|
||||
try {
|
||||
JSON.parse(options.body); // 验证 JSON 是否有效
|
||||
} catch (e) {
|
||||
console.error('请求体不是有效的 JSON:', options.body);
|
||||
throw new Error('请求体必须是有效的 JSON');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`发送 ${options.method || 'GET'} 请求到: ${url}`);
|
||||
if (options.body) {
|
||||
console.log(`请求体: ${options.body}`);
|
||||
}
|
||||
|
||||
// 发送请求,10秒超时
|
||||
const response = await fetchWithTimeout(url, {
|
||||
...options,
|
||||
headers
|
||||
@@ -164,9 +183,23 @@ export async function apiRequest<T>(
|
||||
|
||||
// 解析响应
|
||||
let data = null;
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (contentType && contentType.includes('application/json') && response.status !== 204) {
|
||||
data = await response.json();
|
||||
let responseText = '';
|
||||
|
||||
try {
|
||||
const contentType = response.headers.get('content-type');
|
||||
responseText = await response.text();
|
||||
|
||||
if (contentType && contentType.includes('application/json') && response.status !== 204 && responseText) {
|
||||
try {
|
||||
data = JSON.parse(responseText);
|
||||
} catch (e) {
|
||||
console.error('响应不是有效的 JSON:', responseText);
|
||||
throw new Error('服务器返回无效的 JSON 响应');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('解析响应失败:', e);
|
||||
console.log('原始响应:', responseText);
|
||||
}
|
||||
|
||||
// 收集响应头信息
|
||||
@@ -175,6 +208,51 @@ export async function apiRequest<T>(
|
||||
responseHeaders[key] = value;
|
||||
});
|
||||
|
||||
// 打印响应信息
|
||||
// console.log(`响应状态: ${response.status} ${response.statusText}`);
|
||||
// console.log(`响应头:`, responseHeaders);
|
||||
// console.log(`响应体:`, data || responseText);
|
||||
|
||||
// 检查 PostgREST 特定错误
|
||||
if (!response.ok) {
|
||||
if (response.status === 400) {
|
||||
console.error('PostgREST 错误 - 无效请求:', data || responseText);
|
||||
return {
|
||||
error: '无效的请求格式,请检查数据格式是否正确',
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
} else if (response.status === 401) {
|
||||
console.error('PostgREST 错误 - 未授权:', data || responseText);
|
||||
return {
|
||||
error: '未授权,请检查认证信息',
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
} else if (response.status === 403) {
|
||||
console.error('PostgREST 错误 - 禁止访问:', data || responseText);
|
||||
return {
|
||||
error: '没有权限执行此操作',
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
} else if (response.status === 404) {
|
||||
console.error('PostgREST 错误 - 资源不存在:', data || responseText);
|
||||
return {
|
||||
error: '请求的资源不存在',
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
} else {
|
||||
console.error(`HTTP请求失败: ${response.status} - ${url}`, data || responseText);
|
||||
return {
|
||||
error: data?.msg || `请求失败: ${response.status}`,
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 检查API返回的状态码
|
||||
if (data && 'code' in data && data.code !== 0) {
|
||||
console.error(`API请求失败: ${data.msg || '未知错误'} - ${url}`);
|
||||
@@ -185,15 +263,6 @@ export async function apiRequest<T>(
|
||||
};
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`HTTP请求失败: ${response.status} - ${url}`);
|
||||
return {
|
||||
error: data?.msg || `请求失败: ${response.status}`,
|
||||
status: response.status,
|
||||
headers: responseHeaders
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
status: response.status,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { postgrestGet, type PostgrestParams } from '../postgrest-client';
|
||||
import { postgrestGet, postgrestPost, postgrestPut, postgrestDelete, type PostgrestParams } from '../postgrest-client';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
/**
|
||||
* 评查点分组接口
|
||||
@@ -7,9 +8,75 @@ export interface RuleGroup {
|
||||
id: string;
|
||||
pid: string;
|
||||
name: string;
|
||||
status: boolean;
|
||||
code?: string; // 添加分组编码字段
|
||||
is_enabled: boolean;
|
||||
ruleCount?: number; // 评查点数量
|
||||
children?: RuleGroup[]; // 子分组
|
||||
createdAt?: string; // 添加创建时间字段
|
||||
description?: string; // 描述
|
||||
}
|
||||
|
||||
// API请求模型
|
||||
export interface ApiRuleGroup {
|
||||
id?: number;
|
||||
pid: number;
|
||||
name: string;
|
||||
code?: string;
|
||||
description?: string;
|
||||
is_enabled: boolean;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
// 创建或更新分组请求参数
|
||||
export interface RuleGroupCreateUpdateDto {
|
||||
name: string;
|
||||
code: string;
|
||||
pid: string | null; // 父分组ID,如果是一级分组则为null或'0'
|
||||
description?: string;
|
||||
is_enabled: boolean;
|
||||
}
|
||||
|
||||
// 用于替换代码中的 any 类型
|
||||
interface ApiResponse<T> {
|
||||
code: number;
|
||||
msg: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
* @param dateString 日期字符串
|
||||
* @returns 格式化后的日期字符串
|
||||
*/
|
||||
function formatDate(dateString: string): string {
|
||||
if (!dateString) return '';
|
||||
try {
|
||||
return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
|
||||
} catch (error) {
|
||||
console.error('日期格式化失败:', error);
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从不同格式的 API 响应中提取数据
|
||||
* @param responseData API 响应数据
|
||||
* @returns 提取后的数据或 null
|
||||
*/
|
||||
function extractApiData<T>(responseData: unknown): T | null {
|
||||
if (!responseData) return null;
|
||||
|
||||
// 格式1: { code: number, msg: string, data: T }
|
||||
if (typeof responseData === 'object' && responseData !== null &&
|
||||
'code' in responseData &&
|
||||
'data' in responseData &&
|
||||
(responseData as { data: unknown }).data) {
|
||||
return (responseData as { data: T }).data;
|
||||
}
|
||||
|
||||
// 格式2: 直接是数据对象
|
||||
return responseData as T;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -18,53 +85,62 @@ export interface RuleGroup {
|
||||
*/
|
||||
export async function getRuleGroups(): Promise<{data: RuleGroup[]; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 1. 获取所有一级分组(pid=0)
|
||||
const parentGroupsParams: PostgrestParams = {
|
||||
const params: PostgrestParams = {
|
||||
select: `
|
||||
id,
|
||||
pid,
|
||||
name,
|
||||
status
|
||||
code,
|
||||
description,
|
||||
is_enabled,
|
||||
created_at
|
||||
`,
|
||||
filter: {
|
||||
'pid': 'eq.0'
|
||||
}
|
||||
};
|
||||
|
||||
const parentGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
|
||||
const response = await postgrestGet<{code: number; msg: string; data: Array<{
|
||||
id: number;
|
||||
pid: number;
|
||||
name: string;
|
||||
status: boolean;
|
||||
}>}>('evaluation_point_groups', parentGroupsParams);
|
||||
code?: string;
|
||||
description?: string;
|
||||
is_enabled: boolean;
|
||||
created_at?: string;
|
||||
}>}>('evaluation_point_groups', params);
|
||||
|
||||
if (parentGroupsResponse.error) {
|
||||
return { error: parentGroupsResponse.error, status: parentGroupsResponse.status };
|
||||
if (response.error) {
|
||||
return { error: response.error, status: response.status };
|
||||
}
|
||||
|
||||
// 处理响应数据
|
||||
let parentGroups: RuleGroup[] = [];
|
||||
if (parentGroupsResponse.data && 'code' in parentGroupsResponse.data && parentGroupsResponse.data.data) {
|
||||
parentGroups = parentGroupsResponse.data.data.map(group => ({
|
||||
let groups: RuleGroup[] = [];
|
||||
if (response.data && 'code' in response.data && response.data.data) {
|
||||
groups = response.data.data.map(group => ({
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
children: [] // 初始化子分组数组
|
||||
code: group.code,
|
||||
description: group.description,
|
||||
is_enabled: group.is_enabled,
|
||||
createdAt: group.created_at ? formatDate(group.created_at) : undefined
|
||||
}));
|
||||
} else if (Array.isArray(parentGroupsResponse.data)) {
|
||||
parentGroups = parentGroupsResponse.data.map(group => ({
|
||||
} else if (Array.isArray(response.data)) {
|
||||
groups = response.data.map(group => ({
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
children: [] // 初始化子分组数组
|
||||
code: group.code,
|
||||
description: group.description,
|
||||
is_enabled: group.is_enabled,
|
||||
createdAt: group.created_at ? formatDate(group.created_at) : undefined
|
||||
}));
|
||||
}
|
||||
|
||||
return { data: parentGroups };
|
||||
return { data: groups };
|
||||
} catch (error) {
|
||||
console.error('获取评查点分组列表出错:', error);
|
||||
console.error('获取评查点分组列表失败:', error);
|
||||
return {
|
||||
error: error instanceof Error ? error.message : '获取评查点分组列表失败',
|
||||
status: 500
|
||||
@@ -85,7 +161,9 @@ export async function getChildGroups(parentId: string): Promise<{data: RuleGroup
|
||||
id,
|
||||
pid,
|
||||
name,
|
||||
status
|
||||
code,
|
||||
is_enabled,
|
||||
created_at
|
||||
`,
|
||||
filter: {
|
||||
'pid': `eq.${parentId}`
|
||||
@@ -96,7 +174,9 @@ export async function getChildGroups(parentId: string): Promise<{data: RuleGroup
|
||||
id: number;
|
||||
pid: number;
|
||||
name: string;
|
||||
status: boolean;
|
||||
code?: string;
|
||||
is_enabled: boolean;
|
||||
created_at?: string;
|
||||
}>}>('evaluation_point_groups', childGroupsParams);
|
||||
|
||||
if (childGroupsResponse.error) {
|
||||
@@ -115,18 +195,18 @@ export async function getChildGroups(parentId: string): Promise<{data: RuleGroup
|
||||
}
|
||||
};
|
||||
|
||||
const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
|
||||
const ruleCountResponse = await postgrestGet<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
|
||||
|
||||
return {
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
code: group.code,
|
||||
is_enabled: group.is_enabled,
|
||||
createdAt: group.created_at ? formatDate(group.created_at) : undefined,
|
||||
ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data
|
||||
? ruleCountResponse.data.data?.length || 0
|
||||
: Array.isArray(ruleCountResponse.data)
|
||||
? ruleCountResponse.data.length
|
||||
: 0
|
||||
? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
|
||||
: (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0)
|
||||
};
|
||||
}));
|
||||
} else if (Array.isArray(childGroupsResponse.data)) {
|
||||
@@ -139,18 +219,18 @@ export async function getChildGroups(parentId: string): Promise<{data: RuleGroup
|
||||
}
|
||||
};
|
||||
|
||||
const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
|
||||
const ruleCountResponse = await postgrestGet<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
|
||||
|
||||
return {
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
code: group.code,
|
||||
is_enabled: group.is_enabled,
|
||||
createdAt: group.created_at ? formatDate(group.created_at) : undefined,
|
||||
ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data
|
||||
? ruleCountResponse.data.data?.length || 0
|
||||
: Array.isArray(ruleCountResponse.data)
|
||||
? ruleCountResponse.data.length
|
||||
: 0
|
||||
? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
|
||||
: (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0)
|
||||
};
|
||||
}));
|
||||
}
|
||||
@@ -177,7 +257,7 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
id,
|
||||
pid,
|
||||
name,
|
||||
status
|
||||
is_enabled
|
||||
`
|
||||
};
|
||||
|
||||
@@ -185,7 +265,7 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
id: number;
|
||||
pid: number;
|
||||
name: string;
|
||||
status: boolean;
|
||||
is_enabled: boolean;
|
||||
}>}>('evaluation_point_groups', allGroupsParams);
|
||||
|
||||
if (allGroupsResponse.error) {
|
||||
@@ -199,7 +279,7 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
is_enabled: group.is_enabled,
|
||||
children: []
|
||||
}));
|
||||
} else if (Array.isArray(allGroupsResponse.data)) {
|
||||
@@ -207,7 +287,7 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
id: group.id.toString(),
|
||||
pid: group.pid.toString(),
|
||||
name: group.name,
|
||||
status: group.status,
|
||||
is_enabled: group.is_enabled,
|
||||
children: []
|
||||
}));
|
||||
}
|
||||
@@ -228,13 +308,11 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
}
|
||||
};
|
||||
|
||||
const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
|
||||
const ruleCountResponse = await postgrestGet<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
|
||||
|
||||
child.ruleCount = ruleCountResponse.data && 'code' in ruleCountResponse.data
|
||||
? ruleCountResponse.data.data?.length || 0
|
||||
: Array.isArray(ruleCountResponse.data)
|
||||
? ruleCountResponse.data.length
|
||||
: 0;
|
||||
? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
|
||||
: (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,4 +324,337 @@ export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: ne
|
||||
status: 500
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个评查点分组详情
|
||||
* @param id 分组ID
|
||||
* @returns 分组详情
|
||||
*/
|
||||
export async function getRuleGroup(id: string): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
if (!id) {
|
||||
return { error: '分组ID不能为空', status: 400 };
|
||||
}
|
||||
|
||||
const params: PostgrestParams = {
|
||||
select: `
|
||||
id,
|
||||
pid,
|
||||
name,
|
||||
code,
|
||||
description,
|
||||
is_enabled,
|
||||
created_at
|
||||
`,
|
||||
filter: {
|
||||
'id': `eq.${id}`
|
||||
}
|
||||
};
|
||||
|
||||
const response = await postgrestGet<{code: number; msg: string; data: Array<{
|
||||
id: number;
|
||||
pid: number;
|
||||
name: string;
|
||||
code?: string;
|
||||
description?: string;
|
||||
is_enabled: boolean;
|
||||
created_at?: string;
|
||||
}>}>('evaluation_point_groups', params);
|
||||
|
||||
if (response.error) {
|
||||
return { error: response.error, status: response.status };
|
||||
}
|
||||
|
||||
let group: RuleGroup | null = null;
|
||||
|
||||
if (response.data && 'code' in response.data && response.data.data && response.data.data.length > 0) {
|
||||
const apiGroup = response.data.data[0];
|
||||
group = {
|
||||
id: apiGroup.id.toString(),
|
||||
pid: apiGroup.pid.toString(),
|
||||
name: apiGroup.name,
|
||||
code: apiGroup.code,
|
||||
description: apiGroup.description,
|
||||
is_enabled: apiGroup.is_enabled,
|
||||
createdAt: apiGroup.created_at ? formatDate(apiGroup.created_at) : undefined
|
||||
};
|
||||
} else if (Array.isArray(response.data) && response.data.length > 0) {
|
||||
const apiGroup = response.data[0];
|
||||
group = {
|
||||
id: apiGroup.id.toString(),
|
||||
pid: apiGroup.pid.toString(),
|
||||
name: apiGroup.name,
|
||||
code: apiGroup.code,
|
||||
description: apiGroup.description,
|
||||
is_enabled: apiGroup.is_enabled,
|
||||
createdAt: apiGroup.created_at ? formatDate(apiGroup.created_at) : undefined
|
||||
};
|
||||
}
|
||||
|
||||
if (!group) {
|
||||
return { error: '未找到指定分组', status: 404 };
|
||||
}
|
||||
|
||||
// 如果是父分组,获取评查点数量
|
||||
if (group.pid === '0') {
|
||||
const ruleCountParams: PostgrestParams = {
|
||||
select: 'id',
|
||||
filter: {
|
||||
'evaluation_point_groups_id': `eq.${group.id}`
|
||||
}
|
||||
};
|
||||
|
||||
const ruleCountResponse = await postgrestGet<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
|
||||
|
||||
group.ruleCount = ruleCountResponse.data && 'code' in ruleCountResponse.data
|
||||
? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
|
||||
: (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0);
|
||||
}
|
||||
|
||||
return { data: group };
|
||||
} catch (error) {
|
||||
console.error('获取评查点分组详情失败:', error);
|
||||
return {
|
||||
error: error instanceof Error ? error.message : '获取评查点分组详情失败',
|
||||
status: 500
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建评查点分组
|
||||
* @param groupData 分组数据
|
||||
* @returns 创建的分组
|
||||
*/
|
||||
export async function createRuleGroup(groupData: RuleGroupCreateUpdateDto): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 验证必填字段
|
||||
if (!groupData.name || !groupData.code) {
|
||||
return { error: '分组名称和编码不能为空', status: 400 };
|
||||
}
|
||||
|
||||
// 确保 pid 是合法值
|
||||
let pidValue: number;
|
||||
try {
|
||||
pidValue = groupData.pid ? Number(groupData.pid) : 0;
|
||||
if (isNaN(pidValue)) {
|
||||
return { error: '父分组ID必须是有效的数字', status: 400 };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('父分组ID转换失败:', error);
|
||||
return { error: '父分组ID格式错误', status: 400 };
|
||||
}
|
||||
|
||||
// 构建API请求数据 - 确保字段类型符合数据库要求
|
||||
const apiGroup: ApiRuleGroup = {
|
||||
pid: pidValue,
|
||||
name: groupData.name.trim(),
|
||||
code: groupData.code.trim(),
|
||||
description: groupData.description || '',
|
||||
is_enabled: groupData.is_enabled
|
||||
};
|
||||
|
||||
console.log('创建评查点分组请求数据:', JSON.stringify(apiGroup, null, 2));
|
||||
|
||||
// 直接发送到 PostgreSQL 表
|
||||
const response = await postgrestPost<ApiResponse<ApiRuleGroup> | ApiRuleGroup, ApiRuleGroup>(
|
||||
'evaluation_point_groups', // 表名
|
||||
apiGroup
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
console.error('创建评查点分组API返回错误:', response.error, '状态码:', response.status);
|
||||
return { error: response.error, status: response.status };
|
||||
}
|
||||
|
||||
console.log('创建评查点分组响应数据:', JSON.stringify(response.data, null, 2));
|
||||
|
||||
// 处理响应数据 - 适配不同的API响应格式
|
||||
const apiResponse = extractApiData<ApiRuleGroup>(response.data);
|
||||
|
||||
if (!apiResponse) {
|
||||
console.error('创建分组成功但返回数据格式异常:', response.data);
|
||||
return { error: '创建分组失败,返回数据格式错误', status: 500 };
|
||||
}
|
||||
|
||||
// 构建返回对象
|
||||
const createdGroup: RuleGroup = {
|
||||
id: apiResponse.id?.toString() || '',
|
||||
pid: apiResponse.pid?.toString() || '0', // 兼容没有 pid 的情况
|
||||
name: apiResponse.name || '',
|
||||
code: apiResponse.code?.toString() || '', // 处理可能的数字类型
|
||||
description: apiResponse.description,
|
||||
is_enabled: apiResponse.is_enabled !== undefined ? apiResponse.is_enabled : true,
|
||||
createdAt: apiResponse.created_at ? formatDate(apiResponse.created_at) : undefined
|
||||
};
|
||||
|
||||
return { data: createdGroup };
|
||||
} catch (error) {
|
||||
console.error('创建评查点分组失败:', error);
|
||||
return {
|
||||
error: error instanceof Error ? error.message : '创建评查点分组失败',
|
||||
status: 500
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新评查点分组
|
||||
* @param id 分组ID
|
||||
* @param data 更新的分组数据
|
||||
* @returns 更新后的分组
|
||||
*/
|
||||
export async function updateRuleGroup(id: string, data: RuleGroupCreateUpdateDto): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 使用新的filters参数
|
||||
const response = await postgrestPut<ApiResponse<RuleGroup> | RuleGroup, RuleGroupCreateUpdateDto>(
|
||||
'evaluation_point_groups',
|
||||
data,
|
||||
{ id }
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
return { error: response.error, status: response.status };
|
||||
}
|
||||
|
||||
// 使用辅助函数提取数据
|
||||
const extractedData = extractApiData<RuleGroup>(response.data);
|
||||
|
||||
if (!extractedData) {
|
||||
return { error: '更新成功但未返回数据' };
|
||||
}
|
||||
|
||||
return { data: extractedData };
|
||||
} catch (error) {
|
||||
console.error('更新评查点分组失败:', error);
|
||||
return {
|
||||
error: error instanceof Error ? error.message : '更新评查点分组失败'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除评查点分组
|
||||
* @param id 分组ID
|
||||
* @returns 删除结果
|
||||
*/
|
||||
export async function deleteRuleGroup(id: string): Promise<{success: boolean; error?: string}> {
|
||||
try {
|
||||
// 1. 首先获取分组信息,判断是一级还是二级分组
|
||||
const groupResponse = await getRuleGroup(id);
|
||||
if (groupResponse.error) {
|
||||
return { success: false, error: groupResponse.error };
|
||||
}
|
||||
|
||||
const group = groupResponse.data;
|
||||
if (!group) {
|
||||
return { success: false, error: '未找到指定分组' };
|
||||
}
|
||||
|
||||
// 2. 如果是一级分组,需要先删除所有子分组
|
||||
if (group.pid === '0') {
|
||||
// 获取所有子分组
|
||||
const childGroupsResponse = await getChildGroups(id);
|
||||
if (childGroupsResponse.error) {
|
||||
return { success: false, error: childGroupsResponse.error };
|
||||
}
|
||||
|
||||
const childGroups = childGroupsResponse.data || [];
|
||||
|
||||
// 遍历删除每个子分组
|
||||
for (const childGroup of childGroups) {
|
||||
const deleteChildResult = await deleteChildGroup(childGroup.id);
|
||||
if (!deleteChildResult.success) {
|
||||
return deleteChildResult;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 删除分组下的所有评查点
|
||||
const deletePointsResult = await deleteEvaluationPointsByGroupId(id);
|
||||
if (!deletePointsResult.success) {
|
||||
return deletePointsResult;
|
||||
}
|
||||
|
||||
// 4. 最后删除分组本身
|
||||
const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_point_groups', {
|
||||
filter: {
|
||||
'id': `eq.${id}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.error) {
|
||||
return { success: false, error: response.error };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('删除评查点分组失败:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '删除评查点分组失败'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除子分组及其相关数据
|
||||
* @param id 子分组ID
|
||||
* @returns 删除结果
|
||||
*/
|
||||
async function deleteChildGroup(id: string): Promise<{success: boolean; error?: string}> {
|
||||
try {
|
||||
// 1. 删除子分组下的所有评查点
|
||||
const deletePointsResult = await deleteEvaluationPointsByGroupId(id);
|
||||
if (!deletePointsResult.success) {
|
||||
return deletePointsResult;
|
||||
}
|
||||
|
||||
// 2. 删除子分组本身
|
||||
const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_point_groups', {
|
||||
filter: {
|
||||
'id': `eq.${id}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.error) {
|
||||
return { success: false, error: response.error };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('删除子分组失败:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '删除子分组失败'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定分组下的所有评查点
|
||||
* @param groupId 分组ID
|
||||
* @returns 删除结果
|
||||
*/
|
||||
async function deleteEvaluationPointsByGroupId(groupId: string): Promise<{success: boolean; error?: string}> {
|
||||
try {
|
||||
const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_points', {
|
||||
filter: {
|
||||
'evaluation_point_groups_id': `eq.${groupId}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.error) {
|
||||
return { success: false, error: response.error };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('删除评查点失败:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '删除评查点失败'
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { apiRequest } from './client';
|
||||
import { FileType, Priority } from '~/types/enums';
|
||||
|
||||
/**
|
||||
* 将文件转换为二进制数据
|
||||
*/
|
||||
export async function uploadFileToBinary(file: File): Promise<ArrayBuffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (reader.result instanceof ArrayBuffer) {
|
||||
resolve(reader.result);
|
||||
} else {
|
||||
reject(new Error('文件读取失败'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('文件读取失败'));
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到服务器
|
||||
*/
|
||||
export async function uploadFileToServer(
|
||||
binaryData: ArrayBuffer,
|
||||
fileName: string,
|
||||
fileType: string,
|
||||
documentType: FileType,
|
||||
priority: Priority
|
||||
): Promise<{ success: boolean; fileId?: string; message?: string; error?: string }> {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', new Blob([binaryData], { type: fileType }), fileName);
|
||||
formData.append('documentType', documentType);
|
||||
formData.append('priority', priority);
|
||||
|
||||
const response = await apiRequest<{ success: boolean; fileId?: string; message?: string }>(
|
||||
'/api/files/upload',
|
||||
{
|
||||
method: 'POST',
|
||||
body: formData
|
||||
}
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
return { success: false, error: response.error };
|
||||
}
|
||||
|
||||
return { success: true, fileId: response.data?.fileId, message: response.data?.message };
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : '上传失败' };
|
||||
}
|
||||
}
|
||||
+213
-23
@@ -21,8 +21,9 @@ export interface PostgrestParams {
|
||||
* 打印 PostgREST 查询日志
|
||||
* @param endpoint 端点
|
||||
* @param params 参数
|
||||
* @param method HTTP 方法
|
||||
*/
|
||||
function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
function logPostgrestQuery(endpoint: string, params?: QueryParams, method: string = 'GET'): void {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// const baseUrl = 'http://172.16.0.119:9000/admin';
|
||||
// const baseUrl = 'http://172.18.0.100:3000';
|
||||
@@ -32,6 +33,7 @@ function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
console.log('\n📦 PostgREST 查询日志 ========================');
|
||||
console.log(`📦 HTTP 方法: ${method}`);
|
||||
console.log(`📦 API 端点: ${baseUrl}/${normalizedEndpoint}`);
|
||||
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
@@ -74,7 +76,7 @@ function logPostgrestQuery(endpoint: string, params?: QueryParams): void {
|
||||
console.log(`\n📦 可读URL: ${baseUrl}/${normalizedEndpoint}${readableQueryString ? '?' + readableQueryString : ''}`);
|
||||
|
||||
// 格式化查询为 PostgreSQL 风格的查询
|
||||
let postgrestQuery = `SELECT `;
|
||||
let postgrestQuery = `${method.toUpperCase()} `;
|
||||
|
||||
if (params.select && typeof params.select === 'string') {
|
||||
postgrestQuery += params.select.replace(/\s+/g, ' ').trim();
|
||||
@@ -251,7 +253,7 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams);
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'GET');
|
||||
|
||||
// 提取并移除自定义头部参数
|
||||
const headers: Record<string, string> = params?.headers || {};
|
||||
@@ -285,9 +287,96 @@ export async function postgrestGet<T>(endpoint: string, params?: PostgrestParams
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 PostgreSQL 特定错误
|
||||
* @param error 错误对象或消息
|
||||
* @param responseText 原始响应文本
|
||||
* @returns 格式化的错误信息
|
||||
*/
|
||||
function handlePostgresError(error: unknown, responseText?: string): { message: string, status?: number } {
|
||||
let errorMessage = error instanceof Error ? error.message : String(error);
|
||||
let statusCode: number | undefined = undefined;
|
||||
|
||||
// 如果有原始响应文本,尝试从中提取更详细的错误信息
|
||||
if (responseText) {
|
||||
try {
|
||||
const errorData = JSON.parse(responseText);
|
||||
|
||||
// 处理 PostgreSQL 错误码
|
||||
if (errorData.code) {
|
||||
switch (errorData.code) {
|
||||
case '23505': // 唯一约束冲突
|
||||
errorMessage = '记录已存在,无法创建重复数据';
|
||||
if (errorData.details) {
|
||||
// 尝试提取冲突的字段名
|
||||
const match = errorData.details.match(/Key \((.+?)\)=/);
|
||||
if (match && match[1]) {
|
||||
const field = match[1];
|
||||
errorMessage = `${field} 已存在,请使用不同的值`;
|
||||
}
|
||||
}
|
||||
statusCode = 409; // Conflict
|
||||
break;
|
||||
|
||||
case '23503': // 外键约束失败
|
||||
errorMessage = '引用的记录不存在';
|
||||
if (errorData.details) {
|
||||
// 尝试提取外键字段
|
||||
const match = errorData.details.match(/Key \((.+?)\)=/);
|
||||
if (match && match[1]) {
|
||||
const field = match[1];
|
||||
errorMessage = `所引用的 ${field} 不存在或无效`;
|
||||
}
|
||||
}
|
||||
statusCode = 400; // Bad Request
|
||||
break;
|
||||
|
||||
case '42P01': // 表不存在
|
||||
errorMessage = '所请求的数据表不存在';
|
||||
statusCode = 404; // Not Found
|
||||
break;
|
||||
|
||||
case '42703': // 列不存在
|
||||
errorMessage = '所引用的字段不存在';
|
||||
if (errorData.details) {
|
||||
const match = errorData.details.match(/column "(.+?)"/);
|
||||
if (match && match[1]) {
|
||||
const column = match[1];
|
||||
errorMessage = `字段 "${column}" 不存在`;
|
||||
}
|
||||
}
|
||||
statusCode = 400; // Bad Request
|
||||
break;
|
||||
|
||||
default:
|
||||
// 使用 PostgreSQL 提供的错误消息
|
||||
if (errorData.message) {
|
||||
errorMessage = errorData.message;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理 HTTP 状态码
|
||||
if (errorData.status) {
|
||||
statusCode = errorData.status;
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('解析错误响应失败:', e);
|
||||
// 如果解析失败,尝试直接使用响应文本
|
||||
if (responseText && responseText.length < 200) {
|
||||
errorMessage = responseText;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { message: errorMessage, status: statusCode };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 POST 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param endpoint 端点(表名)
|
||||
* @param data 请求体数据
|
||||
* @returns 响应数据
|
||||
*/
|
||||
@@ -297,46 +386,143 @@ export async function postgrestPost<T, D = Record<string, unknown>>(endpoint: st
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 打印查询信息(POST请求只打印端点)
|
||||
logPostgrestQuery(apiEndpoint);
|
||||
logPostgrestQuery(apiEndpoint, undefined, 'POST');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
headers: {
|
||||
'Prefer': 'return=representation'
|
||||
// 预处理数据,确保所有字段类型符合 PostgreSQL 要求
|
||||
const processedData = preprocessData(data as Record<string, unknown>);
|
||||
|
||||
// 确保数据是合法的JSON对象
|
||||
const requestBody = JSON.stringify(processedData);
|
||||
console.log(`准备发送 PostgreSQL 插入请求到: ${apiEndpoint}`);
|
||||
console.log(`请求体: ${requestBody}`);
|
||||
|
||||
try {
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
body: requestBody,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Prefer': 'return=representation'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
console.error(`POST请求失败: ${response.error}`);
|
||||
throw new Error(response.error);
|
||||
}
|
||||
);
|
||||
|
||||
if (response.error) {
|
||||
throw new Error(response.error);
|
||||
|
||||
console.log(`POST请求成功,响应: `, response.data);
|
||||
return { data: response.data as T };
|
||||
} catch (error) {
|
||||
// 捕获并处理 API 请求错误
|
||||
let errorText = '';
|
||||
|
||||
// 如果错误对象中包含响应文本,尝试提取更详细的错误信息
|
||||
if (error instanceof Error && 'responseText' in error) {
|
||||
errorText = (error as {responseText: string}).responseText;
|
||||
}
|
||||
|
||||
// 处理 PostgreSQL 特定错误
|
||||
const pgError = handlePostgresError(error, errorText);
|
||||
|
||||
console.error(`POST请求错误: ${pgError.message}`);
|
||||
return {
|
||||
error: pgError.message,
|
||||
status: pgError.status || 500
|
||||
};
|
||||
}
|
||||
|
||||
return { data: response.data as T };
|
||||
} catch (error) {
|
||||
console.error(`POST请求处理错误: ${error instanceof Error ? error.message : String(error)}`);
|
||||
const apiError = handleApiError(error);
|
||||
return { error: apiError.message, status: apiError.status };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预处理数据,确保类型与 PostgreSQL 兼容
|
||||
* @param data 原始数据
|
||||
* @returns 处理后的数据
|
||||
*/
|
||||
function preprocessData(data: Record<string, unknown>): Record<string, unknown> {
|
||||
const processed: Record<string, unknown> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
// 确保 null 值被正确处理
|
||||
if (value === null) {
|
||||
processed[key] = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 处理字符串可能被错误解析为数字的情况
|
||||
if (typeof value === 'string' && /^\d+$/.test(value) && key !== 'code' && !key.endsWith('_id')) {
|
||||
// 对于可能需要保持字符串格式的值,我们不进行数字转换
|
||||
processed[key] = value;
|
||||
}
|
||||
// 将字符串 'true'/'false' 转为布尔值
|
||||
else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
|
||||
processed[key] = value.toLowerCase() === 'true';
|
||||
}
|
||||
// 尝试转换 '0'/'1' 为 boolean (如果字段名暗示是布尔值)
|
||||
else if (typeof value === 'string' && (value === '0' || value === '1') &&
|
||||
(key.startsWith('is_') || key.startsWith('has_') || key.endsWith('_enabled'))) {
|
||||
processed[key] = value === '1';
|
||||
}
|
||||
// 对于ID字段确保使用正确的类型
|
||||
else if ((key === 'id' || key.endsWith('_id') || key === 'pid') && value !== undefined) {
|
||||
try {
|
||||
const numValue = Number(value);
|
||||
if (!isNaN(numValue)) {
|
||||
processed[key] = numValue;
|
||||
} else {
|
||||
processed[key] = value;
|
||||
}
|
||||
} catch {
|
||||
processed[key] = value;
|
||||
}
|
||||
}
|
||||
// 其他值保持不变
|
||||
else {
|
||||
processed[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 PUT 请求到 PostgresREST 接口
|
||||
* @param endpoint 端点
|
||||
* @param data 请求体数据
|
||||
* @param filters 过滤条件
|
||||
* @returns 响应数据
|
||||
*/
|
||||
export async function postgrestPut<T, D = Record<string, unknown>>(endpoint: string, data: D): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
export async function postgrestPut<T, D extends object>(
|
||||
endpoint: string,
|
||||
data: D,
|
||||
filters?: Record<string, string>
|
||||
): Promise<{data: T; error?: never} | {data?: never; error: string; status?: number}> {
|
||||
try {
|
||||
// 确保端点没有前导斜杠
|
||||
const apiEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
// 构建完整的URL,包含过滤条件
|
||||
let fullEndpoint = apiEndpoint;
|
||||
if (filters) {
|
||||
const filterString = Object.entries(filters)
|
||||
.map(([key, value]) => `${key}=eq.${value}`)
|
||||
.join('&');
|
||||
fullEndpoint = `${apiEndpoint}?${filterString}`;
|
||||
}
|
||||
|
||||
// 打印查询信息(PUT请求只打印端点)
|
||||
logPostgrestQuery(apiEndpoint);
|
||||
logPostgrestQuery(fullEndpoint, undefined, 'PATCH');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
fullEndpoint,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
@@ -350,7 +536,11 @@ export async function postgrestPut<T, D = Record<string, unknown>>(endpoint: str
|
||||
throw new Error(response.error);
|
||||
}
|
||||
|
||||
return { data: response.data as T };
|
||||
if (!response.data) {
|
||||
throw new Error('更新成功但未返回数据');
|
||||
}
|
||||
|
||||
return { data: response.data };
|
||||
} catch (error) {
|
||||
const apiError = handleApiError(error);
|
||||
return { error: apiError.message, status: apiError.status };
|
||||
@@ -383,7 +573,7 @@ export async function postgrestDelete<T>(endpoint: string, params?: PostgrestPar
|
||||
}
|
||||
|
||||
// 打印查询信息
|
||||
logPostgrestQuery(apiEndpoint, queryParams);
|
||||
logPostgrestQuery(apiEndpoint, queryParams, 'DELETE');
|
||||
|
||||
const response = await apiRequest<T>(
|
||||
apiEndpoint,
|
||||
|
||||
Reference in New Issue
Block a user