diff --git a/skillgraph-web/app/(app)/market/page.tsx b/skillgraph-web/app/(app)/market/page.tsx index 8651138..5be84cd 100644 --- a/skillgraph-web/app/(app)/market/page.tsx +++ b/skillgraph-web/app/(app)/market/page.tsx @@ -7,7 +7,7 @@ import PageTransition from "@/components/PageTransition"; import { Button } from "@/components/ui/button"; interface SkillItem { skill: string; count: number; change: number | null } -interface MarketData { topSkills: SkillItem[]; role: string; totalJobsAnalyzed: number; week: number; lastUpdated: string } +interface MarketData { topSkills: SkillItem[]; role: string; totalJobsAnalyzed: number; week: number | null; lastUpdated: string | null } const roles = ['All Roles', 'Industrial AI Engineer', 'Data Analyst', 'ML Engineer', 'DevOps Engineer', 'Full Stack Dev']; const tabs = ['Skill Demand', 'Live Job Search', 'Salary Explorer']; diff --git a/skillgraph-web/app/(app)/openclaw/page.tsx b/skillgraph-web/app/(app)/openclaw/page.tsx index 6369e91..621ed22 100644 --- a/skillgraph-web/app/(app)/openclaw/page.tsx +++ b/skillgraph-web/app/(app)/openclaw/page.tsx @@ -179,7 +179,7 @@ export default function OpenClawPage() {
= {} +/** Skills asked for by role, counted per job posting. */ +function skillCounts(jobs: { requiredSkills: unknown }[]) { + const freq: Record = {} for (const job of jobs) { - const skills = (job.requiredSkills as string[]) || [] - for (const skill of skills) { - if (skill && skill.length > 1) { - skillFreq[skill] = (skillFreq[skill] || 0) + 1 - } - } + const skills = Array.isArray(job.requiredSkills) ? (job.requiredSkills as string[]) : [] + for (const skill of skills) if (skill && skill.length > 1) freq[skill] = (freq[skill] || 0) + 1 } + return freq +} - // Change = shift in the share of postings that ask for the skill, versus the previous week with data +/** + * Demand from the most recent week of loaded postings, compared with the week before it. + * Weeks are taken from when postings were loaded (scrapedAt), not the stored week number, + * which has no year and would mix this year's data with last year's. + */ +async function computeSkillDemand(role: string | null) { const roleFilter = role ? { role: { contains: role, mode: 'insensitive' as const } } : {} - const prev = await prisma.jobPosting.findFirst({ - where: { demandWeek: { lt: weekToReport }, ...roleFilter }, - orderBy: { demandWeek: 'desc' }, - select: { demandWeek: true }, - }) - const prevJobs = prev - ? await prisma.jobPosting.findMany({ where: { demandWeek: prev.demandWeek, ...roleFilter }, select: { requiredSkills: true }, take: 500 }) - : [] - const prevFreq: Record = {} - for (const job of prevJobs) { - for (const skill of (job.requiredSkills as string[]) || []) prevFreq[skill] = (prevFreq[skill] || 0) + 1 - } + const latest = await prisma.jobPosting.findFirst({ where: roleFilter, orderBy: { scrapedAt: 'desc' }, select: { scrapedAt: true, demandWeek: true } }) + if (!latest) return { week: null, role: role ?? 'All Roles', topSkills: [], totalJobsAnalyzed: 0, lastUpdated: null } + + const end = latest.scrapedAt.getTime() + const window = (from: number, to: number) => + prisma.jobPosting.findMany({ + where: { ...roleFilter, scrapedAt: { gt: new Date(from), lte: new Date(to) } }, + select: { requiredSkills: true }, + take: 500, + }) + const [jobs, prevJobs] = await Promise.all([window(end - 7 * DAY, end), window(end - 14 * DAY, end - 7 * DAY)]) + + const freq = skillCounts(jobs) + const prevFreq = skillCounts(prevJobs) const share = (count: number, total: number) => (total > 0 ? (count / total) * 100 : 0) - const topSkills = Object.entries(skillFreq) + const topSkills = Object.entries(freq) .sort(([, a], [, b]) => b - a) .slice(0, 20) .map(([skill, count]) => ({ skill, count, - // Percentage points; null when there is no earlier week to compare with + // Percentage-point shift in the share of postings asking for the skill; null without an earlier week change: prevJobs.length > 0 ? Math.round(share(count, jobs.length) - share(prevFreq[skill] ?? 0, prevJobs.length)) : null, })) - const lastScraped = await prisma.jobPosting.findFirst({ - orderBy: { scrapedAt: 'desc' }, - select: { scrapedAt: true }, - }) - return { - week: weekToReport, + week: latest.demandWeek, role: role ?? 'All Roles', topSkills, totalJobsAnalyzed: jobs.length, - lastUpdated: lastScraped?.scrapedAt ?? null, + lastUpdated: latest.scrapedAt, } } diff --git a/skillgraph-web/app/api/openclaw/applications/[id]/tailor/route.ts b/skillgraph-web/app/api/openclaw/applications/[id]/tailor/route.ts index e9d866f..c55e26b 100644 --- a/skillgraph-web/app/api/openclaw/applications/[id]/tailor/route.ts +++ b/skillgraph-web/app/api/openclaw/applications/[id]/tailor/route.ts @@ -5,6 +5,7 @@ import { auth } from '@/auth' import { prisma } from '@/lib/prisma' import { ok, unauthorized, badRequest, serverError, aiFailure } from '@/lib/api' import { createTailoredResume, NoResumeSource } from '@/lib/resume/tailor' +import { tailoringLimitReached } from '@/lib/openclaw/limits' // POST /api/openclaw/applications/:id/tailor — build a résumé tailored to this job (for jobs the // student evaluated themselves; the agent and the extension tailor automatically) @@ -19,6 +20,9 @@ export async function POST(_req: NextRequest, { params }: { params: Promise<{ id }) if (!app) return NextResponse.json({ error: 'Application not found' }, { status: 404 }) + const limited = await tailoringLimitReached(session.user.id) + if (limited) return limited + const { listing } = app const resume = await createTailoredResume( session.user.id, diff --git a/skillgraph-web/components/openclaw/AgentStatusCard.tsx b/skillgraph-web/components/openclaw/AgentStatusCard.tsx index cdd9331..e49ec98 100644 --- a/skillgraph-web/components/openclaw/AgentStatusCard.tsx +++ b/skillgraph-web/components/openclaw/AgentStatusCard.tsx @@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button"; interface AgentStatusCardProps { isActive: boolean; - preparedToday: number; + handledToday: number; readyToApply: number; dailyLimit: number; totalApplications: number; @@ -16,7 +16,7 @@ interface AgentStatusCardProps { export default function AgentStatusCard({ isActive, - preparedToday, + handledToday, readyToApply, dailyLimit, totalApplications, @@ -73,11 +73,11 @@ export default function AgentStatusCard({
{readyToApply}
Ready to apply
-
{preparedToday} / {dailyLimit} prepared or submitted today
+
{handledToday} / {dailyLimit} prepared or submitted today
diff --git a/skillgraph-web/lib/openclaw/filters.ts b/skillgraph-web/lib/openclaw/filters.ts index 3a868cb..8e30e51 100644 --- a/skillgraph-web/lib/openclaw/filters.ts +++ b/skillgraph-web/lib/openclaw/filters.ts @@ -40,19 +40,32 @@ export function filtersFromConfig(config: { } } +const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + +/** + * Whether `text` contains `term` as a whole word or phrase: "Java" doesn't match "JavaScript", + * "AI" doesn't match "maintain". Terms ending in symbols ("C++", "Node.js", "5+ years") still match. + */ +export function containsTerm(text: string, term: string): boolean { + const t = norm(term) + if (!t) return false + const start = /^[a-z0-9]/.test(t) ? '(? w && !ROLE_STOPWORDS.has(w)) - return words.length > 0 && words.every(w => t.includes(w)) + if (containsTerm(title, target)) return true + const words = norm(target).split(/[^a-z0-9+#.]+/).filter(w => w && !ROLE_STOPWORDS.has(w)) + return words.length > 0 && words.every(w => containsTerm(title, w)) } /** * Upper end of a CTC band in lakhs per annum, or null if it can't be read. * Understands "8-12 LPA", "6.5-7 Lacs P.A.", "12 lakhs", "₹6,00,000 - ₹9,00,000", "1200000-1800000 INR" - * and monthly amounts ("₹40,000 - ₹50,000 per month"); hourly pay returns null. + * monthly amounts ("₹40,000 - ₹50,000 per month", "60,000 a month") and thousands written as + * "25k". Hourly pay returns null. */ export function maxCtcLpa(band: string | null): number | null { if (!band) return null @@ -60,9 +73,10 @@ export function maxCtcLpa(band: string | null): number | null { // Foreign-currency bands can't be compared with a rupee minimum if (/[$€£]|\b(usd|eur|gbp|aud|cad|sgd)\b/.test(text)) return null // Hourly pay (Glassdoor shows some roles this way) can't be compared with an annual CTC - if (/per hour|hourly|\/\s*h(ou)?r\b/.test(text)) return null - const monthly = /per month|monthly|\/\s*mo(nth)?\b|\bp\.?m\.?(\s|$)/.test(text) - const nums = [...text.matchAll(/\d+(?:\.\d+)?/g)].map(m => Number(m[0])).filter(n => n > 0) + if (/per hour|hourly|an hour|\/\s*h(ou)?r\b/.test(text)) return null + const monthly = /per month|a month|monthly|per mensem|\/\s*mo(nth)?\b|\bp\.?m\.?(\s|$)/.test(text) + // "25k" / "25 K" are thousands + const nums = [...text.matchAll(/(\d+(?:\.\d+)?)\s*(k\b)?/g)].map(m => Number(m[1]) * (m[2] ? 1000 : 1)).filter(n => n > 0) if (nums.length === 0) return null const max = Math.max(...nums) if (/lpa|lakh|lac|\bl\b/.test(text) || max < 200) return monthly ? max * 12 : max @@ -75,7 +89,7 @@ export function checkFilters(job: Pick norm(job.company).includes(norm(c))) + const blocked = f.blacklistedCompanies.find(c => containsTerm(job.company, c)) if (blocked) fail.push(`${job.company} is on your blocked companies list`) if (f.targetRoles.length > 0) { @@ -86,7 +100,7 @@ export function checkFilters(job: Pick 0 && job.location) { const wantsRemote = f.preferredCities.some(c => REMOTE.test(c)) - const city = f.preferredCities.find(c => !REMOTE.test(c) && norm(job.location!).includes(norm(c))) + const city = f.preferredCities.find(c => !REMOTE.test(c) && containsTerm(job.location!, c)) if (city) pass.push(`Location matches ${city}`) else if (wantsRemote && REMOTE.test(job.location)) pass.push('Remote role') else fail.push(`${job.location} isn’t one of your cities (${f.preferredCities.join(', ')})`) @@ -98,11 +112,11 @@ export function checkFilters(job: Pick haystack.includes(norm(k))) + const excluded = f.excludeKeywords.find(k => containsTerm(haystack, k)) if (excluded) fail.push(`Mentions “${excluded}”, which you excluded`) if (f.includeKeywords.length > 0) { - const hit = f.includeKeywords.find(k => haystack.includes(norm(k))) + const hit = f.includeKeywords.find(k => containsTerm(haystack, k)) if (hit) pass.push(`Mentions “${hit}”`) else fail.push(`Mentions none of your keywords (${f.includeKeywords.join(', ')})`) } diff --git a/skillgraph-web/lib/openclaw/limits.ts b/skillgraph-web/lib/openclaw/limits.ts new file mode 100644 index 0000000..0df8da9 --- /dev/null +++ b/skillgraph-web/lib/openclaw/limits.ts @@ -0,0 +1,32 @@ +/** + * The plan's daily OpenClaw allowance (lib/billing/plans.ts → openclawPerDay), counted as job-tailored + * résumés generated today. Shared by the browser extension and "Tailor CV"; the nightly agent + * applies the same plan limit to what it prepares or submits. + */ +import { NextResponse } from 'next/server' +import { prisma } from '@/lib/prisma' +import { getEntitlements } from '@/lib/billing' + +function startOfToday() { + const d = new Date() + d.setHours(0, 0, 0, 0) + return d +} + +/** A 402 response when today's allowance is used up, otherwise null. */ +export async function tailoringLimitReached(userId: string): Promise { + const [{ limits, plan }, usedToday] = await Promise.all([ + getEntitlements(userId), + prisma.resumeVersion.count({ where: { userId, generatedBy: 'AI', createdAt: { gte: startOfToday() } } }), + ]) + if (usedToday < limits.openclawPerDay) return null + return NextResponse.json( + { + error: plan === 'student_free' + ? `You've tailored ${usedToday} résumés today, the Free plan's daily limit. Upgrade to Pro on the Billing page for more.` + : `Daily limit of ${limits.openclawPerDay} tailored résumés reached. It resets at midnight.`, + code: 'plan_limit', + }, + { status: 402 }, + ) +} diff --git a/skillgraph-web/lib/rateLimit.ts b/skillgraph-web/lib/rateLimit.ts index cd84704..249224d 100644 --- a/skillgraph-web/lib/rateLimit.ts +++ b/skillgraph-web/lib/rateLimit.ts @@ -116,6 +116,8 @@ export type RateLimitRule = { windowMs: number methods?: string[] match: (pathname: string) => boolean + /** Count per client IP even for signed-in or token callers (a ceiling that forged tokens can't escape). */ + keyBy?: 'ip' } const MINUTE = 60_000 @@ -209,6 +211,15 @@ export const RATE_LIMIT_RULES: RateLimitRule[] = [ p.startsWith('/api/market/job-details') || p.startsWith('/api/market/company-salary'), }, + { + // Extension calls are limited per token (rules above) plus this per-IP ceiling: generous enough for a + // campus behind one IP, and a stream of made-up tokens can't each get a fresh bucket + name: 'extension_ip', + limit: 600, + windowMs: 15 * MINUTE, + keyBy: 'ip', + match: (p) => p.startsWith('/api/extension/'), + }, ] export type RateLimitResult = @@ -222,13 +233,15 @@ export type RateLimitResult = export async function checkRateLimit( method: string, pathname: string, - clientKey: string + clientKey: string, + ip = 'unknown' ): Promise { for (const rule of RATE_LIMIT_RULES) { if (rule.methods && !rule.methods.includes(method)) continue if (!rule.match(pathname)) continue - const { count, resetAt } = await store.increment(`${rule.name}:${clientKey}`, rule.windowMs) + const key = rule.keyBy === 'ip' ? `ip:${ip}` : clientKey + const { count, resetAt } = await store.increment(`${rule.name}:${key}`, rule.windowMs) if (count > rule.limit) { return { limited: true, rule, retryAfterSec: Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) } } diff --git a/skillgraph-web/lib/scheduled.ts b/skillgraph-web/lib/scheduled.ts index 50d194e..816fb00 100644 --- a/skillgraph-web/lib/scheduled.ts +++ b/skillgraph-web/lib/scheduled.ts @@ -21,6 +21,16 @@ export const NO_DEADLINE = Number.POSITIVE_INFINITY const timeLeft = (deadline: number) => deadline - Date.now() +/** Unbiased (Fisher–Yates) shuffle; sort(() => Math.random() - 0.5) favours some positions. */ +export function shuffle(items: T[]): T[] { + const out = [...items] + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[out[i], out[j]] = [out[j], out[i]] + } + return out +} + async function notify(to: string, subject: string, html: string, text: string) { if (!emailConfigured()) return false await sendEmail(to, subject, html, text) @@ -38,12 +48,19 @@ export async function runBillingMaintenance() { where: { status: 'pending', createdAt: { lt: new Date(now.getTime() - 7 * DAY) } }, }) - // Remind the purchaser once, about 7 days before a period ends (only if no later period is already paid) + // Remind the purchaser once in the last 7 days of a period (only if no later period is already paid). + // "Once" is recorded in WebhookEvent rather than inferred from an exact time window, because + // Vercel Hobby cron can start anywhere within its hour. const ending = await prisma.subscription.findMany({ - where: { status: 'active', periodEnd: { gt: new Date(now.getTime() + 6 * DAY), lte: new Date(now.getTime() + 7 * DAY) } }, + where: { status: 'active', periodEnd: { gt: now, lte: new Date(now.getTime() + 7 * DAY) } }, }) + const reminderId = (subscriptionId: string) => `renewal-reminder:${subscriptionId}` + const alreadySent = new Set( + (await prisma.webhookEvent.findMany({ where: { id: { in: ending.map(s => reminderId(s.id)) } }, select: { id: true } })).map(e => e.id), + ) let reminded = 0 for (const sub of ending) { + if (alreadySent.has(reminderId(sub.id))) continue const renewed = await prisma.subscription.findFirst({ where: { ownerType: sub.ownerType, ownerId: sub.ownerId, plan: sub.plan, status: 'active', periodStart: { gte: sub.periodEnd! } }, select: { id: true }, @@ -60,7 +77,10 @@ export async function runBillingMaintenance() { `

Hi ${escapeHtml(buyer.name)},

Your ${escapeHtml(planName)} plan ends on ${ends}. Renew to keep your benefits without interruption.

Renew now →

`, `Hi ${buyer.name}, your ${planName} plan ends on ${ends}. Renew at ${appUrl('/billing')}`, ) - if (sent) reminded++ + if (sent) { + reminded++ + await prisma.webhookEvent.create({ data: { id: reminderId(sub.id), provider: 'internal', type: 'renewal_reminder' } }) + } } catch (err) { console.error(`[billing] reminder failed for subscription ${sub.id}:`, (err as Error).message) } @@ -122,7 +142,7 @@ export async function runSprintGenerator(deadline: number) { export async function runOpenClawNightly(deadline: number) { const configs = await prisma.openClawConfig.findMany({ where: { isActive: true }, select: { userId: true } }) // Random order, so a run that hits the deadline doesn't always leave out the same students - const order = configs.map(c => c.userId).sort(() => Math.random() - 0.5) + const order = shuffle(configs.map(c => c.userId)) const outcome = { active: order.length, ran: 0, prepared: 0, submitted: 0, notReached: 0 } for (const userId of order) { // An agent run can take ~2 minutes; don't start one that can't finish @@ -240,15 +260,21 @@ async function extractSkills(description: string): Promise { } /** - * Loads this week's postings role by role, skipping roles already loaded this week, so a run + * Loads this week's postings role by role, skipping roles loaded in the last 7 days, so a run * that stops at the deadline is completed by the next one. Each role is written in one * transaction, so a role is either fully loaded or not at all. */ export async function runMarketRefresh(deadline: number) { if (!process.env.RAPIDAPI_KEY) return { skipped: 'RAPIDAPI_KEY is not set' } const week = currentDemandWeek() + // A role counts as loaded if it was loaded in the last 7 days. (The stored week number has no + // year, so matching on it would treat last year's rows for the same week as this week's.) const done = new Set( - (await prisma.jobPosting.findMany({ where: { demandWeek: week, source: 'jsearch' }, distinct: ['role'], select: { role: true } })).map(r => r.role), + (await prisma.jobPosting.findMany({ + where: { source: 'jsearch', scrapedAt: { gte: new Date(Date.now() - 7 * DAY) } }, + distinct: ['role'], + select: { role: true }, + })).map(r => r.role), ) const outcome = { week, loaded: [] as string[], alreadyLoaded: done.size, remaining: 0, failed: [] as string[] } for (const role of MARKET_ROLES) { diff --git a/skillgraph-web/proxy.ts b/skillgraph-web/proxy.ts index e8e62e4..fa66a19 100644 --- a/skillgraph-web/proxy.ts +++ b/skillgraph-web/proxy.ts @@ -47,8 +47,9 @@ export default async function proxy(req: NextRequest) { const isApi = pathname.startsWith('/api/') if (isApi) { - const clientKey = session?.user?.id ?? (await extensionClientKey(req)) ?? `ip:${clientIp(req.headers)}` - const limit = await checkRateLimit(req.method, pathname, clientKey) + const ip = clientIp(req.headers) + const clientKey = session?.user?.id ?? (await extensionClientKey(req)) ?? `ip:${ip}` + const limit = await checkRateLimit(req.method, pathname, clientKey, ip) if (limit.limited) { return tag(NextResponse.json( { error: 'Too many requests. Please try again later.' }, diff --git a/skillgraph-web/tests/core.test.ts b/skillgraph-web/tests/core.test.ts index c548089..456d308 100644 --- a/skillgraph-web/tests/core.test.ts +++ b/skillgraph-web/tests/core.test.ts @@ -68,6 +68,14 @@ test('bulk AI runs and paid job-search lookups are rate limited', async () => { assert.equal((await checkRateLimit('GET', '/api/market/india', 'user:market')).limited, false) }) +test('made-up extension tokens share one per-IP ceiling', async () => { + let last + for (let i = 0; i < 601; i++) last = await checkRateLimit('GET', '/api/extension/me', `ext:forged-${i}`, '9.9.9.9') + assert.equal(last?.limited, true) + assert.equal(last?.limited && last.rule.name, 'extension_ip') + assert.equal((await checkRateLimit('GET', '/api/extension/me', 'ext:real', '8.8.8.8')).limited, false) +}) + // ─── Consent-based identity reveal ─────────────────────────────────────────── const student = { diff --git a/skillgraph-web/tests/openclaw.test.ts b/skillgraph-web/tests/openclaw.test.ts index fd377c9..7d502e6 100644 --- a/skillgraph-web/tests/openclaw.test.ts +++ b/skillgraph-web/tests/openclaw.test.ts @@ -1,6 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' -import { checkFilters, maxCtcLpa, filtersFromConfig, type JobFilters } from '@/lib/openclaw/filters' +import { checkFilters, maxCtcLpa, filtersFromConfig, containsTerm, type JobFilters } from '@/lib/openclaw/filters' +import { shuffle } from '@/lib/scheduled' import { submissionTarget, knownAnswer, splitName, type Applicant } from '@/lib/openclaw/submit' import { resumeFileName } from '@/lib/resume/tailor' import { parseTailoringNotes, submittedViaLabel, statusLabel, recommendationLabel } from '@/components/openclaw/labels' @@ -78,6 +79,31 @@ test('pay bands are read in lakhs per annum', () => { assert.equal(maxCtcLpa('₹7,195.34 - ₹14,390.68 Per hour (Employer provided)'), null) assert.equal(maxCtcLpa('₹40,000 - ₹50,000 per month'), 6) assert.equal(maxCtcLpa('₹500,000.00/yr - ₹1,000,000.00/yr'), 10) + // Thousands written as "k", and "a month" + assert.equal(maxCtcLpa('₹25K - ₹30K per month'), 3.6) + assert.equal(maxCtcLpa('50,000 - 60,000 a month'), 7.2) + assert.equal(maxCtcLpa('₹500 an hour'), null) +}) + +test('filters match whole words, not parts of other words', () => { + assert.equal(containsTerm('JavaScript Developer', 'Java'), false) + assert.equal(containsTerm('Senior Java Developer', 'java'), true) + assert.equal(containsTerm('You will maintain services', 'AI'), false) + assert.equal(containsTerm('Work on AI agents', 'AI'), true) + assert.equal(containsTerm('Strong C++ and Node.js', 'C++'), true) + assert.equal(containsTerm('Strong C++ and Node.js', 'node.js'), true) + assert.equal(containsTerm('Requires 5+ years of experience', '5+ years'), true) + assert.equal(containsTerm('Team bonding events', 'bond'), false) + const java = { ...filters, targetRoles: ['Java Developer'], includeKeywords: [], excludeKeywords: ['bond'] } + assert.equal(checkFilters({ ...job, role: 'JavaScript Developer' }, java).ok, false) + assert.equal(checkFilters({ ...job, role: 'Java Developer', jdText: 'Monthly team bonding' }, java).ok, true) +}) + +test('nightly order shuffle keeps every student exactly once', () => { + const ids = Array.from({ length: 50 }, (_, i) => `u${i}`) + const out = shuffle(ids) + assert.equal(out.length, 50) + assert.deepEqual([...out].sort(), [...ids].sort()) assert.equal(maxCtcLpa(null), null) })