Core utils
Utilidades principales que proporcionan funciones para cada vertical, verificaciones de entorno y envíos de formularios de Zoho.
Implementación
Section titled “Implementación”import type { Verticals } from "@/interfaces/verticals";import type { ZohoConfig, ZohoWebhookMap } from "@/interfaces/zoho";import { PORT as ORIGINAL_PORT } from "@/constants/port";import { VERTICAL_NUMBER_LIST } from "@/core/config";import { zohoClient } from "@/services/fetchApi";import { ZOHO_LANGUAGE_MAP } from "@/constants/languages";
export const isProduction = () => process.env.NODE_ENV === "production";const TEST_PREFIXES = ["pre", "test"];
export function selectVertical(verticals: Verticals[]) { return isProduction() ? verticalSearchEngine(verticals) : selectVerticalForPort(verticals);}
function errorList(verticals: Verticals[]) { if (verticals.length === 0) throw new Error("Verticals list is empty"); if (!Array.isArray(verticals)) throw new Error("Verticals list is not an array"); if (!verticals.every(isValidVertical)) throw new Error("Exist invalid vertical in the verticals list");}
function checkCodeSpaces() { if (window.location.href.includes("github.dev")) return VERTICAL_NUMBER_LIST[1].number;
return typeof window !== "undefined" ? Number(window.location.port) - ORIGINAL_PORT : ORIGINAL_PORT;}
function checkIsTestDomain(url: URL) { const urlSections = url.hostname.split("."); if (TEST_PREFIXES.some((prefix) => urlSections[0] === prefix)) return true; else return false;}
export function verticalSearchEngine(verticals: Verticals[]) { errorList(verticals); const url = new URL(window.location.href); const isTest = checkIsTestDomain(url); const subdomain = isTest ? url.hostname.split(".")[1] : url.hostname.split(".")[0]; const vertical = verticals.find( (vertical) => vertical.subdomain === subdomain ); if (!vertical) throw new Error(`This subdomain isn't registered: ${subdomain}`); return vertical;}
export function selectVerticalForPort(verticals: Verticals[]) { errorList(verticals); const count = checkCodeSpaces(); if (count < 0 || count >= verticals.length) throw new Error("This port no have vertical");
return verticals[count];}
export function isValidVertical(vertical: any): vertical is Verticals { return ( typeof vertical.name === "string" && typeof vertical.subdomain === "string" && typeof vertical.i18nDirectory === "string" && typeof vertical.primaryColor === "string" && typeof vertical.secondaryColor === "string" && typeof vertical.productionURL === "string" && typeof vertical.productionApi === "string" && typeof vertical.developmentApi === "string" && typeof vertical.favicon === "string" && typeof vertical.verticalLogo === "string" && typeof vertical.services === "object" && typeof vertical.localeDirectory === "string" && typeof vertical.layoutDirectory === "string" && (typeof vertical.analyticsCode === "undefined" || typeof vertical.analyticsCode === "string") && (typeof vertical.exclusivePages === "undefined" || Array.isArray(vertical.exclusivePages)) );}
export const sendZohoForm = async ( vertical: Verticals & { zohoConfig?: ZohoConfig }, type: keyof ZohoWebhookMap, userData: Record<string, string | number>) => { const zohoConfig = vertical.zohoConfig; if (!zohoConfig) { return { success: false, error: "Missing Zoho configuration" }; }
const webhook = zohoConfig.webhooks[type]; const constants = zohoConfig.constants[type]; if (!webhook || !constants) { return { success: false, error: `Webhook or constants not defined for type '${type}'`, }; }
const resource = isProduction() ? webhook.production : webhook.test; const cleanedResource = resource.replace("https://flow.zoho.com/", "");
const languageStore = useLanguageStore(); const language = ZOHO_LANGUAGE_MAP[languageStore.language] ?? "español";
const payload = { ...userData, language, calificacion: constants.calification, leadSource: constants.leadSource, businessNature: constants.businessNature, ourCompany: constants.ourCompany, industry: constants.industry, vertical: constants.vertical, consultativeSalesProgram: constants.consultativeSalesProgram ?? "", leadStatus: constants.leadStatus, businessLine: constants.businessLine, acronym: constants.acronym ?? "", subject: typeof userData.subject === "string" ? userData.subject : constants.subject ?? "", };
try { const { response } = await zohoClient.postZoho(cleanedResource, payload); return { success: true, response }; } catch (error) { return { success: false, error }; }};Utilidades del Núcleo
Section titled “Utilidades del Núcleo”isProduction();Comprueba si el entorno es de producción.
Retorna un booleano indicando si el entorno es de producción.
export const isProduction = () => process.env.NODE_ENV === "production";selectVertical(verticals: Verticals[])Selector principal de verticales que escoje el metodo apropiado dependiendo el entorno.
export function selectVertical(verticals: Verticals[]) { return isProduction() ? verticalSearchEngine(verticals) : selectVerticalForPort(verticals);}verticalSearchEngine(verticals: Verticals[])Checkea el subdominio de la vertical seleccionada.
export function verticalSearchEngine(verticals: Verticals[]) { // Implementacion de logica para filtrar la URL actual y devuelve la vertical correspondiente.}selectVerticalForPort(verticals: Verticals[])Selecciona la vertical usando el numero de puerto
export function selectVerticalForPort(verticals: Verticals[]) { // Implementation details}Validation Utilities
Section titled “Validation Utilities”isValidVertical(vertical: any)devuelve si una vertical es valida.
typeof vertical.name === "string";typeof vertical.subdomain === "string";typeof vertical.i18nDirectory === "string";// ...and other property checksZoho Integration
Section titled “Zoho Integration”sendZohoForm();Maneja formularios para Zoho con configuraciones del entorno
Parameters
Section titled “Parameters”export const sendZohoForm = async ( vertical: Verticals & { zohoConfig?: ZohoConfig }, // Configuracion de vertical con settings de zoho type: keyof ZohoWebhookMap, // Form type (contact, demo, etc.) userData: Record<string, string | number> // User-submitted form data) => { // Implementation details};Estructura del Payload :
Section titled “Estructura del Payload :”{...userData,language: string,calificacion: string,leadSource: string,businessNature: string,// ...other Zoho-specific fields}Error Handling
Section titled “Error Handling”Errores comunes
Error("Verticals list is empty");
Error("Exist invalid vertical in the verticals list");
Error("This subdomain isn't registered");
Error("This port no have vertical");Example Usage
Section titled “Example Usage”// Vertical selectionconst verticals = await getVerticals();const currentVertical = selectVertical(verticals);
// Zoho form submissionconst result = await sendZohoForm(currentVertical, "contact", { name: "John Doe", email: "john@example.com", phone: "+1234567890",});