-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepomix-output.txt
5138 lines (4635 loc) · 151 KB
/
repomix-output.txt
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
This file is a merged representation of the entire codebase, combining all repository files into a single document.
Generated by Repomix on: 2024-11-28T07:12:41.160Z
================================================================
File Summary
================================================================
Purpose:
--------
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This summary section
2. Repository information
3. Repository structure
4. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and Repomix's
configuration.
- Binary files are not included in this packed representation. Please refer to
the Repository Structure section for a complete list of file paths, including
binary files.
Additional Info:
----------------
For more information about Repomix, visit: https://github.com/yamadashy/repomix
================================================================
Repository Structure
================================================================
.bolt/config.json
.bolt/prompt
.gitignore
api/ai/chat.ts
api/ai/generate-code.ts
api/ai/generate-document.ts
api/ai/generate-idea.ts
api/auth/login.ts
api/auth/signup.ts
api/db/index.ts
api/index.ts
drizzle.config.ts
drizzle/0000_lean_robbie_robertson.sql
drizzle/meta/_journal.json
drizzle/meta/0000_snapshot.json
eslint.config.js
index.html
netlify.toml
package.json
postcss.config.js
README.md
SECURITY.md
src/@types/xterm-addon-fit.d.ts
src/App.tsx
src/components/AuthModal.tsx
src/components/dashboard/Analytics.tsx
src/components/dashboard/Chat.tsx
src/components/dashboard/CodeBuilder.tsx
src/components/dashboard/Documents.tsx
src/components/dashboard/IdeaGenerator.tsx
src/components/dashboard/Settings.tsx
src/components/dashboard/Terminal.tsx
src/components/ErrorBoundary.tsx
src/components/Features.tsx
src/components/Footer.tsx
src/components/Hero.tsx
src/components/Navbar.tsx
src/components/PaywallModal.tsx
src/components/Pricing.tsx
src/components/PrivateRoute.tsx
src/components/Testimonials.tsx
src/db/index.ts
src/db/migrate.ts
src/db/schema.ts
src/index.css
src/main.tsx
src/pages/Dashboard.tsx
src/pages/LandingPage.tsx
src/services/api.ts
src/services/webcontainer.ts
src/store/authStore.ts
src/vite-env.d.ts
tailwind.config.js
tsconfig.app.json
tsconfig.json
tsconfig.node.json
vercel.json
vite.config.ts
================================================================
Repository Files
================================================================
================
File: .bolt/config.json
================
{
"template": "bolt-vite-react-ts"
}
================
File: .bolt/prompt
================
For all designs I ask you to make, have them be beautiful, not cookie cutter. Make webpages that are fully featured and worthy for production.
By default, this template supports JSX syntax with Tailwind CSS classes, React hooks, and Lucide React for icons. Do not install other packages for UI themes, icons, etc unless absolutely necessary or I request them.
Use icons from lucide-react for logos.
Use stock photos from unsplash where appropriate, only valid URLs you know exist. Do not download the images, only link to them in image tags.
================
File: .gitignore
================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Database
*.db
*.sqlite
*.sqlite3
================
File: api/ai/chat.ts
================
// api/ai/chat.ts
import OpenAI from 'openai';
import type { VercelRequest, VercelResponse } from '@vercel/node';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
// Enable streaming
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Access-Control-Allow-Origin', '*');
try {
// Parse the request body
let messages;
if (typeof req.body === 'string') {
messages = JSON.parse(req.body).messages;
} else {
messages = req.body.messages;
}
if (!messages) {
throw new Error('No messages provided');
}
const completion = await openai.chat.completions.create({
model: 'gpt-4-0125-preview',
messages: [
{
role: 'system',
content: 'You are an AI co-founder assistant, helping entrepreneurs build and grow their startups. Provide strategic advice, answer questions, and help with planning.'
},
...messages
],
stream: true,
temperature: 0.7,
max_tokens: 1000
});
// Stream each chunk of the response
for await (const chunk of completion) {
const content = chunk.choices[0]?.delta?.content || '';
if (content) {
res.write(`data: ${JSON.stringify({ content })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();
} catch (error: any) {
console.error('Chat API error:', error);
res.write(`data: ${JSON.stringify({ error: error.message || 'An error occurred' })}\n\n`);
res.end();
}
}
================
File: api/ai/generate-code.ts
================
import { OpenAIStream } from 'ai';
import { Configuration, OpenAIApi } from 'openai-edge';
import { NextRequest } from 'next/server';
// Configure OpenAI
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
});
const openai = new OpenAIApi(configuration);
// Enable Edge Runtime
export const runtime = 'edge';
export default async function handler(req: NextRequest) {
if (req.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
try {
const { template, specifications, features } = await req.json();
const response = await openai.createChatCompletion({
model: 'gpt-4-0125-preview',
messages: [
{
role: 'system',
content: `You are an expert software developer. Generate production-ready, well-documented code based on the provided specifications.
Include error handling, best practices, and comments explaining key functionality.`
},
{
role: 'user',
content: `Generate code for a ${template} with the following:
Tech Stack: ${specifications.techStack.join(', ')}
Features: ${JSON.stringify(features)}
Specifications: ${JSON.stringify(specifications)}
Provide:
1. Main implementation code
2. Required dependencies
3. Setup instructions
4. API documentation (if applicable)
5. Testing guidelines`
}
],
stream: true,
temperature: 0.2,
max_tokens: 4000
});
// Create a streaming response
const stream = OpenAIStream(response);
return new Response(stream);
} catch (error: any) {
console.error('Code generation error:', error);
return new Response(
JSON.stringify({
error: 'Error generating code',
details: error.message
}),
{
status: 500,
headers: {
'Content-Type': 'application/json'
}
}
);
}
}
================
File: api/ai/generate-document.ts
================
// api/ai/generate-document.ts
import OpenAI from 'openai';
import type { VercelRequest, VercelResponse } from '@vercel/node';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { type, businessInfo, audience, purpose, tone } = req.body;
const documentPrompts = {
'pitch_deck': 'Create a compelling pitch deck outline with key slides and content',
'business_plan': 'Write a detailed business plan following standard industry format',
'marketing_plan': 'Develop a comprehensive marketing strategy and execution plan',
'financial_projection': 'Generate financial projections and analysis',
'executive_summary': 'Write a concise executive summary highlighting key business aspects'
};
const completion = await openai.chat.completions.create({
model: 'gpt-4-0125-preview',
messages: [
{
role: 'system',
content: `You are an expert business document writer. Generate professional ${type} documents that are detailed, well-structured, and tailored to the audience.`
},
{
role: 'user',
content: `${documentPrompts[type as keyof typeof documentPrompts]}
Business Information: ${JSON.stringify(businessInfo)}
Target Audience: ${audience}
Purpose: ${purpose}
Tone: ${tone}
Provide the document in a well-formatted structure with clear sections and professional language.`
}
],
temperature: 0.4,
max_tokens: 3000
});
return res.status(200).json({
document: completion.choices[0].message.content,
type,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('Document generation error:', error);
return res.status(500).json({ error: 'Failed to generate document' });
}
}
================
File: api/ai/generate-idea.ts
================
// api/ai/generate-idea.ts
import OpenAI from 'openai';
import type { VercelRequest, VercelResponse } from '@vercel/node';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
console.log('Method not allowed:', req.method);
return res.status(405).json({ error: 'Method not allowed' });
}
try {
console.log('Received request body:', req.body);
// Parse the request body if it's a string
const bodyData = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
console.log('Parsed request data:', bodyData);
const { industry, targetMarket, technology, problemSpace } = bodyData;
// Validate required fields
if (!industry || !targetMarket || !technology || !problemSpace) {
console.log('Missing required fields:', { industry, targetMarket, technology, problemSpace });
return res.status(400).json({ error: 'Missing required fields' });
}
console.log('Making OpenAI API call with parameters:', {
industry,
targetMarket,
technology,
problemSpace
});
const completion = await openai.chat.completions.create({
model: 'gpt-4-0125-preview',
messages: [
{
role: 'system',
content: 'You are a startup idea generator that creates innovative, market-viable business concepts. Format your response as detailed JSON.'
},
{
role: 'user',
content: `Generate a detailed startup idea with the following parameters:
Industry: ${industry}
Target Market: ${targetMarket}
Technology: ${technology}
Problem Space: ${problemSpace}
Return a JSON object with these exact keys:
{
"name": "startup name",
"pitch": "one line pitch",
"description": "detailed description",
"keyFeatures": ["feature1", "feature2", ...],
"targetAudience": "target audience description",
"revenueModel": "revenue model description",
"challenges": ["challenge1", "challenge2", ...],
"growthStrategy": "growth strategy description"
}`
}
],
temperature: 0.8,
max_tokens: 1000,
response_format: { type: "json_object" }
});
console.log('Received OpenAI response');
const responseContent = completion.choices[0].message.content;
console.log('Response content:', responseContent);
const parsedResponse = JSON.parse(responseContent);
console.log('Parsed response:', parsedResponse);
return res.status(200).json(parsedResponse);
} catch (error: any) {
console.error('Detailed error:', {
name: error.name,
message: error.message,
stack: error.stack,
response: error.response?.data,
status: error.response?.status
});
if (error instanceof SyntaxError) {
return res.status(400).json({
error: 'Invalid request format',
details: error.message
});
}
if (error.response?.status === 429) {
return res.status(429).json({
error: 'Rate limit exceeded. Please try again later.'
});
}
return res.status(500).json({
error: 'Failed to generate idea',
details: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
});
}
}
================
File: api/auth/login.ts
================
// api/auth/login.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { compare } from 'bcryptjs';
import { SignJWT } from 'jose';
import { sql } from '@vercel/postgres';
const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'fallback-secret-key-for-development');
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { email, password } = req.body;
console.log('Attempting login for email:', email);
// Check if email and password are provided
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
// Find user directly with SQL query
const userResult = await sql`
SELECT id, email, name, password_hash
FROM users
WHERE email = ${email}
`;
const user = userResult.rows[0];
if (!user) {
console.log('User not found:', email);
return res.status(401).json({ error: 'Invalid credentials' });
}
// Verify password
const validPassword = await compare(password, user.password_hash);
if (!validPassword) {
console.log('Invalid password for user:', email);
return res.status(401).json({ error: 'Invalid credentials' });
}
// Get subscription
const subscriptionResult = await sql`
SELECT *
FROM subscriptions
WHERE user_id = ${user.id}
AND status = 'active'
AND expires_at > NOW()
ORDER BY created_at DESC
LIMIT 1
`;
const subscription = subscriptionResult.rows[0];
// Generate JWT
const token = await new SignJWT({ userId: user.id })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('24h')
.sign(secret);
console.log('Login successful for user:', email);
return res.status(200).json({
token,
user: {
id: user.id,
email: user.email,
name: user.name
},
subscription
});
} catch (error) {
console.error('Login error:', error);
return res.status(500).json({
error: 'Internal server error',
details: process.env.NODE_ENV === 'development' ? error.message : undefined
});
}
}
================
File: api/auth/signup.ts
================
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { hash } from 'bcryptjs';
import { SignJWT } from 'jose';
import { db } from '../db';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { email, password, name } = req.body;
const existingUser = await db.users.findByEmail(email);
if (existingUser) {
return res.status(400).json({ error: 'Email already exists' });
}
const passwordHash = await hash(password, 10);
const user = await db.users.create({ email, name, passwordHash });
// Create a free trial subscription
const trialEnd = new Date();
trialEnd.setDate(trialEnd.getDate() + 14); // 14-day trial
const subscription = await db.subscriptions.create({
userId: user.id,
plan: 'starter',
status: 'active',
expiresAt: trialEnd
});
const token = await new SignJWT({ userId: user.id })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('24h')
.sign(secret);
res.status(201).json({
token,
user: {
id: user.id,
email: user.email,
name: user.name
},
subscription
});
} catch (error) {
console.error('Signup error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
================
File: api/db/index.ts
================
// api/db/index.ts
import { sql } from '@vercel/postgres';
export const db = {
users: {
create: async (data: { email: string; name: string; passwordHash: string }) => {
try {
const result = await sql`
INSERT INTO users (email, name, password_hash)
VALUES (${data.email}, ${data.name}, ${data.passwordHash})
RETURNING id, email, name;
`;
return result.rows[0];
} catch (error) {
console.error('Database error:', error);
throw error;
}
},
findByEmail: async (email: string) => {
try {
const result = await sql`
SELECT id, email, name, password_hash
FROM users
WHERE email = ${email};
`;
return result.rows[0];
} catch (error) {
console.error('Database error:', error);
throw error;
}
}
},
subscriptions: {
create: async (data: { userId: string; plan: string; status: string; expiresAt: Date }) => {
try {
const result = await sql`
INSERT INTO subscriptions (user_id, plan, status, expires_at)
VALUES (${data.userId}, ${data.plan}, ${data.status}, ${data.expiresAt})
RETURNING *;
`;
return result.rows[0];
} catch (error) {
console.error('Database error:', error);
throw error;
}
},
findByUserId: async (userId: string) => {
try {
const result = await sql`
SELECT *
FROM subscriptions
WHERE user_id = ${userId}
AND status = 'active'
AND expires_at > NOW()
ORDER BY created_at DESC
LIMIT 1;
`;
return result.rows[0];
} catch (error) {
console.error('Database error:', error);
throw error;
}
}
}
};
================
File: api/index.ts
================
import express from 'express';
import { sql } from '@vercel/postgres';
import cors from 'cors';
import { hash, compare } from 'bcryptjs';
import { body, validationResult } from 'express-validator';
import jwt from 'jsonwebtoken';
const app = express();
app.use(express.json());
app.use(cors());
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
// Middleware
const authenticate = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ error: 'Invalid token' });
}
};
// Initialize database
async function initDatabase() {
await sql`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
name TEXT NOT NULL
)
`;
await sql`
CREATE TABLE IF NOT EXISTS ideas (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
title TEXT NOT NULL,
description TEXT,
key_features JSONB,
target_audience TEXT,
revenue_model TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)
`;
await sql`
CREATE TABLE IF NOT EXISTS documents (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
type TEXT NOT NULL,
title TEXT NOT NULL,
content JSONB,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)
`;
}
initDatabase().catch(console.error);
// Auth endpoints
app.post('/api/auth/signup',
body('email').isEmail(),
body('password').isLength({ min: 6 }),
body('name').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password, name } = req.body;
try {
const hashedPassword = await hash(password, 10);
await sql`INSERT INTO users (email, password, name) VALUES (${email}, ${hashedPassword}, ${name})`;
res.status(201).json({ message: 'User created successfully' });
} catch (error) {
console.error('Signup error:', error);
res.status(400).json({ error: 'User creation failed' });
}
});
app.post('/api/auth/login',
body('email').isEmail(),
body('password').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
const result = await sql`SELECT * FROM users WHERE email = ${email}`;
const user = result.rows[0];
if (user && await compare(password, user.password)) {
const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '24h' });
res.json({ token, user: { id: user.id, email: user.email, name: user.name } });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Login failed' });
}
});
// Ideas endpoints
app.post('/api/ideas',
authenticate,
body('title').notEmpty(),
body('description').notEmpty(),
body('keyFeatures').isArray(),
body('targetAudience').notEmpty(),
body('revenueModel').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { title, description, keyFeatures, targetAudience, revenueModel } = req.body;
const userId = req.user.userId;
try {
const result = await sql`
INSERT INTO ideas (user_id, title, description, key_features, target_audience, revenue_model)
VALUES (${userId}, ${title}, ${description}, ${JSON.stringify(keyFeatures)}, ${targetAudience}, ${revenueModel})
RETURNING id
`;
res.status(201).json({ id: result.rows[0].id });
} catch (error) {
console.error('Idea creation error:', error);
res.status(400).json({ error: 'Idea creation failed' });
}
});
app.get('/api/ideas', authenticate, async (req, res) => {
const userId = req.user.userId;
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;
const offset = (page - 1) * limit;
try {
const result = await sql`
SELECT * FROM ideas
WHERE user_id = ${userId}
ORDER BY created_at DESC
LIMIT ${limit} OFFSET ${offset}
`;
const totalCount = await sql`SELECT COUNT(*) FROM ideas WHERE user_id = ${userId}`;
res.json({
ideas: result.rows.map(idea => ({ ...idea, keyFeatures: idea.key_features })),
totalCount: parseInt(totalCount.rows[0].count),
currentPage: page,
totalPages: Math.ceil(parseInt(totalCount.rows[0].count) / limit)
});
} catch (error) {
console.error('Fetch ideas error:', error);
res.status(500).json({ error: 'Failed to fetch ideas' });
}
});
app.put('/api/ideas/:id',
authenticate,
body('title').notEmpty(),
body('description').notEmpty(),
body('keyFeatures').isArray(),
body('targetAudience').notEmpty(),
body('revenueModel').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { id } = req.params;
const { title, description, keyFeatures, targetAudience, revenueModel } = req.body;
const userId = req.user.userId;
try {
const result = await sql`
UPDATE ideas
SET title = ${title}, description = ${description}, key_features = ${JSON.stringify(keyFeatures)},
target_audience = ${targetAudience}, revenue_model = ${revenueModel}
WHERE id = ${id} AND user_id = ${userId}
RETURNING *
`;
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Idea not found or unauthorized' });
}
res.json(result.rows[0]);
} catch (error) {
console.error('Update idea error:', error);
res.status(500).json({ error: 'Failed to update idea' });
}
});
app.delete('/api/ideas/:id', authenticate, async (req, res) => {
const { id } = req.params;
const userId = req.user.userId;
try {
const result = await sql`
DELETE FROM ideas
WHERE id = ${id} AND user_id = ${userId}
RETURNING id
`;
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Idea not found or unauthorized' });
}
res.json({ message: 'Idea deleted successfully' });
} catch (error) {
console.error('Delete idea error:', error);
res.status(500).json({ error: 'Failed to delete idea' });
}
});
// Documents endpoints
app.post('/api/documents',
authenticate,
body('type').notEmpty(),
body('title').notEmpty(),
body('content').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { type, title, content } = req.body;
const userId = req.user.userId;
try {
const result = await sql`
INSERT INTO documents (user_id, type, title, content)
VALUES (${userId}, ${type}, ${title}, ${JSON.stringify(content)})
RETURNING id
`;
res.status(201).json({ id: result.rows[0].id });
} catch (error) {
console.error('Document creation error:', error);
res.status(400).json({ error: 'Document creation failed' });
}
});
app.get('/api/documents', authenticate, async (req, res) => {
const userId = req.user.userId;
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;
const offset = (page - 1) * limit;
try {
const result = await sql`
SELECT * FROM documents
WHERE user_id = ${userId}
ORDER BY created_at DESC
LIMIT ${limit} OFFSET ${offset}
`;
const totalCount = await sql`SELECT COUNT(*) FROM documents WHERE user_id = ${userId}`;
res.json({
documents: result.rows,
totalCount: parseInt(totalCount.rows[0].count),
currentPage: page,
totalPages: Math.ceil(parseInt(totalCount.rows[0].count) / limit)
});
} catch (error) {
console.error('Fetch documents error:', error);
res.status(500).json({ error: 'Failed to fetch documents' });
}
});
app.put('/api/documents/:id',
authenticate,
body('type').notEmpty(),
body('title').notEmpty(),
body('content').notEmpty(),
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { id } = req.params;
const { type, title, content } = req.body;
const userId = req.user.userId;
try {
const result = await sql`
UPDATE documents
SET type = ${type}, title = ${title}, content = ${JSON.stringify(content)}
WHERE id = ${id} AND user_id = ${userId}
RETURNING *
`;
if (result.rows.length === 0) {