Discover how to build a loyalty program with Lovable. Follow our step-by-step guide to boost customer engagement, increase retention, and drive growth.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Setting Up Your Lovable Project
index.html
for your page layout and loyalty.js
where all loyalty program logic will reside.
Creating the HTML Layout with Lovable Dependencies
index.html
file to include the Lovable library from the Content Delivery Network (CDN). Since Lovable does not support a terminal, the dependency is loaded directly in the HTML.index.html
file:
Loyalty Program
Welcome to Our Loyalty Program
Initializing the Loyalty Program in JavaScript
loyalty.js
file. In this file, you will initialize the Lovable Loyalty Program and define its behavior.
/_ Initialize Lovable Loyalty Program with your API Key _/
var apiKey = "YOUR_API_KEY"; // Replace with your actual Lovable API key
var loyaltyProgram = new Lovable.LoyaltyProgram(apiKey);
/_ Optional: Set basic configuration parameters _/
loyaltyProgram.configure({
purchaseThreshold: 50, // Amount required for a reward trigger
rewardPoints: 10 // Points awarded per eligible action
});
Implementing User Actions and Reward Allocation
loyalty.js
to simulate awarding points when the purchase button is clicked:
/_ Add event listener to capture purchase events _/
document.getElementById('purchaseButton').addEventListener('click', function(){
// Simulate processing the purchase and awarding reward points
loyaltyProgram.addRewardPoints(10);
alert("Congratulations! You have earned 10 reward points.");
});
addRewardPoints
method to update the user's points balance.
Creating a User Signup Function
loyalty.js
file after the purchase event logic:
/_ Function to handle user signup and create a loyalty profile _/
function handleUserSignup(username, email) {
var user = loyaltyProgram.createUser(username, email);
console.log("New user created:", user);
// Optionally, display a welcome message or update the UI
alert("Welcome " + username + "! Your loyalty profile has been created.");
}
/_ Example usage: To be integrated with your signup form _/
handleUserSignup("JaneDoe", "[email protected]");
Testing and Final Deployment
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
app.use(bodyParser.json());
// Define schema for loyalty program tracking
const loyaltySchema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
points: { type: Number, default: 0 },
level: { type: Number, default: 1 },
transactions: [{
amount: Number,
date: { type: Date, default: Date.now },
type: String
}]
});
const Loyalty = mongoose.model('Loyalty', loyaltySchema);
// API endpoint to accumulate points after a purchase event
app.post('/api/v1/loyalty/accumulate', async (req, res) => {
try {
const { userId, purchaseAmount } = req.body;
if (!userId || !purchaseAmount) {
return res.status(400).json({ error: 'Missing required parameters' });
}
// Calculate points based on a rule (for example: 1 point per $10 spent)
const earnedPoints = Math.floor(purchaseAmount / 10);
// Get or create the loyalty record for the user
let loyaltyRecord = await Loyalty.findOne({ userId });
if (!loyaltyRecord) {
loyaltyRecord = new Loyalty({ userId });
}
// Update loyalty record
loyaltyRecord.points += earnedPoints;
loyaltyRecord.transactions.push({ amount: purchaseAmount, type: 'purchase' });
// Update loyalty level based on the new points total
if (loyaltyRecord.points >= 1000) {
loyaltyRecord.level = 3;
} else if (loyaltyRecord.points >= 500) {
loyaltyRecord.level = 2;
}
await loyaltyRecord.save();
// Here you might call the external Lovable API to sync the updated loyalty data
// e.g., await axios.post('https://api.lovable.com/sync', { userId, points: loyaltyRecord.points, level: loyaltyRecord.level });
res.json({ userId, newPoints: loyaltyRecord.points, level: loyaltyRecord.level });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Connect to MongoDB and start the server
mongoose.connect('mongodb://localhost:27017/loyalty', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
app.listen(3000, () => console.log('Loyalty API server running on port 3000'));
})
.catch(err => console.error('MongoDB connection error:', err));
const cron = require('node-cron');
const axios = require('axios');
const mongoose = require('mongoose');
// Connect to MongoDB for loyalty transaction records
mongoose.connect('mongodb://localhost:27017/loyalty', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Define schema for tracking unsynced loyalty transactions
const transactionSchema = new mongoose.Schema({
userId: { type: String, required: true },
points: { type: Number, required: true },
synced: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now }
});
const Transaction = mongoose.model('Transaction', transactionSchema);
// Function to sync unsynced transactions with the external Lovable API
async function syncTransactions() {
try {
const unsynced = await Transaction.find({ synced: false });
for (const tx of unsynced) {
try {
const response = await axios.post('https://api.lovable.com/v1/sync', {
userId: tx.userId,
points: tx.points,
timestamp: tx.createdAt
});
if (response.status === 200) {
tx.synced = true;
await tx.save();
}
} catch (err) {
console.error(`Failed to sync transaction ${tx._id}:`, err.message);
}
}
} catch (err) {
console.error('Error retrieving unsynced transactions:', err.message);
}
}
// Schedule the syncTransactions function to run every 5 minutes
cron.schedule('_/5 _ _ _ \*', () => {
console.log('Starting scheduled sync with Lovable API...');
syncTransactions();
});
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const axios = require('axios');
const app = express();
app.use(express.json());
// Define schema for user's loyalty account
const loyaltySchema = new mongoose.Schema({
userId: { type: String, required: true, unique: true },
points: { type: Number, default: 0 },
transactions: [{
type: { type: String },
amount: Number,
date: { type: Date, default: Date.now }
}]
});
// Define schema for rewards available for redemption
const rewardSchema = new mongoose.Schema({
rewardId: { type: String, required: true, unique: true },
description: String,
cost: { type: Number, required: true }
});
const Loyalty = mongoose.model('Loyalty', loyaltySchema);
const Reward = mongoose.model('Reward', rewardSchema);
// API endpoint to redeem a reward using available loyalty points with Lovable integration
app.post('/api/v1/loyalty/redeem', async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const { userId, rewardId } = req.body;
if (!userId || !rewardId) {
throw { status: 400, message: 'Missing required parameters' };
}
const reward = await Reward.findOne({ rewardId }).session(session);
if (!reward) {
throw { status: 404, message: 'Reward not found' };
}
const userLoyalty = await Loyalty.findOne({ userId }).session(session);
if (!userLoyalty) {
throw { status: 404, message: 'User loyalty account not found' };
}
if (userLoyalty.points < reward.cost) {
throw { status: 400, message: 'Insufficient points for redemption' };
}
// Deduct the required points for redemption
userLoyalty.points -= reward.cost;
userLoyalty.transactions.push({
type: 'redeem',
amount: -reward.cost
});
await userLoyalty.save({ session });
// Call external Lovable API to process the redemption
const response = await axios.post('https://api.lovable.com/v1/redeem', {
userId,
rewardId,
pointsRedeemed: reward.cost
});
if (response.status !== 200) {
throw { status: 500, message: 'Lovable API redemption failed' };
}
await session.commitTransaction();
session.endSession();
res.json({ success: true, message: 'Reward redeemed successfully' });
} catch (error) {
await session.abortTransaction();
session.endSession();
res.status(error.status || 500).json({ error: error.message || 'Internal server error' });
}
});
// Connects to MongoDB and starts the Express server
mongoose.connect('mongodb://localhost:27017/loyalty', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
app.listen(3001, () => console.log('Reward Redemption API running on port 3001'));
}).catch(err => console.error('MongoDB connection error:', err));
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Overview and Objectives
Prerequisites
Understanding AI Code Generators
Planning Your Loyalty Program Structure
Designing the Data Model
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative\_base
Base = declarative_base()
class User(Base):
tablename = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
email = Column(String(120), unique=True)
points = Column(Integer, default=0)
created_at = Column(DateTime)
Integrating AI Code Generators
// "Create a Flask route that accepts a POST request to update a user's loyalty points. Include error handling."
Building the API Endpoints
from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(name)
Mock database
users = {
1: {"name": "Alice", "points": 100},
2: {"name": "Bob", "points": 50}
}
@app.route('/update_points', methods=['POST'])
def update_points():
data = request.get_json()
user_id = data.get('user_id')
points = data.get('points')
if user\_id not in users:
return jsonify({"error": "User not found"}), 404
try:
users\[user\_id]\['points'] += int(points)
return jsonify({"message": "Points updated", "new_points": users[user_id]['points']}), 200
except Exception as e:
return jsonify({"error": str(e)}), 400
if name == 'main':
app.run(host="0.0.0.0", port=5000)
Implementing Automation for Code Generation
import requests
def generate_code(prompt):
api_url = "https://api.exampleai.com/v1/generate"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
payload = {"prompt": prompt, "max_tokens": 150}
response = requests.post(api_url, json=payload, headers=headers)
if response.status_code == 200:
return response.json().get("code")
else:
return None
code_snippet = generate_code("Generate a Flask route for redeeming loyalty rewards with proper error handling.")
print(code_snippet)
Testing the Loyalty Program
Deployment and Scaling
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.