mirror of
https://github.com/simstudioai/sim.git
synced 2026-04-06 03:00:16 -04:00
157 lines
5.2 KiB
TypeScript
157 lines
5.2 KiB
TypeScript
import { db } from '@sim/db'
|
|
import { account } from '@sim/db/schema'
|
|
import { createLogger } from '@sim/logger'
|
|
import { eq } from 'drizzle-orm'
|
|
import { type NextRequest, NextResponse } from 'next/server'
|
|
import { getSession } from '@/lib/auth'
|
|
import { validateEnum, validatePathSegment } from '@/lib/core/security/input-validation'
|
|
import { generateRequestId } from '@/lib/core/utils/request'
|
|
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
const logger = createLogger('WealthboxItemAPI')
|
|
|
|
/**
|
|
* Get a single item (note, contact, task) from Wealthbox
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
const requestId = generateRequestId()
|
|
|
|
try {
|
|
// Get the session
|
|
const session = await getSession()
|
|
|
|
// Check if the user is authenticated
|
|
if (!session?.user?.id) {
|
|
logger.warn(`[${requestId}] Unauthenticated request rejected`)
|
|
return NextResponse.json({ error: 'User not authenticated' }, { status: 401 })
|
|
}
|
|
|
|
// Get parameters from query
|
|
const { searchParams } = new URL(request.url)
|
|
const credentialId = searchParams.get('credentialId')
|
|
const itemId = searchParams.get('itemId')
|
|
const type = searchParams.get('type') || 'contact'
|
|
|
|
if (!credentialId || !itemId) {
|
|
logger.warn(`[${requestId}] Missing required parameters`, { credentialId, itemId })
|
|
return NextResponse.json({ error: 'Credential ID and Item ID are required' }, { status: 400 })
|
|
}
|
|
|
|
const typeValidation = validateEnum(type, ['contact'] as const, 'type')
|
|
if (!typeValidation.isValid) {
|
|
logger.warn(`[${requestId}] Invalid item type: ${typeValidation.error}`)
|
|
return NextResponse.json({ error: typeValidation.error }, { status: 400 })
|
|
}
|
|
|
|
const itemIdValidation = validatePathSegment(itemId, {
|
|
paramName: 'itemId',
|
|
maxLength: 100,
|
|
allowHyphens: true,
|
|
allowUnderscores: true,
|
|
allowDots: false,
|
|
})
|
|
if (!itemIdValidation.isValid) {
|
|
logger.warn(`[${requestId}] Invalid item ID: ${itemIdValidation.error}`)
|
|
return NextResponse.json({ error: itemIdValidation.error }, { status: 400 })
|
|
}
|
|
|
|
const credentials = await db.select().from(account).where(eq(account.id, credentialId)).limit(1)
|
|
|
|
if (!credentials.length) {
|
|
logger.warn(`[${requestId}] Credential not found`, { credentialId })
|
|
return NextResponse.json({ error: 'Credential not found' }, { status: 404 })
|
|
}
|
|
|
|
const credential = credentials[0]
|
|
|
|
if (credential.userId !== session.user.id) {
|
|
logger.warn(`[${requestId}] Unauthorized credential access attempt`, {
|
|
credentialUserId: credential.userId,
|
|
requestUserId: session.user.id,
|
|
})
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
|
|
}
|
|
|
|
const accessToken = await refreshAccessTokenIfNeeded(credentialId, session.user.id, requestId)
|
|
|
|
if (!accessToken) {
|
|
logger.error(`[${requestId}] Failed to obtain valid access token`)
|
|
return NextResponse.json({ error: 'Failed to obtain valid access token' }, { status: 401 })
|
|
}
|
|
|
|
const endpoints = {
|
|
contact: 'contacts',
|
|
}
|
|
const endpoint = endpoints[type as keyof typeof endpoints]
|
|
|
|
logger.info(`[${requestId}] Fetching ${type} ${itemId} from Wealthbox`)
|
|
|
|
const response = await fetch(`https://api.crmworkspace.com/v1/${endpoint}/${itemId}`, {
|
|
headers: {
|
|
Authorization: `Bearer ${accessToken}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text()
|
|
logger.error(
|
|
`[${requestId}] Wealthbox API error: ${response.status} ${response.statusText}`,
|
|
{
|
|
error: errorText,
|
|
endpoint,
|
|
itemId,
|
|
}
|
|
)
|
|
|
|
if (response.status === 404) {
|
|
return NextResponse.json({ error: 'Item not found' }, { status: 404 })
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{ error: `Failed to fetch ${type} from Wealthbox` },
|
|
{ status: response.status }
|
|
)
|
|
}
|
|
|
|
const data = await response.json()
|
|
|
|
logger.info(`[${requestId}] Wealthbox API response structure`, {
|
|
type,
|
|
dataKeys: Object.keys(data || {}),
|
|
hasContacts: !!data.contacts,
|
|
totalCount: data.meta?.total_count,
|
|
})
|
|
|
|
let items: any[] = []
|
|
|
|
if (type === 'contact') {
|
|
if (data?.id) {
|
|
const item = {
|
|
id: data.id?.toString() || '',
|
|
name: `${data.first_name || ''} ${data.last_name || ''}`.trim() || `Contact ${data.id}`,
|
|
type: 'contact',
|
|
content: data.background_info || '',
|
|
createdAt: data.created_at,
|
|
updatedAt: data.updated_at,
|
|
}
|
|
items = [item]
|
|
} else {
|
|
logger.warn(`[${requestId}] Unexpected contact response format`, { data })
|
|
items = []
|
|
}
|
|
}
|
|
|
|
logger.info(
|
|
`[${requestId}] Successfully fetched ${items.length} ${type}s from Wealthbox (total: ${data.meta?.total_count || 'unknown'})`
|
|
)
|
|
|
|
return NextResponse.json({ item: items[0] }, { status: 200 })
|
|
} catch (error) {
|
|
logger.error(`[${requestId}] Error fetching Wealthbox item`, error)
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
|
}
|
|
}
|