diff --git a/services/leaseService.ts b/services/leaseService.ts index 88b7387..3e93174 100644 --- a/services/leaseService.ts +++ b/services/leaseService.ts @@ -3,7 +3,7 @@ import { and, eq } from "drizzle-orm"; import { db } from "../db/db.ts"; -import { leases } from "../db/schema.ts"; +import { leases, tenant_invites } from "../db/schema.ts"; import { Lease } from "../db/interfaces.ts"; import { getE2ELeaseById, @@ -259,3 +259,52 @@ export async function getLeaseStatsByOwner(owner_id: string) { + + +/** + * Link a lease to a tenant invite. If an inviteId is provided, update that + * tenant_invites row to reference this lease. Otherwise attempt to find an + * existing invite by the lease's property and owner and attach the lease_id + * there; if none exists, create a new tenant_invites row linking to the lease. + */ +export async function inviteLease(lease_id: string, inviteId?: string) { + // If an explicit inviteId was provided, update that invite record + if (inviteId) { + const now = Date.now(); + return await db.update(tenant_invites) + .set({ lease_id, updated_on: now }) + .where(eq(tenant_invites.id, inviteId)) + .returning(); + } + + // Otherwise derive the property and landlord from the lease + const lease = await getLeaseById(lease_id); + if (!lease) return null; + + const existing = await db.select().from(tenant_invites).where( + and( + eq(tenant_invites.property_id, lease.property_id), + eq(tenant_invites.landlord_id, lease.owner_id), + ), + ); + + const now = Date.now(); + if (existing.length > 0) { + return await db.update(tenant_invites) + .set({ lease_id, updated_on: now }) + .where(eq(tenant_invites.id, existing[0].id)) + .returning(); + } + + // Create a new invite linking to this lease + return await db.insert(tenant_invites).values({ + id: crypto.randomUUID(), + landlord_id: lease.owner_id, + property_id: lease.property_id, + lease_id, + available_on: null, + invited_emails: JSON.stringify([]), + created_on: now, + updated_on: now, + }).returning(); +}