All files / services pro.service.ts

98.43% Statements 63/64
100% Branches 42/42
92.85% Functions 13/14
98.41% Lines 62/63

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                                        5x                                                                                                                   32x             3x 3x       3x       16x 16x 2x   14x       2x 2x 1x   1x       5x     5x     5x               4x                                                                                       4x                 14x     13x 9x 38x 2x           11x 11x 11x 11x 11x 11x 11x 11x       11x   14x 14x                   14x             40x 14x 3x             3x                       10x               10x 1x     9x       2x 2x 1x       1x 1x 2x       1x       1x       1x               1x                             1x       5x 5x 5x 5x 5x         5x 5x 5x      
// Pro Service - Business Logic Layer
import type { Dal } from "../dal";
import type { Pro } from "../db/schema";
import type { ProFilters } from "../dal/pros.dal";
import { NotFoundError, ForbiddenError } from "../lib/errors";
import { generateId, generateSlug, generateUniqueSlug } from "../lib/utils";
import {
	validateBusinessName,
	validateStatus,
	validateTeamSize,
	validateArrayFields,
	validatePrimarySecondaryOverlap,
	validateYearsInBusiness,
	validateEmail,
	validateProfileFields,
	validateRushOrderPremium,
	validateAcceptsRushOrders,
} from "./pro.validators";
 
// Fields that pros cannot modify themselves
const ADMIN_ONLY_FIELDS = [
	"status",
	"isFeatured",
	"isEarlyAdopter",
	"userCreated",
	"dateCreated",
] as const;
 
export type CreateProInput = {
	businessName: string;
	whatsapp?: string;
	description?: string;
	profileImage?: string;
	status?: string;
	isFeatured?: boolean;
	isEarlyAdopter?: boolean;
	// Taxonomy fields
	businessTypeId?: string;
	businessTypesSecondary?: string[];
	timelineCapabilities?: string[];
	customerSegmentId?: string;
	customerSegmentsSecondary?: string[];
	projectScaleIds?: string[];
	serviceCategoryIds?: string[];
	materialTagIds?: string[];
	brandsWorkWith?: string[];
	brandsOfficialPartner?: string[];
	serviceAreaIds?: string[];
	cityId?: string;
	// New profile fields
	phoneAlternate?: string;
	email?: string;
	businessAddress?: string | null;
	addressLine1?: string;
	addressLine2?: string;
	addressCity?: string;
	addressState?: string;
	addressPincode?: string;
	yearsInBusiness?: number;
	teamSize?: string;
	languagesSpoken?: string[];
	coverImage?: string;
	profileFields?: Record<string, unknown>;
	// Rush order fields
	acceptsRushOrders?: boolean;
	rushOrderPremium?: string;
	// SEO fields
	metaTitle?: string;
	metaDescription?: string;
	ogImage?: string;
	// Onboarding fields
	onboardingStatus?: "not_started" | "in_progress" | "completed";
	onboardingStep?: number;
};
 
export type UpdateProInput = Partial<CreateProInput>;
 
export class ProService {
	constructor(private dal: Dal) {}
 
	async list(
		filters: ProFilters,
		page: number,
		limit: number,
	): Promise<{ pros: Pro[]; total: number }> {
		const offset = (page - 1) * limit;
		const [pros, total] = await Promise.all([
			this.dal.pros.findAll(filters, offset, limit),
			this.dal.pros.count(filters),
		]);
		return { pros, total };
	}
 
	async getById(id: string): Promise<Pro> {
		const pro = await this.dal.pros.findById(id);
		if (!pro) {
			throw new NotFoundError("Pro", id);
		}
		return pro;
	}
 
	async getBySlug(slug: string): Promise<Pro> {
		const pro = await this.dal.pros.findBySlug(slug);
		if (!pro) {
			throw new NotFoundError("Pro");
		}
		return pro;
	}
 
	async create(input: CreateProInput, userId: string): Promise<Pro> {
		this.validateInput(input);
 
		// Generate unique slug (use random slug for auto-created profiles with no name)
		let slug = input.businessName
			? generateSlug(input.businessName)
			: `pro-${generateId().slice(0, 8)}`;
		if (await this.dal.pros.slugExists(slug)) {
			/* v8 ignore start -- V8 artifact: ternary false branch */
			slug = input.businessName
				? generateUniqueSlug(input.businessName)
				: `pro-${generateId().slice(0, 8)}`;
			/* v8 ignore stop */
		}
 
		const pro = await this.dal.pros.create({
			id: generateId(),
			businessName: input.businessName,
			slug,
			whatsapp: input.whatsapp,
			description: input.description,
			profileImage: input.profileImage,
			status: (input.status as Pro["status"]) ?? "draft",
			isFeatured: input.isFeatured ?? false,
			isEarlyAdopter: input.isEarlyAdopter ?? false,
			// Taxonomy fields
			businessTypeId: input.businessTypeId,
			businessTypesSecondary: input.businessTypesSecondary,
			timelineCapabilities: input.timelineCapabilities,
			customerSegmentId: input.customerSegmentId,
			customerSegmentsSecondary: input.customerSegmentsSecondary,
			projectScaleIds: input.projectScaleIds,
			serviceCategoryIds: input.serviceCategoryIds,
			materialTagIds: input.materialTagIds,
			brandsWorkWith: input.brandsWorkWith,
			brandsOfficialPartner: input.brandsOfficialPartner,
			serviceAreaIds: input.serviceAreaIds,
			cityId: input.cityId,
			// New profile fields
			phoneAlternate: input.phoneAlternate,
			email: input.email,
			businessAddress: input.businessAddress,
			yearsInBusiness: input.yearsInBusiness,
			teamSize: input.teamSize as Pro["teamSize"],
			languagesSpoken: input.languagesSpoken,
			coverImage: input.coverImage,
			profileFields: input.profileFields,
			// Rush order fields
			acceptsRushOrders: input.acceptsRushOrders ?? false,
			rushOrderPremium: input.rushOrderPremium as Pro["rushOrderPremium"],
			// SEO fields
			metaTitle: input.metaTitle,
			metaDescription: input.metaDescription,
			ogImage: input.ogImage,
			// Audit fields
			userCreated: userId,
			userUpdated: userId,
		});
 
		return pro;
	}
 
	async update(
		id: string,
		input: UpdateProInput,
		userId: string,
		isAdmin: boolean,
	): Promise<Pro> {
		const pro = await this.getById(id);
 
		// Non-admins cannot modify admin-only fields
		if (!isAdmin) {
			for (const field of ADMIN_ONLY_FIELDS) {
				if (field in input) {
					throw new ForbiddenError(`You cannot modify the '${field}' field`);
				}
			}
		}
 
		// Run validations
		validateStatus(input.status);
		validateTeamSize(input.teamSize);
		validateArrayFields(input);
		validateYearsInBusiness(input.yearsInBusiness);
		validateEmail(input.email);
		validateProfileFields(input.profileFields);
		validateRushOrderPremium(input.rushOrderPremium);
		validateAcceptsRushOrders(input.acceptsRushOrders);
 
		// Validate primary/secondary don't overlap for business types
		const effectiveBusinessTypeId =
			input.businessTypeId ?? pro.businessTypeId;
		const effectiveBusinessTypesSecondary =
			input.businessTypesSecondary ?? pro.businessTypesSecondary;
		validatePrimarySecondaryOverlap(
			effectiveBusinessTypeId,
			effectiveBusinessTypesSecondary,
			"business type",
		);
 
		// Slug is immutable once set — never regenerate on business name change.
		// Changing slugs would break published website URLs, SEO links, and bookmarks.
 
		// Auto-compose businessAddress from structured address fields
		const addressFields = [
			"addressLine1",
			"addressLine2",
			"addressCity",
			"addressState",
			"addressPincode",
		] as const;
		const hasAddressUpdate = addressFields.some((f) => f in input);
		if (hasAddressUpdate) {
			const merged = {
				addressLine1: input.addressLine1 ?? pro.addressLine1,
				addressLine2: input.addressLine2 ?? pro.addressLine2,
				addressCity: input.addressCity ?? pro.addressCity,
				addressState: input.addressState ?? pro.addressState,
				addressPincode: input.addressPincode ?? pro.addressPincode,
			};
			input.businessAddress =
				[
					merged.addressLine1,
					merged.addressLine2,
					merged.addressCity,
					merged.addressState,
					merged.addressPincode,
				]
					.filter(Boolean)
					.join(", ") || null;
		}
 
		const updated = await this.dal.pros.update(id, {
			...input,
			status: input.status as Pro["status"],
			teamSize: input.teamSize as Pro["teamSize"],
			rushOrderPremium: input.rushOrderPremium as Pro["rushOrderPremium"],
			userUpdated: userId,
		});
 
		if (!updated) {
			throw new NotFoundError("Pro", id);
		}
 
		return updated;
	}
 
	async delete(id: string): Promise<void> {
		const exists = await this.dal.pros.findById(id);
		if (!exists) {
			throw new NotFoundError("Pro", id);
		}
 
		// Clean up all user roles for this pro first
		const proRoles = await this.dal.userTenantRoles.findByProId(id);
		for (const role of proRoles) {
			await this.dal.userTenantRoles.delete(role.id);
		}
 
		// Now delete the pro
		await this.dal.pros.delete(id);
	}
 
	async disable(id: string, userId: string): Promise<Pro> {
		return this.update(id, { status: "archived" }, userId, true);
	}
 
	async publish(id: string, userId: string): Promise<Pro> {
		return this.update(id, { status: "published" }, userId, true);
	}
 
	async setFeatured(
		id: string,
		isFeatured: boolean,
		userId: string,
	): Promise<Pro> {
		return this.update(id, { isFeatured }, userId, true);
	}
 
	async setEarlyAdopter(
		id: string,
		isEarlyAdopter: boolean,
		userId: string,
	): Promise<Pro> {
		return this.update(id, { isEarlyAdopter }, userId, true);
	}
 
	/**
	 * Increment view count for a pro (called from marketplace API)
	 */
	async incrementViewCount(id: string): Promise<void> {
		await this.dal.pros.incrementViewCount(id);
	}
 
	private validateInput(input: CreateProInput): void {
		validateBusinessName(input.businessName);
		validateStatus(input.status);
		validateTeamSize(input.teamSize);
		validateArrayFields(input);
		validatePrimarySecondaryOverlap(
			input.businessTypeId,
			input.businessTypesSecondary,
			"business type",
		);
		validateYearsInBusiness(input.yearsInBusiness);
		validateEmail(input.email);
		validateProfileFields(input.profileFields);
	}
}