All files / routes/admin/pros team.routes.ts

100% Statements 72/72
100% Branches 20/20
100% Functions 9/9
100% Lines 68/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221                                            1x     1x 3x 3x 3x     3x     4x 2x     3x     2x 4x 4x                             2x   1x         1x 5x 5x 5x   5x         5x 1x     4x 1x       3x 3x 1x       2x       2x 1x             1x               1x 1x   1x                               1x         1x 5x 5x 5x 5x   5x       5x 1x       4x 3x   3x 1x       2x 2x               2x 2x   2x   2x                           2x         1x 4x 4x 4x 4x     4x     3x   3x 3x 1x       2x 1x 1x     2x   1x          
// Team-membership endpoints for /api/admin/pros/:id/team.
// Split out of admin/pros.routes.ts to keep that file under the 500-LOC ceiling.
 
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import { PRO_ROLES } from "../../../db/schema";
import { createDualCache } from "../../../lib/cache";
import { NotFoundError, ValidationError } from "../../../lib/errors";
import { handleError, success } from "../../../lib/response";
import { invalidateUserRoles } from "../../../lib/role-cache";
import type { Services } from "../../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const team = new Hono<Env>();
 
// Get team members for a pro
team.get("/:id/team", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.req.param("id");
 
		// Get all roles for this pro
		const roles = await dal.userTenantRoles.findByProId(proId);
 
		// Batch fetch all users in a single query
		const userIds = roles.map((r) => r.userId);
		const users = await dal.users.findByIds(userIds);
 
		// Create lookup map for users
		const usersMap = new Map(users.map((u) => [u.id, u]));
 
		// Map roles to team members with user details
		const teamMembers = roles.map((role) => {
			const user = usersMap.get(role.userId);
			return {
				id: role.id,
				userId: role.userId,
				role: role.role,
				user: user
					? {
							id: user.id,
							name: user.name,
							email: user.email,
						}
					: null,
				dateCreated: role.dateCreated,
			};
		});
 
		return success(c, teamMembers);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Add team member to pro
team.post("/:id/team", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.req.param("id");
 
		const body = await c.req.json<{
			userId: string;
			role: "owner" | "manager" | "staff";
		}>();
 
		if (!body.userId) {
			return handleError(c, new ValidationError("User ID is required"));
		}
 
		if (!PRO_ROLES.includes(body.role)) {
			throw new ValidationError(`Invalid role: ${body.role}`);
		}
 
		// Check if user exists
		const user = await dal.users.findById(body.userId);
		if (!user) {
			return handleError(c, new NotFoundError("User not found"));
		}
 
		// Check if user already has a role for this pro
		const existingRole = await dal.userTenantRoles.findUserProRole(
			body.userId,
			proId,
		);
		if (existingRole) {
			return handleError(
				c,
				new ValidationError("User already has a role for this pro"),
			);
		}
 
		// Add the role
		const newRole = await dal.userTenantRoles.create({
			userId: body.userId,
			tenantType: "pro",
			tenantId: proId,
			role: body.role,
		});
 
		// Invalidate cached roles for the affected user
		const cache = createDualCache(c.env.KV_CACHE);
		await invalidateUserRoles(cache, body.userId);
 
		return success(
			c,
			{
				id: newRole.id,
				userId: user.id,
				role: newRole.role,
				user: {
					id: user.id,
					name: user.name,
					email: user.email,
				},
				dateCreated: newRole.dateCreated,
			},
			201,
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update team member role
team.put("/:id/team/:roleId", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.req.param("id");
		const roleId = parseInt(c.req.param("roleId"), 10);
 
		const body = await c.req.json<{
			role: "owner" | "manager" | "staff";
		}>();
 
		if (!PRO_ROLES.includes(body.role)) {
			throw new ValidationError(`Invalid role: ${body.role}`);
		}
 
		// Get the existing role
		const roles = await dal.userTenantRoles.findByProId(proId);
		const existingRole = roles.find((r) => r.id === roleId);
 
		if (!existingRole) {
			return handleError(c, new NotFoundError("Team member not found"));
		}
 
		// Delete and recreate with new role
		await dal.userTenantRoles.delete(roleId);
		const newRole = await dal.userTenantRoles.create({
			userId: existingRole.userId,
			tenantType: "pro",
			tenantId: proId,
			role: body.role,
		});
 
		// Invalidate cached roles for the affected user
		const cache = createDualCache(c.env.KV_CACHE);
		await invalidateUserRoles(cache, existingRole.userId);
 
		const user = await dal.users.findById(existingRole.userId);
 
		return success(c, {
			id: newRole.id,
			userId: existingRole.userId,
			role: newRole.role,
			user: user
				? {
						id: user.id,
						name: user.name,
						email: user.email,
					}
				: null,
			dateCreated: newRole.dateCreated,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Remove team member from pro
team.delete("/:id/team/:roleId", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.req.param("id");
		const roleId = parseInt(c.req.param("roleId"), 10);
 
		// Look up the role before deletion to get the userId for cache invalidation
		const roles = await dal.userTenantRoles.findByProId(proId, {
			includeInactive: true,
		});
		const roleToDelete = roles.find((r) => r.id === roleId);
 
		const deleted = await dal.userTenantRoles.delete(roleId);
		if (!deleted) {
			return handleError(c, new NotFoundError("Team member not found"));
		}
 
		// Invalidate cached roles for the affected user
		if (roleToDelete) {
			const cache = createDualCache(c.env.KV_CACHE);
			await invalidateUserRoles(cache, roleToDelete.userId);
		}
 
		return success(c, { message: "Team member removed successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default team;