other
This commit is contained in:
67
backend/utils/createInvitation.js
Normal file
67
backend/utils/createInvitation.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import mongoose from "mongoose";
|
||||
import dotenv from "dotenv";
|
||||
import Staff from "../models/Staff.model.js"
|
||||
import Invitation from "../models/Invitation.model.js"
|
||||
import crypto from "crypto";
|
||||
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// ✅ Connect to MongoDB
|
||||
const mongoUri = process.env.MONGO_URI;
|
||||
mongoose
|
||||
.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true })
|
||||
.then(() => console.log("✅ Connected to MongoDB"))
|
||||
.catch((err) => console.error("❌ MongoDB Connection Error:", err));
|
||||
|
||||
const generateInviteCode = () => {
|
||||
return crypto.randomBytes(16).toString('hex');
|
||||
};
|
||||
|
||||
const createInvitation = async (staffEmail) => {
|
||||
try {
|
||||
// Find staff member
|
||||
const staff = await Staff.findOne({ username: "admin" });
|
||||
if (!staff) {
|
||||
throw new Error("Staff member not found");
|
||||
}
|
||||
|
||||
// Check if staff has permission to create invitations
|
||||
if (!['admin', 'support'].includes(staff.role)) {
|
||||
throw new Error("Insufficient permissions to create vendor invitations");
|
||||
}
|
||||
|
||||
// Generate unique invite code
|
||||
const inviteCode = generateInviteCode();
|
||||
|
||||
// Create invitation
|
||||
const invitation = await Invitation.create({
|
||||
code: inviteCode,
|
||||
createdBy: staff._id,
|
||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days from now
|
||||
isUsed: false
|
||||
});
|
||||
|
||||
console.log(`✅ Vendor invitation created successfully!
|
||||
Code: ${invitation.code}
|
||||
Created by: ${staff.email}
|
||||
Expires: ${invitation.expiresAt}
|
||||
`);
|
||||
|
||||
// Exit process after creating invitation
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
console.error("❌ Error creating invitation:", error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Get staff email from command line argument
|
||||
const staffEmail = process.argv[2];
|
||||
|
||||
if (!staffEmail) {
|
||||
console.error("❌ Please provide staff email: node createInvitation.js <staffEmail>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
createInvitation(staffEmail);
|
||||
Reference in New Issue
Block a user