diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 4b5f477..e144694 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -522,11 +522,11 @@ components: properties: username: type: string - example: new_user_1 + example: alice_dev password: type: string format: password - example: newpassword1234 + example: alice1234 UserResponse: type: object @@ -536,7 +536,7 @@ components: example: 10 username: type: string - example: new_user_1 + example: alice_dev LoginResponse: type: object @@ -554,10 +554,10 @@ components: example: 1 name: type: string - example: AI-Powered Task Manager + example: A Task Manager description: type: string - example: A web app that uses AI to prioritize tasks intelligently + example: A web app that manages tasks. date_created: type: string format: date-time @@ -571,10 +571,10 @@ components: properties: name: type: string - example: AI-Powered Task Manager + example: A Task Manager description: type: string - example: A web app that uses AI to prioritize tasks intelligently + example: A web app that manages tasks. IdeaUpdateRequest: type: object @@ -582,10 +582,10 @@ components: properties: name: type: string - example: AI-Powered Task Manager + example: A task Manager description: type: string - example: A web app that uses AI to prioritize tasks intelligently + example: A web app that manages tasks. Project: type: object diff --git a/package-lock.json b/package-lock.json index 5855e17..ca670fc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,12 +7,14 @@ "": { "name": "Idea_Tracker", "version": "1.0.0", + "hasInstallScript": true, "license": "ISC", "dependencies": { "@prisma/adapter-pg": "^7.3.0", "@prisma/client": "^7.8.0", "archiver": "^7.0.1", "bcrypt": "^6.0.0", + "cross-env": "^10.1.0", "dotenv": "^17.2.3", "express": "^5.1.0", "express-validator": "^7.2.1", @@ -61,6 +63,12 @@ "@electric-sql/pglite": "0.4.1" } }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "license": "MIT" + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", @@ -1503,6 +1511,23 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", diff --git a/package.json b/package.json index 7438730..247181d 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,12 @@ "main": "index.js", "scripts": { "dev": "node --env-file=.env --watch src/server.js", - "seed": "node prisma/seed.js" + "start": "node src/server.js", + "seed:dev": "node --env-file=.env prisma/seed.js", + "seed:prod": "node prisma/seed.js", + "migrate:dev": "npx prisma migrate dev", + "migrate:deploy": "npx prisma migrate deploy", + "postinstall": "npx prisma generate" }, "keywords": [], "author": "", @@ -24,6 +29,7 @@ "@prisma/client": "^7.8.0", "archiver": "^7.0.1", "bcrypt": "^6.0.0", + "cross-env": "^10.1.0", "dotenv": "^17.2.3", "express": "^5.1.0", "express-validator": "^7.2.1", diff --git a/prisma/seed.js b/prisma/seed.js index a157dad..b432e61 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -1,11 +1,21 @@ import bcrypt from 'bcrypt'; import 'dotenv/config'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; import prisma from '../src/config/db.js'; -try { - await prisma.$queryRaw`TRUNCATE users, ideas, projects, materials, files RESTART IDENTITY CASCADE;`; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const seedFilesDir = path.join(__dirname, 'seed_files'); - // Create users +try { + // Clearing the database + if (process.env.NODE_ENV !== 'production') { + console.log('Clearing database for development seed...'); + await prisma.$queryRaw`TRUNCATE users, ideas, projects, materials, files RESTART IDENTITY CASCADE;`; + } + +// Creating my users const usersData = [ { username: 'alice_dev', password: 'alice1234' }, { username: 'bob_maker', password: 'bob1234' }, @@ -13,85 +23,68 @@ try { ]; const users = []; - for (const userData of usersData) { const hashedPassword = await bcrypt.hash(userData.password, 10); - const user = await prisma.user.create({ data: { username: userData.username, password: hashedPassword, }, }); - users.push(user); + console.log(`Created user: ${user.username}`); } - // Create ideas for each user + // Each user gets 3 Ideas, each Idea gets 3 Projects, each Project gets 3 Materials and 3 Files for (const user of users) { await prisma.idea.createMany({ data: [ - { - name: 'AI-Powered Task Manager', - description: - 'A web app that uses AI to prioritize tasks intelligently based on user patterns.', - userId: user.id, - }, - { - name: 'Community Recipe Hub', - description: - 'A platform where users can share, rate, and discover recipes from around the world.', - userId: user.id, - }, - { - name: 'Real-time Collaboration Tool', - description: - 'A tool for teams to brainstorm and collaborate in real-time with visual whiteboarding.', - userId: user.id, - }, + { name: `${user.username} Idea 1`, description: 'Smart Tasking', userId: user.id }, + { name: `${user.username} Idea 2`, description: 'Recipe Hub', userId: user.id }, + { name: `${user.username} Idea 3`, description: 'Collab Tool', userId: user.id }, ], }); - } - // Create projects with materials for each user - for (const user of users) { - const project = await prisma.project.create({ - data: { - name: `${user.username}'s Innovation Lab`, - description: `Main project workspace for ${user.username} to develop and prototype ideas.`, - userId: user.id, - }, - }); + for (let p = 1; p <= 3; p++) { + const project = await prisma.project.create({ + data: { + name: `${user.username} Project ${p}`, + description: `Workspace for project ${p}`, + userId: user.id, + }, + }); - // Add materials to the project - await prisma.material.createMany({ - data: [ - { - name: 'Research Paper on UX Design', - description: 'Key findings on modern UI/UX best practices.', - source: 'Nielsen Norman Group', - author: 'Don Norman', - text: 'User experience encompasses all aspects of the end-users interaction with the company, its services, and its products.', - projectId: project.id, - }, - { - name: 'API Documentation Reference', - description: 'Technical specifications for third-party integrations.', - source: 'OpenAI API Docs', - author: 'OpenAI Team', - text: 'The API provides access to state-of-the-art language models for various NLP tasks.', - projectId: project.id, - }, - { - name: 'Project Budget Template', - description: 'Financial planning and resource allocation framework.', - source: 'Internal Resources', - author: 'Finance Department', - text: 'Ensure all project expenses are tracked and approved according to company policy.', - projectId: project.id, - }, - ], - }); + await prisma.material.createMany({ + data: [ + { name: 'Research Paper', description: 'UX findings', source: 'Group A', author: 'Don Norman', text: 'Sample text...', projectId: project.id }, + { name: 'API Docs', description: 'Specs', source: 'Dev Portal', author: 'Team B', text: 'Technical data...', projectId: project.id }, + { name: 'Budget Template', description: 'Finance', source: 'Internal', author: 'Dept C', text: 'Allocations...', projectId: project.id }, + ], + }); + + // Create 3 Files for each project (pulling from seed_files folder), I put one of each mime type listed on line 94 and it will reuse any to make sure each user has 3. + if (fs.existsSync(seedFilesDir)) { + const availableFiles = fs.readdirSync(seedFilesDir); + if (availableFiles.length > 0) { + for (let f = 0; f < 3; f++) { + const filename = availableFiles[f % availableFiles.length]; + const filePath = path.join(seedFilesDir, filename); + const stats = fs.statSync(filePath); + const fileBuffer = fs.readFileSync(filePath); + + await prisma.file.create({ + data: { + name: `U${user.id}_P${project.id}_${f}_${filename}`, + file: fileBuffer, + size: stats.size, + mimeType: getMimeType(filename), + projectId: project.id, + }, + }); + } + } + } + } } console.log('Seed completed successfully!'); @@ -100,3 +93,15 @@ try { } finally { await prisma.$disconnect(); } + +function getMimeType(filename) { + const ext = path.extname(filename).toLowerCase(); + const mimes = { + '.pdf': 'application/pdf', + '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + '.png': 'image/png', + '.cpp': 'text/x-c', + '.txt': 'text/plain', + }; + return mimes[ext] || 'application/octet-stream'; +} \ No newline at end of file diff --git a/prisma/seed_files/seed_1.docx b/prisma/seed_files/seed_1.docx new file mode 100644 index 0000000..d1945cc Binary files /dev/null and b/prisma/seed_files/seed_1.docx differ diff --git a/prisma/seed_files/seed_2.pdf b/prisma/seed_files/seed_2.pdf new file mode 100644 index 0000000..64c4f17 Binary files /dev/null and b/prisma/seed_files/seed_2.pdf differ diff --git a/prisma/seed_files/seed_3.png b/prisma/seed_files/seed_3.png new file mode 100644 index 0000000..d5809a5 Binary files /dev/null and b/prisma/seed_files/seed_3.png differ diff --git a/prisma/seed_files/seed_4.cpp b/prisma/seed_files/seed_4.cpp new file mode 100644 index 0000000..9265b3a --- /dev/null +++ b/prisma/seed_files/seed_4.cpp @@ -0,0 +1,8 @@ +#include +using namespace std; + +int main() +{ + cout << "Hello Lew Price!\n"; + return 0; +} diff --git a/prisma/seed_files/seed_5.txt b/prisma/seed_files/seed_5.txt new file mode 100644 index 0000000..6f1dbd1 --- /dev/null +++ b/prisma/seed_files/seed_5.txt @@ -0,0 +1,8 @@ +The standard Lorem Ipsum passage, used since the 1500s +"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + +Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC +"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" + +1914 translation by H. Rackham +"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" \ No newline at end of file diff --git a/src/controllers/projectsController.js b/src/controllers/projectsController.js index e55d413..dbe5eac 100644 --- a/src/controllers/projectsController.js +++ b/src/controllers/projectsController.js @@ -82,7 +82,7 @@ export async function addProjectFileHandler(req, res) { name: req.file.originalname, file: req.file.buffer, size: req.file.size, - mimeType: req.file.mimetype + mimeType: req.file.mimetype, }; } catch (error) { return res.status(400).json({ error: 'Invalid file data' }); @@ -103,9 +103,9 @@ export async function addProjectFileHandler(req, res) { export async function deleteProjectFileHandler(req, res) { try { const fileId = parseInt(req.params.id); - + const deletedFile = await deleteProjectFile(fileId, req.user.id); - + if (!deletedFile) { return res.status(404).json({ error: 'File not found or unauthorized' }); } @@ -129,31 +129,31 @@ export async function downloadProjectFilesHandler(req, res) { res.set({ 'Content-Type': 'application/zip', - 'Content-Disposition': `attachment; filename="project_${fileId}_files.zip"` + 'Content-Disposition': `attachment; filename="project_${fileId}_files.zip"`, }); const archive = archiver('zip', { zlib: { level: 9 } }); archive.pipe(res); - files.forEach(f => { - + files.forEach((f) => { const binaryData = f.file; if (binaryData) { const bufferData = Buffer.from(binaryData); archive.append(bufferData, { name: f.name }); - } - else { - console.error(`ERROR: No binary data found for ${f.name}. Object was:`, f); + } else { + console.error( + `ERROR: No binary data found for ${f.name}. Object was:`, + f + ); } }); await archive.finalize(); - } catch (error) { if (!res.headersSent) { res.status(error.status || 500).json({ error: error.message }); } } -} \ No newline at end of file +} diff --git a/src/repositories/projectsRepo.js b/src/repositories/projectsRepo.js index 723ea59..3a5c67f 100644 --- a/src/repositories/projectsRepo.js +++ b/src/repositories/projectsRepo.js @@ -195,8 +195,8 @@ export async function addFile(projectId, userId, fileData) { file: fileData.file, size: fileData.size, mimeType: fileData.mimeType, - projectId: projectId - } + projectId: projectId, + }, }); return newFile; @@ -204,12 +204,17 @@ export async function addFile(projectId, userId, fileData) { export async function deleteFile(fileId, userId) { if (process.env.NODE_ENV === 'development') { - console.log('projectsRepo.deleteFile() called for fileId:', fileId, 'userId:', userId); + console.log( + 'projectsRepo.deleteFile() called for fileId:', + fileId, + 'userId:', + userId + ); } const file = await prisma.file.findUnique({ where: { id: fileId }, - include: { project: true } + include: { project: true }, }); if (!file || file.project.userId !== userId) { @@ -236,7 +241,7 @@ export async function getFilesWithContent(projectId, userId) { file: true, size: true, mimeType: true, - projectId: true - } + projectId: true, + }, }); -} \ No newline at end of file +} diff --git a/src/routes/projectsRoutes.js b/src/routes/projectsRoutes.js index ec43c86..2028b21 100644 --- a/src/routes/projectsRoutes.js +++ b/src/routes/projectsRoutes.js @@ -9,7 +9,7 @@ import { getProjectFilesHandler, addProjectFileHandler, deleteProjectFileHandler, - downloadProjectFilesHandler + downloadProjectFilesHandler, } from '../controllers/projectsController.js'; import { validateGetAllQuery, @@ -21,9 +21,9 @@ import { authenticate } from '../middleware/authenticate.js'; const router = express.Router(); -const upload = multer({ - storage: multer.memoryStorage(), - limits: { fileSize: 10 * 1024 * 1024 } +const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: 10 * 1024 * 1024 }, }); router.use(authenticate); @@ -37,7 +37,12 @@ router.delete('/:id', validateId, deleteProjectHandler); // Project File Routes router.get('/:id/files', validateId, getProjectFilesHandler); -router.post('/:id/files', validateId, upload.single('file'), addProjectFileHandler); +router.post( + '/:id/files', + validateId, + upload.single('file'), + addProjectFileHandler +); router.delete('/files/:id', validateId, deleteProjectFileHandler); router.get('/:id/files/download', validateId, downloadProjectFilesHandler); diff --git a/src/server.js b/src/server.js index 800e23f..7628a23 100644 --- a/src/server.js +++ b/src/server.js @@ -37,9 +37,9 @@ app.use((req, res, next) => { }); app.use((err, req, res, next) => { - if (err.code === "LIMIT_FILE_SIZE") { - return res.status(413).json({ - error: 'File size cannot exceed 10MB' + if (err.code === 'LIMIT_FILE_SIZE') { + return res.status(413).json({ + error: 'File size cannot exceed 10MB', }); } console.log(err.stack); diff --git a/src/services/projectsService.js b/src/services/projectsService.js index 66c0819..91b0d18 100644 --- a/src/services/projectsService.js +++ b/src/services/projectsService.js @@ -8,7 +8,7 @@ import { getFilesByProjectId, getFilesWithContent, addFile, - deleteFile + deleteFile, } from '../repositories/projectsRepo.js'; export async function getAllProjects(userId, options = {}) { @@ -147,7 +147,10 @@ export async function addProjectFile(projectId, userId, fileData) { export async function deleteProjectFile(fileId, userId) { if (process.env.NODE_ENV === 'development') { - console.log('projectsService.deleteProjectFile() called for fileId:', fileId); + console.log( + 'projectsService.deleteProjectFile() called for fileId:', + fileId + ); } const deletedFile = await deleteFile(fileId, userId);