first commit
This commit is contained in:
46
src/app/api/bills/route.ts
Normal file
46
src/app/api/bills/route.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { requireUser } from "@/lib/auth";
|
||||
import {
|
||||
createDocument,
|
||||
databaseConfig,
|
||||
listDocuments,
|
||||
query,
|
||||
updateDocument,
|
||||
} from "@/lib/database/server";
|
||||
import { syncBillLedger } from "@/lib/finance/ledger";
|
||||
import { parseBillInput } from "@/lib/validation/bills";
|
||||
import { nowFields, parseBody } from "@/lib/validation/common";
|
||||
import type { Bill } from "@/types/finance";
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireUser();
|
||||
if ("response" in auth) return auth.response;
|
||||
const { collections } = databaseConfig();
|
||||
const result = await listDocuments<Bill>(collections.bills, [
|
||||
query.equal("userId", auth.user.id),
|
||||
query.orderAsc("dueDate"),
|
||||
query.limit(5000),
|
||||
]);
|
||||
return Response.json(result.documents);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireUser();
|
||||
if ("response" in auth) return auth.response;
|
||||
const parsed = await parseBody(request, parseBillInput);
|
||||
if (!parsed.ok)
|
||||
return Response.json({ error: parsed.error }, { status: 400 });
|
||||
const { collections } = databaseConfig();
|
||||
let bill = await createDocument<Bill>(collections.bills, {
|
||||
...parsed.data,
|
||||
userId: auth.user.id,
|
||||
...nowFields(),
|
||||
});
|
||||
const ledger = await syncBillLedger(bill);
|
||||
if (ledger && bill.linkedPaymentId !== ledger.$id) {
|
||||
bill = await updateDocument<Bill>(collections.bills, bill.$id, {
|
||||
linkedPaymentId: ledger.$id,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
return Response.json(bill, { status: 201 });
|
||||
}
|
||||
Reference in New Issue
Block a user