Skip to content

ammar422/task-management-api

Repository files navigation

Task Management API

A robust Laravel-based Task Management REST API with authentication, role-based access control, audit logging, and email notifications.

πŸ“‹ Table of Contents

πŸš€ Features

  • πŸ” JWT Authentication with role-based access (Admin/User)
  • πŸ“ Task CRUD Operations with advanced filtering and search
  • πŸ“Š Audit Logging for all create/update/delete actions
  • πŸ“§ Email Notifications for task creation and completion
  • πŸ” Full-Text Search on task titles and descriptions
  • πŸ“š Comprehensive API Documentation with Swagger
  • πŸ—οΈ Modular Architecture using nwidart/laravel-modules
  • ⏰ Queue-based Email System for better performance
  • πŸ—‘οΈ Soft Deletes with restoration capabilities
  • πŸ“„ Pagination & Sorting on all list endpoints
  • πŸ§ͺ Comprehensive Testing with 75%+ coverage

πŸ› οΈ Tech Stack

  • Backend Framework: Laravel 10+
  • Authentication: JWT (tymon/jwt-auth)
  • Database: MySQL/PostgreSQL/SQLite
  • API Documentation: L5-Swagger
  • Modules: nwidart/laravel-modules
  • Testing: Pest PHP
  • Queue: Database driver
  • Mail: Laravel Mail (log driver for development)

πŸ“‹ Requirements

  • PHP 8.1 or higher
  • Composer
  • MySQL 5.7+ / PostgreSQL 9.5+ / SQLite 3.8.8+
  • Node.js (optional, for frontend development)

⚑ Quick Start

Prerequisites Check

php --version      # Should be 8.1+
composer --version # Composer should be installed
mysql --version    # MySQL should be installed (or other database)

1. Clone Repository

git clone <your-repository-url>
cd task-management-api

2. Install Dependencies

composer install

3. Environment Setup

cp .env.example .env
php artisan key:generate

4. Database Configuration

Edit .env file with your database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=task_management
DB_USERNAME=your_username
DB_PASSWORD=your_password

5. Database Setup

# Create database (MySQL example)
mysql -u root -p -e "CREATE DATABASE task_management;"

# Run migrations and seeders
php artisan migrate
php artisan db:seed

6. Generate JWT Secret

php artisan jwt:secret

7. Generate Swagger Documentation

php artisan l5-swagger:generate

8. Start Development Server

php artisan serve

9. Start Queue Worker (for emails)

# In a new terminal window
php artisan queue:work

10. Access the Application

πŸ”§ Installation (Detailed)

Step 1: Environment Configuration

Create your .env file:

APP_NAME="Task Management API"
APP_ENV=local
APP_KEY=base64:...
APP_DEBUG=true
APP_URL=http://localhost:8000

# Database Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=task_management
DB_USERNAME=root
DB_PASSWORD=

# Mail Configuration (Development)
MAIL_MAILER=log
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="noreply@taskmanager.com"
MAIL_FROM_NAME="Task Management System"

# Queue Configuration
QUEUE_CONNECTION=database

# JWT Configuration
JWT_SECRET=your-jwt-secret-here

Step 2: Database Setup

For MySQL:

CREATE DATABASE task_management;
CREATE USER 'task_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON task_management.* TO 'task_user'@'localhost';
FLUSH PRIVILEGES;

For SQLite:

DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
touch database/database.sqlite

Step 3: Run Migrations and Seeders

# Run migrations
php artisan migrate

# Seed database with sample data
php artisan db:seed

# Or run specific seeders
php artisan db:seed --class=UserSeeder
php artisan db:seed --class=TaskSeeder

Step 4: Verify Installation

# Check application key
php artisan key:generate

# Check JWT secret
php artisan jwt:secret

# Generate Swagger docs
php artisan l5-swagger:generate

# Test the application
php artisan route:list

πŸ” Authentication

Default Users

The system comes with pre-seeded users:

Email Password Role Access
admin@example.com password Admin Full system access
user@example.com password User Own tasks only

Login Endpoint

POST /api/auth/login
Content-Type: application/json

{
    "email": "admin@example.com",
    "password": "password"
}

Response:

{
    "success": true,
    "message": "Login successful",
    "data": {
        "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
        "token_type": "bearer",
        "data": {
            "id": "550e8400-e29b-41d4-a716-446655440000",
            "name": "Admin User",
            "email": "admin@example.com",
            "role": "admin"
        }
    }
}

Using the Token

Include the JWT token in subsequent requests:

Authorization: Bearer your-jwt-token-here

πŸ“š API Documentation

Access Swagger UI

After starting the server, visit:

http://localhost:8000/api/documentation

The Swagger UI provides:

  • Interactive API documentation
  • Request/response schemas
  • Authentication testing
  • Direct API calls from the browser

πŸ“‘ API Endpoints

Authentication Endpoints

Method Endpoint Description Access
POST /api/auth/login User login Public
POST /api/auth/logout User logout Authenticated
GET /api/auth/me Get current user Authenticated
POST /api/auth/refresh Refresh token Authenticated

User Management (Admin Only)

Method Endpoint Description
GET /api/admin/users List all users
POST /api/admin/users Create user
GET /api/admin/users/{id} Get user details
PUT /api/admin/users/{id} Update user
DELETE /api/admin/users/{id} Soft delete user
GET /api/admin/users/trashed List trashed users
POST /api/admin/users/{id}/restore Restore user
DELETE /api/admin/users/{id}/force Permanently delete user

Task Management - User Endpoints

Method Endpoint Description
GET /api/user/tasks List user's tasks
POST /api/user/tasks Create task
GET /api/user/tasks/{id} Get task details
PUT /api/user/tasks/{id} Update task
DELETE /api/user/tasks/{id} Delete task
PATCH /api/user/tasks/{id}/done Mark task as done

Task Management - Admin Endpoints

Method Endpoint Description
GET /api/admin/tasks List all tasks
GET /api/admin/tasks/{id} Get any task details
DELETE /api/admin/tasks/{id} Delete any task

Audit Logs

Method Endpoint Description Access
GET /api/user/audit-logs Get user's audit logs User
GET /api/admin/audit-logs Get all audit logs Admin
GET /api/admin/audit-logs/entity/{entity}/{id} Get entity logs Admin
GET /api/admin/audit-logs/recent Get recent activity Admin

πŸ” Filtering & Search

Task Filters

Available query parameters for /api/user/tasks and /api/admin/tasks:

  • status - Filter by status: pending, in_progress, done
  • priority - Filter by priority: low, medium, high
  • from_date - Start date for due date range (format: Y-m-d)
  • to_date - End date for due date range (format: Y-m-d)
  • search - Full-text search in title and description
  • per_page - Items per page (default: 10)

Examples:

# Get completed tasks
GET /api/user/tasks?status=done

# Get high priority tasks due next week
GET /api/user/tasks?priority=high&from_date=2024-01-01&to_date=2024-01-07

# Search for tasks containing "meeting"
GET /api/user/tasks?search=meeting

# Get 20 tasks per page
GET /api/user/tasks?per_page=20

User Filters (Admin Only)

  • role - Filter by role: admin, user
  • search - Search in user names

Audit Log Filters

  • action - Filter by action: created, updated, deleted, completed
  • entity - Filter by entity: Task, User
  • user_id - Filter by user ID
  • date_from - Start date for logs
  • date_to - End date for logs

πŸ“§ Notifications

The system automatically sends email notifications for:

  1. Task Creation - When a new task is created
  2. Task Completion - When a task is marked as "done"

Email Configuration

By default, emails are logged to storage. To send actual emails:

  1. Update .env with your SMTP settings:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your-mailtrap-username
MAIL_PASSWORD=your-mailtrap-password
MAIL_ENCRYPTION=tls
  1. Ensure queue worker is running:
php artisan queue:work

πŸ—ƒοΈ Database Schema

Users Table

id (UUID) - Primary Key
name (string)
email (string) - Unique
password (string)
role (enum: admin, user)
deleted_at (timestamp) - Soft delete
created_at (timestamp)
updated_at (timestamp)

Tasks Table

id (UUID) - Primary Key
title (string)
description (text) - Nullable
status (enum: pending, in_progress, done)
priority (enum: low, medium, high)
due_date (date)
user_id (UUID) - Foreign Key to users
deleted_at (timestamp) - Soft delete
created_at (timestamp)
updated_at (timestamp)

Indexes: (status, priority), (due_date), fulltext(title, description)

Audit Logs Table

id (UUID) - Primary Key
user_id (UUID) - Foreign Key to users
action (string) - created, updated, deleted
entity (string) - Task, User
entity_id (UUID)
changes (json) - Nullable
deleted_at (timestamp) - Soft delete
created_at (timestamp)
updated_at (timestamp)

Indexes: (entity, entity_id), (created_at)

πŸ”’ Role-Based Access Control

Admin Role

  • βœ… Manage all users (CRUD operations)
  • βœ… View and manage all tasks
  • βœ… Access all audit logs
  • βœ… Restore soft-deleted users
  • βœ… Permanently delete users

User Role

  • βœ… Manage only own tasks
  • βœ… View only own audit logs
  • ❌ Cannot access admin endpoints
  • ❌ Cannot view other users' tasks
  • ❌ Cannot manage users

πŸ§ͺ Testing

Running Tests

# Run all tests
./vendor/bin/pest

# Run tests with coverage
./vendor/bin/pest --coverage

# Run specific test groups
./vendor/bin/pest --group=auth
./vendor/bin/pest --group=tasks

# Run specific module tests
./vendor/bin/pest modules/Users/Tests
./vendor/bin/pest modules/Tasks/Tests

# Generate HTML coverage report
./vendor/bin/pest --coverage-html coverage-report

Test Coverage

The test suite covers:

  • βœ… Authentication (login, logout, token refresh)
  • βœ… User management (admin operations)
  • βœ… Task CRUD operations
  • βœ… Role-based access control
  • βœ… Filtering and search functionality
  • βœ… Audit logging
  • βœ… Email notifications
  • βœ… Error handling and validation

Current Coverage: 75%+

Test Data

Tests use Laravel Factories to generate:

  • User factories with admin/user roles
  • Task factories with various statuses and priorities
  • Audit log entries for all actions

πŸš€ Deployment

Production Environment Setup

  1. Environment Configuration
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-domain.com

# Database
DB_CONNECTION=mysql
DB_HOST=production-db-host
DB_PORT=3306
DB_DATABASE=production_db
DB_USERNAME=production_user
DB_PASSWORD=strong_password

# Mail (Production)
MAIL_MAILER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-email-password
MAIL_ENCRYPTION=tls

# Queue
QUEUE_CONNECTION=database
  1. Optimization Commands
# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Optimize
php artisan optimize

# Generate Swagger docs
php artisan l5-swagger:generate
  1. Queue Worker Setup For production, set up a supervised queue worker:

Supervisor Configuration (/etc/supervisor/conf.d/laravel-worker.conf):

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/your/project/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/path/to/your/project/storage/logs/worker.log
stopwaitsecs=3600

Docker Deployment (Optional)

Create a docker-compose.yml:

version: '3.8'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: task-management-app
    restart: unless-stopped
    working_dir: /var/www
    volumes:
      - .:/var/www
    environment:
      - APP_ENV=production
      - APP_DEBUG=false
    depends_on:
      - database
      - redis

  database:
    image: mysql:8.0
    container_name: task-management-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: task_management
      MYSQL_ROOT_PASSWORD: rootpassword
    volumes:
      - dbdata:/var/lib/mysql

  redis:
    image: redis:alpine
    container_name: task-management-redis
    restart: unless-stopped

  queue:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: task-management-queue
    restart: unless-stopped
    working_dir: /var/www
    command: php artisan queue:work --sleep=3 --tries=3
    volumes:
      - .:/var/www
    depends_on:
      - app
      - redis

volumes:
  dbdata:

πŸ› Troubleshooting

Common Issues

  1. JWT Token Errors
# Regenerate JWT secret
php artisan jwt:secret

# Clear configuration cache
php artisan config:clear
  1. Queue Not Processing
# Restart queue worker
php artisan queue:restart

# Check failed jobs
php artisan queue:failed

# Retry failed jobs
php artisan queue:retry all
  1. Swagger Documentation Not Generating
# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear

# Regenerate docs
php artisan l5-swagger:generate
  1. Permission Issues
# Fix storage permissions
chmod -R 775 storage
chmod -R 775 bootstrap/cache

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
git checkout -b feature/amazing-feature
  1. Commit your changes
git commit -m 'Add some amazing feature'
  1. Push to the branch
git push origin feature/amazing-feature
  1. Open a Pull Request

Development Guidelines

  • Follow PSR-12 coding standards
  • Write tests for new features
  • Update API documentation
  • Use meaningful commit messages
  • Ensure all tests pass before submitting PR

πŸ“„ License

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

πŸ‘₯ Author

Ammar Samir

πŸ™ Acknowledgments


πŸ“ž Support

If you encounter any issues or have questions:

  1. Check the Troubleshooting section
  2. Review the API Documentation
  3. Create an issue on GitHub
  4. Contact the maintainer

Happy Coding! πŸš€

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published