Skip to content

benspak/PopTask-Server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

40 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PopVia Backend API

A production-ready Node.js/Express backend for the PopVia application with MongoDB integration, comprehensive JWT authentication, OAuth support, user management, file upload capabilities, sharing features, time tracking, collaboration tools, shared content management, company verification, invoice processing, payment integration, job board, proposal templates, and team management.

πŸ’° Business Value

Target Market: SaaS productivity platform serving SMBs, freelancers, and agencies Revenue Potential: $20M+ ARR by 2050 through scalable subscription model Value Delivered: 10x ROI through time savings, team collaboration, business management, and client acquisition Key Features: Complete business management API with authentication, collaboration, job board, proposal templates, invoicing, and analytics

πŸš€ Features

  • RESTful API for task, project, user, company, client, invoice, job, proposal template, and team management
  • Comprehensive Authentication with JWT, refresh tokens, OAuth (Google), email verification, and account locking
  • User Management with registration, login, password reset, profile management, and user tiers (Basic, Pro, Admin)
  • MongoDB Integration with Mongoose ODM and optimized queries
  • File Upload System with GridFS storage (10MB limit) and image processing
  • Task & Project Sharing with permission-based access control and public links
  • Shared Content System for viewing tasks and projects shared with users
  • Time Tracking with start/stop timer, session history, and detailed statistics
  • User Limits with Basic (10 tasks/5 projects) and Pro (unlimited) tiers
  • Collaboration Features with username-based sharing and public links
  • Shared Project Task Creation allowing users to add tasks to shared projects
  • Company Management with verification system, public profiles, logo uploads, and analytics
  • Client Management with contact tracking, project relationships, and engagement analytics
  • Invoice System with line items, calculations, status tracking, and payment processing
  • Payment Integration with Stripe for subscriptions and invoice payments
  • Job Board System with job posting, public job board, application management, and analytics
  • Proposal Templates with variable system, categories, public sharing, and usage analytics
  • Team Management with role-based permissions, member invitations, and team analytics
  • Email System with Resend for verification, notifications, invoice delivery, and pro welcome emails
  • OAuth Integration with Google OAuth for seamless login
  • CORS Configuration for cross-origin requests
  • Security Headers with Helmet.js
  • Rate Limiting on authentication and payment endpoints
  • Health Monitoring with detailed status endpoints
  • Production Logging with Morgan
  • Input Validation with express-validator
  • Environment Configuration for flexible deployment
  • Feedback System for user suggestions and bug reports
  • Analytics & Statistics for comprehensive business insights

πŸ“‹ Prerequisites

  • Node.js 18+
  • MongoDB (local or Atlas)
  • npm or yarn

βš™οΈ Configuration

Environment Variables

Copy the example environment file and configure it:

cp env.example .env

Required Variables

# Server Configuration
PORT=3001
NODE_ENV=production

# Database
MONGODB_URI=mongodb://localhost:27017/taskmanager

# CORS
ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com
FRONTEND_URL=https://yourdomain.com

# File Upload
MAX_FILE_SIZE=10485760

# Authentication
JWT_SECRET=your-super-secret-jwt-key-change-in-production

# OAuth Configuration (OPTIONAL)
GOOGLE_CLIENT_ID=your-google-client-id-here
GOOGLE_CLIENT_SECRET=your-google-client-secret-here

# Email Configuration (for verification and password reset)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password
EMAIL_FROM=PopVia <noreply@popvia.me>

# Email Configuration
RESEND_API_KEY=your-resend-api-key-here
RESEND_FROM=noreply@popvia.me

# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key_here
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key_here
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here

Optional Variables

# Security
SESSION_SECRET=your-session-secret-here

# Logging
LOG_LEVEL=info

πŸ› οΈ Installation

Development Setup

# Install dependencies
npm install

# Start development server with nodemon
npm run dev

# Start production server
npm start

Production Setup

# Install production dependencies only
npm ci --only=production

# Start with PM2
pm2 start server.js --name "popvia-backend"

# Or start directly
npm start

🐳 Docker Deployment

Build and Run

# Build the image
docker build -t popvia-backend .

# Run with environment file
docker run -d \
  --name popvia-backend \
  -p 3001:3001 \
  --env-file .env \
  popvia-backend

Docker Compose

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f backend

# Stop services
docker-compose down

πŸ“‘ API Endpoints

Health Check

  • GET /api/health - Server and database status

Authentication

  • POST /api/auth/register - User registration with email verification
  • POST /api/auth/login - User login with JWT tokens
  • POST /api/auth/logout - User logout
  • POST /api/auth/refresh - Refresh JWT token
  • POST /api/auth/verify-email - Email verification
  • POST /api/auth/forgot-password - Password reset request
  • POST /api/auth/reset-password - Password reset
  • GET /api/auth/me - Get current user profile
  • PUT /api/auth/profile - Update user profile
  • PUT /api/auth/change-password - Change password
  • GET /api/auth/profile/:username - Get public user profile by username
  • PUT /api/auth/profile-picture - Update profile picture
  • GET /api/auth/google - Initiate Google OAuth login
  • GET /api/auth/google/callback - Google OAuth callback
  • POST /api/auth/oauth/token - Exchange OAuth tokens for JWT

Tasks

  • GET /api/tasks - Get all tasks (with filtering)
  • GET /api/tasks/:id - Get task by ID
  • POST /api/tasks - Create new task
  • PUT /api/tasks/:id - Update task
  • DELETE /api/tasks/:id - Delete task
  • PATCH /api/tasks/:id/toggle - Toggle completion
  • POST /api/tasks/:id/share - Share task with user
  • POST /api/tasks/:id/share/add-user - Add user to shared task
  • DELETE /api/tasks/:id/share/remove-user - Remove user from shared task
  • GET /api/tasks/shared - Get shared tasks
  • POST /api/tasks/:id/start-timer - Start time tracking
  • POST /api/tasks/:id/stop-timer - Stop time tracking
  • GET /api/tasks/:id/time-summary - Get time tracking summary
  • GET /api/tasks/limits - Get task limits for user

Projects

  • GET /api/projects - Get all projects
  • GET /api/projects/:id - Get project by ID
  • POST /api/projects - Create new project
  • PUT /api/projects/:id - Update project
  • DELETE /api/projects/:id - Delete project
  • POST /api/projects/:id/share - Share project with user
  • GET /api/projects/shared - Get shared projects
  • GET /api/projects/limits - Get project limits for user

Companies

  • GET /api/companies - Get all companies
  • GET /api/companies/:id - Get company by ID
  • POST /api/companies - Create new company
  • PUT /api/companies/:id - Update company
  • DELETE /api/companies/:id - Delete company
  • GET /api/companies/verified - Get verified companies (public)
  • GET /api/companies/verify/:token - Verify company by token
  • POST /api/companies/:id/request-verification - Request company verification
  • POST /api/companies/:id/generate-public-link - Generate public company link
  • GET /api/companies/public/:slug/:token - Get public company details
  • GET /api/companies/stats - Get company statistics

Clients

  • GET /api/clients - Get all clients
  • GET /api/clients/:id - Get client by ID
  • POST /api/clients - Create new client
  • PUT /api/clients/:id - Update client
  • DELETE /api/clients/:id - Delete client

Invoices

  • GET /api/invoices - Get all invoices
  • GET /api/invoices/:id - Get invoice by ID
  • POST /api/invoices - Create new invoice
  • PUT /api/invoices/:id - Update invoice
  • DELETE /api/invoices/:id - Delete invoice
  • POST /api/invoices/:id/payment-link - Generate payment link
  • POST /api/invoices/:id/send-email - Send invoice email

Jobs

  • GET /api/jobs - Get all jobs (user's jobs)
  • GET /api/jobs/:id - Get job by ID
  • POST /api/jobs - Create new job
  • PUT /api/jobs/:id - Update job
  • DELETE /api/jobs/:id - Delete job
  • GET /api/jobs/public - Get public job board
  • POST /api/jobs/:id/publish - Publish job
  • POST /api/jobs/:id/apply - Apply for job
  • GET /api/jobs/:id/applications - Get job applications
  • GET /api/jobs/:slug - Get job by slug (public)

Proposal Templates

  • GET /api/proposal-templates - Get all templates
  • GET /api/proposal-templates/:id - Get template by ID
  • POST /api/proposal-templates - Create new template
  • PUT /api/proposal-templates/:id - Update template
  • DELETE /api/proposal-templates/:id - Delete template
  • GET /api/proposal-templates/public - Get public templates
  • POST /api/proposal-templates/:id/duplicate - Duplicate template
  • POST /api/proposal-templates/:id/generate - Generate proposal from template
  • GET /api/proposal-templates/categories - Get template categories

Teams

  • GET /api/teams - Get all teams
  • GET /api/teams/:id - Get team by ID
  • POST /api/teams - Create new team
  • PUT /api/teams/:id - Update team
  • DELETE /api/teams/:id - Delete team
  • POST /api/teams/:id/members - Add team member
  • DELETE /api/teams/:id/members/:userId - Remove team member
  • PUT /api/teams/:id/members/:userId/role - Update member role
  • GET /api/teams/limits - Get team limits for user

Payments

  • POST /api/payments/create-link - Create Stripe payment link
  • POST /api/payments/webhook - Handle Stripe webhooks
  • GET /api/payments/verify-session/:sessionId - Verify payment session

File Uploads

  • POST /api/uploads/task/:taskId - Upload file to task
  • DELETE /api/uploads/task/:taskId/file/:filename - Delete file
  • GET /api/uploads/files/:filename - Download file

Shared Content

  • GET /api/tasks/shared/:token - Get shared task by token
  • GET /api/projects/shared/:token - Get shared project by token
  • PUT /api/tasks/shared/:token - Update shared task
  • PUT /api/projects/shared/:token - Update shared project

Dashboard

  • GET /api/dashboard - Get dashboard statistics and data
  • GET /api/dashboard/stats - Get comprehensive analytics

Feedback

  • POST /api/feedback - Send feedback email

πŸ” Query Parameters

Task Filtering

  • ?project=marketing - Filter by project
  • ?tag=analytics - Filter by tag
  • ?completed=true - Filter by completion status
  • ?search=keyword - Search in title and description

Job Filtering

  • ?category=engineering - Filter by job category
  • ?type=full-time - Filter by job type
  • ?locationType=remote - Filter by location type
  • ?search=keyword - Search in job title and description

πŸ“Š Data Models

User Schema

{
  email: String (required, unique),
  username: String (required, unique),
  password: String (hashed with bcrypt),
  firstName: String (required),
  lastName: String (required),
  displayName: String (required),
  biography: String,
  profilePicture: String,
  userType: String (enum: ['basic', 'pro', 'admin'], default: 'basic'),
  isEmailVerified: Boolean (default: false),
  emailVerificationToken: String,
  passwordResetToken: String,
  passwordResetExpires: Date,
  isLocked: Boolean (default: false),
  failedLoginAttempts: Number (default: 0),
  lockUntil: Date,
  role: String (enum: ['user', 'admin'], default: 'user'),
  oauthProvider: String,
  oauthId: String,
  lastLogin: Date,
  createdAt: Date,
  updatedAt: Date
}

Task Schema

{
  title: String (required),
  description: String,
  dueDate: Date,
  project: String,
  tags: [String] (max 3),
  completed: Boolean (default: false),
  priority: String (enum: ['low', 'medium', 'high'], default: 'medium'),
  userId: ObjectId (ref: 'User'),
  // Sharing fields
  shareToken: String (unique),
  sharePermission: String (enum: ['readonly', 'editable']),
  isShared: Boolean (default: false),
  sharedUsernames: [String],
  shareViewCount: Number (default: 0),
  shareCreatedAt: Date,
  shareExpiresAt: Date,
  // Time tracking fields
  timeTracking: {
    isRunning: Boolean (default: false),
    startTime: Date,
    totalTime: Number (default: 0),
    sessions: [{
      startTime: Date,
      endTime: Date,
      duration: Number
    }]
  },
  estimatedTime: Number (default: 0),
  // File attachments
  fileAttachments: [{
    filename: String,
    originalName: String,
    mimetype: String,
    size: Number,
    data: Buffer,
    hash: String,
    uploadedAt: Date
  }],
  createdAt: Date,
  updatedAt: Date
}

Project Schema

{
  name: String (required),
  description: String,
  color: String (default: '#3182ce'),
  active: Boolean (default: true),
  userId: ObjectId (ref: 'User'),
  // Sharing fields
  shareToken: String (unique),
  sharePermission: String (enum: ['readonly', 'editable']),
  isShared: Boolean (default: false),
  sharedUsernames: [String],
  shareViewCount: Number (default: 0),
  shareCreatedAt: Date,
  shareExpiresAt: Date,
  createdAt: Date,
  updatedAt: Date
}

Company Schema

{
  name: String (required),
  description: String,
  industry: String,
  size: String (enum: ['startup', 'small', 'medium', 'large']),
  website: String,
  logo: String,
  location: {
    city: String,
    state: String,
    country: String
  },
  isVerified: Boolean (default: false),
  verificationToken: String,
  isActive: Boolean (default: true),
  shareToken: String (unique),
  slug: String (unique),
  createdBy: ObjectId (ref: 'User'),
  createdAt: Date,
  updatedAt: Date
}

Job Schema

{
  title: String (required),
  description: String,
  requirements: String,
  responsibilities: String,
  category: String (enum: ['engineering', 'design', 'marketing', 'sales', 'product', 'operations', 'finance', 'hr', 'legal', 'customer-support', 'data-science', 'devops', 'qa', 'content', 'other']),
  type: String (enum: ['full-time', 'part-time', 'contract', 'internship', 'freelance']),
  level: String (enum: ['entry', 'junior', 'mid', 'senior', 'lead', 'executive']),
  location: {
    type: String (enum: ['remote', 'onsite', 'hybrid']),
    city: String,
    state: String,
    country: String
  },
  salary: {
    min: Number,
    max: Number,
    currency: String (default: 'USD'),
    period: String (enum: ['hourly', 'daily', 'weekly', 'monthly', 'yearly'])
  },
  skills: [String],
  status: String (enum: ['draft', 'published', 'paused', 'closed', 'archived']),
  isActive: Boolean (default: true),
  publishedAt: Date,
  expiresAt: Date,
  slug: String (unique),
  shareToken: String (unique),
  viewCount: Number (default: 0),
  applicationCount: Number (default: 0),
  applications: [{
    name: String,
    email: String,
    phone: String,
    coverLetter: String,
    portfolio: String,
    appliedAt: Date
  }],
  companyId: ObjectId (ref: 'Company'),
  createdBy: ObjectId (ref: 'User'),
  createdAt: Date,
  updatedAt: Date
}

Proposal Template Schema

{
  title: String (required),
  description: String,
  category: String (enum: ['web-development', 'mobile-development', 'design', 'consulting', 'marketing', 'maintenance', 'other']),
  content: String (required),
  variables: [{
    name: String,
    description: String,
    defaultValue: String,
    required: Boolean
  }],
  isPublic: Boolean (default: false),
  isActive: Boolean (default: true),
  usageCount: Number (default: 0),
  lastUsedAt: Date,
  tags: [String],
  estimatedValue: Number (default: 0),
  estimatedHours: Number (default: 0),
  userId: ObjectId (ref: 'User'),
  createdAt: Date,
  updatedAt: Date
}

Team Schema

{
  name: String (required),
  description: String,
  owner: ObjectId (ref: 'User', required),
  members: [{
    user: ObjectId (ref: 'User', required),
    role: String (enum: ['admin', 'member', 'viewer'], default: 'member'),
    joinedAt: Date (default: Date.now)
  }],
  projects: [ObjectId (ref: 'Project')],
  isActive: Boolean (default: true),
  settings: {
    allowMemberInvites: Boolean (default: true),
    requireApproval: Boolean (default: false),
    defaultRole: String (enum: ['member', 'viewer'], default: 'member')
  },
  createdAt: Date,
  updatedAt: Date
}

πŸ”’ Security Features

Implemented Security

  • JWT Authentication - Secure token-based authentication with 15-minute expiration
  • Refresh Tokens - 7-day refresh tokens for seamless user experience
  • OAuth Integration - Google OAuth with automatic account creation
  • Password Hashing - bcryptjs with 12 salt rounds
  • Email Verification - Required email verification for new accounts
  • Password Reset - Secure password reset via email with 1-hour token expiration
  • Account Locking - Automatic account locking after 5 failed login attempts (2-hour lock)
  • Rate Limiting - Protection against brute force attacks
  • Helmet.js - Security headers
  • CORS - Cross-origin resource sharing
  • Input Validation - Request sanitization with express-validator
  • File Upload Limits - Size and type restrictions (10MB max)
  • Error Handling - No sensitive data exposure
  • Password Requirements - Minimum 12 characters with uppercase, lowercase, and special character
  • User Limits - Basic users limited to 10 tasks and 5 projects
  • Access Control - Proper validation for shared content access
  • Pro Features - Role-based access control for premium features

Production Security Checklist

  • Use HTTPS in production
  • Configure CORS origins
  • Use environment variables
  • Implement security headers
  • Add input validation
  • Secure file uploads
  • Add rate limiting
  • Implement authentication
  • Add OAuth integration
  • Add email verification
  • Add password reset functionality
  • Add account locking
  • Add password strength requirements
  • Add user limits and access control
  • Add role-based permissions
  • Add request logging
  • Add API documentation

πŸ§ͺ Testing

Run Tests

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

Test Coverage

  • Unit tests for models
  • Integration tests for routes
  • Authentication tests (including OAuth)
  • File upload tests
  • Sharing functionality tests
  • Time tracking tests
  • User limits tests
  • Shared content tests
  • Job board tests
  • Proposal template tests
  • Team management tests

πŸ“ˆ Monitoring & Logging

Health Checks

  • Database connection status
  • Server uptime
  • Memory usage
  • Response times
  • API endpoint availability

Logging

  • HTTP request logging with Morgan
  • Error logging to console
  • OAuth authentication logging
  • Payment processing logs
  • File upload logs
  • Production: Configure external logging service

πŸ”§ Development Scripts

Available Scripts

npm start              # Start production server
npm run dev            # Start development server with nodemon
npm test               # Run tests
npm run test:watch     # Run tests in watch mode
npm run test:coverage  # Run tests with coverage
npm run lint           # Run ESLint
npm run lint:fix       # Fix ESLint issues
npm run format         # Format code with Prettier
npm run seed           # Seed database with test data
npm run seed:admin     # Create admin user
npm run health         # Check server health

πŸ—„οΈ Database Management

Seeding

# Seed database with test data
npm run seed

# Create admin user
npm run seed:admin

# Create shared content for testing
node scripts/create-shared-content.js

Backup & Restore

# Backup database
npm run backup

# Restore database
npm run restore

πŸš€ Deployment

Environment Setup

  1. Set NODE_ENV=production
  2. Configure MongoDB connection string
  3. Set CORS origins
  4. Configure JWT secrets
  5. Set up OAuth credentials (Google)
  6. Set up email service credentials (Resend recommended)
  7. Configure Stripe API keys

Platform Deployment

  • Render.com: Web Service deployment
  • Vercel: Serverless deployment
  • Railway: Container deployment
  • Heroku: Container deployment

See the main DEPLOYMENT.md for detailed instructions.

πŸ“š API Documentation

Authentication Flow

  1. User registers with email/password or uses OAuth
  2. Verification email sent automatically (for email registration)
  3. User verifies email (if required)
  4. User can login and receive JWT tokens
  5. Refresh tokens used for session management
  6. Account locked after 5 failed attempts

OAuth Flow

  1. User clicks OAuth login button
  2. Redirected to OAuth provider (Google)
  3. User authorizes application
  4. Callback processes user data
  5. User account created/updated automatically
  6. JWT tokens generated and returned

Time Tracking Flow

  1. User starts timer on a task
  2. Session begins and is tracked
  3. User can stop timer to end session
  4. Total time accumulated across all sessions
  5. Statistics available for progress tracking

Sharing Flow

  1. User shares task/project with username
  2. Shared content appears in recipient's shared panel
  3. Recipient can view and optionally edit (based on permissions)
  4. Public share links available for external access

Job Board Flow

  1. Pro users create job postings
  2. Jobs can be published to public board
  3. Candidates apply through public interface
  4. Applications tracked and managed
  5. Analytics available for job performance

Proposal Template Flow

  1. Users create reusable templates with variables
  2. Templates can be shared publicly
  3. Users generate client-specific proposals
  4. Template usage tracked for analytics
  5. Templates organized by category and tags

Error Responses

All endpoints return consistent error responses:

{
  error: "Error Type",
  message: "User-friendly error message",
  details: [] // Optional validation details
}

Success Responses

{
  message: "Success message",
  data: {}, // Response data
  token: "jwt-token", // For auth endpoints
  refreshToken: "refresh-token" // For auth endpoints
}

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❀️ for productive business management

PopVia Backend - Powering productivity since 2025

Email Features

The application sends several types of emails using Resend:

  • Email Verification: Sent when users register
  • Password Reset: Sent when users request password reset
  • Shared Access: Sent when users share tasks/projects
  • Feedback: Sent when users submit feedback
  • Pro Welcome: Sent when users upgrade to pro membership
  • Company Verification: Sent when companies request verification
  • Job Applications: Sent when candidates apply for jobs

Pro Welcome Email

When a user upgrades to PopVia Pro, they automatically receive a welcome email that includes:

  • Congratulations message
  • Overview of pro features (unlimited tasks, team collaboration, priority support)
  • Link to start using unlimited features
  • Contact information for support

The email is triggered automatically in the following scenarios:

  • Successful Stripe payment completion
  • Subscription creation
  • Subscription status updates to active
  • Manual session verification

Testing Email Features

Test Pro Welcome Email

# Test with a sample user
node scripts/test-pro-welcome-email.js

# Upgrade a specific user to pro and send welcome email
node scripts/upgrade-user-to-pro.js user@example.com

API Endpoints

Payments

  • POST /api/payments/create-link - Create Stripe payment link
  • POST /api/payments/webhook - Handle Stripe webhooks
  • GET /api/payments/verify-session/:sessionId - Verify payment session

Tasks & Projects

  • GET /api/tasks - Get user's tasks
  • POST /api/tasks - Create new task
  • PUT /api/tasks/:id - Update task
  • DELETE /api/tasks/:id - Delete task
  • GET /api/projects - Get user's projects
  • POST /api/projects - Create new project
  • PUT /api/projects/:id - Update project
  • DELETE /api/projects/:id - Delete project

Sharing

  • POST /api/tasks/:id/share - Share task with user
  • POST /api/projects/:id/share - Share project with user
  • GET /api/shared-content - Get shared content

Companies & Clients

  • GET /api/companies - Get user's companies
  • POST /api/companies - Create new company
  • GET /api/clients - Get user's clients
  • POST /api/clients - Create new client

Jobs & Proposals

  • GET /api/jobs - Get user's jobs
  • POST /api/jobs - Create new job
  • GET /api/jobs/public - Get public job board
  • GET /api/proposal-templates - Get user's templates
  • POST /api/proposal-templates - Create new template
  • GET /api/proposal-templates/public - Get public templates

Teams

  • GET /api/teams - Get user's teams
  • POST /api/teams - Create new team
  • PUT /api/teams/:id/members - Add team member

About

Freelancer Task Management

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published