Files
ok_r/app/api/krs/route.ts
2026-01-25 21:55:29 +08:00

115 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const dynamic = 'force-dynamic';
import { NextRequest, NextResponse } from 'next/server';
import { supabase } from '@/lib/supabase';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const projectId = searchParams.get('project_id');
const objectiveId = searchParams.get('objective_id');
const ownerUserId = searchParams.get('owner_user_id');
const status = searchParams.get('status');
let query = supabase
.from('krs')
.select(`
*,
owner:users!krs_owner_user_id_fkey(id, name, role, avatar_url),
project:projects(id, name, status)
`)
.order('period_start', { ascending: false });
if (projectId) query = query.eq('project_id', projectId);
if (objectiveId) query = query.eq('objective_id', objectiveId);
if (ownerUserId) query = query.eq('owner_user_id', ownerUserId);
if (status) query = query.eq('status', status);
const { data, error } = await query;
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json(data);
}
export async function POST(request: NextRequest) {
const body = await request.json();
const {
project_id,
objective_id,
period_type,
period_name,
period_start,
period_end,
title,
metric_name,
unit,
direction,
target_value,
owner_user_id,
confidence,
note,
} = body;
if (!project_id || !title || !metric_name || !unit || !target_value || !period_start || !period_end) {
return NextResponse.json(
{ error: '项目ID、标题、指标名称、单位、目标值、开始和结束日期为必填项' },
{ status: 400 }
);
}
if (target_value <= 0) {
return NextResponse.json({ error: '目标值必须大于0' }, { status: 400 });
}
if (new Date(period_end) < new Date(period_start)) {
return NextResponse.json({ error: '结束日期不能早于开始日期' }, { status: 400 });
}
if (owner_user_id) {
const { data: existingKRs } = await supabase
.from('krs')
.select('id')
.eq('owner_user_id', owner_user_id)
.eq('period_start', period_start)
.eq('period_end', period_end);
if (existingKRs && existingKRs.length >= 3) {
return NextResponse.json(
{ error: '该用户在此周期内已有3个KR,无法继续创建' },
{ status: 400 }
);
}
}
const { data, error } = await supabase
.from('krs')
.insert({
project_id,
objective_id,
period_type: period_type || 'custom',
period_name,
period_start,
period_end,
title,
metric_name,
unit,
direction: direction || 'increase',
target_value,
current_value: 0,
owner_user_id,
confidence: confidence || 80,
status: 'green',
note,
})
.select()
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json(data, { status: 201 });
}