tasko/actions/copy-list/index.ts

83 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-02-16 01:49:19 +00:00
'use server';
2024-02-15 02:30:10 +00:00
2024-03-21 21:15:27 +00:00
import { auth } from '@clerk/nextjs/server';
2024-02-16 01:49:19 +00:00
import { revalidatePath } from 'next/cache';
import { ACTION, ENTITY_TYPE } from '@prisma/client';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { db } from '@/lib/db';
import { createAuditLog } from '@/lib/create-audit-log';
import { createSafeAction } from '@/lib/create-safe-action';
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
import { InputType, ReturnType } from './types';
import { CopyList } from './schema';
2024-02-15 02:30:10 +00:00
const handler = async (data: InputType): Promise<ReturnType> => {
const { userId, orgId } = await auth();
2024-02-15 02:30:10 +00:00
2024-02-16 01:49:19 +00:00
if (!userId || !orgId) return { error: 'Unauthorized' };
2024-02-15 02:30:10 +00:00
const { id, boardId } = data;
let list;
try {
const listToCopy = await db.list.findUnique({
where: {
id,
boardId,
board: {
orgId,
},
},
include: {
cards: true,
},
});
2024-02-16 01:49:19 +00:00
if (!listToCopy) return { error: 'List not found' };
2024-02-15 02:30:10 +00:00
const lastList = await db.list.findFirst({
where: { boardId },
2024-02-16 01:49:19 +00:00
orderBy: { order: 'desc' },
2024-02-15 02:30:10 +00:00
select: { order: true },
});
const newOrder = lastList ? lastList.order + 1 : 1;
list = await db.list.create({
data: {
boardId: listToCopy.boardId,
title: `${listToCopy.title} - Copy`,
order: newOrder,
cards: {
createMany: {
data: listToCopy.cards.map((card) => ({
title: card.title,
description: card.description,
order: card.order,
})),
},
},
},
include: {
cards: true,
},
});
await createAuditLog({
entityTitle: list.title,
entityType: ENTITY_TYPE.LIST,
entityId: list.id,
action: ACTION.CREATE,
});
} catch (error) {
return {
2024-02-16 01:49:19 +00:00
error: 'Failed to copy list',
2024-02-15 02:30:10 +00:00
};
}
revalidatePath(`/board/${boardId}`);
return { data: list };
};
export const copyList = createSafeAction(CopyList, handler);