CCCPaste

goaffpro.ts

interface GoAffProAffiliate {
    id: number;
    email: string;
    ref_code: string;
    status: string;
    created_at: string;
    updated_at: string;
}

interface CreateAffiliateRequest {
    email: string;
    first_name?: string;
    last_name?: string;
    name: string;
    password: string;
}

interface CreateAffiliateResponse {
    success: boolean;
    affiliate: GoAffProAffiliate | null;
    message?: string;
    errors?: Record;
}

/**
 * Helper function to update an affiliate via PATCH
 */
async function updateGoAffProAffiliate(
    id: number,
    body: Record,
): Promise<{ success: boolean; data?: unknown; error?: string }> {
    try {
        const response = await fetch(
            `${serverConfig.goaffproApiUrl}/admin/affiliates/${id}`,
            {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    "x-goaffpro-access-token": serverConfig.goaffproApiKey,
                },
                body: JSON.stringify(body),
            },
        );

        const responseData = await response.json();

        if (!response.ok) {
            return {
                success: false,
                error: responseData.error || responseData.message ||
                    "Failed to update affiliate",
            };
        }

        return {
            success: true,
            data: responseData,
        };
    } catch (error) {
        console.error("Error updating GoAffPro affiliate:", error);

        return {
            success: false,
            error: "Internal server error",
        };
    }
}

/**
 * Create a new affiliate in GoAffPro
 */
export async function createGoAffProAffiliate(
    affiliateData: CreateAffiliateRequest,
): Promise {
    console.log("affiliateData", affiliateData);
    try {
        const response = await fetch(
            `${serverConfig.goaffproApiUrl}/admin/affiliates`,
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "x-goaffpro-access-token": serverConfig.goaffproApiKey,
                },
                body: JSON.stringify({
                    email: affiliateData.email,
                    name: affiliateData.name,
                    password: affiliateData.password,
                    password_expired: true,
                    status: "pending",
                    first_name: affiliateData.first_name,
                    last_name: affiliateData.last_name,
                }),
            },
        );

        const responseData = await response.json();

        if (!response.ok) {
            console.error("Error creating GoAffPro affiliate:", responseData);
            return {
                success: false,
                affiliate: null,
                message: responseData.error || "Failed to create affiliate",
                errors: responseData.errors,
            };
        }

        // Get the affiliate ID from the response
        const createdAffiliateId = responseData.affiliate_id;

        // Update name fields immediately after creation
        // This is necessary because the creation endpoint doesn't always persist these fields
        if (
            createdAffiliateId &&
            (affiliateData.name || affiliateData.first_name ||
                affiliateData.last_name)
        ) {
            const updateResult = await updateGoAffProAffiliate(
                createdAffiliateId,
                {
                    ...(affiliateData.name && { name: affiliateData.name }),
                    ...(affiliateData.first_name &&
                        { first_name: affiliateData.first_name }),
                    ...(affiliateData.last_name &&
                        { last_name: affiliateData.last_name }),
                },
            );

            if (!updateResult.success) {
                console.warn(
                    "Failed to update affiliate name fields:",
                    updateResult.error,
                );
                // Don't fail the entire creation if update fails
            }
        }

        const affiliate = await getGoAffProAffiliateByEmail(
            affiliateData.email,
        );

        return {
            success: true,
            affiliate: affiliate,
            message: "Affiliate created successfully",
        };
    } catch (error) {
        console.error("Error creating GoAffPro affiliate:", error);
        return {
            success: false,
            affiliate: null,
            message: "Internal server error",
        };
    }
}

/**
 * Approve affiliate by id from GoAffPro
 */
export async function approveGoAffProAffiliate(
    id: number,
): Promise<
    { success: boolean; message?: string; error?: string; id?: number }
> {
    try {
        const updateResult = await updateGoAffProAffiliate(id, {
            status: "approved",
            first_name: "David",
            last_name: "Baker",
        });

        if (!updateResult.success) {
            return {
                success: false,
                message: updateResult.error ||
                    "Failed to approve affiliate in GoAffPro",
            };
        }

        const responseData = updateResult.data as {
            affiliate?: string | Record;
            updated?: boolean;
            id?: number;
        };

        // Parse affiliate if it's a JSON string
        const affiliate = typeof responseData.affiliate === "string"
            ? JSON.parse(responseData.affiliate)
            : responseData.affiliate;

        const success = affiliate?.status === "approved" &&
            responseData.updated === true &&
            responseData.id != null;

        console.log("success", success);
        console.log("responseData", responseData);
        console.log("parsed affiliate", affiliate);

        if (!success) {
            return {
                success: false,
                message: "Failed to approve affiliate in GoAffPro",
            };
        }

        return {
            success: true,
            message: "Affiliate approved successfully",
            id: responseData.id,
        };
    } catch (error) {
        console.error("Error approving GoAffPro affiliate:", error);
        return { success: false, message: "Internal server error" };
    }
}