Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 27 additions & 23 deletions apps/app/src/actions/policies/accept-requested-policy-changes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use server';

import { sendNewPolicyEmail } from '@/jobs/tasks/email/new-policy-email';
import { db, PolicyStatus } from '@db';
import { tasks } from '@trigger.dev/sdk';
import { revalidatePath, revalidateTag } from 'next/cache';
import { z } from 'zod';
import { authActionClient } from '../safe-action';
Expand Down Expand Up @@ -92,34 +94,36 @@ export const acceptRequestedPolicyChangesAction = authActionClient
return roles.includes('employee');
});

// Call /api/send-policy-email to send emails to employees

// Prepare the events array for the API
const events = employeeMembers
.filter((employee) => employee.user.email)
.map((employee) => ({
subscriberId: `${employee.user.id}-${session.activeOrganizationId}`,
email: employee.user.email,
userName: employee.user.name || employee.user.email || 'Employee',
policyName: policy.name,
organizationName: policy.organization.name,
url: `${process.env.NEXT_PUBLIC_PORTAL_URL ?? 'https://portal.trycomp.ai'}/${session.activeOrganizationId}`,
description: `The "${policy.name}" policy has been ${isNewPolicy ? 'created' : 'updated'}.`,
}));
.map((employee) => {
let notificationType: 'new' | 're-acceptance' | 'updated';
const wasAlreadySigned = policy.signedBy.includes(employee.id);
if (isNewPolicy) {
notificationType = 'new';
} else if (wasAlreadySigned) {
notificationType = 're-acceptance';
} else {
notificationType = 'updated';
}

return {
email: employee.user.email,
userName: employee.user.name || employee.user.email || 'Employee',
policyName: policy.name,
organizationId: session.activeOrganizationId || '',
organizationName: policy.organization.name,
notificationType,
};
});

// Call the API route to send the emails
try {
await fetch(`${process.env.BETTER_AUTH_URL ?? ''}/api/send-policy-email`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(events),
});
} catch (error) {
console.error('Failed to call /api/send-policy-email:', error);
// Don't throw, just log
}
await Promise.all(
events.map((event) =>
tasks.trigger<typeof sendNewPolicyEmail>('send-new-policy-email', event),
),
);

// If a comment was provided, create a comment
if (comment && comment.trim() !== '') {
Expand Down
50 changes: 0 additions & 50 deletions apps/app/src/app/api/send-policy-email/route.ts

This file was deleted.

49 changes: 49 additions & 0 deletions apps/app/src/jobs/tasks/email/new-policy-email.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { sendPolicyNotificationEmail } from '@comp/email';
import { logger, queue, task } from '@trigger.dev/sdk';

// Queue with concurrency limit of 1 to ensure rate limiting (1 email per second max)
const policyEmailQueue = queue({
name: 'policy-email-queue',
concurrencyLimit: 2,
});

interface PolicyEmailPayload {
email: string;
userName: string;
policyName: string;
organizationId: string;
organizationName: string;
notificationType: 'new' | 'updated' | 're-acceptance';
}

export const sendNewPolicyEmail = task({
id: 'send-new-policy-email',
queue: policyEmailQueue,
run: async (payload: PolicyEmailPayload) => {
logger.info('Sending new policy email', {
email: payload.email,
policyName: payload.policyName,
});

try {
await sendPolicyNotificationEmail(payload);

logger.info('Successfully sent policy email', {
email: payload.email,
policyName: payload.policyName,
});

return {
success: true,
email: payload.email,
};
} catch (error) {
logger.error('Failed to send policy email', {
email: payload.email,
error: error instanceof Error ? error.message : String(error),
});

throw error;
}
},
});