Skip to content

ngcodhub/cakelo

Repository files navigation

Cake Delivery Application

A full-stack application for a cake delivery service, including a customer-facing website, admin dashboard, and backend API.

Project Structure

Thought for 1 second```markdown project="Cake Delivery" file="README.md" ...


┌─────────────────┐     ┌─────────────────┐
│                 │     │                 │
│  Customer UI    │     │   Admin UI      │
│  (Next.js)      │     │   (Next.js)     │
│                 │     │                 │
└────────┬────────┘     └────────┬────────┘
│                       │
│                       │
│                       │
│     ┌─────────────────┴─────┐
│     │                       │
└─────►    Backend API        │
│    (Express.js)       │
│                       │
└───────────┬───────────┘
│
│
┌─────┴─────┐
│           │
│ MongoDB   │
│           │
└───────────┘

```plaintext

- **Frontend Applications**: Separate Next.js applications for customers and administrators
- **Backend API**: Centralized Express.js API with RESTful endpoints
- **Database**: MongoDB for data persistence
- **Authentication**: JWT-based authentication for secure access

## Backend API

### Backend Technologies

The backend is built with the following technologies:

| Technology | Purpose | Description |
|------------|---------|-------------|
| Express.js | Web Framework | Fast, unopinionated, minimalist web framework for Node.js |
| MongoDB | Database | NoSQL document database for storing application data |
| Mongoose | ODM | MongoDB object modeling tool designed to work in an asynchronous environment |
| JWT | Authentication | JSON Web Tokens for secure authentication between client and server |
| bcryptjs | Password Hashing | Library to hash and compare passwords securely |
| express-validator | Validation | Middleware for validating and sanitizing request data |
| multer | File Uploads | Middleware for handling multipart/form-data for file uploads |
| cors | CORS Support | Middleware to enable Cross-Origin Resource Sharing |
| morgan | Logging | HTTP request logger middleware |
| dotenv | Configuration | Module to load environment variables from .env file |

### Backend Directory Structure

backend/ ├── config/ # Configuration files │ ├── auth.config.js # Authentication configuration │ └── db.config.js # Database configuration ├── controllers/ # Request handlers │ ├── auth.controller.js │ ├── cake.controller.js │ ├── category.controller.js │ ├── order.controller.js │ └── user.controller.js ├── middleware/ # Custom middleware │ ├── auth.middleware.js # Authentication middleware │ └── upload.middleware.js # File upload middleware ├── models/ # Database models │ ├── cake.model.js │ ├── category.model.js │ ├── order.model.js │ └── user.model.js ├── routes/ # API routes │ ├── auth.routes.js │ ├── cake.routes.js │ ├── category.routes.js │ ├── order.routes.js │ └── user.routes.js ├── scripts/ # Utility scripts │ └── seed.js # Database seeding script ├── uploads/ # Uploaded files storage ├── utils/ # Utility functions │ └── helpers.js ├── .env # Environment variables ├── .env.example # Example environment variables ├── package.json # Project dependencies └── server.js # Entry point


### API Endpoints

The backend provides the following RESTful API endpoints:

#### Authentication

- `POST /api/auth/register` - Register a new user
- `POST /api/auth/login` - Authenticate user & get token
- `GET /api/auth/me` - Get current user profile

#### Cakes

- `GET /api/cakes` - Get all cakes (with filtering, sorting, pagination)
- `GET /api/cakes/featured` - Get featured cakes
- `GET /api/cakes/:id` - Get cake by ID
- `POST /api/cakes` - Create a new cake (admin only)
- `PUT /api/cakes/:id` - Update a cake (admin only)
- `DELETE /api/cakes/:id` - Delete a cake (admin only)

#### Categories

- `GET /api/categories` - Get all categories
- `GET /api/categories/:id` - Get category by ID
- `POST /api/categories` - Create a new category (admin only)
- `PUT /api/categories/:id` - Update a category (admin only)
- `DELETE /api/categories/:id` - Delete a category (admin only)

#### Orders

- `GET /api/orders` - Get all orders (admin only)
- `GET /api/orders/user` - Get user orders
- `GET /api/orders/:id` - Get order by ID
- `POST /api/orders` - Create a new order
- `PUT /api/orders/:id` - Update order status (admin only)
- `PUT /api/orders/:id/cancel` - Cancel an order

#### Users

- `GET /api/users` - Get all users (admin only)
- `GET /api/users/:id` - Get user by ID (admin only)
- `PUT /api/users/profile` - Update user profile
- `PUT /api/users/:id/role` - Update user role (admin only)
- `DELETE /api/users/:id` - Delete user (admin only)

### Data Models

The application uses the following data models:

#### User Model

```javascript
{
  name: String,
  email: String,
  password: String,
  role: String, // "user" or "admin"
  address: {
    street: String,
    city: String,
    state: String,
    zipCode: String,
    country: String
  },
  phone: String,
  createdAt: Date
}

Cake Model

{
  name: String,
  description: String,
  price: Number,
  image: String,
  category: ObjectId, // Reference to Category
  ingredients: [String],
  featured: Boolean,
  inStock: Boolean,
  createdBy: ObjectId, // Reference to User
  createdAt: Date
}

Category Model

{
  name: String,
  description: String,
  image: String,
  createdAt: Date
}

Order Model

{
  user: ObjectId, // Reference to User
  items: [
    {
      cake: ObjectId, // Reference to Cake
      quantity: Number,
      price: Number
    }
  ],
  totalAmount: Number,
  shippingAddress: {
    street: String,
    city: String,
    state: String,
    zipCode: String,
    country: String
  },
  paymentMethod: String, // "credit_card", "paypal", "cash_on_delivery"
  paymentStatus: String, // "pending", "paid", "failed"
  status: String, // "pending", "processing", "shipped", "delivered", "cancelled"
  deliveryLocation: {
    latitude: Number,
    longitude: Number
  },
  notes: String,
  createdAt: Date
}

Authentication & Authorization

The backend implements JWT-based authentication:

  1. Registration: Users register with name, email, and password
  2. Password Security: Passwords are hashed using bcrypt before storage
  3. Login: Users receive a JWT token upon successful authentication
  4. Authorization: Middleware verifies JWT tokens and user roles for protected routes
  5. Admin Access: Special routes are protected with admin-only middleware

Admin Dashboard

Admin Technologies

The admin dashboard is built with the following technologies:

Technology Purpose Description
Next.js Framework React framework for server-rendered applications
React UI Library JavaScript library for building user interfaces
TypeScript Language Typed superset of JavaScript for better development experience
Tailwind CSS Styling Utility-first CSS framework
shadcn/ui UI Components High-quality UI components built with Radix UI and Tailwind CSS
React Hook Form Forms Performant, flexible and extensible forms with easy validation
Zod Validation TypeScript-first schema validation with static type inference
Axios HTTP Client Promise-based HTTP client for making API requests
Chart.js Charts Simple yet flexible JavaScript charting library
date-fns Date Utility Modern JavaScript date utility library
Lucide React Icons Beautiful & consistent icons for React

Admin Features

The admin dashboard provides the following features:

  1. Authentication

  2. Secure login for administrators

  3. JWT-based session management

  4. Dashboard

  5. Overview of key business metrics

  6. Revenue charts and statistics

  7. Recent orders and activities

  8. Cake Management

  9. List, create, edit, and delete cakes

  10. Upload cake images

  11. Manage cake categories

  12. Toggle featured status

  13. Order Management

  14. View all orders with filtering and search

  15. Update order status (processing, shipped, delivered, etc.)

  16. View order details including customer information

  17. Customer Management

  18. View customer list with search functionality

  19. Access customer details and order history

  20. Category Management

  21. Create, edit, and delete cake categories

  22. Assign categories to cakes

  23. Settings

  24. Update admin profile information

  25. Change password

  26. Configure notification preferences

Admin Directory Structure

admin-ui/
├── app/                # Next.js app directory
│   ├── cakes/          # Cake management pages
│   ├── categories/     # Category management pages
│   ├── customers/      # Customer management pages
│   ├── login/          # Authentication pages
│   ├── orders/         # Order management pages
│   ├── settings/       # Settings pages
│   ├── globals.css     # Global styles
│   ├── layout.tsx      # Root layout component
│   └── page.tsx        # Dashboard page
├── components/         # Reusable components
│   ├── ui/             # UI components (shadcn/ui)
│   ├── Header.tsx      # Header component
│   └── Sidebar.tsx     # Sidebar navigation
├── context/            # React context providers
│   └── AuthContext.tsx # Authentication context
├── lib/                # Utility functions
│   └── utils.ts        # Helper functions
├── middleware.ts       # Next.js middleware for auth protection
├── public/             # Static assets
├── .env.local          # Environment variables
└── package.json        # Project dependencies

Admin Key Components

Authentication Flow

The admin dashboard implements a secure authentication flow:

  1. Login Page: Administrators enter credentials
  2. Authentication: Credentials are verified against the backend API
  3. Session Management: JWT token is stored in localStorage
  4. Route Protection: Middleware prevents access to protected routes without authentication
  5. Auto-logout: Session expires after token expiration

Dashboard Analytics

The dashboard provides business insights through:

  1. Key Metrics: Total revenue, orders, customers, and products
  2. Charts: Revenue trends over time
  3. Recent Activity: Latest orders and customer registrations

Data Management Interfaces

All data management interfaces follow a consistent pattern:

  1. List View: Paginated, searchable, and filterable table of items
  2. Detail View: Comprehensive view of a single item
  3. Create/Edit Forms: Validated forms for data entry
  4. Delete Confirmation: Confirmation dialogs for destructive actions

Customer Website

Customer Technologies

The customer website is built with the following technologies:

Technology Purpose Description
Next.js Framework React framework for server-rendered applications
React UI Library JavaScript library for building user interfaces
TypeScript Language Typed superset of JavaScript for better development experience
Tailwind CSS Styling Utility-first CSS framework
shadcn/ui UI Components High-quality UI components built with Radix UI and Tailwind CSS
React Slick Carousel Carousel component for React
React Hot Toast Notifications Smoking hot React notifications
Geolocation API Location Browser API for getting user's location for delivery

Customer Features

The customer website provides the following features:

  1. Product Browsing

  2. Browse cakes by category

  3. View featured cakes

  4. Search for specific cakes

  5. User Authentication

  6. Register new account

  7. Login to existing account

  8. View and update profile

  9. Shopping Cart

  10. Add cakes to cart

  11. Adjust quantities

  12. Remove items

  13. View cart summary

  14. Checkout Process

  15. Enter shipping information

  16. Choose payment method

  17. Place order

  18. Share location for delivery

  19. Order Management

  20. View order history

  21. Check order status

  22. Cancel orders (if eligible)

Customer Directory Structure

app/
├── app/                # Next.js app directory
│   ├── cart/           # Shopping cart page
│   ├── checkout/       # Checkout process
│   ├── login/          # User login page
│   ├── order/          # Order cakes page
│   ├── profile/        # User profile page
│   ├── signup/         # User registration page
│   ├── globals.css     # Global styles
│   ├── layout.tsx      # Root layout component
│   └── page.tsx        # Homepage
├── components/         # Reusable components
│   ├── ui/             # UI components (shadcn/ui)
│   ├── Footer.tsx      # Footer component
│   └── Header.tsx      # Header component
├── context/            # React context providers
│   ├── AuthContext.tsx # Authentication context
│   └── CartContext.tsx # Shopping cart context
├── hooks/              # Custom React hooks
│   └── useGeolocation.ts # Geolocation hook
├── public/             # Static assets
├── .env.local          # Environment variables
└── package.json        # Project dependencies

Customer Key Components

Shopping Cart Implementation

The shopping cart is implemented using React Context:

  1. Cart Context: Provides cart state and methods to all components
  2. Add to Cart: Adds items to cart with quantity
  3. Update Quantity: Increases or decreases item quantity
  4. Remove Items: Removes items from cart
  5. Persistence: Cart is persisted in localStorage

Checkout Flow

The checkout process follows these steps:

  1. Cart Review: User reviews items in cart
  2. Authentication: User must be logged in to proceed
  3. Shipping Information: User enters or selects delivery address
  4. Location Sharing: Optional geolocation for precise delivery
  5. Payment Method: User selects payment method
  6. Order Confirmation: Order is submitted to the backend
  7. Confirmation: User receives order confirmation

Responsive Design

The customer website is fully responsive:

  1. Mobile-First: Designed for mobile devices first
  2. Adaptive Layout: Adjusts layout based on screen size
  3. Touch-Friendly: Large touch targets for mobile users
  4. Performance Optimized: Fast loading on all devices

Installation & Setup

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (local or Atlas)
  • npm or yarn

Backend Setup

# Navigate to backend directory
cd backend

# Install dependencies
npm install

# Create .env file (copy from .env.example)
cp .env.example .env

# Seed the database with initial data
npm run seed

# Start the development server
npm run dev

Admin Dashboard Setup

# Navigate to admin-ui directory
cd admin-ui

# Install dependencies
npm install

# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api" > .env.local

# Start the development server
npm run dev

Customer Website Setup

# Navigate to app directory
cd app

# Install dependencies
npm install

# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api" > .env.local

# Start the development server
npm run dev

Environment Variables

Backend (.env)

PORT=5000
NODE_ENV=development
MONGODB_URI=mongodb://localhost:27017/cake-delivery
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRES_IN=1d
CORS_ORIGIN=http://localhost:3000,http://localhost:3001
UPLOAD_DIR=uploads
MAX_FILE_SIZE=5242880
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=adminpassword

Admin Dashboard (.env.local)

NEXT_PUBLIC_API_URL=http://localhost:5000/api

Customer Website (.env.local)

NEXT_PUBLIC_API_URL=http://localhost:5000/api

Deployment

The application can be deployed using various methods:

Docker Deployment

Use the provided Docker configuration:

# Build and start all services
docker-compose up -d

Manual Deployment

  1. Backend: Deploy to a Node.js hosting service (Heroku, DigitalOcean, AWS)
  2. Frontend Applications: Deploy to Vercel, Netlify, or other static hosting
  3. Database: Use MongoDB Atlas for production database

Main Application Logic

Order Processing Flow

The core business logic revolves around the order processing flow:

  1. Cart Creation: User adds cakes to their cart (managed in CartContext)

  2. Checkout Initiation: User proceeds to checkout

  3. Order Creation: Backend creates an order record with status "pending"

  4. Payment Processing: Payment is processed (simulated in the current version)

  5. Order Fulfillment: Admin updates order status through admin dashboard

  6. "processing" - Order is being prepared

  7. "shipped" - Order is out for delivery

  8. "delivered" - Order has been delivered

  9. "cancelled" - Order has been cancelled

  10. Notifications: Status updates are reflected in the customer's order history

Authentication Logic

The authentication system works as follows:

  1. Registration:

  2. User submits registration form

  3. Backend validates data and checks for existing users

  4. Password is hashed using bcrypt

  5. User record is created in database

  6. JWT token is generated and returned

  7. Login:

  8. User submits login form

  9. Backend validates credentials

  10. If valid, JWT token is generated and returned

  11. Token contains user ID and role information

  12. Authorization:

  13. Protected routes check for valid JWT token

  14. Admin routes additionally check for admin role

  15. Tokens expire after the configured time period

Data Flow Architecture

The application follows a clear data flow pattern:

  1. API Requests: Frontend components make requests to the backend API
  2. Controller Logic: API controllers handle requests and apply business logic
  3. Database Operations: Mongoose models interact with MongoDB
  4. Response Handling: API responses are processed by frontend components
  5. State Management: React contexts manage application state
  6. UI Updates: Components re-render based on state changes

Future Enhancements

Potential future enhancements for the application:

  1. Payment Integration: Integrate with Stripe or PayPal for real payments
  2. Real-time Delivery Tracking: Implement real-time tracking with WebSockets
  3. Reviews & Ratings: Allow customers to review and rate cakes
  4. Loyalty Program: Implement a points-based loyalty system
  5. Email Notifications: Send order confirmations and status updates via email
  6. Advanced Analytics: Enhance admin dashboard with more detailed analytics
  7. Mobile Applications: Develop native mobile apps for customers and delivery personnel
  8. Multi-language Support: Add internationalization for multiple languages
  9. Subscription Service: Implement recurring cake delivery subscriptions

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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


This comprehensive README provides a detailed explanation of your cake delivery project, covering all aspects from the system architecture to specific implementation details. It explains the technologies used, the directory structure, key components, and the main application logic in a step-by-step manner.

The document is structured to be useful for both developers who need to understand the technical details and stakeholders who want to understand the overall functionality and flow of the application.

Would you like me to expand on any particular section or add more details about a specific aspect of the project?

Please make sure to add the following environment variables to your project:

<AddEnvironmentVariables names={["PORT", "MONGODB_URI", "JWT_SECRET", "NEXT_PUBLIC_API_URL"]} />

/// Thought for 1 secondGreat! Now that you've added the ADMIN_PASSWORD and ADMIN_EMAIL environment variables to your Vercel project, you're ready to deploy your cake delivery application. Let me guide you through the deployment process and provide some final recommendations.

Deploying to Vercel

Backend API Deployment

Since Vercel is primarily designed for frontend applications, you have a few options for deploying your Express backend:

  1. Deploy to Vercel Serverless Functions:

  2. Convert your Express app to use serverless functions

  3. Create a vercel.json configuration file in your backend directory:

{
  "version": 2,
  "builds": [
    {
      "src": "server.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "server.js"
    }
  ]
}
  1. Alternative Backend Hosting:

  2. Deploy your Express backend to a service like:

  3. Render

  4. Railway

  5. Heroku

  6. DigitalOcean App Platform

Frontend and Admin UI Deployment

  1. Deploy to Vercel:

  2. Push your code to a Git repository (GitHub, GitLab, or Bitbucket)

  3. Import your repository in the Vercel dashboard

  4. Configure the build settings:

  5. For the customer website: Set the root directory to app

  6. For the admin UI: Set the root directory to admin-ui

  7. Environment Variables:

  8. Add the following environment variables to your Vercel project for each frontend:

  9. NEXT_PUBLIC_API_URL: The URL of your deployed backend API

Database Setup

For MongoDB, you have several options:

  1. MongoDB Atlas (Recommended for production):

  2. Create a free cluster at MongoDB Atlas

  3. Configure network access to allow connections from your backend

  4. Add the connection string to your backend's environment variables

  5. Alternative MongoDB Hosting:

  6. DigitalOcean Managed MongoDB

  7. ScaleGrid

Final Production Checklist

Before going live, ensure you've completed these steps:

  1. Security:

  2. Enable HTTPS for all services

  3. Set up CORS properly to only allow your frontend domains

  4. Implement rate limiting for API endpoints

  5. Add security headers (Content-Security-Policy, X-XSS-Protection, etc.)

  6. Performance:

  7. Enable compression middleware in Express

  8. Implement caching for frequently accessed data

  9. Optimize images and assets

  10. Monitoring:

  11. Set up error tracking with a service like Sentry

  12. Implement application monitoring

  13. Configure alerts for critical errors

  14. Backup:

  15. Set up automated database backups

  16. Implement a disaster recovery plan

  17. Testing:

  18. Perform thorough testing of all features

  19. Test payment processing if implemented

  20. Verify mobile responsiveness

Connecting Everything

Once all components are deployed:

  1. Update the NEXT_PUBLIC_API_URL in both frontend applications to point to your deployed backend
  2. Update the CORS_ORIGIN in your backend to allow requests from your frontend domains
  3. Run the database seed script to initialize your database with sample data
  4. Test the complete flow from the customer website to the admin dashboard

Going Forward

As your application grows, consider these enhancements:

  1. Payment Integration:

  2. Integrate with Stripe or PayPal for real payments

  3. Implement order confirmation emails

  4. Delivery Tracking:

  5. Add real-time delivery tracking with Google Maps

  6. Implement SMS notifications for order updates

  7. Analytics:

  8. Add Google Analytics or a similar service

  9. Implement sales and customer analytics in the admin dashboard

  10. Marketing:

  11. Add a newsletter subscription feature

  12. Implement promotional codes and discounts

Your cake delivery application is now production-ready with a robust backend API, an intuitive admin dashboard, and a user-friendly customer website. The architecture is scalable and can be extended with additional features as your business grows.

Please make sure to add the following environment variables to your project:

Environment Variables Not Added

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published