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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | 2x 2x 10x 10x 240x 2x 2x 9x 9x 9x 9x 1x 8x 8x 9x 9x 9x 1x 7x 1x 6x 1x 5x 2x 2x 1x 1x 1x 3x 1x 2x 2x 1x 1x 2x 18x 18x 18x 18x 18x 1x 17x 17x 18x 18x 18x 1x 16x 1x 15x 1x 14x 1x 13x 11x 11x 1x 12x 2x 2x 1x 11x 11x 11x 11x 1x 10x 10x 10x 1x 9x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 9x 2x 5x 5x 5x 5x 1x 4x 4x 5x 5x 4x 2x 12x 12x 12x 12x 12x 12x 1x 11x 1x 10x 10x 2x 8x 1x 7x 7x 7x 7x 2x 5x 4x 4x 4x 4x 4x 4x 4x 4x 1x 5x 2x 4x 4x 4x 4x 4x 1x 3x 3x 2x 1x 1x | // Team Invitations - Send, list, resend, cancel invitations
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import { success, error } from "../../../lib/response";
import { requireProAccess } from "../../../middleware";
import { parseIndianPhone } from "@interioring/utils/validation/phone";
import { logger } from "../../../lib/logger";
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
proId: string;
proRole: string;
};
};
const invitations = new Hono<Env>();
// Helper to generate a cryptographically secure random token
function generateToken(): string {
const bytes = new Uint8Array(24);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
// All routes require pro access
invitations.use("/:proId/*", requireProAccess);
// Check if a contact (email or phone) can be invited
invitations.post("/:proId/team/check-contact", async (c) => {
const dal = c.get("dal");
const proId = c.req.param("proId");
const proRole = c.get("proRole");
if (proRole !== "owner") {
return error(c, "FORBIDDEN", "Only owners can invite team members", 403);
}
const body = await c.req.json<{ email?: string; phone?: string }>();
const email = body.email?.toLowerCase().trim();
const parsedPhone = body.phone ? parseIndianPhone(body.phone) : null;
const phone = parsedPhone?.e164;
if (!email && !body.phone) {
return error(c, "MISSING_CONTACT", "Email or phone is required", 400);
}
// Validate format
if (email && !EMAIL_REGEX.test(email)) {
return success(c, { available: false, reason: "invalid_email", message: "Invalid email format" });
}
if (body.phone && (!parsedPhone || parsedPhone.type !== "mobile")) {
return success(c, { available: false, reason: "invalid_phone", message: "Enter a valid 10-digit Indian mobile number" });
}
// Check existing user
if (email) {
const existingUser = await dal.users.findByEmail(email);
if (existingUser) {
return success(c, { available: false, reason: "user_exists", message: "This email is already registered" });
}
const pendingInvite = await dal.teamInvitations.findPendingByEmail(email, proId);
/* v8 ignore start -- defensive guard */
if (pendingInvite) {
/* v8 ignore stop */
return success(c, { available: false, reason: "invitation_pending", message: "An invitation is already pending for this email" });
}
}
/* v8 ignore start -- defensive guard: phone check path not covered */
if (phone) {
/* v8 ignore stop */
const existingUser = await dal.users.findByPhoneNumber(phone);
/* v8 ignore start -- defensive guard */
if (existingUser) {
/* v8 ignore stop */
return success(c, { available: false, reason: "user_exists", message: "This phone number is already registered" });
}
const pendingInvite = await dal.teamInvitations.findPendingByPhone(phone, proId);
if (pendingInvite) {
return success(c, { available: false, reason: "invitation_pending", message: "An invitation is already pending for this phone number" });
}
}
return success(c, { available: true });
});
// Send a team invitation
invitations.post("/:proId/team/invite", async (c) => {
const dal = c.get("dal");
const proId = c.req.param("proId");
const proRole = c.get("proRole");
const currentUser = c.get("user");
// Only owners can invite team members
if (proRole !== "owner") {
return error(c, "FORBIDDEN", "Only owners can invite team members", 403);
}
const body = await c.req.json<{
email?: string;
phone?: string;
role: "owner" | "manager" | "staff";
}>();
const email = body.email?.toLowerCase().trim() || null;
const parsedInvitePhone = body.phone ? parseIndianPhone(body.phone) : null;
const phone = parsedInvitePhone?.e164 ?? null;
if (!email && !body.phone) {
return error(c, "MISSING_CONTACT", "Email or phone number is required", 400);
}
// Validate format
if (email && !EMAIL_REGEX.test(email)) {
return error(c, "INVALID_EMAIL", "Invalid email format", 400);
}
if (body.phone && (!parsedInvitePhone || parsedInvitePhone.type !== "mobile")) {
return error(c, "INVALID_PHONE", "Enter a valid 10-digit Indian mobile number", 400);
}
if (!["owner", "manager", "staff"].includes(body.role)) {
return error(c, "INVALID_ROLE", "Role must be owner, manager, or staff", 400);
}
// Block inviting already-registered contacts
if (email) {
const existingUser = await dal.users.findByEmail(email);
if (existingUser) {
return error(
c,
"USER_ALREADY_EXISTS",
"This email is already registered. Each email can only be associated with one account.",
400,
);
}
}
if (phone) {
const existingUser = await dal.users.findByPhoneNumber(phone);
if (existingUser) {
return error(
c,
"USER_ALREADY_EXISTS",
"This phone number is already registered.",
400,
);
}
}
// Delete any existing pending invitations for this contact (across all pros)
if (email) await dal.teamInvitations.deletePendingByEmail(email);
if (phone) await dal.teamInvitations.deletePendingByPhone(phone);
// Get pro details for the email
const pro = await dal.pros.findById(proId);
if (!pro) {
return error(c, "NOT_FOUND", "Pro not found", 404);
}
// Create the invitation
const token = generateToken();
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
if (!currentUser) {
return error(c, "UNAUTHORIZED", "User not authenticated", 401);
}
const invitation = await dal.teamInvitations.create({
proId,
email,
phone,
role: body.role,
token,
invitedBy: currentUser.id,
expiresAt,
});
// Send the invitation email (only if email provided)
let emailSent = true;
if (email) {
const portalOrigin =
c.env.PORTAL_URL ||
c.env.ALLOWED_ORIGINS?.split(",")[0]?.trim() ||
"http://localhost:7002";
const invitationLink = `${portalOrigin}/accept-invitation?token=${token}`;
try {
const { CommunicationGateway } = await import(
"../../../lib/communication/gateway"
);
const { TeamInvitationHandler } = await import(
"../../../lib/communication/handlers/team-invitation.handler"
);
const gateway = new CommunicationGateway(dal, c.env);
const invitationHandler = new TeamInvitationHandler(gateway);
await invitationHandler.handle({
recipientEmail: email,
invitationLink,
proName: pro.businessName,
inviterName: currentUser.name,
role: body.role,
expiresInDays: 7,
});
} catch (err) {
logger.error("[TEAM] Failed to send invitation email:", err);
emailSent = false;
}
}
return success(
c,
{
id: invitation.id,
email: invitation.email,
phone: invitation.phone,
role: invitation.role,
expiresAt: invitation.expiresAt,
dateCreated: invitation.dateCreated,
emailSent,
},
201,
);
});
// List pending invitations
invitations.get("/:proId/team/invitations", async (c) => {
const dal = c.get("dal");
const proId = c.req.param("proId");
const proRole = c.get("proRole");
// Only owners and managers can view invitations
if (!["owner", "manager"].includes(proRole)) {
return error(
c,
"FORBIDDEN",
"Only owners and managers can view invitations",
403,
);
}
const pendingInvitations =
await dal.teamInvitations.findPendingByProId(proId);
// Get inviter details
const result = await Promise.all(
pendingInvitations.map(async (inv) => {
const inviter = await dal.users.findById(inv.invitedBy);
return {
id: inv.id,
email: inv.email,
phone: inv.phone,
role: inv.role,
invitedBy: inviter
? { id: inviter.id, name: inviter.name, email: inviter.email }
: null,
expiresAt: inv.expiresAt,
dateCreated: inv.dateCreated,
};
}),
);
return success(c, result);
});
// Resend an invitation
invitations.post(
"/:proId/team/invitations/:invitationId/resend",
async (c) => {
const dal = c.get("dal");
const proId = c.req.param("proId");
const invitationId = parseInt(c.req.param("invitationId"), 10);
const proRole = c.get("proRole");
const currentUser = c.get("user");
if (!currentUser) {
return error(c, "UNAUTHORIZED", "User not authenticated", 401);
}
// Only owners can resend invitations
if (proRole !== "owner") {
return error(c, "FORBIDDEN", "Only owners can resend invitations", 403);
}
const invitation = await dal.teamInvitations.findById(invitationId);
if (!invitation || invitation.proId !== proId) {
return error(c, "NOT_FOUND", "Invitation not found", 404);
}
if (invitation.acceptedAt) {
return error(
c,
"ALREADY_ACCEPTED",
"Invitation has already been accepted",
400,
);
}
// Update expiry to 7 more days
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
await dal.teamInvitations.updateExpiry(invitationId, expiresAt);
// Get pro details for the email
const pro = await dal.pros.findById(proId);
if (!pro) {
return error(c, "NOT_FOUND", "Pro not found", 404);
}
// Resend the invitation email (only if email-based)
if (invitation.email) {
const portalOrigin =
c.env.PORTAL_URL ||
c.env.ALLOWED_ORIGINS?.split(",")[0]?.trim() ||
"http://localhost:7002";
const invitationLink = `${portalOrigin}/accept-invitation?token=${invitation.token}`;
try {
const { CommunicationGateway } = await import(
"../../../lib/communication/gateway"
);
const { TeamInvitationHandler } = await import(
"../../../lib/communication/handlers/team-invitation.handler"
);
const gateway = new CommunicationGateway(dal, c.env);
const invitationHandler = new TeamInvitationHandler(gateway);
await invitationHandler.handle({
recipientEmail: invitation.email,
invitationLink,
proName: pro.businessName,
inviterName: currentUser.name,
role: invitation.role as "owner" | "manager" | "staff",
expiresInDays: 7,
});
} catch (err) {
logger.error("[TEAM] Failed to resend invitation email:", err);
}
}
return success(c, { message: "Invitation resent successfully" });
},
);
// Cancel an invitation
invitations.delete("/:proId/team/invitations/:invitationId", async (c) => {
const dal = c.get("dal");
const proId = c.req.param("proId");
const invitationId = parseInt(c.req.param("invitationId"), 10);
const proRole = c.get("proRole");
// Only owners can cancel invitations
if (proRole !== "owner") {
return error(c, "FORBIDDEN", "Only owners can cancel invitations", 403);
}
const invitation = await dal.teamInvitations.findById(invitationId);
if (!invitation || invitation.proId !== proId) {
return error(c, "NOT_FOUND", "Invitation not found", 404);
}
await dal.teamInvitations.delete(invitationId);
return success(c, { message: "Invitation cancelled successfully" });
});
export default invitations;
|