Archived
feat: add recurring invoices, public links, time tracker, payments, reminders
- Recurring invoices: schedule-based auto-generation with CRUD UI at /dashboard/invoices/recurring and POST /api/cron/generate-recurring cron endpoint - Public invoice link: generate/revoke shareable /i/[token] page for unauthenticated clients with PDF download - Live time tracker: localStorage-persisted timer widget in invoice editor that appends a line item on stop (rounds to nearest 0.25h) - Partial payment tracking: record payments per invoice, auto-mark paid when fully covered, balance due display - Send reminder: email reminder via Resend with custom message dialog and last-sent indicator Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -6,13 +6,10 @@ import { emailRouter } from "~/server/api/routers/email";
|
||||
import { dashboardRouter } from "~/server/api/routers/dashboard";
|
||||
import { expensesRouter } from "~/server/api/routers/expenses";
|
||||
import { invoiceTemplatesRouter } from "~/server/api/routers/invoiceTemplates";
|
||||
import { paymentsRouter } from "~/server/api/routers/payments";
|
||||
import { recurringInvoicesRouter } from "~/server/api/routers/recurring-invoices";
|
||||
import { createCallerFactory, createTRPCRouter } from "~/server/api/trpc";
|
||||
|
||||
/**
|
||||
* This is the primary router for your server.
|
||||
*
|
||||
* All routers added in /api/routers should be manually added here.
|
||||
*/
|
||||
export const appRouter = createTRPCRouter({
|
||||
clients: clientsRouter,
|
||||
businesses: businessesRouter,
|
||||
@@ -22,6 +19,8 @@ export const appRouter = createTRPCRouter({
|
||||
dashboard: dashboardRouter,
|
||||
expenses: expensesRouter,
|
||||
invoiceTemplates: invoiceTemplatesRouter,
|
||||
payments: paymentsRouter,
|
||||
recurringInvoices: recurringInvoicesRouter,
|
||||
});
|
||||
|
||||
// export type definition of API
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { desc, eq, inArray } from "drizzle-orm";
|
||||
import { createTRPCRouter, protectedProcedure } from "../trpc";
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
|
||||
import {
|
||||
invoices,
|
||||
invoiceItems,
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
} from "~/server/db/schema";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { generateInvoicePDFBlob } from "~/lib/pdf-export";
|
||||
import { Resend } from "resend";
|
||||
import { env } from "~/env";
|
||||
import { generateReminderEmailTemplate } from "~/lib/email-templates/reminder-email";
|
||||
import type { db } from "~/server/db";
|
||||
|
||||
type InvoiceRouterContext = {
|
||||
@@ -626,4 +629,128 @@ export const invoicesRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
// ── Public token (shareable link) ──────────────────────────────────────────
|
||||
|
||||
generatePublicToken: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, input.id),
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
const token = crypto.randomUUID();
|
||||
await ctx.db
|
||||
.update(invoices)
|
||||
.set({ publicToken: token })
|
||||
.where(eq(invoices.id, input.id));
|
||||
return { token };
|
||||
}),
|
||||
|
||||
revokePublicToken: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, input.id),
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
await ctx.db
|
||||
.update(invoices)
|
||||
.set({ publicToken: null })
|
||||
.where(eq(invoices.id, input.id));
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
getByPublicToken: publicProcedure
|
||||
.input(z.object({ token: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.publicToken, input.token),
|
||||
with: { client: true, business: true, items: { orderBy: (i, { asc }) => [asc(i.position)] } },
|
||||
});
|
||||
if (!invoice) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
return invoice;
|
||||
}),
|
||||
|
||||
// ── Send reminder ──────────────────────────────────────────────────────────
|
||||
|
||||
sendReminder: protectedProcedure
|
||||
.input(z.object({ id: z.string(), customMessage: z.string().optional() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, input.id),
|
||||
with: { client: true, business: true },
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
if (!invoice.client?.email) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Client has no email address" });
|
||||
}
|
||||
|
||||
const userName =
|
||||
invoice.business?.emailFromName ?? invoice.business?.name ?? ctx.session.user.name ?? "";
|
||||
const userEmail = invoice.business?.email ?? ctx.session.user.email ?? "";
|
||||
|
||||
const { html, text, subject } = generateReminderEmailTemplate({
|
||||
invoice: {
|
||||
invoiceNumber: invoice.invoiceNumber,
|
||||
issueDate: invoice.issueDate,
|
||||
dueDate: invoice.dueDate,
|
||||
totalAmount: invoice.totalAmount,
|
||||
currency: invoice.currency,
|
||||
client: { name: invoice.client.name, email: invoice.client.email },
|
||||
business: invoice.business,
|
||||
},
|
||||
customMessage: input.customMessage,
|
||||
userName,
|
||||
userEmail,
|
||||
});
|
||||
|
||||
// Resolve Resend instance (same two-tier logic as email router)
|
||||
let resendInstance: Resend;
|
||||
let fromEmail: string;
|
||||
if (invoice.business?.resendApiKey && invoice.business?.resendDomain) {
|
||||
resendInstance = new Resend(invoice.business.resendApiKey);
|
||||
const fromName = invoice.business.emailFromName ?? invoice.business.name;
|
||||
fromEmail = `${fromName} <noreply@${invoice.business.resendDomain}>`;
|
||||
} else if (env.RESEND_API_KEY && env.RESEND_DOMAIN) {
|
||||
resendInstance = new Resend(env.RESEND_API_KEY);
|
||||
fromEmail = `noreply@${env.RESEND_DOMAIN}`;
|
||||
} else if (env.RESEND_API_KEY) {
|
||||
resendInstance = new Resend(env.RESEND_API_KEY);
|
||||
fromEmail = invoice.business?.email ?? "noreply@example.com";
|
||||
} else {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Email delivery is not configured. Add a Resend API key.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = await resendInstance.emails.send({
|
||||
from: fromEmail,
|
||||
to: [invoice.client.email],
|
||||
subject,
|
||||
html,
|
||||
text,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: result.error.message,
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
.update(invoices)
|
||||
.set({ lastReminderSentAt: new Date() })
|
||||
.where(eq(invoices.id, input.id));
|
||||
|
||||
return { sent: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { z } from "zod";
|
||||
import { eq, sum } from "drizzle-orm";
|
||||
import { createTRPCRouter, protectedProcedure } from "../trpc";
|
||||
import { invoicePayments, invoices } from "~/server/db/schema";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const PAYMENT_METHODS = ["cash", "check", "bank_transfer", "credit_card", "paypal", "other"] as const;
|
||||
|
||||
export const paymentsRouter = createTRPCRouter({
|
||||
getByInvoice: protectedProcedure
|
||||
.input(z.object({ invoiceId: z.string() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, input.invoiceId),
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
return ctx.db.query.invoicePayments.findMany({
|
||||
where: eq(invoicePayments.invoiceId, input.invoiceId),
|
||||
orderBy: (p, { desc }) => [desc(p.date)],
|
||||
});
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
invoiceId: z.string(),
|
||||
amount: z.number().positive(),
|
||||
date: z.date(),
|
||||
method: z.enum(PAYMENT_METHODS).default("other"),
|
||||
notes: z.string().max(500).optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, input.invoiceId),
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
await ctx.db.insert(invoicePayments).values({
|
||||
invoiceId: input.invoiceId,
|
||||
amount: input.amount,
|
||||
currency: invoice.currency,
|
||||
date: input.date,
|
||||
method: input.method,
|
||||
notes: input.notes ?? null,
|
||||
createdById: ctx.session.user.id,
|
||||
});
|
||||
|
||||
// Auto-mark paid if total payments >= invoice total
|
||||
const [totals] = await ctx.db
|
||||
.select({ paid: sum(invoicePayments.amount) })
|
||||
.from(invoicePayments)
|
||||
.where(eq(invoicePayments.invoiceId, input.invoiceId));
|
||||
|
||||
const totalPaid = Number(totals?.paid ?? 0);
|
||||
if (totalPaid >= invoice.totalAmount && invoice.status !== "paid") {
|
||||
await ctx.db
|
||||
.update(invoices)
|
||||
.set({ status: "paid" })
|
||||
.where(eq(invoices.id, input.invoiceId));
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const payment = await ctx.db.query.invoicePayments.findFirst({
|
||||
where: eq(invoicePayments.id, input.id),
|
||||
});
|
||||
if (!payment) throw new TRPCError({ code: "NOT_FOUND" });
|
||||
|
||||
const invoice = await ctx.db.query.invoices.findFirst({
|
||||
where: eq(invoices.id, payment.invoiceId),
|
||||
});
|
||||
if (invoice?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
|
||||
await ctx.db.delete(invoicePayments).where(eq(invoicePayments.id, input.id));
|
||||
|
||||
// Re-check paid status after deletion
|
||||
const [totals] = await ctx.db
|
||||
.select({ paid: sum(invoicePayments.amount) })
|
||||
.from(invoicePayments)
|
||||
.where(eq(invoicePayments.invoiceId, payment.invoiceId));
|
||||
|
||||
const totalPaid = Number(totals?.paid ?? 0);
|
||||
if (totalPaid < invoice.totalAmount && invoice.status === "paid") {
|
||||
await ctx.db
|
||||
.update(invoices)
|
||||
.set({ status: "sent" })
|
||||
.where(eq(invoices.id, payment.invoiceId));
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { z } from "zod";
|
||||
import { and, eq, lte } from "drizzle-orm";
|
||||
import { createTRPCRouter, protectedProcedure } from "../trpc";
|
||||
import {
|
||||
recurringInvoices,
|
||||
recurringInvoiceItems,
|
||||
invoices,
|
||||
invoiceItems,
|
||||
clients,
|
||||
businesses,
|
||||
} from "~/server/db/schema";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import type { db as DbType } from "~/server/db";
|
||||
|
||||
export function nextDueDate(schedule: string, from = new Date()): Date {
|
||||
const d = new Date(from);
|
||||
switch (schedule) {
|
||||
case "weekly": d.setDate(d.getDate() + 7); break;
|
||||
case "biweekly": d.setDate(d.getDate() + 14); break;
|
||||
case "monthly": d.setMonth(d.getMonth() + 1); break;
|
||||
case "quarterly": d.setMonth(d.getMonth() + 3); break;
|
||||
case "yearly": d.setFullYear(d.getFullYear() + 1); break;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
type RecurringWithItems = typeof recurringInvoices.$inferSelect & {
|
||||
items: (typeof recurringInvoiceItems.$inferSelect)[];
|
||||
};
|
||||
|
||||
export async function generateInvoiceFromRecurring(
|
||||
db: typeof DbType,
|
||||
recurring: RecurringWithItems,
|
||||
): Promise<{ id: string }> {
|
||||
const now = new Date();
|
||||
const invoiceNumber = `REC-${Date.now()}`;
|
||||
|
||||
const subtotal = recurring.items.reduce((s, i) => s + i.hours * i.rate, 0);
|
||||
const taxAmount = (subtotal * recurring.taxRate) / 100;
|
||||
const total = subtotal + taxAmount;
|
||||
|
||||
const [newInvoice] = await db
|
||||
.insert(invoices)
|
||||
.values({
|
||||
invoiceNumber,
|
||||
invoicePrefix: recurring.invoicePrefix ?? "#",
|
||||
clientId: recurring.clientId,
|
||||
businessId: recurring.businessId ?? null,
|
||||
issueDate: now,
|
||||
dueDate: nextDueDate("monthly", now),
|
||||
status: "draft",
|
||||
totalAmount: total,
|
||||
taxRate: recurring.taxRate,
|
||||
notes: recurring.notes ?? null,
|
||||
emailMessage: recurring.emailMessage ?? null,
|
||||
currency: recurring.currency,
|
||||
createdById: recurring.createdById,
|
||||
})
|
||||
.returning({ id: invoices.id });
|
||||
|
||||
if (!newInvoice) throw new Error("Failed to create invoice");
|
||||
|
||||
if (recurring.items.length > 0) {
|
||||
await db.insert(invoiceItems).values(
|
||||
recurring.items.map((item, idx) => ({
|
||||
invoiceId: newInvoice.id,
|
||||
date: now,
|
||||
description: item.description,
|
||||
hours: item.hours,
|
||||
rate: item.rate,
|
||||
amount: item.hours * item.rate,
|
||||
position: item.position ?? idx,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return newInvoice;
|
||||
}
|
||||
|
||||
export async function generateDueRecurringInvoices(db: typeof DbType): Promise<number> {
|
||||
const now = new Date();
|
||||
const due = await db.query.recurringInvoices.findMany({
|
||||
where: and(
|
||||
eq(recurringInvoices.status, "active"),
|
||||
lte(recurringInvoices.nextDueAt, now),
|
||||
),
|
||||
with: { items: true },
|
||||
});
|
||||
|
||||
let generated = 0;
|
||||
for (const rec of due) {
|
||||
try {
|
||||
await generateInvoiceFromRecurring(db, rec);
|
||||
await db
|
||||
.update(recurringInvoices)
|
||||
.set({ lastGeneratedAt: now, nextDueAt: nextDueDate(rec.schedule, now) })
|
||||
.where(eq(recurringInvoices.id, rec.id));
|
||||
generated++;
|
||||
} catch {
|
||||
// continue on individual failures
|
||||
}
|
||||
}
|
||||
return generated;
|
||||
}
|
||||
|
||||
const scheduleEnum = z.enum(["weekly", "biweekly", "monthly", "quarterly", "yearly"]);
|
||||
|
||||
const recurringItemSchema = z.object({
|
||||
description: z.string().min(1),
|
||||
hours: z.number().min(0),
|
||||
rate: z.number().min(0),
|
||||
position: z.number().int().default(0),
|
||||
});
|
||||
|
||||
const recurringInvoiceSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
clientId: z.string().min(1),
|
||||
businessId: z.string().optional().or(z.literal("")),
|
||||
schedule: scheduleEnum,
|
||||
invoicePrefix: z.string().optional().default("#"),
|
||||
taxRate: z.number().min(0).max(100).default(0),
|
||||
currency: z.string().length(3).default("USD"),
|
||||
notes: z.string().optional().or(z.literal("")),
|
||||
emailMessage: z.string().optional().or(z.literal("")),
|
||||
items: z.array(recurringItemSchema).min(1),
|
||||
});
|
||||
|
||||
export const recurringInvoicesRouter = createTRPCRouter({
|
||||
getAll: protectedProcedure.query(async ({ ctx }) => {
|
||||
return ctx.db.query.recurringInvoices.findMany({
|
||||
where: eq(recurringInvoices.createdById, ctx.session.user.id),
|
||||
with: { client: true, business: true, items: true },
|
||||
orderBy: (r, { asc }) => [asc(r.nextDueAt)],
|
||||
});
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(recurringInvoiceSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const client = await ctx.db.query.clients.findFirst({
|
||||
where: eq(clients.id, input.clientId),
|
||||
});
|
||||
if (client?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Client not found" });
|
||||
}
|
||||
if (input.businessId) {
|
||||
const biz = await ctx.db.query.businesses.findFirst({
|
||||
where: eq(businesses.id, input.businessId),
|
||||
});
|
||||
if (biz?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Business not found" });
|
||||
}
|
||||
}
|
||||
|
||||
const [rec] = await ctx.db
|
||||
.insert(recurringInvoices)
|
||||
.values({
|
||||
name: input.name,
|
||||
clientId: input.clientId,
|
||||
businessId: input.businessId ?? null,
|
||||
schedule: input.schedule,
|
||||
status: "active",
|
||||
invoicePrefix: input.invoicePrefix,
|
||||
taxRate: input.taxRate,
|
||||
currency: input.currency,
|
||||
notes: input.notes ?? null,
|
||||
emailMessage: input.emailMessage ?? null,
|
||||
nextDueAt: nextDueDate(input.schedule),
|
||||
createdById: ctx.session.user.id,
|
||||
})
|
||||
.returning({ id: recurringInvoices.id });
|
||||
|
||||
if (!rec) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
|
||||
await ctx.db.insert(recurringInvoiceItems).values(
|
||||
input.items.map((item, idx) => ({
|
||||
recurringInvoiceId: rec.id,
|
||||
description: item.description,
|
||||
hours: item.hours,
|
||||
rate: item.rate,
|
||||
position: item.position ?? idx,
|
||||
})),
|
||||
);
|
||||
|
||||
return rec;
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
.input(recurringInvoiceSchema.extend({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db.query.recurringInvoices.findFirst({
|
||||
where: eq(recurringInvoices.id, input.id),
|
||||
});
|
||||
if (existing?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
.update(recurringInvoices)
|
||||
.set({
|
||||
name: input.name,
|
||||
clientId: input.clientId,
|
||||
businessId: input.businessId ?? null,
|
||||
schedule: input.schedule,
|
||||
invoicePrefix: input.invoicePrefix,
|
||||
taxRate: input.taxRate,
|
||||
currency: input.currency,
|
||||
notes: input.notes ?? null,
|
||||
emailMessage: input.emailMessage ?? null,
|
||||
})
|
||||
.where(eq(recurringInvoices.id, input.id));
|
||||
|
||||
await ctx.db
|
||||
.delete(recurringInvoiceItems)
|
||||
.where(eq(recurringInvoiceItems.recurringInvoiceId, input.id));
|
||||
|
||||
await ctx.db.insert(recurringInvoiceItems).values(
|
||||
input.items.map((item, idx) => ({
|
||||
recurringInvoiceId: input.id,
|
||||
description: item.description,
|
||||
hours: item.hours,
|
||||
rate: item.rate,
|
||||
position: item.position ?? idx,
|
||||
})),
|
||||
);
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
pause: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const rec = await ctx.db.query.recurringInvoices.findFirst({
|
||||
where: eq(recurringInvoices.id, input.id),
|
||||
});
|
||||
if (rec?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
await ctx.db
|
||||
.update(recurringInvoices)
|
||||
.set({ status: "paused" })
|
||||
.where(eq(recurringInvoices.id, input.id));
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
resume: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const rec = await ctx.db.query.recurringInvoices.findFirst({
|
||||
where: eq(recurringInvoices.id, input.id),
|
||||
});
|
||||
if (rec?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
await ctx.db
|
||||
.update(recurringInvoices)
|
||||
.set({ status: "active" })
|
||||
.where(eq(recurringInvoices.id, input.id));
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
delete: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const rec = await ctx.db.query.recurringInvoices.findFirst({
|
||||
where: eq(recurringInvoices.id, input.id),
|
||||
});
|
||||
if (rec?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
await ctx.db
|
||||
.delete(recurringInvoices)
|
||||
.where(eq(recurringInvoices.id, input.id));
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
generateNow: protectedProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const rec = await ctx.db.query.recurringInvoices.findFirst({
|
||||
where: eq(recurringInvoices.id, input.id),
|
||||
with: { items: true },
|
||||
});
|
||||
if (rec?.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const newInvoice = await generateInvoiceFromRecurring(ctx.db, rec);
|
||||
|
||||
await ctx.db
|
||||
.update(recurringInvoices)
|
||||
.set({ lastGeneratedAt: new Date(), nextDueAt: nextDueDate(rec.schedule) })
|
||||
.where(eq(recurringInvoices.id, input.id));
|
||||
|
||||
return { invoiceId: newInvoice.id };
|
||||
}),
|
||||
});
|
||||
@@ -87,6 +87,7 @@ export const usersRelations = relations(users, ({ many }) => ({
|
||||
sessions: many(sessions),
|
||||
expenses: many(expenses),
|
||||
invoiceTemplates: many(invoiceTemplates),
|
||||
recurringInvoices: many(recurringInvoices),
|
||||
}));
|
||||
|
||||
export const accounts = createTable(
|
||||
@@ -326,6 +327,8 @@ export const invoices = createTable(
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
publicToken: d.varchar({ length: 255 }).unique(),
|
||||
lastReminderSentAt: d.timestamp(),
|
||||
createdAt: d
|
||||
.timestamp()
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
@@ -338,6 +341,7 @@ export const invoices = createTable(
|
||||
index("invoice_created_by_idx").on(t.createdById),
|
||||
index("invoice_number_idx").on(t.invoiceNumber),
|
||||
index("invoice_status_idx").on(t.status),
|
||||
index("invoice_public_token_idx").on(t.publicToken),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -355,6 +359,7 @@ export const invoicesRelations = relations(invoices, ({ one, many }) => ({
|
||||
references: [users.id],
|
||||
}),
|
||||
items: many(invoiceItems),
|
||||
payments: many(invoicePayments),
|
||||
}));
|
||||
|
||||
export const invoiceItems = createTable(
|
||||
@@ -491,3 +496,149 @@ export const invoiceTemplatesRelations = relations(
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// ─── Invoice Payments ────────────────────────────────────────────────────────
|
||||
|
||||
export const invoicePayments = createTable(
|
||||
"invoice_payment",
|
||||
(d) => ({
|
||||
id: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
invoiceId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => invoices.id, { onDelete: "cascade" }),
|
||||
amount: d.real().notNull(),
|
||||
currency: d.varchar({ length: 3 }).default("USD").notNull(),
|
||||
date: d.timestamp().notNull(),
|
||||
method: d
|
||||
.varchar({ length: 50 })
|
||||
.notNull()
|
||||
.default("other"), // cash | check | bank_transfer | credit_card | paypal | other
|
||||
notes: d.varchar({ length: 500 }),
|
||||
createdById: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
createdAt: d
|
||||
.timestamp()
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
}),
|
||||
(t) => [
|
||||
index("invoice_payment_invoice_id_idx").on(t.invoiceId),
|
||||
index("invoice_payment_created_by_idx").on(t.createdById),
|
||||
],
|
||||
);
|
||||
|
||||
export const invoicePaymentsRelations = relations(invoicePayments, ({ one }) => ({
|
||||
invoice: one(invoices, {
|
||||
fields: [invoicePayments.invoiceId],
|
||||
references: [invoices.id],
|
||||
}),
|
||||
createdBy: one(users, {
|
||||
fields: [invoicePayments.createdById],
|
||||
references: [users.id],
|
||||
}),
|
||||
}));
|
||||
|
||||
// ─── Recurring Invoices ───────────────────────────────────────────────────────
|
||||
|
||||
export const recurringInvoices = createTable(
|
||||
"recurring_invoice",
|
||||
(d) => ({
|
||||
id: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
name: d.varchar({ length: 255 }).notNull(),
|
||||
clientId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => clients.id),
|
||||
businessId: d.varchar({ length: 255 }).references(() => businesses.id),
|
||||
schedule: d.varchar({ length: 20 }).notNull().default("monthly"), // weekly | biweekly | monthly | quarterly | yearly
|
||||
status: d.varchar({ length: 20 }).notNull().default("active"), // active | paused
|
||||
invoicePrefix: d.varchar({ length: 20 }).default("#"),
|
||||
taxRate: d.real().notNull().default(0),
|
||||
currency: d.varchar({ length: 3 }).default("USD").notNull(),
|
||||
notes: d.varchar({ length: 1000 }),
|
||||
emailMessage: d.varchar({ length: 2000 }),
|
||||
nextDueAt: d.timestamp().notNull(),
|
||||
lastGeneratedAt: d.timestamp(),
|
||||
createdById: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
createdAt: d
|
||||
.timestamp()
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
updatedAt: d.timestamp().$onUpdate(() => new Date()),
|
||||
}),
|
||||
(t) => [
|
||||
index("recurring_invoice_created_by_idx").on(t.createdById),
|
||||
index("recurring_invoice_client_id_idx").on(t.clientId),
|
||||
index("recurring_invoice_status_idx").on(t.status),
|
||||
index("recurring_invoice_next_due_idx").on(t.nextDueAt),
|
||||
],
|
||||
);
|
||||
|
||||
export const recurringInvoicesRelations = relations(
|
||||
recurringInvoices,
|
||||
({ one, many }) => ({
|
||||
client: one(clients, {
|
||||
fields: [recurringInvoices.clientId],
|
||||
references: [clients.id],
|
||||
}),
|
||||
business: one(businesses, {
|
||||
fields: [recurringInvoices.businessId],
|
||||
references: [businesses.id],
|
||||
}),
|
||||
createdBy: one(users, {
|
||||
fields: [recurringInvoices.createdById],
|
||||
references: [users.id],
|
||||
}),
|
||||
items: many(recurringInvoiceItems),
|
||||
}),
|
||||
);
|
||||
|
||||
export const recurringInvoiceItems = createTable(
|
||||
"recurring_invoice_item",
|
||||
(d) => ({
|
||||
id: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
recurringInvoiceId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => recurringInvoices.id, { onDelete: "cascade" }),
|
||||
description: d.varchar({ length: 500 }).notNull(),
|
||||
hours: d.real().notNull(),
|
||||
rate: d.real().notNull(),
|
||||
position: d.integer().notNull().default(0),
|
||||
createdAt: d
|
||||
.timestamp()
|
||||
.default(sql`CURRENT_TIMESTAMP`)
|
||||
.notNull(),
|
||||
}),
|
||||
(t) => [
|
||||
index("recurring_invoice_item_recurring_id_idx").on(t.recurringInvoiceId),
|
||||
],
|
||||
);
|
||||
|
||||
export const recurringInvoiceItemsRelations = relations(
|
||||
recurringInvoiceItems,
|
||||
({ one }) => ({
|
||||
recurringInvoice: one(recurringInvoices, {
|
||||
fields: [recurringInvoiceItems.recurringInvoiceId],
|
||||
references: [recurringInvoices.id],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user