Create an App for Label generation with Backend User can register and login to generate…
- User
Create an App for Label generation with Backend User can register and login to generate the Label User purchase the Labels quantities and admin assign the credits to user from backend. User create a label first and have option to generate the Label Admin will enter the range of serial numbers and the same record of range will also maintain the count of number of used labels. mean i have a series of 10000 - 20000, and i assign 2000 to any user, then it will save the count of consumed and available labels in record. User have dashboard for their labels listing
Assistant
I'll help you create a label generation application with the features you've described. This will be a full-stack application with user authentication, credit management, and label generation capabilities.
System Architecture
Backend (Node.js + Express + MongoDB)
Let me start with the backend structure:
Project Structure:
label-generation-app/ ├── backend/ │ ├── config/ │ │ └── db.js │ ├── models/ │ │ ├── User.js │ │ ├── Label.js │ │ ├── SerialRange.js │ │ └── Transaction.js │ ├── routes/ │ │ ├── auth.js │ │ ├── labels.js │ │ ├── admin.js │ │ └── dashboard.js │ ├── middleware/ │ │ ├── auth.js │ │ └── admin.js │ ├── controllers/ │ │ ├── authController.js │ │ ├── labelController.js │ │ ├── adminController.js │ │ └── dashboardController.js │ ├── utils/ │ │ └── serialNumberManager.js │ ├── .env │ ├── server.js │ └── package.jsonBackend Implementation:
package.json:
{ "name": "label-generation-backend", "version": "1.0.0", "description": "Backend for label generation app", "main": "server.js", "scripts": { "start": "node server.js", "dev": "nodemon server.js" }, "dependencies": { "express": "^4.18.2", "mongoose": "^7.0.0", "bcryptjs": "^2.4.3", "jsonwebtoken": "^9.0.0", "dotenv": "^16.0.3", "cors": "^2.8.5", "express-validator": "^7.0.1" }, "devDependencies": { "nodemon": "^2.0.20" } }server.js:
const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); require('dotenv').config(); const authRoutes = require('./routes/auth'); const labelRoutes = require('./routes/labels'); const adminRoutes = require('./routes/admin'); const dashboardRoutes = require('./routes/dashboard'); const app = express(); // Middleware app.use(cors()); app.use(express.json()); // Database connection mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.error('MongoDB connection error:', err)); // Routes app.use('/api/auth', authRoutes); app.use('/api/labels', labelRoutes); app.use('/api/admin', adminRoutes); app.use('/api/dashboard', dashboardRoutes); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });models/User.js:
const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true, lowercase: true }, password: { type: String, required: true }, role: { type: String, enum: ['user', 'admin'], default: 'user' }, credits: { type: Number, default: 0 }, totalPurchased: { type: Number, default: 0 }, totalUsed: { type: Number, default: 0 }, createdAt: { type: Date, default: Date.now } }); userSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); try { const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next(); } catch (error) { next(error); } }); userSchema.methods.comparePassword = async function(password) { return await bcrypt.compare(password, this.password); }; module.exports = mongoose.model('User', userSchema);models/Label.js:
const mongoose = require('mongoose'); const labelSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, name: { type: String, required: true }, description: { type: String }, template: { type: Object, required: true }, serialNumber: { type: String, unique: true, sparse: true }, status: { type: String, enum: ['draft', 'generated'], default: 'draft' }, generatedAt: { type: Date }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Label', labelSchema);models/SerialRange.js:
const mongoose = require('mongoose'); const serialRangeSchema = new mongoose.Schema({ startRange: { type: Number, required: true }, endRange: { type: Number, required: true }, totalCount: { type: Number, required: true }, usedCount: { type: Number, default: 0 }, availableCount: { type: Number, required: true }, lastUsedSerial: { type: Number }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, createdAt: { type: Date, default: Date.now } }); serialRangeSchema.methods.getNextSerial = function() { if (this.availableCount <= 0) { throw new Error('No serial numbers available in this range'); } const nextSerial = this.lastUsedSerial ? this.lastUsedSerial + 1 : this.startRange; if (nextSerial > this.endRange) { throw new Error('Serial range exhausted'); } return nextSerial; }; module.exports = mongoose.model('SerialRange', serialRangeSchema);models/Transaction.js:
const mongoose = require('mongoose'); const transactionSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, type: { type: String, enum: ['purchase', 'credit_assignment', 'label_generation'], required: true }, amount: { type: Number, required: true }, description: { type: String }, performedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Transaction', transactionSchema);middleware/auth.js:
const jwt = require('jsonwebtoken'); const User = require('../models/User'); const auth = async (req, res, next) => { try { const token = req.header('Authorization')?.replace('Bearer ', ''); if (!token) { throw new Error(); } const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(decoded.userId).select('-password'); if (!user) { throw new Error(); } req.user = user; req.token = token; next(); } catch (error) { res.status(401).json({ error: 'Please authenticate' }); } }; module.exports = auth;middleware/admin.js:
const admin = (req, res, next) => { if (req.user.role !== 'admin') { return res.status(403).json({ error: 'Access denied. Admin only.' }); } next(); }; module.exports = admin;controllers/authController.js:
const User = require('../models/User'); const jwt = require('jsonwebtoken'); const { validationResult } = require('express-validator'); const generateToken = (userId) => { return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '7d' }); }; exports.register = async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { name, email, password } = req.body; const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(400).json({ error: 'User already exists' }); } const user = new User({ name, email, password }); await user.save(); const token = generateToken(user._id); res.status(201).json({ message: 'User registered successfully', token, user: { id: user._id, name: user.name, email: user.email, role: user.role, credits: user.credits } }); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } }; exports.login = async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } const isMatch = await user.comparePassword(password); if (!isMatch) { return res.status(401).json({ error: 'Invalid credentials' }); } const token = generateToken(user._id); res.json({ message: 'Login successful', token, user: { id: user._id, name: user.name, email: user.email, role: user.role, credits: user.credits } }); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } };controllers/labelController.js:
const Label = require('../models/Label'); const SerialRange = require('../models/SerialRange'); const Transaction = require('../models/Transaction'); const User = require('../models/User'); exports.createLabel = async (req, res) => { try { const { name, description, template } = req.body; const label = new Label({ userId: req.user._id, name, description, template, status: 'draft' }); await label.save(); res.status(201).json({ message: 'Label created successfully', label }); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } }; exports.generateLabel = async (req, res) => { try { const { labelId } = req.params; // Check if user has credits if (req.user.credits <= 0) { return res.status(400).json({ error: 'Insufficient credits' }); } const label = await Label.findOne({ _id: labelId, userId: req.user._id }); if (!label) { return res.status(404).json({ error: 'Label not found' }); } if (label.status === 'generated') { return res.status(400).json({ error: 'Label already generated' }); } // Get available serial range const serialRange = await SerialRange.findOne({ availableCount: { $gt: 0 } }); if (!serialRange) { return res.status(400).json({ error: 'No serial numbers available' }); } // Get next serial number const nextSerial = serialRange.getNextSerial(); // Update serial range serialRange.lastUsedSerial = nextSerial; serialRange.usedCount += 1; serialRange.availableCount -= 1; await serialRange.save(); // Update label label.serialNumber = nextSerial.toString(); label.status = 'generated'; label.generatedAt = new Date(); await label.save(); // Update user credits await User.findByIdAndUpdate(req.user._id, { $inc: { credits: -1, totalUsed: 1 } }); // Create transaction await Transaction.create({ userId: req.user._id, type: 'label_generation', amount: -1, description: `Generated label: ${label.name}` }); res.json({ message: 'Label generated successfully', label }); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } }; exports.getUserLabels = async (req, res) => { try { const labels = await Label.find({ userId: req.user._id }) .sort({ createdAt: -1 }); res.json({ labels }); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } };controllers/adminController.js:
const User = require('../models/User'); const SerialRange = require('../models/SerialRange'); const Transaction = require('../models/Transaction'); exports.assignCredits = async (req, res) => { try { const { userId, credits } = req.body; if (credits <= 0) { return res.status(400).json({ error: 'Credits must be positive' }); } const user = await User.findById(userId); if (!user) { return res.status(404).json({ error: 'User not found' }); } user.credits += credits; user.totalPurchased += credits; await user.save(); await Transaction.create({ userId: user._id, type: 'credit_assignment', amount: credits, description: `Admin assigned ${credits} credits`, performedBy: req.user._id }); res.json({ message: 'Credits assigned successfully', user: { id: user._id, name: user.name, email: user.email, credits: user.credits } }); } catch (error) { console.error(
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.