Kundenportal arbeiten
This commit is contained in:
@@ -4,6 +4,7 @@ import { and, eq, inArray, isNull } from "drizzle-orm";
|
||||
import {
|
||||
authTenantUsers,
|
||||
authProfiles,
|
||||
customers,
|
||||
authRoles,
|
||||
authUserRoles,
|
||||
authUsers,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
tenants,
|
||||
} from "../../db/schema";
|
||||
import { generateRandomPassword, hashPassword } from "../utils/password";
|
||||
import { sendMail } from "../utils/mailer";
|
||||
|
||||
export default async function adminRoutes(server: FastifyInstance) {
|
||||
const deriveNameFromEmail = (email: string) => {
|
||||
@@ -255,6 +257,33 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
return currentUser;
|
||||
};
|
||||
|
||||
const ensurePortalRoleForTenant = async (tenantId: number, createdBy: string) => {
|
||||
const existingRoles = await server.db
|
||||
.select({
|
||||
id: authRoles.id,
|
||||
name: authRoles.name,
|
||||
})
|
||||
.from(authRoles)
|
||||
.where(eq(authRoles.tenant_id, tenantId));
|
||||
|
||||
const portalRole = existingRoles.find((role) => role.name === "Kundenportal");
|
||||
if (portalRole) return portalRole.id;
|
||||
|
||||
const [createdRole] = await server.db
|
||||
.insert(authRoles)
|
||||
.values({
|
||||
name: "Kundenportal",
|
||||
description: "Automatisch angelegte Rolle für eingeladene Kundenportal-Benutzer",
|
||||
tenant_id: tenantId,
|
||||
created_by: createdBy,
|
||||
})
|
||||
.returning({
|
||||
id: authRoles.id,
|
||||
});
|
||||
|
||||
return createdRole.id;
|
||||
};
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// GET /admin/overview
|
||||
// -------------------------------------------------------------
|
||||
@@ -422,6 +451,233 @@ export default async function adminRoutes(server: FastifyInstance) {
|
||||
}
|
||||
});
|
||||
|
||||
server.post("/admin/customers/:customerId/invite-portal-user", async (req, reply) => {
|
||||
try {
|
||||
const currentUser = await requireAdmin(req, reply);
|
||||
if (!currentUser) return;
|
||||
|
||||
const tenantId = Number(req.user?.tenant_id);
|
||||
const { customerId } = req.params as { customerId: string };
|
||||
|
||||
if (!tenantId) {
|
||||
return reply.code(400).send({ error: "No tenant selected" });
|
||||
}
|
||||
|
||||
const [tenantRecord] = await server.db
|
||||
.select({
|
||||
id: tenants.id,
|
||||
name: tenants.name,
|
||||
portalDomain: tenants.portalDomain,
|
||||
})
|
||||
.from(tenants)
|
||||
.where(eq(tenants.id, tenantId))
|
||||
.limit(1);
|
||||
|
||||
const [customerRecord] = await server.db
|
||||
.select()
|
||||
.from(customers)
|
||||
.where(and(eq(customers.id, Number(customerId)), eq(customers.tenant, tenantId)))
|
||||
.limit(1);
|
||||
|
||||
if (!customerRecord) {
|
||||
return reply.code(404).send({ error: "Customer not found" });
|
||||
}
|
||||
|
||||
const customerInfo = customerRecord.infoData && typeof customerRecord.infoData === "object" ? customerRecord.infoData as Record<string, any> : {};
|
||||
const email = String(customerInfo.email || customerInfo.invoiceEmail || "").trim().toLowerCase();
|
||||
|
||||
if (!email) {
|
||||
return reply.code(400).send({ error: "Customer has no email address" });
|
||||
}
|
||||
|
||||
const generatedPassword = generateRandomPassword(14);
|
||||
const passwordHash = await hashPassword(generatedPassword);
|
||||
|
||||
const [existingUser] = await server.db
|
||||
.select({
|
||||
id: authUsers.id,
|
||||
email: authUsers.email,
|
||||
is_admin: authUsers.is_admin,
|
||||
})
|
||||
.from(authUsers)
|
||||
.where(eq(authUsers.email, email))
|
||||
.limit(1);
|
||||
|
||||
const derivedName = deriveNameFromEmail(email);
|
||||
const firstName = customerRecord.firstname?.trim() || derivedName.first_name;
|
||||
const lastName = customerRecord.lastname?.trim() || derivedName.last_name;
|
||||
|
||||
let userId = existingUser?.id || null;
|
||||
let createdNewUser = false;
|
||||
|
||||
if (existingUser) {
|
||||
const [existingProfile] = await server.db
|
||||
.select({
|
||||
id: authProfiles.id,
|
||||
customer_for_portal: authProfiles.customer_for_portal,
|
||||
})
|
||||
.from(authProfiles)
|
||||
.where(and(
|
||||
eq(authProfiles.user_id, existingUser.id),
|
||||
eq(authProfiles.tenant_id, tenantId)
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser.is_admin) {
|
||||
return reply.code(409).send({ error: "Email address is already used by an admin user" });
|
||||
}
|
||||
|
||||
if (!existingProfile) {
|
||||
return reply.code(409).send({ error: "Email address is already used by another user" });
|
||||
}
|
||||
|
||||
if (existingProfile.customer_for_portal && existingProfile.customer_for_portal !== customerRecord.id) {
|
||||
return reply.code(409).send({ error: "Email address is already assigned to another portal customer" });
|
||||
}
|
||||
|
||||
await server.db
|
||||
.update(authUsers)
|
||||
.set({
|
||||
passwordHash,
|
||||
must_change_password: true,
|
||||
multiTenant: false,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(authUsers.id, existingUser.id));
|
||||
|
||||
userId = existingUser.id;
|
||||
} else {
|
||||
const [createdUser] = await server.db
|
||||
.insert(authUsers)
|
||||
.values({
|
||||
email,
|
||||
passwordHash,
|
||||
is_admin: false,
|
||||
multiTenant: false,
|
||||
must_change_password: true,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning({
|
||||
id: authUsers.id,
|
||||
});
|
||||
|
||||
userId = createdUser.id;
|
||||
createdNewUser = true;
|
||||
}
|
||||
|
||||
const portalRoleId = await ensurePortalRoleForTenant(tenantId, currentUser.id);
|
||||
|
||||
const existingMemberships = await server.db
|
||||
.select()
|
||||
.from(authTenantUsers)
|
||||
.where(and(
|
||||
eq(authTenantUsers.user_id, userId!),
|
||||
eq(authTenantUsers.tenant_id, tenantId)
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (!existingMemberships.length) {
|
||||
await server.db
|
||||
.insert(authTenantUsers)
|
||||
.values({
|
||||
tenant_id: tenantId,
|
||||
user_id: userId!,
|
||||
created_by: currentUser.id,
|
||||
});
|
||||
}
|
||||
|
||||
const existingPortalRoleAssignment = await server.db
|
||||
.select()
|
||||
.from(authUserRoles)
|
||||
.where(and(
|
||||
eq(authUserRoles.user_id, userId!),
|
||||
eq(authUserRoles.tenant_id, tenantId),
|
||||
eq(authUserRoles.role_id, portalRoleId)
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (!existingPortalRoleAssignment.length) {
|
||||
await server.db
|
||||
.insert(authUserRoles)
|
||||
.values({
|
||||
user_id: userId!,
|
||||
tenant_id: tenantId,
|
||||
role_id: portalRoleId,
|
||||
created_by: currentUser.id,
|
||||
});
|
||||
}
|
||||
|
||||
const [existingTenantProfile] = await server.db
|
||||
.select({
|
||||
id: authProfiles.id,
|
||||
user_id: authProfiles.user_id,
|
||||
customer_for_portal: authProfiles.customer_for_portal,
|
||||
})
|
||||
.from(authProfiles)
|
||||
.where(and(
|
||||
eq(authProfiles.user_id, userId!),
|
||||
eq(authProfiles.tenant_id, tenantId)
|
||||
))
|
||||
.limit(1);
|
||||
|
||||
if (existingTenantProfile) {
|
||||
await server.db
|
||||
.update(authProfiles)
|
||||
.set({
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
email,
|
||||
customer_for_portal: customerRecord.id,
|
||||
active: true,
|
||||
})
|
||||
.where(eq(authProfiles.id, existingTenantProfile.id));
|
||||
} else {
|
||||
await server.db
|
||||
.insert(authProfiles)
|
||||
.values({
|
||||
user_id: userId!,
|
||||
tenant_id: tenantId,
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
email,
|
||||
customer_for_portal: customerRecord.id,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
|
||||
const portalUrl = tenantRecord?.portalDomain ? `https://${tenantRecord.portalDomain}/login` : null;
|
||||
|
||||
const mailResult = await sendMail(
|
||||
email,
|
||||
`FEDEO | Einladung ins Kundenportal`,
|
||||
`
|
||||
<p>Hallo${customerRecord.name ? ` ${customerRecord.name}` : ""},</p>
|
||||
<p>für Sie wurde ein Zugang zum FEDEO Kundenportal eingerichtet.</p>
|
||||
<p><strong>E-Mail:</strong> ${email}</p>
|
||||
<p><strong>Initialpasswort:</strong> ${generatedPassword}</p>
|
||||
<p>Bitte ändern Sie dieses Passwort direkt nach dem ersten Login.</p>
|
||||
${portalUrl ? `<p><strong>Login:</strong> <a href="${portalUrl}">${portalUrl}</a></p>` : ""}
|
||||
<p>Viele Grüße<br>${tenantRecord?.name || "FEDEO"}</p>
|
||||
`
|
||||
);
|
||||
|
||||
if (!mailResult.success) {
|
||||
return reply.code(500).send({ error: "Invitation email could not be sent" });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
createdNewUser,
|
||||
email,
|
||||
initialPassword: generatedPassword,
|
||||
portalUrl,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("ERROR /admin/customers/:customerId/invite-portal-user:", err);
|
||||
return reply.code(500).send({ error: "Internal Server Error" });
|
||||
}
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// POST /admin/tenants
|
||||
// -------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user