Skip to content

Commit

Permalink
fix: edge case of portal user existing before employee record
Browse files Browse the repository at this point in the history
  • Loading branch information
carhartlewis committed Feb 19, 2025
1 parent 2f29525 commit 4588407
Showing 1 changed file with 61 additions and 14 deletions.
75 changes: 61 additions & 14 deletions apps/app/src/actions/people/create-employee-action.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use server";

import { db } from "@bubba/db";
import { type Employee, db } from "@bubba/db";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { authActionClient } from "../safe-action";
import { createEmployeeSchema } from "../schema";
Expand Down Expand Up @@ -46,20 +46,56 @@ export const createEmployeeAction = authActionClient
}

try {
// Create the employee
const employee = await db.employee.create({
data: {
name,
email,
department,
organizationId: user.organizationId,
isActive: true,
externalEmployeeId,
// First check if an employee exists (active or inactive)
const existingEmployee = await db.employee.findUnique({
where: {
email_organizationId: {
email,
organizationId: user.organizationId,
},
},
});

const portalUser = await db.portalUser.create({
data: {
let employee: Employee;

if (existingEmployee) {
if (existingEmployee.isActive) {
return {
success: false,
error:
"An employee with this email already exists in your organization",
};
}

// Reactivate the existing employee
employee = await db.employee.update({
where: { id: existingEmployee.id },
data: {
name,
department,
isActive: true,
externalEmployeeId,
organizationId: user.organizationId,
updatedAt: new Date(),
},
});
} else {
employee = await db.employee.create({
data: {
name,
email,
department,
organizationId: user.organizationId,
isActive: true,
externalEmployeeId,
},
});
}

// Update or create portalUser
const portalUser = await db.portalUser.upsert({
where: { email },
create: {
id: employee.id,
name,
email,
Expand All @@ -73,6 +109,17 @@ export const createEmployeeAction = authActionClient
},
},
},
update: {
updatedAt: new Date(),
name,
email,
organizationId: user.organizationId,
employees: {
connect: {
id: employee.id,
},
},
},
});

// Create or get the required task definitions first and store their IDs
Expand All @@ -87,7 +134,7 @@ export const createEmployeeAction = authActionClient
},
update: {},
});
})
}),
);

// Now create the employee tasks using the actual task IDs
Expand All @@ -100,7 +147,7 @@ export const createEmployeeAction = authActionClient
status: "assigned",
},
});
})
}),
);

return {
Expand Down

0 comments on commit 4588407

Please sign in to comment.