open-swe-dev-andrinoid[bot] 9dd9520532 Apply patch [skip ci]
2026-01-22 21:32:58 +00:00

539 lines
19 KiB
TypeScript

// routes/landlord/properties/cleanup.tsx
import { define } from "../../../utils.ts";
import { page } from "fresh";
import { SessionCookie } from "../../auth/callback.ts";
import {
getLeasesByOwner,
getPropertiesByOwner,
} from "../../../services/propertyService.ts";
import { getMaintenanceDataByLandlord } from "../../../services/maintenanceRequestService.ts";
import { getTenantApplicationsByLandlord } from "../../../services/tenantApplicationService.ts";
import { mergeDuplicateProperty } from "../../../services/propertyMergeService.ts";
import { Property } from "../../../db/interfaces.ts";
interface PropertyStats {
leaseCount: number;
activeLeaseCount: number;
applicationCount: number;
maintenanceCount: number;
}
interface DuplicateGroup {
key: string;
label: string;
properties: Property[];
}
interface CleanupPageData {
stateData: SessionCookie;
properties: Property[];
duplicateGroups: DuplicateGroup[];
statsByPropertyId: Record<string, PropertyStats>;
success?: string;
error?: string;
}
function formatPropertyAddress(property: Property) {
const street = [property.address_1, property.address_2]
.filter(Boolean)
.join(" ")
.trim();
const cityState = [property.city, property.state]
.filter(Boolean)
.join(", ")
.trim();
const zip = property.zip?.trim() || "";
const region = [cityState, zip].filter(Boolean).join(" ").trim();
return [street, region].filter(Boolean).join(", ").trim();
}
function formatPropertyLabel(property: Property) {
const base = property.title || property.address_1 || "Property";
const location = [property.city, property.state].filter(Boolean).join(", ");
return location ? `${base} (${location})` : base;
}
function buildPropertyKey(property: Property) {
const parts = [
property.address_1,
property.city,
property.state,
property.zip,
]
.map((part) => part?.trim().toLowerCase())
.filter(Boolean);
if (parts.length === 0) return null;
return parts.join("|");
}
function buildDuplicateGroups(properties: Property[]) {
const groups = new Map<string, Property[]>();
for (const property of properties) {
const key = buildPropertyKey(property);
if (!key) continue;
const entry = groups.get(key) || [];
entry.push(property);
groups.set(key, entry);
}
return Array.from(groups.entries())
.filter(([, group]) => group.length > 1)
.map(([key, group]) => ({
key,
label: formatPropertyAddress(group[0]) || group[0].address_1 ||
"Possible duplicates",
properties: group,
}));
}
function buildStatsByPropertyId(
properties: Property[],
leases: { property_id?: string | null; lease_status?: string | null }[],
applications: { property_id?: string | null }[],
maintenance: { property_id?: string | null }[],
) {
const stats: Record<string, PropertyStats> = {};
for (const property of properties) {
stats[property.id] = {
leaseCount: 0,
activeLeaseCount: 0,
applicationCount: 0,
maintenanceCount: 0,
};
}
for (const lease of leases) {
const propertyId = lease.property_id || "";
if (!propertyId || !stats[propertyId]) continue;
stats[propertyId].leaseCount += 1;
if (lease.lease_status === "active") {
stats[propertyId].activeLeaseCount += 1;
}
}
for (const application of applications) {
const propertyId = application.property_id || "";
if (!propertyId || !stats[propertyId]) continue;
stats[propertyId].applicationCount += 1;
}
for (const request of maintenance) {
const propertyId = request.property_id || "";
if (!propertyId || !stats[propertyId]) continue;
stats[propertyId].maintenanceCount += 1;
}
return stats;
}
async function loadCleanupData(userId: string) {
const [properties, leases, maintenanceRequests, applications] = await Promise
.all([
getPropertiesByOwner(userId),
getLeasesByOwner(userId),
getMaintenanceDataByLandlord(userId),
getTenantApplicationsByLandlord(userId),
]);
const statsByPropertyId = buildStatsByPropertyId(
properties,
leases,
applications,
maintenanceRequests,
);
return {
properties,
duplicateGroups: buildDuplicateGroups(properties),
statsByPropertyId,
};
}
export const handler = define.handlers({
async GET(ctx) {
const stateData: SessionCookie = ctx.state.data;
const { user_id } = stateData;
if (!user_id) {
return new Response("", {
status: 302,
headers: { Location: "/auth/login" },
});
}
try {
const url = new URL(ctx.req.url);
const mergedCount = Number(url.searchParams.get("merged") || 0);
const canonicalId = url.searchParams.get("canonical") || "";
const { properties, duplicateGroups, statsByPropertyId } =
await loadCleanupData(user_id);
let success: string | undefined;
if (mergedCount > 0) {
const canonical = canonicalId
? properties.find((property) => property.id === canonicalId)
: null;
const canonicalLabel = canonical
? formatPropertyLabel(canonical)
: "selected property";
const noun = mergedCount === 1 ? "property" : "properties";
success =
`Merged ${mergedCount} duplicate ${noun} into ${canonicalLabel}.`;
}
return page({
stateData,
properties,
duplicateGroups,
statsByPropertyId,
success,
});
} catch (error) {
console.error("Error loading cleanup page:", error);
return page({
stateData,
properties: [],
duplicateGroups: [],
statsByPropertyId: {},
error: "Failed to load property cleanup data.",
});
}
},
async POST(ctx) {
const stateData: SessionCookie = ctx.state.data;
const { user_id } = stateData;
if (!user_id) {
return new Response("", {
status: 302,
headers: { Location: "/auth/login" },
});
}
try {
const formData = await ctx.req.formData();
const canonicalPropertyId =
formData.get("canonical_property_id")?.toString() || "";
const duplicatePropertyIds = formData
.getAll("duplicate_property_id")
.map((id) => id.toString())
.filter(Boolean)
.filter((id) => id !== canonicalPropertyId);
const uniqueDuplicateIds = Array.from(new Set(duplicatePropertyIds));
if (!canonicalPropertyId || uniqueDuplicateIds.length === 0) {
const cleanupData = await loadCleanupData(user_id);
return page({
stateData,
...cleanupData,
error:
"Select one canonical property and at least one duplicate to merge.",
});
}
const warnings: string[] = [];
for (const duplicateId of uniqueDuplicateIds) {
const result = await mergeDuplicateProperty(
canonicalPropertyId,
duplicateId,
user_id,
);
warnings.push(...result.warnings);
}
if (warnings.length > 0) {
console.warn("Property merge warnings:", warnings);
}
return new Response("", {
status: 303,
headers: {
Location:
`/landlord/properties/cleanup?merged=${uniqueDuplicateIds.length}&canonical=${canonicalPropertyId}`,
},
});
} catch (error) {
console.error("Error merging properties:", error);
const cleanupData = await loadCleanupData(user_id);
return page({
stateData,
...cleanupData,
error: "Failed to merge properties. Please try again.",
});
}
},
});
export default define.page(function LandlordPropertyCleanup({ data }) {
const {
properties,
duplicateGroups,
statsByPropertyId,
success,
error,
} = data as CleanupPageData;
const hasEnoughProperties = properties.length > 1;
return (
<div class="min-h-screen bg-gray-50">
<div class="bg-white shadow">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex flex-col gap-4 py-6 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 class="text-3xl font-bold text-gray-900">
Property Cleanup
</h1>
<p class="mt-1 text-sm text-gray-500">
Merge duplicate properties to keep your portfolio clean.
</p>
</div>
<div class="flex flex-wrap gap-3">
<a
href="/landlord/properties"
class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
>
Back to Properties
</a>
<a
href="/landlord/dashboard"
class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
>
Back to Dashboard
</a>
</div>
</div>
</div>
</div>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{success && (
<div class="mb-6 bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded">
{success}
</div>
)}
{error && (
<div class="mb-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
{error}
</div>
)}
{!hasEnoughProperties && (
<div class="bg-white shadow rounded-lg p-6">
<h2 class="text-lg font-semibold text-gray-900">
Add more properties to start cleaning duplicates
</h2>
<p class="mt-2 text-sm text-gray-500">
You need at least two properties before you can merge duplicates.
</p>
<div class="mt-4">
<a
href="/landlord/properties/add"
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
>
Add Property
</a>
</div>
</div>
)}
{hasEnoughProperties && (
<>
<div class="bg-white shadow rounded-lg p-6 mb-8">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 class="text-lg font-semibold text-gray-900">
Quick Duplicate Merge
</h2>
<p class="text-sm text-gray-500">
Suggested matches based on address details.
</p>
</div>
</div>
{duplicateGroups.length === 0 && (
<p class="mt-4 text-sm text-gray-500">
No obvious duplicates found. Use the manual merge section
below if needed.
</p>
)}
{duplicateGroups.map((group) => (
<form
key={group.key}
method="post"
class="mt-6 border border-gray-200 rounded-lg p-4"
>
<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div>
<p class="text-sm font-medium text-gray-900">
Possible duplicates: {group.label}
</p>
<p class="text-xs text-gray-500">
{group.properties.length} properties match this address.
</p>
</div>
<button class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
Merge Selected
</button>
</div>
<div class="grid grid-cols-1 gap-6 mt-4 lg:grid-cols-2">
<div>
<label class="block text-sm font-medium text-gray-700">
Keep this property
</label>
<select
name="canonical_property_id"
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
>
{group.properties.map((property) => (
<option key={property.id} value={property.id}>
{formatPropertyLabel(property)}
</option>
))}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">
Merge these duplicates
</label>
<p class="mt-1 text-xs text-gray-500">
Select the properties you want to merge into the
canonical record.
</p>
<div class="mt-3 space-y-3">
{group.properties.map((property) => {
const stats = statsByPropertyId[property.id];
return (
<label
key={property.id}
class="flex items-start gap-3"
>
<input
type="checkbox"
name="duplicate_property_id"
value={property.id}
class="mt-1 h-4 w-4 text-blue-600 border-gray-300 rounded"
/>
<div>
<p class="text-sm font-medium text-gray-900">
{formatPropertyLabel(property)}
</p>
<p class="text-xs text-gray-500">
ID: {property.id}
</p>
<p class="text-xs text-gray-500 mt-1">
Leases: {stats?.leaseCount || 0} (active
{` ${stats?.activeLeaseCount || 0}`}) |{" "}
Applications: {stats?.applicationCount || 0}
{" | "}
Maintenance: {stats?.maintenanceCount || 0}
</p>
</div>
</label>
);
})}
</div>
</div>
</div>
<p class="mt-4 text-xs text-gray-500">
Leases, rent schedules, applications, maintenance requests,
and media will be reassigned to the canonical property.
Selected duplicates are deleted afterward.
</p>
</form>
))}
</div>
<div class="bg-white shadow rounded-lg p-6">
<h2 class="text-lg font-semibold text-gray-900">
Manual Merge
</h2>
<p class="mt-1 text-sm text-gray-500">
Use this when duplicates are not automatically detected.
</p>
<form method="post" class="mt-6 space-y-6">
<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
<div>
<label class="block text-sm font-medium text-gray-700">
Keep this property
</label>
<select
name="canonical_property_id"
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
>
{properties.map((property) => (
<option key={property.id} value={property.id}>
{formatPropertyLabel(property)}
</option>
))}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">
Merge these duplicates
</label>
<p class="mt-1 text-xs text-gray-500">
Pick the duplicate properties to merge into the canonical
record.
</p>
<div class="mt-3 space-y-3 max-h-72 overflow-y-auto pr-2">
{properties.map((property) => {
const stats = statsByPropertyId[property.id];
return (
<label
key={property.id}
class="flex items-start gap-3"
>
<input
type="checkbox"
name="duplicate_property_id"
value={property.id}
class="mt-1 h-4 w-4 text-blue-600 border-gray-300 rounded"
/>
<div>
<p class="text-sm font-medium text-gray-900">
{formatPropertyLabel(property)}
</p>
<p class="text-xs text-gray-500">
ID: {property.id}
</p>
<p class="text-xs text-gray-500 mt-1">
Leases: {stats?.leaseCount || 0} (active
{` ${stats?.activeLeaseCount || 0}`}) |{" "}
Applications: {stats?.applicationCount || 0}
{" | "}
Maintenance: {stats?.maintenanceCount || 0}
</p>
</div>
</label>
);
})}
</div>
</div>
</div>
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p class="text-xs text-gray-500 max-w-xl">
Select the duplicates only. The canonical property stays and
absorbs the records from selected duplicates.
</p>
<button class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
Merge Selected
</button>
</div>
</form>
</div>
</>
)}
</div>
</div>
);
});