All files / routes/pro/onboarding steps.routes.ts

100% Statements 139/139
99.21% Branches 126/127
100% Functions 3/3
100% Lines 136/136

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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294                                                                                                66x   66x     16x 16x   16x 10x 1x   9x   9x 16x   16x 9x 9x   9x 3x   9x       6x 6x 6x 6x 6x 2x 6x 2x 6x       19x 19x 18x 18x 2x 18x 4x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x               18x         19x 7x 7x   18x       5x 5x 5x 2x 4x 4x 4x 2x 4x 2x 4x 4x 4x       7x 7x 7x 1x 5x 5x 3x         5x         5x       5x   5x       9x 9x   9x 9x     9x 5x 9x 1x 9x 3x 9x 1x 9x 1x 9x 1x 9x 3x 9x 1x 9x 1x 9x 2x 9x 2x 9x 1x 9x 1x 9x 1x 9x 9x       3x 3x     1x       54x 54x 54x 54x     54x 54x     1x     1x       1x         33x 33x 33x 33x 33x     33x 21x 21x 1x         1x             30x     30x               19x             14x 10x     12x       4x            
// Onboarding Step Save Routes
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import { BadRequestError } from "../../../lib/errors";
import { handleError, success } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import { requireProAccess } from "../../../middleware";
import type { Services } from "../../../services";
import {
	step1Schema,
	step2Schema,
	step3Schema,
	step4Schema,
	step5Schema,
	step6Schema,
	step7Schema,
	type Step1Data,
	type Step2Data,
	type Step3Data,
	type Step4Data,
	type Step5Data,
	type Step6Data,
	type ProfileFields,
} from "./schemas";
import { flattenProForOnboarding } from "./utils";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
// Helper function to handle step saving with typed data
export async function handleStepSave(
	stepNumber: number,
	body: unknown,
	dal: Dal,
	proId: string,
	userId: string,
) {
	const updateData: Record<string, unknown> = {};
 
	switch (stepNumber) {
		case 1: {
			// Step 1: Simplified Business Info
			const data = step1Schema.parse(body) as Step1Data;
			updateData.businessName = data.businessName;
			// Validate slug uniqueness
			const existingPro = await dal.pros.findBySlug(data.slug);
			if (existingPro && existingPro.id !== proId) {
				throw new BadRequestError("This slug is already taken");
			}
			updateData.slug = data.slug;
			// Empty string means "other" city — store as null
			updateData.cityId = data.cityId || null;
			updateData.businessTypeId = data.businessTypeId;
			// Sync whatsapp to both columns
			if (data.whatsapp) {
				updateData.whatsapp = data.whatsapp;
				updateData.whatsappBusinessNumber = data.whatsapp;
			}
			if (data.logoUrl !== undefined) {
				updateData.logoUrl = data.logoUrl || null;
			}
			break;
		}
		case 2: {
			// Step 2: About Your Brand
			const data = step2Schema.parse(body) as Step2Data;
			if (data.tagline !== undefined) updateData.tagline = data.tagline;
			if (data.about !== undefined) updateData.about = data.about;
			if (data.logoUrl !== undefined) updateData.logoUrl = data.logoUrl || null;
			if (data.coverImage !== undefined)
				updateData.coverImage = data.coverImage || null;
			if (data.processDescription !== undefined)
				updateData.processDescription = data.processDescription || null;
			break;
		}
		case 3: {
			// Step 3: Contact & Social
			const data = step3Schema.parse(body) as Step3Data;
			if (data.whatsapp !== undefined)
				updateData.whatsapp = data.whatsapp || null;
			if (data.email !== undefined)
				updateData.email = data.email || null;
			if (data.instagramHandle !== undefined)
				updateData.instagramHandle = data.instagramHandle;
			if (data.facebookUrl !== undefined)
				updateData.facebookUrl = data.facebookUrl || null;
			if (data.youtubeUrl !== undefined)
				updateData.youtubeUrl = data.youtubeUrl || null;
			if (data.googleBusinessUrl !== undefined)
				updateData.googleBusinessUrl = data.googleBusinessUrl || null;
			if (data.websiteUrl !== undefined)
				updateData.websiteUrl = data.websiteUrl || null;
			if (data.linkedinUrl !== undefined)
				updateData.linkedinUrl = data.linkedinUrl || null;
			Eif (data.whatsappBusinessNumber !== undefined)
				updateData.whatsappBusinessNumber =
					data.whatsappBusinessNumber || null;
 
			// Keep whatsapp and whatsappBusinessNumber in sync: resolve the
			// effective number from whichever field was provided, then write
			// it to both columns so profile display and completeness checks
			// always find the value regardless of which column they read.
			const effectiveWhatsapp =
				(updateData.whatsapp as string | null) ??
				(updateData.whatsappBusinessNumber as string | null) ??
				data.whatsapp ??
				data.whatsappBusinessNumber ??
				null;
			if (effectiveWhatsapp) {
				updateData.whatsapp = effectiveWhatsapp;
				updateData.whatsappBusinessNumber = effectiveWhatsapp;
			}
			break;
		}
		case 4: {
			// Step 4: What You Do (Services, Materials & Brands)
			const data = step4Schema.parse(body) as Step4Data;
			updateData.businessTypeId = data.businessTypeId;
			if (data.businessTypesSecondary !== undefined)
				updateData.businessTypesSecondary = data.businessTypesSecondary;
			if (data.serviceCategoryIds !== undefined)
				updateData.serviceCategoryIds = data.serviceCategoryIds;
			if (data.materialTagIds !== undefined)
				updateData.materialTagIds = data.materialTagIds;
			if (data.brandsWorkWith !== undefined)
				updateData.brandsWorkWith = data.brandsWorkWith;
			if (data.brandsOfficialPartner !== undefined)
				updateData.brandsOfficialPartner = data.brandsOfficialPartner;
			break;
		}
		case 5: {
			// Step 5: Your Customers
			const data = step5Schema.parse(body) as Step5Data;
			updateData.customerSegmentId = data.customerSegmentId;
			if (data.customerSegmentsSecondary !== undefined)
				updateData.customerSegmentsSecondary = data.customerSegmentsSecondary;
			updateData.priceRangeMin = data.priceRangeMin;
			if (data.priceRangeMax !== undefined)
				updateData.priceRangeMax = data.priceRangeMax;
			// pricingModel is stored in profileFields
			/* v8 ignore start -- defensive guard: pricingModel branch not covered */
			if (data.pricingModel !== undefined) {
			/* v8 ignore stop */
				const pro5 = await dal.pros.findById(proId);
				/* v8 ignore start -- V8 artifact: || fallback */
				const existingProfileFields5 =
					(pro5?.profileFields as ProfileFields) || {};
				/* v8 ignore stop */
				const profileFieldsUpdate5: ProfileFields = {
					...existingProfileFields5,
					pricingModel: data.pricingModel,
				};
				updateData.profileFields = profileFieldsUpdate5;
			}
			break;
		}
		case 6: {
			// Step 6: How You Deliver
			const data = step6Schema.parse(body) as Step6Data;
			const pro6 = await dal.pros.findById(proId);
			const existingProfileFields6 =
				(pro6?.profileFields as ProfileFields) || {};
			const profileFieldsUpdate6: ProfileFields = {
				...existingProfileFields6,
			};
			if (data.factoryMade !== undefined)
				profileFieldsUpdate6.factoryMade = data.factoryMade;
			if (data.factoryType !== undefined)
				profileFieldsUpdate6.factoryType = data.factoryType;
			if (data.siteExecution !== undefined)
				profileFieldsUpdate6.siteExecution = data.siteExecution;
			if (data.labourOnly !== undefined)
				profileFieldsUpdate6.labourOnly = data.labourOnly;
			if (data.fullSiteExecution !== undefined)
				profileFieldsUpdate6.fullSiteExecution = data.fullSiteExecution;
			if (data.materialApproach !== undefined)
				profileFieldsUpdate6.materialApproach = data.materialApproach;
			if (data.billingModel !== undefined)
				profileFieldsUpdate6.billingModel = data.billingModel;
			if (data.deliveryDaysMin !== undefined)
				profileFieldsUpdate6.deliveryDaysMin = data.deliveryDaysMin;
			if (data.deliveryDaysMax !== undefined)
				profileFieldsUpdate6.deliveryDaysMax = data.deliveryDaysMax;
			if (data.consultationFee !== undefined)
				profileFieldsUpdate6.consultationFee = data.consultationFee;
			if (data.warrantyYears !== undefined)
				profileFieldsUpdate6.warrantyYears = data.warrantyYears;
			if (data.hasAfterSalesService !== undefined)
				profileFieldsUpdate6.hasAfterSalesService = data.hasAfterSalesService;
			if (data.hasShowroom !== undefined)
				profileFieldsUpdate6.hasShowroom = data.hasShowroom;
			if (data.provides3DDesign !== undefined)
				profileFieldsUpdate6.provides3DDesign = data.provides3DDesign;
			updateData.profileFields = profileFieldsUpdate6;
			break;
		}
		case 7: {
			// Step 7: Your First Project - navigation step, no data to save
			step7Schema.parse(body);
			break;
		}
		default:
			throw new BadRequestError(`Invalid step number: ${stepNumber}`);
	}
 
	// Update onboarding progress
	updateData.onboardingStatus = "in_progress";
	updateData.onboardingStep = Math.max(stepNumber, 0);
	updateData.userUpdated = userId;
	updateData.dateUpdated = new Date();
 
	// Update pro (DAL takes 2 args: id, data)
	const pro = await dal.pros.update(proId, updateData);
	return pro;
}
 
const stepsRouter = new Hono<Env>();
 
// Save a step's data
const saveStepParamsSchema = z.object({
	stepNumber: z.coerce.number().min(1).max(7),
});
 
stepsRouter.post(
	"/step/:stepNumber",
	requireProAccess,
	zValidator("param", saveStepParamsSchema),
	async (c) => {
		try {
			const dal = c.get("dal");
			const user = requireUser(c.get("user"));
			const proId = c.get("proId");
			const { stepNumber } = c.req.valid("param");
 
			// Validate steps are completed in order
			if (stepNumber > 1) {
				const pro = await dal.pros.findById(proId);
				if (!pro) {
					throw new BadRequestError("Pro profile not found");
				}
				/* v8 ignore start -- V8 artifact: || 0 fallback */
				if ((pro.onboardingStep || 0) < stepNumber - 1) {
				/* v8 ignore stop */
					throw new BadRequestError(
						`Please complete step ${stepNumber - 1} first`,
					);
				}
			}
 
			// Parse request body
			const body = await c.req.json();
 
			// Handle step save with validation
			const pro = await handleStepSave(
				stepNumber,
				body,
				dal,
				proId,
				user.id,
			);
 
			return success(c, {
				step: stepNumber,
				saved: true,
				pro: flattenProForOnboarding(pro as Record<string, unknown>),
			});
		} catch (err) {
			// Handle Zod validation errors
			if (err instanceof z.ZodError) {
				return handleError(
					c,
					new BadRequestError(
						`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`,
					),
				);
			}
			return handleError(c, err);
		}
	},
);
 
export default stepsRouter;