Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/tfr2 176 integrate welcome email after 24h of sign up #78

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
2 changes: 1 addition & 1 deletion apps/engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"standardwebhooks": "^1.0.0",
"superjson": "^2.2.1",
"tailwind-merge": "^2.4.0",
"zod": "^3.23.8",
"zod": "catalog:",
"zod-form-data": "^2.0.2"
},
"devDependencies": {
Expand Down
66 changes: 66 additions & 0 deletions apps/engine/src/app/api/email/cron/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { serverEnv } from '@/env/server-env';
import { api } from '@ds-project/api/service';
import { sendEmail } from '@ds-project/email';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { Webhook } from 'standardwebhooks';

/**
* Checks the scheduled emails in the database and sends the emails that are due
*/

export async function POST(request: NextRequest) {
const wh = new Webhook(serverEnv.SERVICE_HOOK_SECRET);
const payload = await request.text();
const headers = Object.fromEntries(request.headers);

// Verify the request is coming from an authorized source
try {
wh.verify(payload, headers);
} catch (error) {
return NextResponse.json(
{ error },
{
status: 401,
}
);
}

const dueEmailJobs = await api.jobs.getDueEmailList();

console.log(`👀 ${dueEmailJobs.length} due email jobs found.`);
// Run all the possible jobs, don't break if one fails. This way we can process all the jobs
await Promise.allSettled(
dueEmailJobs.map(async (job, jobIndex) => {
console.log(
`⚙️ (${jobIndex + 1}/${dueEmailJobs.length}) Processing job ${job.id}.`
);
// Only process jobs of type email
if (job.data?.type !== 'email') {
console.log(
`⏭️ (${jobIndex + 1}/${dueEmailJobs.length}) Skipped job ${job.id}.`
);
return;
}

await sendEmail({
accountId: job.accountId,
subject: job.data.subject,
template: job.data.template,
});

await api.jobs.markCompleted({ id: job.id });

console.log(
`📧 (${jobIndex + 1}/${dueEmailJobs.length}) Email job ${job.id} processed successfully.`
);
})
);

return NextResponse.json(
{},
{
status: 200,
}
);
}
52 changes: 25 additions & 27 deletions apps/engine/src/app/api/email/route.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { serverEnv } from '@/env/server-env';
import { SignUpEmail } from '@ds-project/email/src/templates/sign-up';
import { Resend } from '@ds-project/email/src/resend';
import { render } from '@ds-project/email/src/render';
import { config } from '@/config';
import { Webhook } from 'standardwebhooks';
import { sendEmail } from '@ds-project/email';

const resend = new Resend(serverEnv.RESEND_API_KEY);
interface WebhookPayload {
user: {
email: string;
};
email_data: {
token: string;
};
}

/**
* Sends a sign up email with an OTP code so the user can authenticate
* @param request
* @returns
*/
export async function POST(request: NextRequest) {
const wh = new Webhook(serverEnv.SEND_EMAIL_HOOK_SECRET);
const payload = await request.text();
Expand All @@ -18,32 +28,20 @@ export async function POST(request: NextRequest) {
const {
user,
email_data: { token },
} = wh.verify(payload, headers) as {
user: {
email: string;
};
email_data: {
token: string;
};
};

const html = await render(
<SignUpEmail
otpCode={token}
staticPathUrl={`${config.pageUrl}/static/email`}
/>
);
} = wh.verify(payload, headers) as WebhookPayload;

const { error } = await resend.emails.send({
from: 'DS Pro <noreply@getds.pro>',
to: [user.email],
// Send OTP email to the user
await sendEmail({
email: user.email,
subject: 'DS Pro - Confirmation Code',
html,
template: {
key: 'verify-otp',
props: {
otpCode: token,
staticPathUrl: `${config.pageUrl}/static/email`,
},
},
});

if (error) {
throw new Error(error.message, { cause: error.name });
}
} catch (error) {
return NextResponse.json(
{ error },
Expand Down
4 changes: 2 additions & 2 deletions apps/engine/src/app/auth/_actions/auth.action.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use server';

import { z } from 'zod';
import { unprotectedAction } from '@/lib/safe-action';
import { publicAction } from '@/lib/safe-action';

export const authAction = unprotectedAction
export const authAction = publicAction
.metadata({ actionName: 'authAction' })
.schema(
z.object({
Expand Down
50 changes: 43 additions & 7 deletions apps/engine/src/app/auth/_actions/verify-otp.action.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
'use server';

import { z } from 'zod';
import { unprotectedAction } from '@/lib/safe-action';
import { publicAction } from '@/lib/safe-action';
import { zfd } from 'zod-form-data';
import { scheduleOnboardingEmails } from '../_utils/schedule-onboarding-emails';
import { sendEmail } from '@ds-project/email';
import { config } from '@/config';

export const verifyOtpAction = unprotectedAction
export const verifyOtpAction = publicAction
.metadata({ actionName: 'verifyOtpAction' })
.schema(
z.object({
Expand All @@ -17,20 +20,53 @@ export const verifyOtpAction = unprotectedAction
})
)
.action(async ({ ctx, parsedInput: { email, token } }) => {
const { error } = await ctx.authClient.auth.verifyOtp({
const { error, data } = await ctx.authClient.auth.verifyOtp({
email,
token,
type: 'email',
});

if (!error) {
return {
ok: true,
};
if (
data.user?.id &&
data.user.email_confirmed_at &&
new Date(data.user.email_confirmed_at).getTime() <
new Date().getTime() + 1000 * 60 * 1 // 1 minute
) {
const result = await ctx.authClient
.from('accounts')
.select('id')
.eq('user_id', data.user.id)
.single();

if (result.error) {
return {
error: result.error.message,
ok: false,
};
}

await sendEmail({
accountId: result.data.id,
subject: 'Welcome to DS Pro',
template: {
key: 'welcome',
props: {
staticPathUrl: `${config.pageUrl}/static/email`,
},
},
scheduledAt: 'in 5 minutes',
});

await scheduleOnboardingEmails(result.data.id);
return {
ok: true,
};
}
}

return {
error: error.message,
error: error?.message ?? 'Error verifying OTP',
ok: false,
};
});
37 changes: 37 additions & 0 deletions apps/engine/src/app/auth/_utils/schedule-onboarding-emails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { config } from '@/config';
import { api } from '@ds-project/api/service';

export async function scheduleOnboardingEmails(accountId: string) {
await api.jobs.create([
{
type: 'email',
accountId,
dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24 hours
data: {
type: 'email',
subject: 'DS Pro - Ready to sync?',
template: {
key: 'onboarding-1d',
props: {
staticPathUrl: `${config.pageUrl}/static/email`,
},
},
},
},
{
type: 'email',
accountId,
dueDate: new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString(), // 72 hours
data: {
type: 'email',
subject: 'DS Pro - The Future of Design Tokens',
template: {
key: 'onboarding-3d',
props: {
staticPathUrl: `${config.pageUrl}/static/email`,
},
},
},
},
]);
}
1 change: 1 addition & 0 deletions apps/engine/src/env/server-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const serverEnv = createEnv({
SENTRY_AUTH_TOKEN: z.string().min(1).optional(),
RESEND_API_KEY: z.string().min(1),
SEND_EMAIL_HOOK_SECRET: z.string().min(1),
SERVICE_HOOK_SECRET: z.string().min(1),
// Feature Flags
ENABLE_RELEASES_FLAG: z.coerce.boolean(),
},
Expand Down
2 changes: 1 addition & 1 deletion apps/engine/src/lib/safe-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const actionClient = createSafeActionClient({
return next({ ctx: { ...ctx, authClient } });
});

export const unprotectedAction = actionClient;
export const publicAction = actionClient;

// Auth client defined by extending the base one.
// Note that the same initialization options and middleware functions of the base client
Expand Down
8 changes: 8 additions & 0 deletions apps/engine/vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"crons": [
{
"path": "/api/email/cron",
"schedule": "10 10 * * *"
}
]
}
4 changes: 4 additions & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
"types": "./dist/react.d.ts",
"default": "./src/react.tsx"
},
"./service": {
"types": "./dist/service.d.ts",
"default": "./src/service.tsx"
},
"./operations": {
"types": "./dist/operations.d.ts",
"default": "./src/operations/index.ts"
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/app-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { accountsRouter } from './router/accounts';
import { apiKeysRouter } from './router/api-keys';
import { githubRouter } from './router/github';
import { integrationsRouter } from './router/integrations';
import { jobsRouter } from './router/jobs';
import { projectsRouter } from './router/projects';
import { resourcesRouter } from './router/resources';
import { usersRouter } from './router/users';
Expand All @@ -15,6 +16,7 @@ export const appRouter = createTRPCRouter({
resources: resourcesRouter,
projects: projectsRouter,
github: githubRouter,
jobs: jobsRouter,
});

// export type definition of API
Expand Down
8 changes: 6 additions & 2 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server';

import type { AppRouter } from './app-router';
import { appRouter } from './app-router';
import { createTRPCContext, createCallerFactory } from './trpc';
import { createClientTRPCContext, createCallerFactory } from './trpc';

/**
* Create a server-side caller for the tRPC API
Expand All @@ -29,5 +29,9 @@ type RouterInputs = inferRouterInputs<AppRouter>;
**/
type RouterOutputs = inferRouterOutputs<AppRouter>;

export { createTRPCContext, appRouter, createCaller };
export {
createClientTRPCContext as createTRPCContext,
appRouter,
createCaller,
};
export type { AppRouter, RouterInputs, RouterOutputs };
18 changes: 17 additions & 1 deletion packages/api/src/router/accounts.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import { eq } from '@ds-project/database';

import { createTRPCRouter, authenticatedProcedure } from '../trpc';
import {
createTRPCRouter,
authenticatedProcedure,
serviceProcedure,
} from '../trpc';
import { SelectAccountsSchema } from '@ds-project/database/schema';

export const accountsRouter = createTRPCRouter({
getCurrent: authenticatedProcedure.query(({ ctx }) => {
return ctx.database.query.Accounts.findFirst({
where: (accounts) => eq(accounts.id, ctx.account.id),
});
}),
get: serviceProcedure
.input(SelectAccountsSchema.pick({ id: true }))
.query(({ ctx, input }) => {
return ctx.database.query.Accounts.findFirst({
where: (accounts) => eq(accounts.id, input.id),
columns: {
email: true,
id: true,
},
});
}),
});
Loading
Loading