Files
wfh/src/lib/google-drive.ts
T

190 lines
7.4 KiB
TypeScript
Raw Normal View History

import { google, Auth } from 'googleapis';
2026-03-12 17:09:22 -05:00
import { Readable } from 'stream';
2026-03-13 16:00:33 -05:00
import { prisma } from './prisma';
import type { Prisma } from '@prisma/client';
type ReportWithRelations = Prisma.ReportGetPayload<{
include: { tasks: true; user: true };
}>;
2026-03-12 17:09:22 -05:00
2026-03-13 16:00:33 -05:00
export async function getGoogleAuth(userId: string) {
const account = await prisma.account.findFirst({
where: { userId, provider: 'google' },
});
2026-03-12 17:09:22 -05:00
2026-03-13 16:00:33 -05:00
if (!account) {
throw new Error('Google account not found');
}
const auth = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET
);
auth.setCredentials({
access_token: account.access_token,
refresh_token: account.refresh_token,
expiry_date: account.expires_at ? account.expires_at * 1000 : null,
});
// Check if the token is expired or will expire in the next 1 minute
// NextAuth stores expires_at in seconds
const isExpired = account.expires_at ? (account.expires_at * 1000) < (Date.now() + 60000) : true;
if (isExpired && account.refresh_token) {
try {
const { credentials } = await auth.refreshAccessToken();
auth.setCredentials(credentials);
// Update database with new tokens
await prisma.account.update({
where: { id: account.id },
data: {
access_token: credentials.access_token,
refresh_token: credentials.refresh_token || account.refresh_token,
expires_at: credentials.expiry_date ? Math.floor(credentials.expiry_date / 1000) : null,
},
});
console.log('Successfully refreshed Google access token for user:', userId);
} catch (error) {
console.error('Error refreshing access token:', error);
// If refresh fails, we still return the auth object, but requests will fail with 401
}
}
return auth;
}
export async function uploadToDrive(auth: Auth.OAuth2Client, fileName: string, content: string, folderId?: string) {
2026-03-12 17:09:22 -05:00
const drive = google.drive({ version: 'v3', auth });
const fileMetadata: { name: string; mimeType: string; parents?: string[] } = {
2026-03-12 17:09:22 -05:00
name: fileName,
mimeType: 'application/vnd.google-apps.document', // Automatically convert to Google Doc
};
if (folderId) {
fileMetadata.parents = [folderId];
}
const media = {
2026-03-13 16:16:59 -05:00
mimeType: 'text/html',
2026-03-12 17:09:22 -05:00
body: Readable.from([content]),
};
try {
const response = await drive.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id, webViewLink'
});
return response.data;
} catch (error) {
console.error('Error uploading to Google Drive:', error);
throw error;
}
}
export async function updateDriveFile(auth: Auth.OAuth2Client, fileId: string, content: string) {
2026-03-13 11:13:45 -05:00
const drive = google.drive({ version: 'v3', auth });
const media = {
2026-03-13 16:16:59 -05:00
mimeType: 'text/html',
2026-03-13 11:13:45 -05:00
body: Readable.from([content]),
};
try {
const response = await drive.files.update({
fileId,
media,
fields: 'id, webViewLink',
});
return response.data;
} catch (error) {
console.error('Error updating Google Drive file:', error);
throw error;
}
}
function escapeHtml(value: unknown): string {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Only allow plain http(s) URLs into href attributes
function safeLink(link: unknown): string | null {
const url = String(link ?? '').trim();
return /^https?:\/\//i.test(url) ? url : null;
}
export function generateReportHTML(report: ReportWithRelations) {
2026-03-13 16:16:59 -05:00
const dateObj = new Date(report.date);
const dateStr = dateObj.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
const plannedTasks = report.tasks.filter((t) => t.type === 'PLANNED');
const completedTasks = report.tasks.filter((t) => t.type === 'COMPLETED');
2026-03-13 16:16:59 -05:00
const cellStyle = "padding: 10px; border-bottom: 1px solid #e2e8f0; font-family: Arial, sans-serif; font-size: 11pt;";
const headerStyle = "padding: 12px 10px; background-color: #f1f5f9; border-bottom: 2px solid #cbd5e1; font-family: Arial, sans-serif; font-size: 11pt; font-weight: bold; text-align: left; color: #334155;";
return `
<html>
<body style="font-family: Arial, sans-serif; color: #334155; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px;">
<h1 style="color: #0f172a; border-bottom: 3px solid #3b82f6; padding-bottom: 10px; font-family: Arial, sans-serif; margin-bottom: 20px;">WFH Daily Report</h1>
<div style="background-color: #f8fafc; padding: 20px; border-left: 4px solid #3b82f6; border-radius: 4px; margin-bottom: 30px; font-family: Arial, sans-serif;">
<p style="margin: 0 0 8px 0; font-size: 11pt;"><strong>Date:</strong> ${dateStr}</p>
<p style="margin: 0 0 8px 0; font-size: 11pt;"><strong>Employee:</strong> ${escapeHtml(report.user.name)}</p>
<p style="margin: 0; font-size: 11pt;"><strong>Manager:</strong> ${escapeHtml(report.managerName || 'N/A')}</p>
2026-03-13 16:16:59 -05:00
</div>
<h2 style="color: #1e293b; margin-top: 30px; margin-bottom: 15px; font-family: Arial, sans-serif;">Planned Tasks</h2>
${plannedTasks.length > 0 ? `
<table style="width: 100%; border-collapse: collapse; margin-bottom: 30px;">
<tr>
<th style="${headerStyle} width: 45%;">Description</th>
<th style="${headerStyle} width: 20%;">Estimate</th>
<th style="${headerStyle} width: 35%;">Notes</th>
</tr>
${plannedTasks.map((t) => `
2026-03-13 16:16:59 -05:00
<tr>
<td style="${cellStyle}">${escapeHtml(t.description)}</td>
<td style="${cellStyle} color: #64748b;">${escapeHtml(t.timeEstimate || '-')}</td>
<td style="${cellStyle} color: #64748b;">${escapeHtml(t.notes || '-')}</td>
2026-03-13 16:16:59 -05:00
</tr>
`).join('')}
</table>
` : `<p style="font-style: italic; color: #94a3b8; font-family: Arial, sans-serif; margin-bottom: 30px;">No planned tasks for today.</p>`}
<h2 style="color: #1e293b; margin-top: 30px; margin-bottom: 15px; font-family: Arial, sans-serif;">Completed Tasks</h2>
${completedTasks.length > 0 ? `
<table style="width: 100%; border-collapse: collapse; margin-bottom: 30px;">
<tr>
<th style="${headerStyle} width: 40%;">Description</th>
<th style="${headerStyle} width: 20%;">Status</th>
<th style="${headerStyle} width: 40%;">Work Link</th>
</tr>
${completedTasks.map((t) => {
const link = safeLink(t.link);
return `
2026-03-13 16:16:59 -05:00
<tr>
<td style="${cellStyle}">${escapeHtml(t.description)}</td>
<td style="${cellStyle} font-weight: bold; color: #059669;">${escapeHtml(t.status || 'Done')}</td>
<td style="${cellStyle}">${link ? `<a href="${escapeHtml(link)}" style="color: #2563eb; text-decoration: none;">${escapeHtml(link)}</a>` : '-'}</td>
2026-03-13 16:16:59 -05:00
</tr>
`;
}).join('')}
2026-03-13 16:16:59 -05:00
</table>
` : `<p style="font-style: italic; color: #94a3b8; font-family: Arial, sans-serif; margin-bottom: 30px;">No completed tasks reported today.</p>`}
<div style="margin-top: 50px; font-size: 9pt; color: #cbd5e1; text-align: center; border-top: 1px solid #e2e8f0; padding-top: 20px; font-family: Arial, sans-serif;">
Generated automatically by WFH App
</div>
</body>
</html>
`;
2026-03-12 17:09:22 -05:00
}