diff --git a/src/lib/actions/paymentCreateUpdate.ts b/src/lib/actions/paymentCreateUpdate.ts new file mode 100644 index 0000000..d49646d --- /dev/null +++ b/src/lib/actions/paymentCreateUpdate.ts @@ -0,0 +1,77 @@ +import { z } from 'zod'; +import { ActionResponse } from '@/lib/types/ActionResponse'; +import { prismaClient } from '@/prisma'; +import { getUser } from '@/auth'; +import { URL_SIGN_IN } from '@/lib/constants'; +import { paymentFormSchema } from '@/lib/form-schemas/paymentFormSchema'; + +export default async function paymentCreateUpdate({ + id, + amount, + date, + payorId, + payeeId, + categoryId, + note, +}: z.infer): Promise { + 'use server'; + + // check that user is logged in + const user = await getUser(); + if (!user) { + return { + type: 'error', + message: 'You must be logged in to create/update a payment.', + redirect: URL_SIGN_IN, + }; + } + + // create/update payment + try { + if (id) { + await prismaClient.payment.update({ + where: { + id: id, + }, + data: { + amount: amount, + date: date, + payorId: payorId, + payeeId: payeeId, + categoryId: categoryId, + note: note, + }, + }, + ); + + // return success + return { + type: 'success', + message: `Payment updated`, + }; + } else { + await prismaClient.payment.create({ + data: { + userId: user.id, + amount: amount, + date: date, + payorId: payorId, + payeeId: payeeId, + categoryId: categoryId, + note: note, + }, + }); + + // return success + return { + type: 'success', + message: `Payment created`, + }; + } + } catch (e) { + return { + type: 'error', + message: 'Failed creating/updating payment', + }; + } +} diff --git a/src/lib/actions/paymentDelete.ts b/src/lib/actions/paymentDelete.ts new file mode 100644 index 0000000..46ee086 --- /dev/null +++ b/src/lib/actions/paymentDelete.ts @@ -0,0 +1,62 @@ +import { ActionResponse } from '@/lib/types/ActionResponse'; +import { prismaClient } from '@/prisma'; +import { getUser } from '@/auth'; +import { URL_SIGN_IN } from '@/lib/constants'; + +export default async function paymentDelete(id: number): Promise { + 'use server'; + + // check that id is a number + if (!id || isNaN(id)) { + return { + type: 'error', + message: 'Invalid payment ID', + }; + } + + // check that user is logged in + const user = await getUser(); + if (!user) { + return { + type: 'error', + message: 'You must be logged in to delete a payment.', + redirect: URL_SIGN_IN, + }; + } + + // check that payment is associated with user + const payment = await prismaClient.payment.findFirst({ + where: { + id: id, + userId: user.id, + }, + }); + if (!payment) { + return { + type: 'error', + message: 'Payment not found', + }; + } + + // delete payment + try { + await prismaClient.payment.delete({ + where: { + id: payment.id, + userId: user.id, + }, + }, + ); + } catch (e) { + return { + type: 'error', + message: 'Failed deleting payment', + }; + } + + // return success + return { + type: 'success', + message: `Payment deleted`, + }; +}