All files / services resume_service.ts

10% Statements 9/90
0% Branches 0/47
0% Functions 0/9
10% Lines 9/90

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                                    1x     1x           1x                                                         1x                                                                                                   1x                                                             1x                           1x                                         1x                                                   1x                                                            
import { config } from '../config/config';
import path from 'path';
import fs from 'fs';
import { chatWithAI, streamChatWithAI } from './chat_api_service';
import mammoth from 'mammoth';
import pdfParse from 'pdf-parse';
import AdmZip from 'adm-zip';
import { DOMParser, XMLSerializer } from 'xmldom';
import {ParsedResume, ResumeData} from 'types/resume_types';
import {createResumeExtractionPrompt, createResumeModificationPrompt, feedbackTemplate, SYSTEM_TEMPLATE} from "../utils/resume_handlers/resume_AI_handler";
import { parseDocument } from '../utils/resume_handlers/resume_files_handler';
import {ResumeModel} from "../models/resume_model";
import {Document} from 'mongoose';
 
 
 
 
 
const FEEDBACK_ERROR_MESSAGE = 'The Chat AI feature is turned off. Could not score your resume.';
 
 
const resumeToResumeData = async (resume: Document<unknown, {}, any> & any): Promise<ResumeData> => {
    // The mongoose schema's toJSON transform already handles basic conversion
    // You could add additional fields here if needed in the future
    return resume.toJSON();
};
 
const scoreResume = async (resumePath: string, jobDescription?: string): Promise<{ score: number; feedback: string }> => {
    try {
        const resumeText = await parseDocument(resumePath);
        if (resumeText.trim() == '') {
            throw new TypeError('Could not parse the resume file');
        }
        const prompt = feedbackTemplate(resumeText, jobDescription || 'No job description provided.');
 
        let feedback = FEEDBACK_ERROR_MESSAGE;
        if (config.chatAi.turned_on()) {
            // Get feedback from the AI
            feedback = await chatWithAI(SYSTEM_TEMPLATE, [prompt]);
        }
 
        // Extract the score from the feedback
        const scoreMatch = feedback.match(/SCORE: (\d+)/);
        const score = scoreMatch ? parseInt(scoreMatch[1]) : 0;
        return { score, feedback };
    } catch (error: any) {
        if (error instanceof TypeError) {
            console.error('TypeError while scoring resume:', error);
            throw error;
        } else {
            console.error('Unexpected error while scoring resume:', error);
            throw new Error('Failed to score resume');
        }
    }
};
 
const streamScoreResume = async (
    resumePath: string,
    jobDescription: string | undefined,
    onChunk: (chunk: string) => void
): Promise<[number, string]> => {
    try {
        const resumeText = await parseDocument(resumePath);
        if (resumeText.trim() == '') {
            throw new TypeError('Could not parse the resume file');
        }
        const prompt = feedbackTemplate(resumeText, jobDescription || 'No job description provided.');
        
        let fullResponse = '';
        let finalScore = 0;
 
        if (config.chatAi.turned_on()) {
            await streamChatWithAI(
                SYSTEM_TEMPLATE,
                [prompt],
                (chunk) => {
                    fullResponse += chunk;
                    onChunk(chunk);
                    
                    // Try to extract score from the accumulated response
                    const scoreMatch = fullResponse.match(/SCORE: (\d+)/);
                    if (scoreMatch) {
                        finalScore = parseInt(scoreMatch[1]);
                    }
                }
            );
        } else {
            onChunk(FEEDBACK_ERROR_MESSAGE);
        }
 
        return [finalScore, fullResponse];
    } catch (error: any) {
        if (error instanceof TypeError) {
            console.error('TypeError while streaming resume score:', error);
            throw error;
        } else {
            console.error('Unexpected error while streaming resume score:', error);
            throw new Error('Failed to stream resume score');
        }
    }
};
 
/**
 * Extracts raw text from the uploaded resume buffer,
 * prompts the AI to return { aboutMe, skills[], roleMatch, experience[] } as JSON.
 */
const parseResumeFields = async (
    fileBuffer: Buffer,
    originalName: string
  ): Promise<ParsedResume> => {
    // 1) Extract text
    const ext = path.extname(originalName).toLowerCase();
    let text: string;
    if (ext === '.pdf') {
      const data = await pdfParse(fileBuffer);
      text = data.text;
    } else {
      // mammoth supports buffer input
      const { value } = await mammoth.extractRawText({ buffer: fileBuffer });
      text = value;
    }
  
    // 2) Build the extraction prompt
    const prompt = createResumeExtractionPrompt(text);
  
    // 3) Call Chat AI
    const aiResponse = await chatWithAI(
      SYSTEM_TEMPLATE,
      [prompt]
    );
  
    // 4) Parse & return
    const parsed = JSON.parse(aiResponse.trim().replace("```json", "").replace("```", "")) as ParsedResume;
    return parsed;
  };
 
 
const getLatestResumeByUser = async (ownerId: string): Promise<number> => {
    try {
        const latestResume = await ResumeModel.findOne({ owner: ownerId })
            .sort({ version: -1 })
            .exec();
 
        return latestResume ? latestResume.version : 0; // Return version number or 0 if no resume exists
    } catch (error) {
        console.error('Error finding latest resume:', error);
        throw new Error('Failed to retrieve latest resume');
    }
};
 
 
const saveParsedResume = async (parsedData: ParsedResume, ownerId: string, resumeRawLink: string, filename: string): Promise<ResumeData> => {
    const lastVersion = await getLatestResumeByUser(ownerId);
    const newVersion = lastVersion + 1;
 
    const newResume = new ResumeModel({
        owner: ownerId,
        version: newVersion,
        rawContentLink: resumeRawLink,
        parsedData: {
            fileName: filename,
            aboutMe: parsedData.aboutMe,
            skills: parsedData.skills,
            roleMatch: parsedData.roleMatch,
            experience: parsedData.experience
        }
    });
 
    const savedResume = await newResume.save();
    return resumeToResumeData(savedResume);
};
 
const updateResume = async (ownerId: string, jobDescription: string, feedback?: string, score?: number, filename?: string): Promise<void> => {
    try {
        const resume = await getResumeByOwner(ownerId);
        if (!resume) {
            throw new Error(`Resume not found`);
        }
        const parsedData = resume.parsedData as ParsedResume; // Ensure parsedData is of type ParsedResume
        if (jobDescription !== parsedData.jobDescription) {
            resume.parsedData = {
                ...parsedData,
                jobDescription: jobDescription || parsedData.jobDescription,
                feedback: feedback || parsedData.feedback || '',
                score: score || parsedData.score || 0,
                fileName: parsedData.fileName || filename || ''
            };
            resume.markModified('parsedData');
            await resume.save();
            
        }
    }
    catch (error) {
            console.error('Error updating resume:', error);
            throw new Error(`Failed to update resume`);
        }
}
 
const getResumeByOwner = async (ownerId: string, version?: number) => {
    try {
        let query: {owner: string, version?: number} = {
            owner: ownerId,
        };
 
        // If version is specified, add it to the query
        if (version !== undefined) {
            query = { ...query, version };
        }
 
        const resume = await ResumeModel.findOne(query)
            .sort(version === undefined ? { version: -1 } : {}) // Sort by version descending only if no specific version requested
            .exec();
 
        if (!resume) {
            if (version !== undefined) {
                throw new Error(`Resume version ${version} not found for user ${ownerId}`);
            }
            console.log(`No resume found for user ${ownerId}`);
        }
 
        return resume;
    } catch (error) {
        console.error('Error retrieving resume:', error);
        throw error;
    }
};
 
export { scoreResume, streamScoreResume, parseResumeFields,
    saveParsedResume, getResumeByOwner, updateResume, };