Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: send project invitation emails (#261)

I'm Groot 🌳f47c94f45035
diff --git a/apps/api/src/modules/invites/__tests__/integration/invites.test.ts b/apps/api/src/modules/invites/__tests__/integration/invites.test.ts
index d8fce128..de91db03 100644
--- a/apps/api/src/modules/invites/__tests__/integration/invites.test.ts
+++ b/apps/api/src/modules/invites/__tests__/integration/invites.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi } from '#tests/helpers/app';
+import { app, authedApi } from '#tests/helpers/app';
import { signUpTestUser, type TestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
@@ -11,11 +11,49 @@ import { resetDb } from '#tests/helpers/db';
// Creates a project MKT owned by a fresh user and returns a Treaty client acting
// as that owner. The first user in a reset DB is "god"; the owner still reaches
// the project only through its project_member row, so this is a plain owner.
-async function setupOwner(): Promise<{ user: TestUser; api: ReturnType<typeof authedApi> }> {
+async function setupOwner(): Promise<{
+ user: TestUser;
+ api: ReturnType<typeof authedApi>;
+ projectId: number;
+}> {
const user = await signUpTestUser();
const api = authedApi(user.cookie);
- await api.projects.post({ key: 'MKT', name: 'Marketing' });
- return { user, api };
+ const project = await api.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { user, api, projectId: project.data!.id };
+}
+
+async function configureEmail(owner: ReturnType<typeof authedApi>) {
+ const result = await owner.god['email-settings'].put({
+ from: "It's a Plan <[email protected]>",
+ resend: { enabled: true, apiKey: 're_test_key' },
+ allowProjects: false,
+ });
+ expect(result.status).toBe(200);
+}
+
+async function deliverInvite(projectId: number, projectInviteId: number) {
+ const token = 'invite-email-test-worker-token';
+ const previousToken = process.env.WORKER_INTERNAL_TOKEN;
+ process.env.WORKER_INTERNAL_TOKEN = token;
+ let response: Response;
+ try {
+ response = await app.handle(
+ new Request('http://localhost/internal/notification-deliveries/send', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-worker-token': token },
+ body: JSON.stringify({
+ projectId,
+ channel: 'email',
+ recipient: '[email protected]',
+ payload: { text: 'Invitation', projectInviteId },
+ }),
+ }),
+ );
+ } finally {
+ if (previousToken == null) delete process.env.WORKER_INTERNAL_TOKEN;
+ else process.env.WORKER_INTERNAL_TOKEN = previousToken;
+ }
+ return { status: response.status, body: await response.json() };
}
describe('invites', () => {
@@ -36,6 +74,7 @@ describe('invites', () => {
role: 'member',
status: 'pending',
+ emailQueued: false,
respondedAt: null,
invitedByEmail: owner.user.email,
});
@@ -43,6 +82,18 @@ describe('invites', () => {
expect(res.data?.token.length).toBeGreaterThan(0);
});
+ it('queues an email from the instance provider without project opt-in', async () => {
+ const owner = await setupOwner();
+ await configureEmail(owner.api);
+
+ const res = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+
+ expect(res.status).toBe(201);
+ expect(res.data?.emailQueued).toBe(true);
+ });
+
it('normalizes the email to lowercase', async () => {
const owner = await setupOwner();
@@ -134,6 +185,97 @@ describe('invites', () => {
});
});
+ describe('email — POST /projects/:projectKey/invites/:inviteId/email', () => {
+ it('reports that email is unavailable without blocking the invite', async () => {
+ const owner = await setupOwner();
+ const invite = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+
+ const res = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites({ inviteId: invite.data!.id })
+ .email.post();
+
+ expect(res.status).toBe(200);
+ expect(res.data).toEqual({ emailQueued: false });
+ });
+
+ it('queues a pending invite and accepts concurrent repeat requests', async () => {
+ const owner = await setupOwner();
+ const invite = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ await configureEmail(owner.api);
+ const client = owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites({ inviteId: invite.data!.id }).email;
+
+ const [first, second] = await Promise.all([client.post(), client.post()]);
+
+ expect(first.status).toBe(200);
+ expect(first.data).toEqual({ emailQueued: true });
+ expect(second.status).toBe(200);
+ expect(second.data).toEqual({ emailQueued: true });
+ });
+
+ it('returns 404 for an unknown invite id', async () => {
+ const owner = await setupOwner();
+
+ const res = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites({ inviteId: 999999 })
+ .email.post();
+
+ expect(res.status).toBe(404);
+ });
+
+ it('returns 409 after an invite was accepted', async () => {
+ const owner = await setupOwner();
+ const invitee = await signUpTestUser();
+ const invite = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: invitee.email, role: 'member' });
+ await authedApi(invitee.cookie).invites({ token: invite.data!.token }).accept.post();
+
+ const res = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites({ inviteId: invite.data!.id })
+ .email.post();
+
+ expect(res.status).toBe(409);
+ });
+
+ it('drops a queued delivery after the invite was accepted', async () => {
+ const owner = await setupOwner();
+ const invitee = await signUpTestUser();
+ const invite = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: invitee.email, role: 'member' });
+ await authedApi(invitee.cookie).invites({ token: invite.data!.token }).accept.post();
+
+ const result = await deliverInvite(owner.projectId, invite.data!.id);
+
+ expect(result.status).toBe(200);
+ expect(result.body).toEqual({ ok: true });
+ });
+
+ it('denies a non-member', async () => {
+ const owner = await setupOwner();
+ const invite = await owner.api
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ const outsider = authedApi((await signUpTestUser()).cookie);
+
+ const res = await outsider
+ .projects({ projectKey: 'MKT' })
+ .invites({ inviteId: invite.data!.id })
+ .email.post();
+
+ expect(res.status).toBe(403);
+ });
+ });
+
describe('list — GET /projects/:projectKey/invites', () => {
it("lists the project's invites, newest first", async () => {
const owner = await setupOwner();
diff --git a/apps/api/src/modules/invites/email.ts b/apps/api/src/modules/invites/email.ts
new file mode 100644
index 00000000..f91a2095
--- /dev/null
+++ b/apps/api/src/modules/invites/email.ts
@@ -0,0 +1,69 @@
+import { randomUUID } from 'node:crypto';
+import { db, notificationDelivery } from '@repo/db';
+import { getEmailConfig, trustedOrigins } from '@repo/auth';
+import { hasEmailProvider } from '@repo/mailer';
+import { and, eq, sql } from 'drizzle-orm';
+import type { InviteRow } from './service';
+
+interface InviteProject {
+ id: number;
+ name: string;
+}
+
+// Serializes enqueue attempts for one invite across API replicas. Without this,
+// two clicks arriving together can both observe an empty outbox and insert the
+// same email before either transaction commits.
+const INVITE_EMAIL_LOCK_NAMESPACE = 8242;
+
+export async function enqueueInviteEmail(
+ project: InviteProject,
+ invite: InviteRow,
+): Promise<boolean> {
+ const config = await getEmailConfig();
+ if (!config || !hasEmailProvider(config)) return false;
+
+ const dedupeKey = `project-invite:${invite.id}`;
+ const inviter = invite.invitedByName ?? invite.invitedByEmail ?? "An It's a Plan user";
+ const role = invite.role === 'owner' ? 'owner' : (invite.roleName ?? 'member');
+ const projectName = project.name.replace(/[\r\n]+/g, ' ');
+ const url = new URL(`/invite/${invite.token}`, trustedOrigins[0]).toString();
+
+ await db.transaction(async (tx) => {
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(${INVITE_EMAIL_LOCK_NAMESPACE}, ${invite.id})`,
+ );
+ const [pending] = await tx
+ .select({ id: notificationDelivery.id })
+ .from(notificationDelivery)
+ .where(
+ and(
+ eq(notificationDelivery.projectId, project.id),
+ eq(notificationDelivery.channel, 'email'),
+ eq(notificationDelivery.recipient, invite.email),
+ eq(notificationDelivery.status, 'pending'),
+ sql`${notificationDelivery.payload}->>'dedupeKey' = ${dedupeKey}`,
+ ),
+ )
+ .limit(1);
+ if (pending) return;
+
+ await tx.insert(notificationDelivery).values({
+ projectId: project.id,
+ channel: 'email',
+ recipient: invite.email,
+ payload: {
+ subject: `You were invited to ${projectName} on It's a Plan`,
+ text:
+ `${inviter} invited you to join ${projectName} as ${role}.\n\n` +
+ 'Open the invitation to sign in or create an account. ' +
+ 'If you did not expect this invitation, you can ignore this email.',
+ url,
+ emailSource: 'instance',
+ idempotencyKey: `project-invite/${invite.id}/${randomUUID()}`,
+ dedupeKey,
+ projectInviteId: invite.id,
+ },
+ });
+ });
+ return true;
+}
diff --git a/apps/api/src/modules/invites/index.ts b/apps/api/src/modules/invites/index.ts
index 7f32d811..83ca7518 100644
--- a/apps/api/src/modules/invites/index.ts
+++ b/apps/api/src/modules/invites/index.ts
@@ -9,8 +9,9 @@ import { accessErrors, commonErrors, errors } from '#shared/responses';
import { getRole } from '#modules/roles/service';
import {
AcceptInviteResponse,
+ InviteCreateResponse,
+ InviteEmailResponse,
InviteRowListResponse,
- InviteRowResponse,
InviteViewResponse,
createInviteBody,
inviteParams,
@@ -20,11 +21,13 @@ import {
createInvite,
listInvites,
deleteInvite,
+ getInviteById,
getInviteByToken,
getInviteRowByToken,
acceptInvite,
rejectInvite,
} from './service';
+import { enqueueInviteEmail } from './email';
// Shared by accept and reject: an invite is actionable only by the account whose
// email it names, and only while it is still pending.
@@ -61,23 +64,56 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
roleId,
invitedByUserId: requireUser(user).id,
});
+ let emailQueued = false;
+ try {
+ emailQueued = await enqueueInviteEmail(project, invite);
+ } catch (err) {
+ // Creating the invite link is the primary operation. A transient outbox
+ // failure must not discard a valid link that can still be copied.
+ console.error('[invites] email enqueue failed:', err);
+ }
set.status = 201;
- return invite;
+ return { ...invite, emailQueued };
},
{
body: createInviteBody,
permission: ['members_invite', 'create'],
- response: { 201: InviteRowResponse, ...commonErrors, ...errors(409) },
+ response: { 201: InviteCreateResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Create an invite',
description:
'Create an invite link for an email and role (owner or member). For a member, roleId ' +
- 'picks the custom role, or null for the default role.',
+ 'picks the custom role, or null for the default role. Queues an email when the ' +
+ 'instance email provider is configured.',
...mcpTool('create_invite'),
},
},
)
+ .post(
+ '/projects/:projectKey/invites/:inviteId/email',
+ async ({ project, params }) => {
+ const invite = await getInviteById(project.id, params.inviteId);
+ if (!invite) throw new HttpError(404, 'Invite not found');
+ if (invite.status !== 'pending') {
+ throw new HttpError(409, 'This invite is no longer pending');
+ }
+ return { emailQueued: await enqueueInviteEmail(project, invite) };
+ },
+ {
+ params: inviteParams,
+ permission: ['members_invite', 'create'],
+ response: { 200: InviteEmailResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Send an invite email',
+ description:
+ 'Queue an email for a pending project invite. Returns false when the instance email ' +
+ 'provider is not configured.',
+ ...mcpTool('send_invite_email'),
+ },
+ },
+ )
+
.get(
'/projects/:projectKey/invites',
async ({ project }) => {
diff --git a/apps/api/src/modules/invites/model.ts b/apps/api/src/modules/invites/model.ts
index a51d7af2..66f6ffc5 100644
--- a/apps/api/src/modules/invites/model.ts
+++ b/apps/api/src/modules/invites/model.ts
@@ -31,6 +31,13 @@ export const InviteRowResponse = t.Object({
invitedByEmail: t.Nullable(t.String()),
});
+export const InviteCreateResponse = t.Composite([
+ InviteRowResponse,
+ t.Object({ emailQueued: t.Boolean() }),
+]);
+
+export const InviteEmailResponse = t.Object({ emailQueued: t.Boolean() });
+
export const InviteRowListResponse = t.Array(InviteRowResponse);
// The invitee-facing invite view (InviteView from the service).
diff --git a/apps/api/src/modules/invites/service.ts b/apps/api/src/modules/invites/service.ts
index fcee4515..c457f8c6 100644
--- a/apps/api/src/modules/invites/service.ts
+++ b/apps/api/src/modules/invites/service.ts
@@ -122,6 +122,21 @@ export async function getInviteById(projectId: number, id: number): Promise<Invi
};
}
+export async function isInvitePending(projectId: number, id: number): Promise<boolean> {
+ const rows = await db
+ .select({ id: projectInvite.id })
+ .from(projectInvite)
+ .where(
+ and(
+ eq(projectInvite.projectId, projectId),
+ eq(projectInvite.id, id),
+ eq(projectInvite.status, 'pending'),
+ ),
+ )
+ .limit(1);
+ return rows.length > 0;
+}
+
export async function listInvites(projectId: number): Promise<InviteRow[]> {
const rows = await db
.select({
diff --git a/apps/api/src/modules/notifications/internal-routes.ts b/apps/api/src/modules/notifications/internal-routes.ts
index fbb4c314..85a82d35 100644
--- a/apps/api/src/modules/notifications/internal-routes.ts
+++ b/apps/api/src/modules/notifications/internal-routes.ts
@@ -1,4 +1,5 @@
import { Elysia } from 'elysia';
+import { isInvitePending } from '#modules/invites/service';
import { getDeliveryConfig } from '#modules/notification-settings/service';
import { sendDeliveryBody } from './model';
import { sendDelivery } from './send';
@@ -20,6 +21,14 @@ export const internalNotificationRoutes = new Elysia({
set.status = 401;
return { ok: false, retryable: false, error: 'Unauthorized' };
}
+ if (
+ body.payload.projectInviteId != null &&
+ !(await isInvitePending(body.projectId, body.payload.projectInviteId))
+ ) {
+ // The invite was accepted, rejected, or revoked while its email waited in
+ // the outbox. Treat it as delivered so the worker removes the stale row.
+ return { ok: true };
+ }
const config = await getDeliveryConfig(body.projectId);
return sendDelivery({
channel: body.channel,
diff --git a/apps/api/src/modules/notifications/model.ts b/apps/api/src/modules/notifications/model.ts
index c9d6d62e..5e981ac1 100644
--- a/apps/api/src/modules/notifications/model.ts
+++ b/apps/api/src/modules/notifications/model.ts
@@ -72,5 +72,8 @@ export const sendDeliveryBody = t.Object({
// plain-text fallback instead.
html: t.Optional(t.String()),
url: t.Optional(t.String()),
+ emailSource: t.Optional(t.UnionEnum(['project', 'instance'])),
+ idempotencyKey: t.Optional(t.String()),
+ projectInviteId: t.Optional(t.Integer({ minimum: 1 })),
}),
});
diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.ts
index 7e86c290..e968491d 100644
--- a/apps/api/src/modules/notifications/outbound.ts
+++ b/apps/api/src/modules/notifications/outbound.ts
@@ -28,6 +28,10 @@ export interface DeliveryPayload {
text: string;
html?: string;
url?: string;
+ emailSource?: 'project' | 'instance';
+ idempotencyKey?: string;
+ dedupeKey?: string;
+ projectInviteId?: number;
}
interface OutboxRow {
diff --git a/apps/api/src/modules/notifications/send.ts b/apps/api/src/modules/notifications/send.ts
index c65ca156..d9c397b3 100644
--- a/apps/api/src/modules/notifications/send.ts
+++ b/apps/api/src/modules/notifications/send.ts
@@ -1,5 +1,5 @@
import { sendEmail, emailBody, type EmailConfig, type SendResult } from '@repo/mailer';
-import { getProjectEmailConfig } from '@repo/auth';
+import { getEmailConfig, getProjectEmailConfig } from '@repo/auth';
import { emailSource, type NotificationConfig } from '#modules/notification-settings/service';
import type { DeliveryPayload } from './outbound';
import { getInstanceBotConfig, isInstanceBotUsable } from '#modules/telegram/service';
@@ -30,11 +30,13 @@ async function sendNotificationEmail(input: SendInput): Promise<SendResult> {
// provider stops sending when the administrator withdraws it.
const source = emailSource(input.config);
const config: EmailConfig | null =
- source === 'system'
- ? await getProjectEmailConfig()
- : source === 'none'
- ? null
- : { smtp: input.config.smtp, resend: input.config.resend };
+ input.payload.emailSource === 'instance'
+ ? await getEmailConfig()
+ : source === 'system'
+ ? await getProjectEmailConfig()
+ : source === 'none'
+ ? null
+ : { smtp: input.config.smtp, resend: input.config.resend };
if (!config) return { ok: false, retryable: false, error: 'email not configured' };
const { text, html } = emailBody(input.payload.text, input.payload.url);
return sendEmail(config, {
@@ -42,6 +44,7 @@ async function sendNotificationEmail(input: SendInput): Promise<SendResult> {
subject: input.payload.subject ?? '',
text,
html,
+ idempotencyKey: input.payload.idempotencyKey,
});
}
diff --git a/apps/web/messages/ar/members.json b/apps/web/messages/ar/members.json
index c358b7f6..dcb704f1 100644
--- a/apps/web/messages/ar/members.json
+++ b/apps/web/messages/ar/members.json
@@ -34,6 +34,11 @@
"pendingCount": "{count, plural, zero {لا دعوات معلّقة} one {دعوة معلّقة واحدة} two {دعوتان معلّقتان} few {# دعوات معلّقة} many {# دعوة معلّقة} other {# دعوة معلّقة}}",
"copyLink": "نسخ الرابط",
"copied": "تم النسخ",
+ "emailQueued": "اتضاف إيميل الدعوة لطابور الإرسال",
+ "emailUnavailable": "الدعوة اتعملت، بس الإيميل ماتضافش لطابور الإرسال. انسخ الرابط وشاركه.",
+ "resendUnavailable": "البريد الإلكتروني غير مهيأ. انسخ رابط الدعوة وشاركه.",
+ "resendEmail": "إرسال إيميل",
+ "resendingEmail": "جارٍ الإضافة…",
"revokeAction": "إلغاء الدعوة",
"removeAction": "إزالة الدعوة",
"invitedBy": "بدعوة من {name} · ",
diff --git a/apps/web/messages/en/members.json b/apps/web/messages/en/members.json
index 233b1564..2362c786 100644
--- a/apps/web/messages/en/members.json
+++ b/apps/web/messages/en/members.json
@@ -34,6 +34,11 @@
"pendingCount": "{count, plural, one {# pending invite} other {# pending invites}}",
"copyLink": "Copy link",
"copied": "Copied",
+ "emailQueued": "Invitation email queued",
+ "emailUnavailable": "Invite created, but email was not queued. Copy the link to share it.",
+ "resendUnavailable": "Email is not configured. Copy the invitation link to share it.",
+ "resendEmail": "Send email",
+ "resendingEmail": "Queueing…",
"revokeAction": "Revoke invite",
"removeAction": "Remove invite",
"invitedBy": "Invited by {name} · ",
diff --git a/apps/web/messages/ru/members.json b/apps/web/messages/ru/members.json
index 48ca5334..565da3cc 100644
--- a/apps/web/messages/ru/members.json
+++ b/apps/web/messages/ru/members.json
@@ -34,6 +34,11 @@
"pendingCount": "{count, plural, one {# приглашение в ожидании} few {# приглашения в ожидании} many {# приглашений в ожидании} other {# приглашения в ожидании}}",
"copyLink": "Скопировать ссылку",
"copied": "Скопировано",
+ "emailQueued": "Письмо с приглашением поставлено в очередь",
+ "emailUnavailable": "Приглашение создано, но письмо не поставлено в очередь. Скопируйте ссылку.",
+ "resendUnavailable": "Почта не настроена. Скопируйте ссылку на приглашение.",
+ "resendEmail": "Отправить письмо",
+ "resendingEmail": "В очередь…",
"revokeAction": "Отозвать приглашение",
"removeAction": "Убрать приглашение",
"invitedBy": "Пригласил {name} · ",
diff --git a/apps/web/messages/uk/members.json b/apps/web/messages/uk/members.json
index e367b88b..7230bfe5 100644
--- a/apps/web/messages/uk/members.json
+++ b/apps/web/messages/uk/members.json
@@ -34,6 +34,11 @@
"pendingCount": "{count, plural, one {# запрошення в очікуванні} few {# запрошення в очікуванні} many {# запрошень в очікуванні} other {# запрошення в очікуванні}}",
"copyLink": "Скопіювати посилання",
"copied": "Скопійовано",
+ "emailQueued": "Лист із запрошенням поставлено в чергу",
+ "emailUnavailable": "Запрошення створено, але лист не поставлено в чергу. Скопіюйте посилання.",
+ "resendUnavailable": "Пошту не налаштовано. Скопіюйте посилання на запрошення.",
+ "resendEmail": "Надіслати лист",
+ "resendingEmail": "У чергу…",
"revokeAction": "Відкликати запрошення",
"removeAction": "Прибрати запрошення",
"invitedBy": "Запросив {name} · ",
diff --git a/apps/web/messages/zh-CN/members.json b/apps/web/messages/zh-CN/members.json
index 1d351ca9..702090a0 100644
--- a/apps/web/messages/zh-CN/members.json
+++ b/apps/web/messages/zh-CN/members.json
@@ -34,6 +34,11 @@
"pendingCount": "{count, plural, other {# 个待处理邀请}}",
"copyLink": "复制链接",
"copied": "已复制",
+ "emailQueued": "邀请邮件已加入发送队列",
+ "emailUnavailable": "邀请已创建,但邮件未加入发送队列。请复制链接进行分享。",
+ "resendUnavailable": "邮件尚未配置。请复制邀请链接进行分享。",
+ "resendEmail": "发送邮件",
+ "resendingEmail": "正在加入队列…",
"revokeAction": "撤销邀请",
"removeAction": "移除邀请",
"invitedBy": "由 {name} 邀请 · ",
diff --git a/apps/web/src/features/members/components/invites/InviteRow.tsx b/apps/web/src/features/members/components/invites/InviteRow.tsx
index a54253df..863bcc93 100644
--- a/apps/web/src/features/members/components/invites/InviteRow.tsx
+++ b/apps/web/src/features/members/components/invites/InviteRow.tsx
@@ -1,7 +1,7 @@
'use client';
import { useState } from 'react';
-import { Check, Copy, X } from 'lucide-react';
+import { Check, Copy, Mail, X } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { type InviteRow as Invite } from '@/lib/api';
import { inviteLink } from '@/utils/paths';
@@ -13,14 +13,18 @@ import { Item, ItemActions, ItemContent, ItemTitle } from '@/components/ui/item'
const STATUS_VARIANT = { pending: 'secondary', accepted: 'default', rejected: 'outline' } as const;
// One invite row: the invited email and role, its status, who sent it, and — for
-// a pending invite — a copy-link button and a revoke action. Copy reads the link
-// from the current web origin so it works in any deployment.
+// a pending invite — email, copy-link, and revoke actions. Copy reads the link from
+// the current web origin so it works in any deployment.
export default function InviteRow({
invite,
+ onResend,
onRevoke,
+ resending,
}: {
invite: Invite;
- onRevoke: (invite: Invite) => void;
+ onResend?: (invite: Invite) => void;
+ onRevoke?: (invite: Invite) => void;
+ resending: boolean;
}) {
const t = useTranslations('members.invites');
const tCommon = useTranslations('common');
@@ -46,6 +50,14 @@ export default function InviteRow({
}
}
+ function resend() {
+ onResend?.(invite);
+ }
+
+ function revoke() {
+ onRevoke?.(invite);
+ }
+
const invitedBy = invite.invitedByName || invite.invitedByEmail;
// Owner invites bypass roles; a member invite shows its chosen role, falling
// back to the default role's label when none was pinned.
@@ -55,11 +67,11 @@ export default function InviteRow({
return (
<Item
size="sm"
- className="h-14 border-0 border-b border-border last:border-b-0 hover:bg-accent/50"
+ className="min-h-14 border-0 border-b border-border last:border-b-0 hover:bg-accent/50"
>
- <ItemContent className="gap-0.5">
- <ItemTitle className="flex items-center gap-2">
- {invite.email}
+ <ItemContent className="min-w-0 gap-0.5">
+ <ItemTitle className="max-w-full flex-wrap">
+ <span className="break-all">{invite.email}</span>
<Badge variant="outline" className="px-1.5 py-0 text-[10px] font-normal">
{roleLabel}
</Badge>
@@ -75,7 +87,19 @@ export default function InviteRow({
{timestamp}
</span>
</ItemContent>
- <ItemActions>
+ <ItemActions className="ms-auto w-full justify-end sm:w-auto">
+ {pending && onResend && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
+ disabled={resending}
+ onClick={resend}
+ >
+ <Mail className="size-3.5" />
+ {resending ? t('resendingEmail') : t('resendEmail')}
+ </Button>
+ )}
{pending && (
<Button
variant="ghost"
@@ -87,15 +111,17 @@ export default function InviteRow({
{copied ? t('copied') : t('copyLink')}
</Button>
)}
- <Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground hover:text-destructive"
- title={pending ? t('revokeAction') : t('removeAction')}
- onClick={() => onRevoke(invite)}
- >
- <X className="size-4" />
- </Button>
+ {onRevoke && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-muted-foreground hover:text-destructive"
+ title={pending ? t('revokeAction') : t('removeAction')}
+ onClick={revoke}
+ >
+ <X className="size-4" />
+ </Button>
+ )}
</ItemActions>
</Item>
);
diff --git a/apps/web/src/features/members/components/invites/InvitesManager.tsx b/apps/web/src/features/members/components/invites/InvitesManager.tsx
index a488937c..324b0766 100644
--- a/apps/web/src/features/members/components/invites/InvitesManager.tsx
+++ b/apps/web/src/features/members/components/invites/InvitesManager.tsx
@@ -5,7 +5,7 @@ import { useTranslations } from 'next-intl';
import { type InviteRow as Invite } from '@/lib/api';
import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
import { ItemGroup } from '@/components/ui/item';
-import { useDeleteInvite, useInvitesQuery } from '@/services/members.service';
+import { useDeleteInvite, useInvitesQuery, useSendInviteEmail } from '@/services/members.service';
import { usePermissions } from '@/hooks/usePermissions';
import InviteCreateForm from './InviteCreateForm';
import InviteRow from './InviteRow';
@@ -19,10 +19,16 @@ export default function InvitesManager({ projectKey }: { projectKey: string }) {
const { can } = usePermissions();
const canRead = can('members_invite', 'read');
const canCreate = can('members_invite', 'create');
+ const canDelete = can('members_invite', 'delete');
const invitesQuery = useInvitesQuery(projectKey, canRead);
const deleteInvite = useDeleteInvite(projectKey);
+ const sendEmail = useSendInviteEmail(projectKey);
const [target, setTarget] = useState<Invite | null>(null);
+ function resendInvite(invite: Invite) {
+ sendEmail.mutate(invite.id);
+ }
+
if (!canRead) return null;
const pending = (invitesQuery.data ?? []).filter((invite) => invite.status === 'pending');
@@ -39,13 +45,19 @@ export default function InvitesManager({ projectKey }: { projectKey: string }) {
</div>
<ItemGroup>
{pending.map((invite) => (
- <InviteRow key={invite.id} invite={invite} onRevoke={setTarget} />
+ <InviteRow
+ key={invite.id}
+ invite={invite}
+ onResend={canCreate ? resendInvite : undefined}
+ onRevoke={canDelete ? setTarget : undefined}
+ resending={sendEmail.isPending && sendEmail.variables === invite.id}
+ />
))}
</ItemGroup>
</div>
)}
- {target && (
+ {canDelete && target && (
<ConfirmDialog
title={t('revokeTitle', { email: target.email })}
confirmLabel={t('revokeConfirm')}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 716dfb18..058e9420 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -2485,6 +2485,14 @@ export interface InviteRow {
invitedByEmail: string | null;
}
+export interface InviteCreateResult extends InviteRow {
+ emailQueued: boolean;
+}
+
+export interface InviteEmailResult {
+ emailQueued: boolean;
+}
+
// An invite as shown to the invitee opening the link: enough project context to
// decide, never the internal project id.
export interface InviteView {
@@ -3344,16 +3352,20 @@ export const api = {
deleteRole: (projectKey: string, roleId: number) =>
request<void>(`/projects/${projectKey}/roles/${roleId}`, { method: 'DELETE' }),
- // Invites — owner side: create, list, and revoke a project's invite links.
+ // Invites — owner side: create, list, email, and revoke a project's invite links.
listInvites: (projectKey: string) => request<InviteRow[]>(`/projects/${projectKey}/invites`),
createInvite: (
projectKey: string,
input: { email: string; role: MemberRole; roleId?: number | null },
) =>
- request<InviteRow>(`/projects/${projectKey}/invites`, {
+ request<InviteCreateResult>(`/projects/${projectKey}/invites`, {
method: 'POST',
body: JSON.stringify(input),
}),
+ sendInviteEmail: (projectKey: string, inviteId: number) =>
+ request<InviteEmailResult>(`/projects/${projectKey}/invites/${inviteId}/email`, {
+ method: 'POST',
+ }),
deleteInvite: (projectKey: string, inviteId: number) =>
request<void>(`/projects/${projectKey}/invites/${inviteId}`, { method: 'DELETE' }),
diff --git a/apps/web/src/services/members.service.ts b/apps/web/src/services/members.service.ts
index 76f1194c..c02675c1 100644
--- a/apps/web/src/services/members.service.ts
+++ b/apps/web/src/services/members.service.ts
@@ -67,11 +67,27 @@ export function useInvitesQuery(projectKey: string | null, enabled = true) {
}
export function useCreateInvite(projectKey: string) {
+ const t = useTranslations('members.invites');
const qc = useQueryClient();
return useMutation({
mutationFn: (input: { email: string; role: MemberRole; roleId?: number | null }) =>
api.createInvite(projectKey, input),
- onSuccess: () => qc.invalidateQueries({ queryKey: qk.invites(projectKey) }),
+ onSuccess: (result) => {
+ qc.invalidateQueries({ queryKey: qk.invites(projectKey) });
+ if (result.emailQueued) toast.success(t('emailQueued'));
+ else toast.info(t('emailUnavailable'));
+ },
+ });
+}
+
+export function useSendInviteEmail(projectKey: string) {
+ const t = useTranslations('members.invites');
+ return useMutation({
+ mutationFn: (inviteId: number) => api.sendInviteEmail(projectKey, inviteId),
+ onSuccess: (result) => {
+ if (result.emailQueued) toast.success(t('emailQueued'));
+ else toast.info(t('resendUnavailable'));
+ },
});
}
diff --git a/packages/mailer/src/index.ts b/packages/mailer/src/index.ts
index eb48cf5b..d4658915 100644
--- a/packages/mailer/src/index.ts
+++ b/packages/mailer/src/index.ts
@@ -34,6 +34,7 @@ export interface EmailMessage {
subject: string;
text: string;
html: string;
+ idempotencyKey?: string;
}
export interface SendResult {
@@ -101,6 +102,7 @@ async function sendResend(
headers: {
authorization: `Bearer ${resend.apiKey}`,
'content-type': 'application/json',
+ ...(message.idempotencyKey ? { 'idempotency-key': message.idempotencyKey } : {}),
},
signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),
body: JSON.stringify({