|
| 1 | +'use server'; |
| 2 | + |
| 3 | +import { apiHandler } from "@/lib/apiHandler"; |
| 4 | +import { serviceErrorResponse } from "@/lib/serviceError"; |
| 5 | +import { isServiceError } from "@/lib/utils"; |
| 6 | +import { withAuthV2 } from "@/withAuthV2"; |
| 7 | +import { getEntitlements } from "@sourcebot/shared"; |
| 8 | +import { AccountPermissionSyncJobStatus } from "@sourcebot/db"; |
| 9 | +import { StatusCodes } from "http-status-codes"; |
| 10 | +import { ErrorCode } from "@/lib/errorCodes"; |
| 11 | + |
| 12 | +export interface PermissionSyncStatusResponse { |
| 13 | + hasPendingFirstSync: boolean; |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Returns whether a user has a account that has it's permissions |
| 18 | + * synced for the first time. |
| 19 | + */ |
| 20 | +export const GET = apiHandler(async () => { |
| 21 | + const entitlements = getEntitlements(); |
| 22 | + if (!entitlements.includes('permission-syncing')) { |
| 23 | + return serviceErrorResponse({ |
| 24 | + statusCode: StatusCodes.FORBIDDEN, |
| 25 | + errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS, |
| 26 | + message: "Permission syncing is not enabled for your license", |
| 27 | + }); |
| 28 | + } |
| 29 | + |
| 30 | + const result = await withAuthV2(async ({ prisma, user }) => { |
| 31 | + const accounts = await prisma.account.findMany({ |
| 32 | + where: { |
| 33 | + userId: user.id, |
| 34 | + provider: { in: ['github', 'gitlab'] } |
| 35 | + }, |
| 36 | + include: { |
| 37 | + permissionSyncJobs: { |
| 38 | + orderBy: { createdAt: 'desc' }, |
| 39 | + take: 1, |
| 40 | + } |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + const activeStatuses: AccountPermissionSyncJobStatus[] = [ |
| 45 | + AccountPermissionSyncJobStatus.PENDING, |
| 46 | + AccountPermissionSyncJobStatus.IN_PROGRESS |
| 47 | + ]; |
| 48 | + |
| 49 | + const hasPendingFirstSync = accounts.some(account => |
| 50 | + account.permissionSyncedAt === null && |
| 51 | + account.permissionSyncJobs.length > 0 && |
| 52 | + activeStatuses.includes(account.permissionSyncJobs[0].status) |
| 53 | + ); |
| 54 | + |
| 55 | + return { hasPendingFirstSync } satisfies PermissionSyncStatusResponse; |
| 56 | + }); |
| 57 | + |
| 58 | + if (isServiceError(result)) { |
| 59 | + return serviceErrorResponse(result); |
| 60 | + } |
| 61 | + |
| 62 | + return Response.json(result, { status: StatusCodes.OK }); |
| 63 | +}); |
0 commit comments