EventBuzz_Backend/scripts/update-crest-microsite-spea...

172 lines
5.4 KiB
JavaScript

/**
* Set placeholder speaker / committee names on all Crest org static microsites.
*
* Usage:
* node scripts/update-crest-microsite-speakers.js [--publish] [--org-id=<id>]
*/
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
const mongoose = require('mongoose');
const { connectDB } = require('../src/config/database');
const EventStaticMicrosite = require('../src/models/EventStaticMicrosite');
const Event = require('../src/models/Event');
const MicrositeV2Template = require('../src/models/MicrositeV2Template');
const User = require('../src/models/User');
const { publishStaticMicrosite } = require('../src/utils/publishStaticMicrosite');
const DEFAULT_ORG_ID = '6a43dfeddc940a0d6e057eef';
const TEAM_IMAGES = [
'https://did94hhhcgq1d.cloudfront.net/eventbuzz/microsite-v2/templates/crest-novel/assets/img/team/team-01.jpg',
'https://did94hhhcgq1d.cloudfront.net/eventbuzz/microsite-v2/templates/crest-novel/assets/img/team/team-02.jpg',
'https://did94hhhcgq1d.cloudfront.net/eventbuzz/microsite-v2/templates/crest-novel/assets/img/team/team-03.jpg',
'https://did94hhhcgq1d.cloudfront.net/eventbuzz/microsite-v2/templates/crest-novel/assets/img/team/team-04.jpg',
];
function argValue(name, fallback) {
const hit = process.argv.find((a) => a.startsWith(`--${name}=`));
return hit ? hit.split('=').slice(1).join('=').trim() : fallback;
}
function namePrefixForTab(label) {
const normalized = String(label || '').trim().toLowerCase();
if (normalized === 'speakers') return 'Speaker';
if (normalized.includes('organis')) return 'Organising Committee';
if (normalized.includes('scientific')) return 'Scientific Committee';
return String(label || 'Member').trim() || 'Member';
}
function placeholderItem(index, imageIndex = 0) {
return {
image: TEAM_IMAGES[imageIndex % TEAM_IMAGES.length],
name: '',
role: '',
url: 'index.html#',
};
}
function renameTabItems(tab) {
const prefix = namePrefixForTab(tab.label);
const items = Array.isArray(tab.items) ? tab.items : [];
return {
...tab,
items: items.map((item, index) => ({
...item,
name: `${prefix} ${index + 1}`,
})),
};
}
function defaultSpeakersSection() {
const counts = [
{ label: 'Speakers', count: 4 },
{ label: 'Organising Committee', count: 3 },
{ label: 'Scientific Committee', count: 3 },
];
let imageIndex = 0;
const tabs = counts.map(({ label, count }) => ({
label,
items: Array.from({ length: count }, () => {
const item = placeholderItem(imageIndex, imageIndex);
imageIndex += 1;
return item;
}),
}));
return {
show: true,
heading: 'Our Speakers',
subtitle: 'Leading respiratory medicine experts and committee members from across India.',
tabs: tabs.map(renameTabItems),
};
}
function applyPlaceholderNames(speakers) {
if (!speakers || typeof speakers !== 'object') {
return defaultSpeakersSection();
}
const next = { ...speakers, show: true };
if (Array.isArray(next.tabs) && next.tabs.length) {
next.tabs = next.tabs.map(renameTabItems);
delete next.items;
return next;
}
if (Array.isArray(next.items) && next.items.length) {
next.items = next.items.map((item, index) => ({
...item,
name: `Speaker ${index + 1}`,
}));
return next;
}
return defaultSpeakersSection();
}
async function findPublishUser() {
const userIdArg = argValue('user-id', '');
if (userIdArg) {
const u = await User.findById(userIdArg);
if (u) return u;
}
const platform = await User.findOne({ platform_admin: 'yes', isActive: { $ne: false } }).sort({ createdAt: 1 });
if (platform) return platform;
const superAdmin = await User.findOne({ role: 'super_admin' }).sort({ createdAt: 1 });
if (superAdmin) return superAdmin;
throw new Error('No user found for publish. Pass --user-id=<mongoId>');
}
async function main() {
const orgId = argValue('org-id', DEFAULT_ORG_ID);
const shouldPublish = process.argv.includes('--publish');
if (!mongoose.Types.ObjectId.isValid(orgId)) {
throw new Error(`Invalid org id: ${orgId}`);
}
await connectDB();
const sites = await EventStaticMicrosite.find({ organization: orgId })
.populate('event', 'name')
.populate('template')
.sort({ subdomain: 1 });
if (!sites.length) {
throw new Error(`No static microsites found for organization ${orgId}`);
}
const user = shouldPublish ? await findPublishUser() : null;
for (const site of sites) {
const config = site.config && typeof site.config === 'object' ? { ...site.config } : {};
const sections = { ...(config.sections || {}) };
sections.speakers = applyPlaceholderNames(sections.speakers);
config.sections = sections;
site.config = config;
site.markModified('config');
await site.save();
console.log(`Updated ${site.subdomain} (${site.event?.name || site.event})`);
if (shouldPublish) {
const result = await publishStaticMicrosite({
staticMicrosite: site,
template: site.template,
userId: user._id,
});
Object.assign(site, result);
await site.save();
console.log(` Published: ${result.publicUrl}`);
}
}
console.log(`Done. ${sites.length} microsite(s) updated.${shouldPublish ? '' : ' Re-run with --publish to publish.'}`);
await mongoose.disconnect();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});