67 lines
1.9 KiB
JavaScript
67 lines
1.9 KiB
JavaScript
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); |