export const inviteUserHandler = async (c) => {
const { id: invitedBy } = c.user;
const now = Date.now().valueOf();
const values = { ...c.body, status: 'Invited', invitedBy, createdAt: now, updatedAt: now };
await db.transaction(async (tx) => {
try {
const existingUser = await tx.query.Users.findFirst({
where: eq(Users.email, c.body.email),
});
let dbUserId = null;
if (existingUser) {
if (!['Active', 'Blocked'].includes(existingUser.status)) {
await tx.update(Users).set(values).where(eq(Users.id, existingUser.id)).returning();
dbUserId = existingUser.id;
} else {
return c.text('USER ALREADY ACTIVE ON THE PLATFORM', 400);
}
} else {
const newUser = { ...c.body, status: 'Invited', invitedBy, createdAt: now, updatedAt: now };
await tx.insert(Users).values(values);
const dbUser = await tx.query.Users.findFirst({
where: eq(Users.email, c.body.email),
with: { company: true, inviter: true },
});
await sendInvite(dbUser);
}
return c.json({ ok: true });
} catch (ex) {
console.log(ex);
return c.text('Error inviting user', 501);
}
});
};
export const inviteUserHandler = async (c) => {
const { id: invitedBy } = c.user;
const now = Date.now().valueOf();
const values = { ...c.body, status: 'Invited', invitedBy, createdAt: now, updatedAt: now };
await db.transaction(async (tx) => {
try {
const existingUser = await tx.query.Users.findFirst({
where: eq(Users.email, c.body.email),
});
let dbUserId = null;
if (existingUser) {
if (!['Active', 'Blocked'].includes(existingUser.status)) {
await tx.update(Users).set(values).where(eq(Users.id, existingUser.id)).returning();
dbUserId = existingUser.id;
} else {
return c.text('USER ALREADY ACTIVE ON THE PLATFORM', 400);
}
} else {
const newUser = { ...c.body, status: 'Invited', invitedBy, createdAt: now, updatedAt: now };
await tx.insert(Users).values(values);
const dbUser = await tx.query.Users.findFirst({
where: eq(Users.email, c.body.email),
with: { company: true, inviter: true },
});
await sendInvite(dbUser);
}
return c.json({ ok: true });
} catch (ex) {
console.log(ex);
return c.text('Error inviting user', 501);
}
});
};