102 lines
2.9 KiB
TypeScript
102 lines
2.9 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
import { prisma } from "@/lib/prisma"
|
|
import type { Transaction } from "@/lib/types"
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const transactions: Transaction[] = await request.json()
|
|
|
|
// Filter out duplicates based on fitId
|
|
const existingTransactions = await prisma.transaction.findMany({
|
|
where: {
|
|
accountId: { in: transactions.map((t) => t.accountId) },
|
|
fitId: { in: transactions.map((t) => t.fitId) },
|
|
},
|
|
select: {
|
|
accountId: true,
|
|
fitId: true,
|
|
},
|
|
})
|
|
|
|
const existingSet = new Set(
|
|
existingTransactions.map((t) => `${t.accountId}-${t.fitId}`),
|
|
)
|
|
|
|
const newTransactions = transactions.filter(
|
|
(t) => !existingSet.has(`${t.accountId}-${t.fitId}`),
|
|
)
|
|
|
|
if (newTransactions.length === 0) {
|
|
return NextResponse.json({ count: 0, transactions: [] })
|
|
}
|
|
|
|
const created = await prisma.transaction.createMany({
|
|
data: newTransactions.map((t) => ({
|
|
accountId: t.accountId,
|
|
date: t.date,
|
|
amount: t.amount,
|
|
description: t.description,
|
|
type: t.type,
|
|
categoryId: t.categoryId,
|
|
isReconciled: t.isReconciled,
|
|
fitId: t.fitId,
|
|
memo: t.memo,
|
|
checkNum: t.checkNum,
|
|
})),
|
|
})
|
|
|
|
return NextResponse.json({ count: created.count, transactions: newTransactions })
|
|
} catch (error) {
|
|
console.error("Error creating transactions:", error)
|
|
return NextResponse.json({ error: "Failed to create transactions" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function PUT(request: Request) {
|
|
try {
|
|
const transaction: Transaction = await request.json()
|
|
|
|
const updated = await prisma.transaction.update({
|
|
where: { id: transaction.id },
|
|
data: {
|
|
accountId: transaction.accountId,
|
|
date: transaction.date,
|
|
amount: transaction.amount,
|
|
description: transaction.description,
|
|
type: transaction.type,
|
|
categoryId: transaction.categoryId,
|
|
isReconciled: transaction.isReconciled,
|
|
fitId: transaction.fitId,
|
|
memo: transaction.memo,
|
|
checkNum: transaction.checkNum,
|
|
},
|
|
})
|
|
|
|
return NextResponse.json(updated)
|
|
} catch (error) {
|
|
console.error("Error updating transaction:", error)
|
|
return NextResponse.json({ error: "Failed to update transaction" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: Request) {
|
|
try {
|
|
const { searchParams } = new URL(request.url)
|
|
const id = searchParams.get("id")
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ error: "Transaction ID is required" }, { status: 400 })
|
|
}
|
|
|
|
await prisma.transaction.delete({
|
|
where: { id },
|
|
})
|
|
|
|
return NextResponse.json({ success: true })
|
|
} catch (error) {
|
|
console.error("Error deleting transaction:", error)
|
|
return NextResponse.json({ error: "Failed to delete transaction" }, { status: 500 })
|
|
}
|
|
}
|
|
|