Skip to content

A386official/A386-Restro

Repository files navigation

A386 Restro - Food Ordering Backend

A complete backend system for food ordering with database management and Stripe payment integration.

Features

  • User Authentication - JWT-based authentication with role-based access control (admin/customer)
  • Menu Management - Full CRUD operations for menu items with categories and filters
  • Order Management - Complete order lifecycle from creation to delivery
  • Stripe Payment Integration - Secure payment processing with webhooks
  • Database - MongoDB for data persistence
  • RESTful API - Clean and well-documented API endpoints
  • Validation - Input validation and error handling
  • Security - Password hashing, JWT tokens, and secure payment handling

Tech Stack

  • Node.js - Runtime environment
  • Express.js - Web framework
  • MongoDB - NoSQL database
  • Mongoose - MongoDB ODM
  • Stripe - Payment processing
  • JWT - Authentication
  • bcryptjs - Password hashing
  • express-validator - Input validation

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v14 or higher)
  • MongoDB (v4.4 or higher)
  • npm or yarn
  • Stripe account (for payment integration)

Installation

  1. Clone the repository:
git clone <repository-url>
cd A386-Restro
  1. Install dependencies:
npm install
  1. Set up environment variables:

Create a .env file in the root directory:

cp .env.example .env

Edit the .env file with your configuration:

# Server Configuration
PORT=5000
NODE_ENV=development

# MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/a386-restro

# JWT Secret (generate a strong random string)
JWT_SECRET=your_jwt_secret_key_here_make_it_very_long_and_random

# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:3000
  1. Start MongoDB:

Make sure MongoDB is running on your system:

# On macOS with Homebrew
brew services start mongodb-community

# On Linux
sudo systemctl start mongod

# On Windows
# Start MongoDB from Services or run mongod.exe
  1. Seed the database (optional but recommended):
npm run seed

This will create:

  • Admin user: admin@a386restro.com / admin123
  • Test customer: john@example.com / password123
  • 15 sample menu items across all categories
  1. Start the server:

Development mode with auto-reload:

npm run dev

Production mode:

npm start

The server will start on http://localhost:5000

Stripe Setup

  1. Create a Stripe account at https://stripe.com

  2. Get your API keys:

    • Go to Stripe Dashboard → Developers → API keys
    • Copy your Publishable key and Secret key
    • Add them to your .env file
  3. Set up webhooks (for production):

    • Go to Stripe Dashboard → Developers → Webhooks
    • Add endpoint: https://your-domain.com/api/payments/webhook
    • Select events: payment_intent.succeeded, payment_intent.payment_failed, charge.refunded
    • Copy the webhook signing secret to your .env file
  4. Test webhook locally (optional):

# Install Stripe CLI
brew install stripe/stripe-cli/stripe

# Login to Stripe
stripe login

# Forward webhooks to local server
stripe listen --forward-to localhost:5000/api/payments/webhook

API Documentation

Complete API documentation is available in API_DOCUMENTATION.md

Quick Test

Test if the server is running:

curl http://localhost:5000/api/health

Expected response:

{
  "status": "ok",
  "message": "A386 Restro Backend is running",
  "timestamp": "2025-01-15T18:30:00.000Z"
}

API Endpoints Overview

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user
  • PUT /api/auth/profile - Update profile

Menu

  • GET /api/menu - Get all menu items
  • GET /api/menu/:id - Get single menu item
  • POST /api/menu - Create menu item (admin)
  • PUT /api/menu/:id - Update menu item (admin)
  • DELETE /api/menu/:id - Delete menu item (admin)

Orders

  • GET /api/orders - Get orders
  • GET /api/orders/:id - Get single order
  • POST /api/orders - Create new order
  • PUT /api/orders/:id/status - Update order status (admin)
  • DELETE /api/orders/:id - Cancel order

Payments

  • POST /api/payments/create-payment-intent - Create Stripe payment
  • POST /api/payments/webhook - Stripe webhook handler
  • POST /api/payments/refund - Process refund (admin)
  • GET /api/payments/config - Get Stripe public key

Project Structure

A386-Restro/
├── models/               # Database models
│   ├── User.js          # User model with authentication
│   ├── MenuItem.js      # Menu item model
│   └── Order.js         # Order model
├── routes/              # API routes
│   ├── auth.js          # Authentication routes
│   ├── menu.js          # Menu routes
│   ├── orders.js        # Order routes
│   └── payments.js      # Payment routes
├── middleware/          # Custom middleware
│   └── auth.js          # Authentication middleware
├── seeders/            # Database seeders
│   └── seed.js         # Seed script for sample data
├── server.js           # Main application file
├── package.json        # Dependencies and scripts
├── .env.example        # Environment variables template
├── .gitignore         # Git ignore file
├── README.md          # This file
└── API_DOCUMENTATION.md # Complete API docs

Database Schema

User Schema

  • name, email, password (hashed)
  • phone, address
  • role (customer/admin)
  • timestamps

MenuItem Schema

  • name, description, price
  • category (appetizer, main-course, dessert, beverage, special)
  • image, ingredients, allergens
  • dietary flags (vegetarian, vegan, gluten-free)
  • availability status
  • rating system

Order Schema

  • order number (auto-generated)
  • user reference
  • items with quantities and prices
  • pricing breakdown (subtotal, tax, delivery fee, total)
  • status tracking (pending → confirmed → preparing → ready → out-for-delivery → delivered)
  • payment status (pending → processing → completed)
  • delivery address and customer info
  • Stripe payment intent ID
  • timestamps

Order Flow

  1. Customer creates order - POST /api/orders
  2. Order created with "pending" status
  3. Customer creates payment intent - POST /api/payments/create-payment-intent
  4. Customer completes payment (frontend with Stripe.js)
  5. Stripe webhook confirms payment
  6. Order status automatically updated to "confirmed"
  7. Admin updates status through the order lifecycle
  8. Order delivered - Status: "delivered"

Payment Flow

  1. Create order through API
  2. Get payment intent with client secret
  3. Use Stripe.js on frontend to collect payment
  4. Webhook automatically updates order status
  5. Customer receives confirmation

Security Features

  • Password hashing with bcryptjs
  • JWT token authentication
  • Role-based access control
  • Input validation and sanitization
  • Stripe webhook signature verification
  • CORS configuration
  • Environment variable protection
  • Mongoose schema validation

Testing

Test Accounts (after running seed script)

Admin Account:

  • Email: admin@a386restro.com
  • Password: admin123
  • Can manage menu items and view all orders

Customer Account:

  • Email: john@example.com
  • Password: password123
  • Can place orders and view own orders

Test with Postman

  1. Import the API endpoints into Postman
  2. Set up environment variables for base URL and token
  3. Test the authentication flow
  4. Create orders and process payments

Stripe Test Cards

Use these test cards for payment testing:

  • Success: 4242 4242 4242 4242
  • Declined: 4000 0000 0000 0002
  • Requires authentication: 4000 0025 0000 3155

Use any future expiry date, any 3-digit CVC, and any postal code.

Deployment

Environment Variables for Production

Ensure all production environment variables are set:

  • Use strong, random JWT_SECRET
  • Use production Stripe keys
  • Set NODE_ENV=production
  • Configure production MongoDB URI
  • Set proper FRONTEND_URL for CORS

Recommended Hosting

  • Backend: Heroku, Railway, Render, DigitalOcean
  • Database: MongoDB Atlas (free tier available)
  • Domain: Configure custom domain with SSL

Deployment Checklist

  • Set all environment variables
  • Configure MongoDB Atlas
  • Set up Stripe webhook endpoint
  • Enable HTTPS
  • Configure CORS for production frontend
  • Set up error logging (e.g., Sentry)
  • Implement rate limiting
  • Set up database backups
  • Monitor server health
  • Configure auto-scaling if needed

Common Issues

MongoDB Connection Error

  • Ensure MongoDB is running
  • Check MongoDB URI in .env
  • Verify network connectivity

Stripe Payment Fails

  • Verify Stripe keys are correct
  • Check webhook is configured
  • Ensure using test mode for development

JWT Token Invalid

  • Check JWT_SECRET is set
  • Verify token is being sent in headers
  • Check token hasn't expired (30 days)

CORS Error

  • Check FRONTEND_URL in .env
  • Verify CORS middleware configuration
  • Ensure proper headers on frontend

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

Support

For issues and questions:

  • Check API_DOCUMENTATION.md
  • Review common issues above
  • Create an issue on GitHub

License

ISC

Authors

A386 Restro Development Team


Next Steps

After setup, you can:

  1. ✅ Test API endpoints with Postman or cURL
  2. ✅ Build a frontend application (React, Vue, etc.)
  3. ✅ Integrate Stripe.js for payment collection
  4. ✅ Add more features (reviews, favorites, recommendations)
  5. ✅ Implement real-time order tracking with WebSockets
  6. ✅ Add email notifications
  7. ✅ Create admin dashboard
  8. ✅ Deploy to production

Happy coding! 🚀

About

Restaurant-Website

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors