Spaces:
Running
Running
File size: 9,784 Bytes
29ff11a f237798 6068938 f237798 d6596e1 f237798 6f30bfd f237798 6f30bfd f237798 29ff11a f237798 e8163f2 f237798 6068938 f237798 6068938 f237798 e8163f2 f237798 e8163f2 f237798 e8163f2 f237798 e8163f2 f237798 e8163f2 f237798 6068938 f237798 6068938 f237798 e8163f2 6068938 f237798 6068938 f237798 | 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 | import { getSupabaseAdmin } from '../_shared/supabaseAdmin.js';
import type {
AggregatedSkillScore,
CertificationTrack,
ProjectEvidence,
PublicProfile,
ValidationSummary,
} from '../_types.js';
type JsonRecord = Record<string, unknown>;
type UserRow = {
id: string;
username: string;
referral_code: string | null;
};
type CertificateRow = {
id: string;
topic: string;
project_title: string | null;
issued_at: string;
metadata: JsonRecord | null;
};
const CANONICAL_PUBLIC_DOMAIN = 'https://getcert.eu.cc';
function appBaseUrl(): string {
const configured = (process.env.CERTIFICATE_VERIFY_BASE_URL || process.env.APP_ORIGIN || '').trim();
if (
!configured ||
configured.includes('hf.space') ||
configured.includes('huggingface.co') ||
configured.includes('vercel.app') ||
configured.includes('localhost')
) {
return CANONICAL_PUBLIC_DOMAIN;
}
return configured.replace(/\/$/, '');
}
function toStringValue(value: unknown): string | null {
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function toNumberValue(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return null;
}
function getObject(value: unknown): JsonRecord | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return null;
}
return value as JsonRecord;
}
function parseValidationSummary(metadata: JsonRecord): ValidationSummary | null {
const nested = getObject(metadata.validation_summary);
if (!nested) {
return null;
}
const suspiciousSignals = Array.isArray(nested.suspicious_signals)
? nested.suspicious_signals.filter((item): item is string => typeof item === 'string')
: [];
return {
overallPassed: Boolean(nested.overall_passed),
commitPassed: Boolean(nested.commit_passed),
readmePassed: Boolean(nested.readme_passed),
proofPassed: Boolean(nested.proof_passed),
commitCount: Math.round(toNumberValue(nested.commit_count) ?? 0),
fileCount: Math.round(toNumberValue(nested.file_count) ?? 0),
meaningfulFileCount: Math.round(toNumberValue(nested.meaningful_file_count) ?? 0),
readmeRichness: Math.round(toNumberValue(nested.readme_richness) ?? 0),
suspiciousSignals,
};
}
function getDifficultyWeight(projectType: string | null): number {
if (projectType === 'data') {
return 1.3;
}
if (projectType === 'python') {
return 1.15;
}
if (projectType === 'web' || projectType === 'fullstack') {
return 1.2;
}
return 1;
}
function getDifficultyLevel(weight: number): 'beginner' | 'intermediate' | 'advanced' {
if (weight >= 1.26) {
return 'advanced';
}
if (weight >= 1.16) {
return 'intermediate';
}
return 'beginner';
}
function roundValue(value: number): number {
return Math.round(value * 100) / 100;
}
function buildPassConfidence(finalScore: number, summary: ValidationSummary | null): number {
if (!summary) {
return Math.max(0, Math.min(100, Math.round(finalScore * 0.8)));
}
let confidence = finalScore * 0.6;
confidence += summary.overallPassed ? 22 : 10;
confidence += Math.min(10, summary.commitCount * 0.6);
confidence += summary.readmePassed ? 8 : 2;
return Math.max(0, Math.min(100, Math.round(confidence)));
}
export async function getPublicProfile(userId: string): Promise<PublicProfile> {
const supabase = getSupabaseAdmin();
const base = appBaseUrl();
const { data: user, error: userError } = await supabase
.from('users')
.select('id, username, referral_code')
.eq('id', userId)
.single();
if (userError || !user) {
throw new Error('User not found');
}
const { data: certificates, error: certError } = await supabase
.from('certificates')
.select('id, topic, project_title, issued_at, metadata')
.eq('user_id', userId)
.order('issued_at', { ascending: false });
const { count: referredUsersCount } = await supabase
.from('users')
.select('id', { count: 'exact', head: true })
.eq('referred_by', userId);
if (certError) {
throw new Error(`Failed to fetch certificates: ${certError.message}`);
}
const rows = (certificates || []) as CertificateRow[];
const allProjects: ProjectEvidence[] = rows.map((item) => {
const metadata = item.metadata || {};
const validationSummary = parseValidationSummary(metadata);
const projectType = toStringValue(metadata.project_type);
const difficultyWeight = getDifficultyWeight(projectType);
const finalScore = Math.round(toNumberValue(metadata.final_score) ?? 0);
const commitCount = Math.round(
toNumberValue(metadata.commit_count) ??
toNumberValue(validationSummary?.commitCount) ??
0
);
const fileCount = Math.round(toNumberValue(validationSummary?.fileCount) ?? 0);
const readmeScore = Math.round(toNumberValue(validationSummary?.readmeRichness) ?? 0);
const track = (toStringValue(metadata.certification_track) || 'verifiedcert') as CertificationTrack;
return {
certificateId: toStringValue(metadata.certificate_id),
certificateDbId: item.id,
skill: item.topic,
projectTitle: item.project_title,
projectType,
difficultyLevel: getDifficultyLevel(difficultyWeight),
difficultyWeight,
githubRepoUrl: toStringValue(metadata.github_repo_url) || toStringValue(metadata.github_url),
liveDemoUrl: toStringValue(metadata.live_demo_url) || toStringValue(metadata.proof_url),
finalScore,
commitCount,
fileCount,
validationSummary,
passConfidence: buildPassConfidence(finalScore, validationSummary),
issuedAt: item.issued_at,
track,
trustSignals: {
commitCount,
validationPassed: validationSummary ? validationSummary.overallPassed : finalScore >= 60,
readmeScore,
projectType,
},
};
});
const projects = allProjects.filter((p) => p.track === 'verifiedcert');
const skillAccumulator = new Map<string, {
totalScore: number;
weightedScore: number;
totalWeight: number;
count: number;
}>();
for (const project of projects) {
const current = skillAccumulator.get(project.skill) || {
totalScore: 0,
weightedScore: 0,
totalWeight: 0,
count: 0,
};
current.totalScore += project.finalScore;
current.weightedScore += project.finalScore * project.difficultyWeight;
current.totalWeight += project.difficultyWeight;
current.count += 1;
skillAccumulator.set(project.skill, current);
}
const aggregatedSkills: AggregatedSkillScore[] = Array.from(skillAccumulator.entries())
.map(([skill, aggregate]) => ({
skill,
averageScore: roundValue(aggregate.totalScore / Math.max(1, aggregate.count)),
weightedScore: roundValue(aggregate.weightedScore / Math.max(1, aggregate.totalWeight)),
projectCount: aggregate.count,
totalWeight: roundValue(aggregate.totalWeight),
}))
.sort((left, right) => right.weightedScore - left.weightedScore);
const totalCertificates = rows.length;
const verifiedProjects = projects;
const verifiedCount = verifiedProjects.length;
const totalCommitCount = verifiedProjects.reduce((sum, project) => sum + project.commitCount, 0);
const averageFinalScore = verifiedCount
? roundValue(verifiedProjects.reduce((sum, project) => sum + project.finalScore, 0) / verifiedCount)
: 0;
const averageReadmeScore = verifiedCount
? roundValue(verifiedProjects.reduce((sum, project) => sum + project.trustSignals.readmeScore, 0) / verifiedCount)
: 0;
const validationPassRate = verifiedCount
? roundValue(
(verifiedProjects.filter((project) => project.trustSignals.validationPassed).length / verifiedCount) * 100
)
: 0;
const certificatesPayload = rows.map((item) => {
const metadata = item.metadata || {};
const projectType = toStringValue(metadata.project_type);
const track = (toStringValue(metadata.certification_track) || 'verifiedcert') as CertificationTrack;
return {
id: item.id,
skill: item.topic,
projectTitle: item.project_title,
issuedAt: item.issued_at,
githubUrl: toStringValue(metadata.github_repo_url) || toStringValue(metadata.github_url),
proofUrl: toStringValue(metadata.live_demo_url) || toStringValue(metadata.proof_url),
certificateId: toStringValue(metadata.certificate_id),
finalScore: Math.round(toNumberValue(metadata.final_score) ?? 0),
difficultyLevel: getDifficultyLevel(getDifficultyWeight(projectType)),
track,
};
});
const quickCertCount = allProjects.filter((p) => p.track === 'quickcert').length;
const verifiedCertCount = verifiedCount;
return {
userId,
username: (user as UserRow).username,
referralCode: (user as UserRow).referral_code,
referredUsersCount: referredUsersCount || 0,
certificates: certificatesPayload,
aggregatedSkills,
projects,
trustMetrics: {
totalCertificates,
averageFinalScore,
totalCommitCount,
validationPassRate,
averageReadmeScore,
topSkill: aggregatedSkills[0]?.skill || null,
quickCertCount,
verifiedCertCount,
},
shareLinks: {
profile: `${base}/user/${encodeURIComponent(userId)}`,
recruiter: `${base}/recruiter/${encodeURIComponent(userId)}`,
referral: (user as UserRow).referral_code
? `${base}/?ref=${encodeURIComponent((user as UserRow).referral_code as string)}`
: null,
},
};
}
|