All files / services/import materialize.service.ts

98.14% Statements 53/54
86.48% Branches 32/37
100% Functions 2/2
100% Lines 49/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219                                                                                                                                          1x             1x             8x               8x 8x 14x 14x 13x 13x 13x   8x 5x       5x       8x 8x   8x 7x 6x 6x 1x 1x       5x                     5x 1x 1x     4x 4x                                     4x               4x 7x 1x 1x       3x 3x 6x 6x   5x 6x 6x 6x 6x 5x 2x       2x     3x                       3x     3x       8x               8x    
/**
 * Materialize an approved pro-import into live `pros`/`projects`/`rooms`/`media`.
 *
 * D1 has no transactions (see api/CLAUDE.md). Writes are sequential and
 * ordered so a mid-flight failure leaves a recoverable partial state:
 *
 *   1. Profile patch on `pros` (selected fields only)
 *   2. For each included project:
 *        a. Insert `projects` row (status='draft', sourceImportId, sourceUrl)
 *        b. Insert one default `rooms` row (roomType='other', isDefault=true)
 *        c. For each selected photo: copy R2 object from
 *           `imports/{importId}/images/{relPath}` to
 *           `{proId}/projects/{projectId}/{photoId}.{ext}`, then insert media row
 *   3. Stamp `pro_imports.approvedAt`/`approvedBy`
 *
 * A failure anywhere does NOT undo prior writes; the next approve retry
 * skips already-materialized projects via `(proId, sourceImportId, slug)`
 * dedupe lookup so the operation is idempotent.
 */
 
import { and, eq } from "drizzle-orm";
import type { getDb } from "../../db";
import * as schema from "../../db/schema";
import { copyImportImage, imageKey } from "../../import-agent/r2-artifact";
import type {
	ScrapedProData,
	ScrapedProject,
} from "../../import-agent/scraped-data";
 
export interface ProfileSelection {
	/** Field names from ScrapedProfile to write onto `pros`. */
	fields: string[];
}
 
export interface ProjectSelection {
	scrapedSlug: string;
	include: boolean;
	/** photo.file paths (relative to imports/{id}/images/) to include. */
	photos: string[];
	overrides?: Partial<{
		title: string;
		description: string;
	}>;
}
 
export interface MaterializeSelection {
	profile: ProfileSelection;
	projects: ProjectSelection[];
}
 
export interface MaterializeInput {
	importId: string;
	proId: string;
	approvedBy: string;
	data: ScrapedProData;
	selection: MaterializeSelection;
}
 
export interface MaterializeEnv {
	R2: R2Bucket;
}
 
export interface MaterializeResult {
	profileFieldsApplied: number;
	projectsCreated: number;
	photosCopied: number;
	skipped: { reason: string; slug: string }[];
}
 
const SCRAPED_TO_PRO_FIELD: Record<string, keyof typeof schema.pros.$inferInsert> = {
	tagline: "tagline",
	about: "description",
	whatsapp: "whatsapp",
	email: "email",
};
 
const DEFAULT_ROOM_TYPE = "other";
 
export async function materializeImport(
	input: MaterializeInput,
	env: MaterializeEnv,
	db: ReturnType<typeof getDb>,
): Promise<MaterializeResult> {
	const result: MaterializeResult = {
		profileFieldsApplied: 0,
		projectsCreated: 0,
		photosCopied: 0,
		skipped: [],
	};
 
	// 1. Profile patch
	const profilePatch: Record<string, unknown> = {};
	for (const field of input.selection.profile.fields) {
		const target = SCRAPED_TO_PRO_FIELD[field];
		if (!target) continue;
		const value = (input.data.pro as unknown as Record<string, unknown>)[field];
		Iif (value === undefined || value === null || value === "") continue;
		profilePatch[target] = value;
	}
	if (Object.keys(profilePatch).length > 0) {
		await db
			.update(schema.pros)
			.set(profilePatch)
			.where(eq(schema.pros.id, input.proId));
		result.profileFieldsApplied = Object.keys(profilePatch).length;
	}
 
	// 2. Projects
	const projectsBySlug = new Map<string, ScrapedProject>(
		input.data.projects.map((p) => [p.slug, p]),
	);
	for (const sel of input.selection.projects) {
		if (!sel.include) continue;
		const scraped = projectsBySlug.get(sel.scrapedSlug);
		if (!scraped) {
			result.skipped.push({ reason: "scraped_missing", slug: sel.scrapedSlug });
			continue;
		}
 
		// Idempotency: skip if already materialized for this import + slug.
		const existing = await db
			.select({ id: schema.projects.id })
			.from(schema.projects)
			.where(
				and(
					eq(schema.projects.proId, input.proId),
					eq(schema.projects.sourceImportId, input.importId),
					eq(schema.projects.slug, scraped.slug),
				),
			)
			.limit(1);
		if (existing.length > 0) {
			result.skipped.push({ reason: "already_materialized", slug: scraped.slug });
			continue;
		}
 
		const projectId = `prj_${crypto.randomUUID()}`;
		await db.insert(schema.projects).values({
			id: projectId,
			proId: input.proId,
			status: "draft",
			title: sel.overrides?.title ?? scraped.title,
			slug: scraped.slug,
			description: sel.overrides?.description ?? scraped.description,
			propertyType:
				scraped.propertyTypeRaw &&
				["apartment", "villa", "independent_house", "commercial"].includes(
					scraped.propertyTypeRaw.toLowerCase(),
				)
					? (scraped.propertyTypeRaw.toLowerCase() as never)
					: undefined,
			sourceImportId: input.importId,
			sourceUrl: scraped.photos[0]?.originalUrl ?? null,
		});
 
		// Default room
		const roomInsert = await db
			.insert(schema.rooms)
			.values({
				projectId,
				roomType: DEFAULT_ROOM_TYPE,
				isDefault: true,
			})
			.returning({ id: schema.rooms.id });
		const roomId = roomInsert[0]?.id;
		if (!roomId) {
			result.skipped.push({ reason: "room_insert_failed", slug: scraped.slug });
			continue;
		}
 
		// Photos
		const includedPhotos = new Set(sel.photos);
		for (let i = 0; i < scraped.photos.length; i++) {
			const photo = scraped.photos[i];
			if (!includedPhotos.has(photo.file)) continue;
 
			const ext = (photo.file.split(".").pop() ?? "jpg").toLowerCase();
			const photoId = crypto.randomUUID();
			const sourceKey = imageKey(input.importId, photo.file);
			const destKey = `${input.proId}/projects/${projectId}/${photoId}.${ext}`;
			const copied = await copyImportImage(env.R2, sourceKey, destKey);
			if (!copied) {
				result.skipped.push({
					reason: "r2_copy_failed",
					slug: `${scraped.slug}:${photo.file}`,
				});
				continue;
			}
 
			await db.insert(schema.media).values({
				roomId,
				mediaType: "image",
				filename: `${photoId}.${ext}`,
				storageKey: destKey,
				caption: photo.caption || null,
				sortOrder: i,
				isCover: photo.isCover,
				photoType: "after",
				sourceImportId: input.importId,
				sourceUrl: photo.originalUrl || null,
			});
			result.photosCopied++;
		}
 
		result.projectsCreated++;
	}
 
	// 3. Stamp approval on the import row
	await db
		.update(schema.proImports)
		.set({
			approvedAt: Date.now(),
			approvedBy: input.approvedBy,
		})
		.where(eq(schema.proImports.id, input.importId));
 
	return result;
}