/how-to-build-lovable

How to build Online test booking with Lovable?

Learn how to create an online test booking system with Lovable. Our step-by-step guide helps you streamline scheduling and boost efficiency.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build Online test booking with Lovable?

 
Creating a New Lovable Project
 

  • Log into your Lovable account and open the dashboard.
  • Click “New Project” and choose a blank project template. Name it "OnlineTestBooking".
  • The Lovable editor opens with a default file structure. We will add new files for our booking system.

 
Configuring Project Dependencies
 

  • Lovable does not have a terminal, so dependencies are declared in-code. Create a file in your project root named lovable.config.json.
  • Add the following JSON snippet into lovable.config.json to include the booking and database libraries:
    • 
      {
        "dependencies": {
          "lovable-booking": "latest",
          "lovable-db": "latest"
        }
      }
            
  • This configuration instructs Lovable to automatically load the "lovable-booking" module (for booking logic) and "lovable-db" module (for database connectivity) when the project runs.

 
Setting Up the Server and Routing
 

  • Create a new file named server.lov. This file will contain your backend code.
  • Add the following code snippet to server.lov to import dependencies, set up the server, and define a booking route:
    • 
      // Import the built-in modules from Lovable
      import Booking from "lovable-booking";
      import Database from "lovable-db";
      
      

      // Initialize the database connection
      let db = new Database("OnlineTestDB");

      // Create an instance of the booking manager
      let bookingManager = new Booking(db);

      // Define a route for creating a new test booking
      lovable.route("POST", "/book-test", (req, res) => {
      // Extract the booking details from the request body
      let { fullName, email, testDate } = req.body;

      // Validate the input
      if (!fullName || !email || !testDate) {
          res.status(400).send({ error: "Missing required booking information." });
          return;
      }
      
      // Save booking to the database
      bookingManager.createBooking({ fullName, email, testDate })
          .then(result => {
              res.status(200).send({ message: "Booking confirmed", bookingId: result.id });
          })
          .catch(error => {
              res.status(500).send({ error: "Booking failed: " + error.message });
          });
      

      });

      // Start the server on Lovable's default port
      lovable.startServer();




  • This code sets up the server and defines a POST endpoint at "/book-test" for incoming bookings.

 
Creating the Booking Form (Frontend)
 

  • Create a new file named bookingForm.html for the booking form page.
  • Paste the following HTML code snippet into bookingForm.html to define the form structure:
    • 
      
      
      
        
        Online Test Booking
        
      
      
        

      Book Your Test



      <label for="email">Email Address:</label>
      <input type="email" id="email" name="email" required><br><br>
      
      <label for="testDate">Test Date:</label>
      <input type="date" id="testDate" name="testDate" required><br><br>
      
      <button type="submit">Book Test</button>
      
  • This form collects the customer's full name, email address, and desired test date.

 
Adding Client-Side Logic
 

  • Create a new file named booking.js to handle the form submission.
  • Insert the following code snippet inside booking.js to capture form data and send it to the server:
    • 
      document.getElementById('bookingForm').addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent the default form submission
      
      

      // Gather form data
      let fullName = document.getElementById('fullName').value;
      let email = document.getElementById('email').value;
      let testDate = document.getElementById('testDate').value;

      // Create the booking data object
      let bookingData = { fullName, email, testDate };

      // Send a POST request to the server endpoint using Lovable's HTTP client
      lovable.http.post("/book-test", bookingData)
      .then(response => {
      alert("Booking confirmed. Your Booking ID: " + response.bookingId);
      })
      .catch(error => {
      alert("Error during booking: " + error.error);
      });
      });




  • This script listens for the form submission, collects the input values, and sends them as a POST request to the server route defined earlier.

 
Styling the Booking Form
 

  • Create a new file named styles.css to improve the form's appearance.
  • Add the following CSS snippet into styles.css:
    • 
      body {
        font-family: Arial, sans-serif;
        background-color: #f9f9f9;
        padding: 20px;
      }
      
      

      h1 {
      color: #333;
      }

      form {
      background-color: #fff;
      padding: 25px;
      border-radius: 5px;
      box-shadow: 0px 0px 10px #ccc;
      max-width: 400px;
      margin: auto;
      }

      input[type="text"],
      input[type="email"],
      input[type="date"] {
      width: 100%;
      padding: 10px;
      margin: 8px 0;
      border: 1px solid #ccc;
      border-radius: 3px;
      }

      button {
      background-color: #5cb85c;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
      }

      button:hover {
      background-color: #4cae4c;
      }




  • This style sheet provides a clean design for the booking form.

 
Connecting All Components in Lovable
 

  • In your Lovable project settings, set the server.lov file as the main backend file.
  • Set bookingForm.html as the landing (home) page of your project.
  • Lovable automatically links these files based on the paths; ensure that all files (bookingForm.html, booking.js, styles.css, and server.lov) are saved in the correct directory (typically the project root or designated folders as outlined in your Lovable documentation).

 
Testing Your Booking Application
 

  • Click on the “Run” button in the Lovable editor. Your project will compile and start the server defined in server.lov.
  • The built-in Lovable preview pane will open the bookingForm.html page.
  • Fill in the form fields and submit a booking. The frontend script will send a POST request to your backend, and you should see a confirmation alert with the booking ID.
  • Review any errors logged in the Lovable console to debug if necessary.

 
Deploying and Sharing Your Application
 

  • After thorough testing and debugging, click the “Deploy” button in Lovable to publish your Online Test Booking application.
  • Lovable will generate a shareable URL which you can use to distribute your booking app.
  • You can update the booking system at any time by saving changes in the editor and redeploying.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to build an online test booking API with Lovable


const express = require('express');
const mongoose = require('mongoose');
const app = express();

app.use(express.json());

mongoose.connect('mongodb://localhost:27017/lovableTestBooking', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const testBookingSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  testId: { type: mongoose.Schema.Types.ObjectId, required: true },
  bookingDate: { type: Date, required: true },
  status: { type: String, default: 'pending' },
  additionalInfo: { type: Object },
  createdAt: { type: Date, default: Date.now }
});

const TestBooking = mongoose.model('TestBooking', testBookingSchema);

app.post('/api/bookTest', async (req, res) => {
  const { userId, testId, bookingDate, additionalInfo } = req.body;

  // Check if desired slot is already booked
  const existingBooking = await TestBooking.findOne({ testId, bookingDate });
  if (existingBooking) {
    return res.status(409).json({ message: 'Test slot already booked' });
  }
  
  // Create and save new test booking
  const newBooking = new TestBooking({ userId, testId, bookingDate, additionalInfo });
  try {
    await newBooking.save();
    res.status(201).json({ message: 'Booking successful', booking: newBooking });
  } catch (error) {
    res.status(500).json({ message: 'Error booking test', error });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

How to set up an Express endpoint that validates test bookings with Lovable?


const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/api/external/bookTest', async (req, res) => {
  const { bookingId, userId, testId, scheduleTime } = req.body;
  try {
    const apiPayload = {
      bookingReference: bookingId,
      user: userId,
      test: testId,
      time: scheduleTime
    };
    const externalResponse = await axios.post(
      'https://api.lovable-external.com/validateBooking',
      apiPayload,
      { headers: { 'Authorization': `Bearer ${process.env.EXTERNAL_API_KEY}` } }
    );
    if (externalResponse.data.status === 'approved') {
      res.status(200).json({ message: 'Test booking approved', details: externalResponse.data });
    } else {
      res.status(400).json({ message: 'Test booking rejected', reason: externalResponse.data.reason });
    }
  } catch (error) {
    res.status(500).json({ message: 'Error processing booking with external service', error: error.message });
  }
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));

How to reschedule your test booking with Lovable using Node.js and Mongoose


const express = require('express');
const mongoose = require('mongoose');
const app = express();

app.use(express.json());

mongoose.connect('mongodb://localhost:27017/lovableTestBooking', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const testBookingSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  testId: { type: mongoose.Schema.Types.ObjectId, required: true },
  bookingDate: { type: Date, required: true },
  status: { type: String, enum: ['pending', 'approved', 'rescheduled', 'cancelled'], default: 'pending' },
  createdAt: { type: Date, default: Date.now }
});

const auditLogSchema = new mongoose.Schema({
  bookingId: { type: mongoose.Schema.Types.ObjectId, required: true },
  action: { type: String, required: true },
  timestamp: { type: Date, default: Date.now },
  details: { type: Object }
});

const TestBooking = mongoose.model('TestBooking', testBookingSchema);
const AuditLog = mongoose.model('AuditLog', auditLogSchema);

app.post('/api/rescheduleBooking', async (req, res) => {
  const session = await mongoose.startSession();
  session.startTransaction();
  try {
    const { bookingId, newBookingDate } = req.body;
    const booking = await TestBooking.findById(bookingId).session(session);
    if (!booking) {
      await session.abortTransaction();
      return res.status(404).json({ message: 'Booking not found' });
    }
    
    const conflictBooking = await TestBooking.findOne({
      testId: booking.testId,
      bookingDate: newBookingDate
    }).session(session);
    
    if (conflictBooking) {
      await session.abortTransaction();
      return res.status(409).json({ message: 'New slot already booked' });
    }
    
    const originalDate = booking.bookingDate;
    booking.bookingDate = newBookingDate;
    booking.status = 'rescheduled';
    await booking.save({ session });
    
    const audit = new AuditLog({
      bookingId: booking.\_id,
      action: 'Rescheduled',
      details: { oldDate: originalDate, newDate: newBookingDate }
    });
    await audit.save({ session });
    
    await session.commitTransaction();
    res.status(200).json({ message: 'Booking rescheduled successfully', booking });
  } catch (error) {
    await session.abortTransaction();
    res.status(500).json({ message: 'Error rescheduling booking', error: error.message });
  } finally {
    session.endSession();
  }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a Online test booking with AI Code Generators

 
Introduction to Building an Online Test Booking with AI Code Generators
 

Building an online test booking system enhanced by AI code generators involves integrating a robust backend, a user-friendly frontend, and AI-based components to automate code generation and testing tasks. This guide provides non-technical users with a step-by-step walkthrough to understand the process and adopt best practices.

 
Prerequisites
 

  • A basic understanding of web applications and online booking systems.
  • Access to a modern web browser and an internet connection.
  • An account on an AI code generation platform (such as OpenAI, GitHub Copilot, or similar tools).
  • A hosting platform or service to deploy the web application.
  • Familiarity with cloud-based development environments is a plus, but not mandatory.

 
Defining the Feature Requirements
 

  • Identify the target audience and specify the types of tests available for booking (e.g., academic tests, certification exams, diagnostics).
  • Determine user roles such as Admin, Test Taker, and possibly Test Creator.
  • List features including user registration, test scheduling, notifications, payment integration, and AI-generated code assistance for customizing test practices.

 
Planning the System Architecture
 

  • Design a modular architecture separating the frontend, backend, and AI integration modules.
  • Decide on whether to use a serverless model or a traditional server-based model based on scalability needs.
  • Involve API gateways to facilitate communication between the booking system and AI code generators.

 
Integrating AI Code Generators
 

  • Select an AI platform that fits your project's requirement. This platform will help generate code snippets for dynamic functionalities like creating test forms, scheduling logic, or even automating responses.
  • Learn the API documentation provided by the AI service to understand the endpoints and parameters.
  • Example integration snippet for calling an AI code generator API:
  • 
    fetch('https://api.aicodeservice.com/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: JSON.stringify({
        prompt: 'Generate a booking form for a test appointment.',
        language: 'HTML'
      })
    })
    .then(response => response.json())
    .then(data => {
      console.log('Generated Code:', data.generated\_code);
    })
    .catch(error => {
      console.error('Error:', error);
    });
        
  • Utilize AI-generated snippets to customize or automate parts of your booking system.

 
Designing the Frontend User Interface
 

  • Create a simple, responsive design that allows users to select tests, choose dates, and complete bookings quickly.
  • Use drag-and-drop UI builders or no-code tools if coding is not your forte.
  • Example of a basic HTML structure for the booking form:
  • 
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Test Booking</title>
    </head>
    <body>
      <h1>Book Your Test</h1>
      <form id="bookingForm">
        <label for="testType">Select Test:</label>
        <select id="testType" name="testType">
          <option value="math">Math</option>
          <option value="science">Science</option>
        </select>
        <br>
        <label for="date">Select Date:</label>
        <input type="date" id="date" name="date">
        <br>
        <button type="submit">Book Now</button>
      </form>
    </body>
    </html>
        

 
Implementing the Backend System
 

  • Choose a backend framework that simplifies development (e.g., Node.js with Express, Python with Flask, etc.).
  • Set up RESTful APIs for managing user data, test details, bookings, and AI interactions.
  • Ensure your backend communicates with the AI service securely using API keys.
  • Example of a simple endpoint using a Node.js Express server:
  • 
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    

    app.use(bodyParser.json());

    app.post('/book-test', (req, res) => {
    const { testType, date } = req.body;
    // Process the booking logic here
    res.json({ message: 'Test booked successfully', testType, date });
    });

    app.listen(3000, () => {
    console.log('Server is running on port 3000');
    });


 
Ensuring Security and Data Privacy
 

  • Implement HTTPS to secure data transmission.
  • Store sensitive information, such as user details and API keys, securely using environment variables or a vault service.
  • Regularly update your dependencies to address security vulnerabilities.
  • Set access controls so that only authorized users can access administrative functions.

 
Integrating Payment Gateways and Notifications
 

  • Integrate reliable payment systems (like Stripe, PayPal, etc.) for processing test fees.
  • Configure email and SMS notifications for booking confirmations and reminders.
  • Consider using third-party services to manage these integrations without deep technical knowledge.

 
Testing and Quality Assurance
 

  • Perform regular testing to ensure that booking flows work as intended.
  • Use tools such as Postman to test your API endpoints.
  • Conduct user experience testing sessions to gather feedback and improve the system.
  • Example of an API test using Postman-like scripts:

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022