All files / routes/pro/website index.ts

100% Statements 58/58
100% Branches 43/43
100% Functions 3/3
100% Lines 58/58

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 220 221 222 223 224 225 226 227 228 229                                            13x 13x                                   1x                                     1x     1x 15x 15x 15x       15x           15x 1x     14x   14x   5x           5x 6x     6x 1x 1x           5x         5x 1x   4x         13x         13x 13x 13x             15x 15x 4x     4x 1x   3x       13x                         2x         1x         10x 10x 10x 1x     9x 9x 9x     9x   9x   2x   2x   2x                       7x 2x     2x 1x         6x                   8x   1x           1x 1x 1x      
// Pro Website Routes - Barrel: mounts sub-routers + basic website GET/settings routes
 
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import { BadRequestError, NotFoundError } from "../../../lib/errors";
import { error, handleError, success } from "../../../lib/response";
import { requireProAccess } from "../../../middleware";
import type { Services } from "../../../services";
import {
	resolveEnvironment,
	getProjectName,
	getPublishedDomain,
	getProSiteUrls,
} from "../../../lib/domain-utils";
import templateRoutes from "./templates.routes";
import domainRoutes from "./domain.routes";
import publishRoutes from "./publish.routes";
 
// Adapter: convert CloudflareBindings to domain-utils parameters
function getUrls(slug: string | null, env: CloudflareBindings) {
	const resolvedEnv = resolveEnvironment(env.ENVIRONMENT);
	return getProSiteUrls(slug, resolvedEnv, {
		localBaseUrl: env.PRO_SITES_URL,
	});
}
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
// Schema for updating website settings
const updateWebsiteSchema = z.object({
	templateId: z.string().optional(),
	seoTitle: z.string().max(60).optional().nullable(),
	seoDescription: z.string().max(160).optional().nullable(),
	ogImage: z.string().url().optional().nullable(),
	analyticsId: z.string().max(50).optional().nullable(),
	customizations: z
		.object({
			primaryColor: z.string().optional(),
			secondaryColor: z.string().optional(),
			fontFamily: z.string().optional(),
			logoUrl: z.string().url().optional(),
			faviconUrl: z.string().url().optional(),
			headerStyle: z.string().optional(),
			footerStyle: z.string().optional(),
		})
		.optional(),
});
 
const websiteRoutes = new Hono<Env>();
 
// Get website settings and status
websiteRoutes.get("/:proId/website", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		// OPTIMIZATION: Fetch pro, website, and templates in parallel
		// These are independent queries that don't depend on each other
		const [pro, existingWebsite, templates] = await Promise.all([
			dal.pros.findById(proId),
			dal.proWebsites.findByProId(proId),
			dal.websiteTemplates.findAll(),
		]);
 
		if (!pro) {
			throw new NotFoundError("Pro not found");
		}
 
		let website = existingWebsite;
 
		if (!website) {
			// Find default template based on pro's business type
			let defaultTemplate = templates[0]; // Fallback to first template
 
			/* v8 ignore start -- V8 artifact: pro always has businessTypeId in tests */
			if (pro.businessTypeId) {
			/* v8 ignore stop */
				// Find template that matches pro's business type
				for (const template of templates) {
					const defaultTypes = template.defaultForBusinessTypes as
						| string[]
						| null;
					if (defaultTypes?.includes(pro.businessTypeId)) {
						defaultTemplate = template;
						break;
					}
				}
			}
 
			// Auto-create website settings for pro
			const newWebsite = await dal.proWebsites.create({
				proId,
				templateId: defaultTemplate?.id ?? "modern-minimal",
				status: "draft",
			});
			if (!newWebsite) {
				throw new Error("Failed to create website settings");
			}
			website = newWebsite;
		}
 
		// OPTIMIZATION: Fetch latest build and template info in parallel
		// These depend on website existing, but are independent of each other
		const [latestBuild, template] = await Promise.all([
			dal.websiteBuildJobs.findLatestBuildJob(website.id),
			dal.websiteTemplates.findById(website.templateId),
		]);
 
		const urls = getUrls(pro.slug, c.env);
		const env = resolveEnvironment(c.env.ENVIRONMENT);
		const cnameTarget = pro.slug
			? `${getProjectName(pro.slug, env)}.pages.dev`
			: null;
 
		// Use the custom domain URL when the site has been deployed,
		// so "Visit Site" points to e.g. local-{slug}.decorrocket.com
		// instead of localhost in local dev.
		let publishedUrl: string | null = null;
		if (website?.status === "published") {
			const publishedDomain = pro.slug
				? getPublishedDomain(pro.slug, env)
				: null;
			if (latestBuild?.status === "deployed" && publishedDomain) {
				publishedUrl = `https://${publishedDomain}`;
			} else {
				publishedUrl = urls.publishedUrl;
			}
		}
 
		return success(c, {
			website,
			template,
			latestBuild,
			previewUrl: urls.previewUrl,
			publishedUrl,
			customDomainUrl:
				website?.customDomain && website.customDomainVerified
					? `https://${website.customDomain}`
					: null,
			cnameTarget,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update website settings
websiteRoutes.put(
	"/:proId/website",
	requireProAccess,
	zValidator("json", updateWebsiteSchema),
	async (c) => {
		try {
			const proRole = c.get("proRole");
			if (proRole !== "owner" && proRole !== "admin") {
				return error(c, "FORBIDDEN", "Only owners can manage website settings", 403);
			}
 
			const dal = c.get("dal");
			const proId = c.get("proId");
			const body = c.req.valid("json");
 
			// Check if website exists
			let website = await dal.proWebsites.findByProId(proId);
 
			if (!website) {
				// Create with provided settings
				const templates = await dal.websiteTemplates.findAll();
				const templateId =
					body.templateId ?? templates[0]?.id ?? "modern-minimal";
 
				website = await dal.proWebsites.create({
					proId,
					templateId,
					seoTitle: body.seoTitle,
					seoDescription: body.seoDescription,
					ogImage: body.ogImage,
					analyticsId: body.analyticsId,
					customizations: body.customizations,
					status: "draft",
				});
			} else {
				// Validate template exists if changing
				if (body.templateId && body.templateId !== website.templateId) {
					const template = await dal.websiteTemplates.findById(
						body.templateId,
					);
					if (!template) {
						throw new BadRequestError("Template not found");
					}
				}
 
				// Update website settings
				website = await dal.proWebsites.update(website.id, {
					...body,
					// Mark as having unpublished changes if template changed
					hasUnpublishedChanges:
						body.templateId && body.templateId !== website.templateId
							? true
							: website.hasUnpublishedChanges,
				});
			}
 
			return success(c, website);
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Mount sub-routers
websiteRoutes.route("/", templateRoutes);
websiteRoutes.route("/", domainRoutes);
websiteRoutes.route("/", publishRoutes);
 
export default websiteRoutes;