Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ STELLAR_HORIZON_URL="https://horizon-testnet.stellar.org"
# Mainnet: https://soroban-rpc.mainnet.stellar.org
SOROBAN_RPC_URL="https://soroban-testnet.stellar.org"

OPENAI_API_KEY =

# Stellar Account Configuration (for blockchain transactions)
# These are used for issuing certificates on-chain
# IMPORTANT: Never commit real secret keys to version control!
Expand Down
9 changes: 8 additions & 1 deletion backend/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@
export default {
preset: 'ts-jest',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.tsx?$': [
'ts-jest',
{
useESM: true,
isolatedModules: true,
},
],
},
testMatch: ['**/tests/**/*.test.ts'],
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
Expand Down
3,636 changes: 1,051 additions & 2,585 deletions backend/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"dotenv": "^17.3.1",
"express": "^5.2.1",
"jsonwebtoken": "^9.0.2",
"openai": "^6.32.0",
"pg": "^8.20.0",
"prisma": "^7.5.0"
},
Expand Down
12 changes: 12 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,15 @@ model Feedback {
@@unique([studentId, courseId]) // One review per student per course
@@map("feedback")
}

model LearningProgress {
id String @id @default(cuid())
userId String @unique
completedLessons String[] // Array of strings for PostgreSQL
currentModule String @default("mod-1")
percentage Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

@@map("learning_progress")
}
66 changes: 66 additions & 0 deletions backend/src/generator/generator.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import OpenAI from 'openai';
import dotenv from 'dotenv';

dotenv.config();

export interface ProjectIdea {
title: string;
description: string;
keyFeatures: string[];
recommendedTech: string[];
difficulty: 'Beginner' | 'Intermediate' | 'Advanced';
}

export class GeneratorService {
private openai: OpenAI;

constructor() {
this.openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
}

async generateProjectIdea(
theme: string,
techStack: string[],
difficulty: string
): Promise<ProjectIdea> {
const prompt = `
As an expert Web3 and Software Architect, generate a unique and innovative hackathon project idea.

Theme: ${theme}
Technology Stack: ${techStack.join(', ')}
Target Difficulty: ${difficulty}

Return the response in a structured JSON format with the following keys:
- title: A catchy name for the project.
- description: A detailed description of the project and its value proposition.
- keyFeatures: An array of 3-5 core functionalities.
- recommendedTech: An array of tools and libraries that would be useful.
- difficulty: The suggested level (Beginner, Intermediate, or Advanced).

Ensure the idea is practical for a 48-hour hackathon but still innovative.
`;

try {
const response = await this.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'You are a helpful assistant that generates innovative hackathon project ideas in JSON format.' },
{ role: 'user', content: prompt }
],
response_format: { type: "json_object" }
});

const content = response.choices[0]?.message?.content;
if (!content) {
throw new Error('No content received from OpenAI');
}

return JSON.parse(content) as ProjectIdea;
} catch (error) {
console.error('Error generating project idea:', error);
throw new Error('Failed to generate project idea');
}
}
}
6 changes: 3 additions & 3 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import express, { Request, Response } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { requestLogger } from './middleware/requestLogger.js';
import authRoutes from './routes/auth/auth.routes.js';
import learningRoutes from './routes/learning/learning.routes.js';
import { requestLogger } from './middleware/requestLogger.js';
import authRoutes from './routes/auth/auth.routes';
import learningRoutes from './routes/learning/learning.routes';
import generatorRoutes from './routes/generator/generator.routes.js';
import routes from './routes/index.js';
import prisma from './db/index.js';

Expand All @@ -26,6 +25,7 @@ app.get('/health', (req: Request, res: Response) => {
// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/learning', learningRoutes);
app.use('/api/generator', generatorRoutes);
app.use('/api', routes);

// Start server only if not in test environment
Expand Down
34 changes: 34 additions & 0 deletions backend/src/routes/generator/generator.routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Router, Request, Response } from 'express';
import { GeneratorService } from '../../generator/generator.service.js';

const router = Router();
const generatorService = new GeneratorService();

/**
* @route POST /api/generator/generate
* @desc Generate a new project idea using AI
* @access Public
*/
router.post('/generate', async (req: Request, res: Response) => {
try {
const { theme, techStack, difficulty } = req.body;

if (!theme || !techStack || !difficulty) {
res.status(400).json({ error: 'Theme, techStack, and difficulty are required' });
return;
}

const projectIdea = await generatorService.generateProjectIdea(
theme,
techStack,
difficulty
);

res.json({ projectIdea });
} catch (error) {
console.error('Generator Route Error:', error);
res.status(500).json({ error: 'Failed to generate project idea' });
}
});

export default router;
62 changes: 57 additions & 5 deletions backend/src/routes/learning/learning.routes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Request, Response, Router } from 'express';
import * as LearningService from './learning.service.js';
import { Module } from './types.js';
import { Router, Request, Response } from 'express';
import { Module, Lesson, Progress } from './types.js';
import prisma from '../../db/index.js';

const router = Router();

Expand Down Expand Up @@ -50,6 +50,8 @@ const modules: Module[] = [
},
];

// Prisma handles progress storage now

/**
* @route GET /api/learning/modules
* @desc Get all learning modules
Expand Down Expand Up @@ -105,7 +107,22 @@ router.get('/modules/:moduleId', (req: Request, res: Response) => {
router.get('/progress/:userId', async (req: Request, res: Response) => {
try {
const userId = req.params.userId as string;
const progress = await LearningService.getStudentProgress(userId);
const progress = await prisma.learningProgress.findUnique({
where: { userId },
});

if (!progress) {
// Return default progress if user has no progress yet
res.json({
progress: {
userId,
completedLessons: [],
currentModule: 'mod-1',
percentage: 0,
},
});
return;
}

res.json({ progress });
} catch (error) {
Expand Down Expand Up @@ -138,7 +155,42 @@ router.post('/progress/:userId/complete', async (req: Request, res: Response) =>
return;
}

const progress = await LearningService.updateProgress(userId, lessonId);
// Get user progress from DB
let progressRecord = await prisma.learningProgress.findUnique({
where: { userId }
});

let completedLessons = progressRecord ? progressRecord.completedLessons : [];
let percentage = progressRecord ? progressRecord.percentage : 0;

// Mark lesson as complete if not already
if (!completedLessons.includes(lessonId)) {
completedLessons.push(lessonId);

// Calculate new percentage
const totalLessons = modules.reduce(
(acc, mod) => acc + mod.lessons.length,
0
);
percentage = Math.round(
(completedLessons.length / totalLessons) * 100
);
}

// Save back to DB
const progress = await prisma.learningProgress.upsert({
where: { userId },
update: {
completedLessons,
percentage
},
create: {
userId,
completedLessons,
currentModule: 'mod-1',
percentage
}
});

res.json({ progress, message: 'Lesson marked as complete' });
} catch (error) {
Expand Down
70 changes: 70 additions & 0 deletions backend/tests/generator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import request from 'supertest';
import { jest } from '@jest/globals';

// Mock OpenAI
jest.unstable_mockModule('openai', () => {
return {
default: jest.fn().mockImplementation(() => ({
chat: {
completions: {
// @ts-ignore
create: jest.fn().mockResolvedValue({
choices: [
{
message: {
content: JSON.stringify({
title: 'Test Project',
description: 'A test project description',
keyFeatures: ['Feature 1', 'Feature 2'],
recommendedTech: ['Node.js', 'React'],
difficulty: 'Intermediate'
})
}
}
]
})
}
}
}))
};
});

describe('Generator API Integration Tests', () => {
let app: any;

beforeAll(async () => {
// Dynamic import to ensure mock is registered first
const module = await import('../src/index.js');
app = module.app;
});

describe('POST /api/generator/generate', () => {
it('should generate a project idea with valid input', async () => {
const response = await request(app)
.post('/api/generator/generate')
.send({
theme: 'Environment',
techStack: ['React', 'Solidity'],
difficulty: 'Intermediate'
})
.expect(200);

expect(response.body).toHaveProperty('projectIdea');
expect(response.body.projectIdea).toHaveProperty('title', 'Test Project');
expect(response.body.projectIdea).toHaveProperty('description');
expect(Array.isArray(response.body.projectIdea.keyFeatures)).toBe(true);
});

it('should return 400 if required fields are missing', async () => {
const response = await request(app)
.post('/api/generator/generate')
.send({
theme: 'Environment'
// missing techStack and difficulty
})
.expect(400);

expect(response.body).toHaveProperty('error');
});
});
});
5 changes: 2 additions & 3 deletions backend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

// Environment Settings
// See also https://aka.ms/tsconfig/module
"module": "commonjs",
"module": "ESNext",
"target": "ES2022",
"moduleResolution": "bundler",
"esModuleInterop": true,
Expand Down Expand Up @@ -36,7 +36,6 @@
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*", "tests/**/*"],
"include": ["src/**/*", "src/generated/**/*"],
"include": ["src/**/*", "src/generated/**/*", "tests/**/*"],
"exclude": ["node_modules"]
}
Loading