Adding features
This commit is contained in:
parent
600fef2b7c
commit
2b55ca4104
75 changed files with 9796 additions and 2759 deletions
|
|
@ -1,55 +1,57 @@
|
|||
// server/api/auth/login.post.js
|
||||
import jwt from 'jsonwebtoken'
|
||||
import { Resend } from 'resend'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
import jwt from "jsonwebtoken";
|
||||
import { Resend } from "resend";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
const resend = new Resend(process.env.RESEND_API_KEY)
|
||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Connect to database
|
||||
await connectDB()
|
||||
|
||||
const { email } = await readBody(event)
|
||||
|
||||
await connectDB();
|
||||
|
||||
const { email } = await readBody(event);
|
||||
|
||||
if (!email) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Email is required'
|
||||
})
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Email is required",
|
||||
});
|
||||
}
|
||||
|
||||
const member = await Member.findOne({ email })
|
||||
|
||||
const member = await Member.findOne({ email });
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'No account found with that email address'
|
||||
})
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "No account found with that email address",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Generate magic link token
|
||||
const token = jwt.sign(
|
||||
{ memberId: member._id },
|
||||
{ memberId: member._id },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '15m' } // Shorter expiry for security
|
||||
)
|
||||
|
||||
{ expiresIn: "15m" }, // Shorter expiry for security
|
||||
);
|
||||
|
||||
// Get the base URL for the magic link
|
||||
const headers = getHeaders(event)
|
||||
const baseUrl = process.env.BASE_URL || `${headers.host?.includes('localhost') ? 'http' : 'https'}://${headers.host}`
|
||||
|
||||
const headers = getHeaders(event);
|
||||
const baseUrl =
|
||||
process.env.BASE_URL ||
|
||||
`${headers.host?.includes("localhost") ? "http" : "https"}://${headers.host}`;
|
||||
|
||||
// Send magic link via Resend
|
||||
try {
|
||||
await resend.emails.send({
|
||||
from: 'Ghost Guild <noreply@ghostguild.org>',
|
||||
from: "Ghost Guild <ghostguild@babyghosts.org>",
|
||||
to: email,
|
||||
subject: 'Your Ghost Guild login link',
|
||||
subject: "Your Ghost Guild login link",
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #2563eb;">Welcome back to Ghost Guild!</h2>
|
||||
<p>Click the button below to sign in to your account:</p>
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${baseUrl}/api/auth/verify?token=${token}"
|
||||
<a href="${baseUrl}/api/auth/verify?token=${token}"
|
||||
style="background-color: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">
|
||||
Sign In to Ghost Guild
|
||||
</a>
|
||||
|
|
@ -58,19 +60,18 @@ export default defineEventHandler(async (event) => {
|
|||
This link will expire in 15 minutes for security. If you didn't request this login link, you can safely ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Login link sent to your email'
|
||||
}
|
||||
|
||||
`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Login link sent to your email",
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to send email:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Failed to send login email. Please try again.'
|
||||
})
|
||||
console.error("Failed to send email:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to send login email. Please try again.",
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,45 +1,59 @@
|
|||
import jwt from 'jsonwebtoken'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB()
|
||||
|
||||
const token = getCookie(event, 'auth-token')
|
||||
console.log('Auth check - token found:', !!token)
|
||||
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
console.log("Auth check - token found:", !!token);
|
||||
|
||||
if (!token) {
|
||||
console.log('No auth token found in cookies')
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Not authenticated'
|
||||
})
|
||||
console.log("No auth token found in cookies");
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET)
|
||||
const member = await Member.findById(decoded.memberId).select('-__v')
|
||||
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const member = await Member.findById(decoded.memberId).select("-__v");
|
||||
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Member not found'
|
||||
})
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Member not found",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
_id: member._id,
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
membershipLevel: `${member.circle}-${member.contributionTier}`
|
||||
}
|
||||
membershipLevel: `${member.circle}-${member.contributionTier}`,
|
||||
// Profile fields
|
||||
pronouns: member.pronouns,
|
||||
timeZone: member.timeZone,
|
||||
avatar: member.avatar,
|
||||
studio: member.studio,
|
||||
bio: member.bio,
|
||||
skills: member.skills,
|
||||
location: member.location,
|
||||
socialLinks: member.socialLinks,
|
||||
offering: member.offering,
|
||||
lookingFor: member.lookingFor,
|
||||
showInDirectory: member.showInDirectory,
|
||||
privacy: member.privacy,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Token verification error:', err)
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Invalid or expired token'
|
||||
})
|
||||
console.error("Token verification error:", err);
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
|
|
|||
19
server/api/contributions/options.get.js
Normal file
19
server/api/contributions/options.get.js
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Get available contribution options
|
||||
import { getContributionOptions } from '../../config/contributions.js'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const options = getContributionOptions()
|
||||
|
||||
return {
|
||||
success: true,
|
||||
options
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching contribution options:', error)
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Failed to fetch contribution options'
|
||||
})
|
||||
}
|
||||
})
|
||||
69
server/api/events/[id]/cancel-registration.post.js
Normal file
69
server/api/events/[id]/cancel-registration.post.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import Event from '../../../models/event';
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const id = getRouterParam(event, 'id');
|
||||
const body = await readBody(event);
|
||||
const { email } = body;
|
||||
|
||||
if (!email) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Email is required'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if id is a valid ObjectId or treat as slug
|
||||
const isObjectId = /^[0-9a-fA-F]{24}$/.test(id);
|
||||
const query = isObjectId
|
||||
? { $or: [{ _id: id }, { slug: id }] }
|
||||
: { slug: id };
|
||||
|
||||
const eventDoc = await Event.findOne(query);
|
||||
|
||||
if (!eventDoc) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Event not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Find the registration index
|
||||
const registrationIndex = eventDoc.registrations.findIndex(
|
||||
registration => registration.email.toLowerCase() === email.toLowerCase()
|
||||
);
|
||||
|
||||
if (registrationIndex === -1) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Registration not found'
|
||||
});
|
||||
}
|
||||
|
||||
// Remove the registration
|
||||
eventDoc.registrations.splice(registrationIndex, 1);
|
||||
|
||||
// Update registered count
|
||||
eventDoc.registeredCount = eventDoc.registrations.length;
|
||||
|
||||
await eventDoc.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Registration cancelled successfully',
|
||||
registeredCount: eventDoc.registeredCount
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error cancelling registration:', error);
|
||||
|
||||
// Re-throw known errors
|
||||
if (error.statusCode) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Failed to cancel registration'
|
||||
});
|
||||
}
|
||||
});
|
||||
49
server/api/events/[id]/check-registration.post.js
Normal file
49
server/api/events/[id]/check-registration.post.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import Event from "../../../models/event";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const id = getRouterParam(event, "id");
|
||||
const body = await readBody(event);
|
||||
const { email } = body;
|
||||
|
||||
if (!email) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Email is required",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if id is a valid ObjectId or treat as slug
|
||||
const isObjectId = /^[0-9a-fA-F]{24}$/.test(id);
|
||||
const query = isObjectId
|
||||
? { $or: [{ _id: id }, { slug: id }] }
|
||||
: { slug: id };
|
||||
|
||||
const eventDoc = await Event.findOne(query);
|
||||
|
||||
if (!eventDoc) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Event not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if the email exists in the registrations array
|
||||
const isRegistered = eventDoc.registrations.some(
|
||||
(registration) =>
|
||||
registration.email.toLowerCase() === email.toLowerCase(),
|
||||
);
|
||||
|
||||
return {
|
||||
isRegistered,
|
||||
eventId: eventDoc._id,
|
||||
eventTitle: eventDoc.title,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error checking registration:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to check registration status",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -1,130 +1,141 @@
|
|||
import Event from '../../../models/event.js'
|
||||
import Member from '../../../models/member.js'
|
||||
import { connectDB } from '../../../utils/mongoose.js'
|
||||
import mongoose from 'mongoose'
|
||||
import Event from "../../../models/event.js";
|
||||
import Member from "../../../models/member.js";
|
||||
import { connectDB } from "../../../utils/mongoose.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
// Ensure database connection
|
||||
await connectDB()
|
||||
const identifier = getRouterParam(event, 'id')
|
||||
const body = await readBody(event)
|
||||
|
||||
await connectDB();
|
||||
const identifier = getRouterParam(event, "id");
|
||||
const body = await readBody(event);
|
||||
|
||||
if (!identifier) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Event identifier is required'
|
||||
})
|
||||
statusMessage: "Event identifier is required",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Validate required fields
|
||||
if (!body.name || !body.email) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Name and email are required'
|
||||
})
|
||||
statusMessage: "Name and email are required",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Fetch the event - try by slug first, then by ID
|
||||
let eventData
|
||||
|
||||
let eventData;
|
||||
|
||||
// Check if identifier is a valid MongoDB ObjectId
|
||||
if (mongoose.Types.ObjectId.isValid(identifier)) {
|
||||
eventData = await Event.findById(identifier)
|
||||
eventData = await Event.findById(identifier);
|
||||
}
|
||||
|
||||
|
||||
// If not found by ID or not a valid ObjectId, try by slug
|
||||
if (!eventData) {
|
||||
eventData = await Event.findOne({ slug: identifier })
|
||||
eventData = await Event.findOne({ slug: identifier });
|
||||
}
|
||||
|
||||
|
||||
if (!eventData) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Event not found'
|
||||
})
|
||||
statusMessage: "Event not found",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Check if event is full
|
||||
if (eventData.maxAttendees && eventData.registrations.length >= eventData.maxAttendees) {
|
||||
if (
|
||||
eventData.maxAttendees &&
|
||||
eventData.registrations.length >= eventData.maxAttendees
|
||||
) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Event is full'
|
||||
})
|
||||
statusMessage: "Event is full",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Check if already registered
|
||||
const alreadyRegistered = eventData.registrations.some(
|
||||
reg => reg.email.toLowerCase() === body.email.toLowerCase()
|
||||
)
|
||||
|
||||
(reg) => reg.email.toLowerCase() === body.email.toLowerCase(),
|
||||
);
|
||||
|
||||
if (alreadyRegistered) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'You are already registered for this event'
|
||||
})
|
||||
statusMessage: "You are already registered for this event",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Check member status and handle different registration scenarios
|
||||
const member = await Member.findOne({ email: body.email.toLowerCase() })
|
||||
|
||||
const member = await Member.findOne({ email: body.email.toLowerCase() });
|
||||
|
||||
if (eventData.membersOnly && !member) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: 'This event is for members only. Please become a member to register.'
|
||||
})
|
||||
statusMessage:
|
||||
"This event is for members only. Please become a member to register.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// If event requires payment and user is not a member, redirect to payment flow
|
||||
if (eventData.pricing.paymentRequired && !eventData.pricing.isFree && !member) {
|
||||
if (
|
||||
eventData.pricing.paymentRequired &&
|
||||
!eventData.pricing.isFree &&
|
||||
!member
|
||||
) {
|
||||
throw createError({
|
||||
statusCode: 402, // Payment Required
|
||||
statusMessage: 'This event requires payment. Please use the payment registration endpoint.'
|
||||
})
|
||||
statusMessage:
|
||||
"This event requires payment. Please use the payment registration endpoint.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Set member status and membership level
|
||||
let isMember = false
|
||||
let membershipLevel = 'non-member'
|
||||
|
||||
let isMember = false;
|
||||
let membershipLevel = "non-member";
|
||||
|
||||
if (member) {
|
||||
isMember = true
|
||||
membershipLevel = `${member.circle}-${member.contributionTier}`
|
||||
isMember = true;
|
||||
membershipLevel = `${member.circle}-${member.contributionTier}`;
|
||||
}
|
||||
|
||||
|
||||
// Add registration
|
||||
eventData.registrations.push({
|
||||
memberId: member ? member._id : null,
|
||||
name: body.name,
|
||||
email: body.email.toLowerCase(),
|
||||
membershipLevel,
|
||||
isMember,
|
||||
paymentStatus: 'not_required', // Free events or member registrations
|
||||
paymentStatus: "not_required", // Free events or member registrations
|
||||
amountPaid: 0,
|
||||
dietary: body.dietary || false,
|
||||
registeredAt: new Date()
|
||||
})
|
||||
|
||||
registeredAt: new Date(),
|
||||
});
|
||||
|
||||
// Save the updated event
|
||||
await eventData.save()
|
||||
|
||||
await eventData.save();
|
||||
|
||||
// TODO: Send confirmation email using Resend
|
||||
// await sendEventRegistrationEmail(body.email, eventData)
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Successfully registered for the event',
|
||||
registrationId: eventData.registrations[eventData.registrations.length - 1]._id
|
||||
}
|
||||
message: "Successfully registered for the event",
|
||||
registrationId:
|
||||
eventData.registrations[eventData.registrations.length - 1]._id,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error registering for event:', error)
|
||||
|
||||
console.error("Error registering for event:", error);
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error
|
||||
throw error;
|
||||
}
|
||||
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: 'Failed to register for event'
|
||||
})
|
||||
statusMessage: "Failed to register for event",
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
|
|
|||
61
server/api/helcim/create-plan.post.js
Normal file
61
server/api/helcim/create-plan.post.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// Create a new Helcim payment plan
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
const config = useRuntimeConfig(event)
|
||||
const body = await readBody(event)
|
||||
|
||||
// Validate required fields
|
||||
if (!body.name || !body.amount || !body.frequency) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Name, amount, and frequency are required'
|
||||
})
|
||||
}
|
||||
|
||||
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
|
||||
|
||||
console.log('Creating payment plan:', body.name)
|
||||
|
||||
const response = await fetch(`${HELCIM_API_BASE}/payment-plans`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'content-type': 'application/json',
|
||||
'api-token': helcimToken
|
||||
},
|
||||
body: JSON.stringify({
|
||||
planName: body.name,
|
||||
planAmount: parseFloat(body.amount),
|
||||
planFrequency: body.frequency, // 'monthly', 'weekly', 'biweekly', etc.
|
||||
planCurrency: body.currency || 'CAD'
|
||||
})
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
console.error('Failed to create payment plan:', response.status, errorText)
|
||||
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
statusMessage: `Failed to create payment plan: ${errorText}`
|
||||
})
|
||||
}
|
||||
|
||||
const planData = await response.json()
|
||||
console.log('Payment plan created:', planData)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
plan: planData
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating Helcim payment plan:', error)
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || 'Failed to create payment plan'
|
||||
})
|
||||
}
|
||||
})
|
||||
83
server/api/helcim/customer-code.get.js
Normal file
83
server/api/helcim/customer-code.get.js
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
// Get customer code for an existing Helcim customer
|
||||
import jwt from 'jsonwebtoken'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await connectDB()
|
||||
const config = useRuntimeConfig(event)
|
||||
const token = getCookie(event, 'auth-token')
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Not authenticated'
|
||||
})
|
||||
}
|
||||
|
||||
// Decode JWT token
|
||||
let decoded
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.JWT_SECRET)
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Invalid or expired token'
|
||||
})
|
||||
}
|
||||
|
||||
// Get member
|
||||
const member = await Member.findById(decoded.memberId)
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Member not found'
|
||||
})
|
||||
}
|
||||
|
||||
if (!member.helcimCustomerId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'No Helcim customer ID found'
|
||||
})
|
||||
}
|
||||
|
||||
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
|
||||
|
||||
const response = await fetch(
|
||||
`${HELCIM_API_BASE}/customers/${member.helcimCustomerId}`,
|
||||
{
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'api-token': helcimToken
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw createError({
|
||||
statusCode: response.status,
|
||||
statusMessage: `Failed to get customer: ${errorText}`
|
||||
})
|
||||
}
|
||||
|
||||
const customerData = await response.json()
|
||||
|
||||
return {
|
||||
success: true,
|
||||
customerId: customerData.id,
|
||||
customerCode: customerData.customerCode
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error getting customer code:', error)
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || 'Failed to get customer code'
|
||||
})
|
||||
}
|
||||
})
|
||||
130
server/api/helcim/get-or-create-customer.post.js
Normal file
130
server/api/helcim/get-or-create-customer.post.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// Get existing or create new Helcim customer (for upgrading members)
|
||||
import jwt from 'jsonwebtoken'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await connectDB()
|
||||
const config = useRuntimeConfig(event)
|
||||
const token = getCookie(event, 'auth-token')
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Not authenticated'
|
||||
})
|
||||
}
|
||||
|
||||
// Decode JWT token
|
||||
let decoded
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.JWT_SECRET)
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: 'Invalid or expired token'
|
||||
})
|
||||
}
|
||||
|
||||
// Get member
|
||||
const member = await Member.findById(decoded.memberId)
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Member not found'
|
||||
})
|
||||
}
|
||||
|
||||
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
|
||||
|
||||
// First, search for existing customer
|
||||
try {
|
||||
const searchResponse = await fetch(
|
||||
`${HELCIM_API_BASE}/customers?search=${encodeURIComponent(member.email)}`,
|
||||
{
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'api-token': helcimToken
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (searchResponse.ok) {
|
||||
const searchData = await searchResponse.json()
|
||||
|
||||
if (searchData.customers && searchData.customers.length > 0) {
|
||||
const existingCustomer = searchData.customers.find(c => c.email === member.email)
|
||||
|
||||
if (existingCustomer) {
|
||||
console.log('Found existing Helcim customer:', existingCustomer.id)
|
||||
|
||||
// Update member record with customer ID if not already set
|
||||
if (!member.helcimCustomerId) {
|
||||
member.helcimCustomerId = existingCustomer.id
|
||||
await member.save()
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
customerId: existingCustomer.id,
|
||||
customerCode: existingCustomer.customerCode,
|
||||
existing: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (searchError) {
|
||||
console.log('Error searching for customer:', searchError)
|
||||
// Continue to create new customer
|
||||
}
|
||||
|
||||
// No existing customer found, create new one
|
||||
console.log('Creating new Helcim customer for:', member.email)
|
||||
const createResponse = await fetch(`${HELCIM_API_BASE}/customers`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'content-type': 'application/json',
|
||||
'api-token': helcimToken
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contactName: member.name,
|
||||
businessName: member.name,
|
||||
email: member.email
|
||||
})
|
||||
})
|
||||
|
||||
if (!createResponse.ok) {
|
||||
const errorText = await createResponse.text()
|
||||
console.error('Failed to create Helcim customer:', createResponse.status, errorText)
|
||||
throw createError({
|
||||
statusCode: createResponse.status,
|
||||
statusMessage: `Failed to create Helcim customer: ${errorText}`
|
||||
})
|
||||
}
|
||||
|
||||
const customerData = await createResponse.json()
|
||||
console.log('Created Helcim customer:', customerData.id)
|
||||
|
||||
// Update member record with customer ID
|
||||
member.helcimCustomerId = customerData.id
|
||||
await member.save()
|
||||
|
||||
return {
|
||||
success: true,
|
||||
customerId: customerData.id,
|
||||
customerCode: customerData.customerCode,
|
||||
existing: false
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error in get-or-create-customer:', error)
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || 'Failed to get or create customer'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
|
@ -2,9 +2,74 @@
|
|||
import { getHelcimPlanId, requiresPayment } from '../../config/contributions.js'
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
import { getSlackService } from '../../utils/slack.ts'
|
||||
|
||||
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
|
||||
|
||||
// Function to invite member to Slack
|
||||
async function inviteToSlack(member) {
|
||||
try {
|
||||
const slackService = getSlackService()
|
||||
if (!slackService) {
|
||||
console.warn('Slack service not configured, skipping invitation')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`Processing Slack invitation for ${member.email}...`)
|
||||
|
||||
const inviteResult = await slackService.inviteUserToSlack(
|
||||
member.email,
|
||||
member.name
|
||||
)
|
||||
|
||||
if (inviteResult.success) {
|
||||
// Update member record based on the actual result
|
||||
if (inviteResult.status === 'existing_user_added_to_channel' ||
|
||||
inviteResult.status === 'user_already_in_channel' ||
|
||||
inviteResult.status === 'new_user_invited_to_workspace') {
|
||||
member.slackInviteStatus = 'sent'
|
||||
member.slackUserId = inviteResult.userId
|
||||
member.slackInvited = true
|
||||
} else {
|
||||
// Manual invitation required
|
||||
member.slackInviteStatus = 'pending'
|
||||
member.slackInvited = false
|
||||
}
|
||||
await member.save()
|
||||
|
||||
// Send notification to vetting channel
|
||||
await slackService.notifyNewMember(
|
||||
member.name,
|
||||
member.email,
|
||||
member.circle,
|
||||
member.contributionTier,
|
||||
inviteResult.status
|
||||
)
|
||||
|
||||
console.log(`Successfully processed Slack invitation for ${member.email}: ${inviteResult.status}`)
|
||||
} else {
|
||||
// Update member record to reflect failed invitation
|
||||
member.slackInviteStatus = 'failed'
|
||||
await member.save()
|
||||
|
||||
console.error(`Failed to process Slack invitation for ${member.email}: ${inviteResult.error}`)
|
||||
// Don't throw error - subscription creation should still succeed
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during Slack invitation process:', error)
|
||||
|
||||
// Update member record to reflect failed invitation
|
||||
try {
|
||||
member.slackInviteStatus = 'failed'
|
||||
await member.save()
|
||||
} catch (saveError) {
|
||||
console.error('Failed to update member Slack status:', saveError)
|
||||
}
|
||||
|
||||
// Don't throw error - subscription creation should still succeed
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await connectDB()
|
||||
|
|
@ -44,6 +109,9 @@ export default defineEventHandler(async (event) => {
|
|||
|
||||
console.log('Updated member for free tier:', member)
|
||||
|
||||
// Send Slack invitation for free tier members
|
||||
await inviteToSlack(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: null,
|
||||
|
|
@ -82,6 +150,9 @@ export default defineEventHandler(async (event) => {
|
|||
{ new: true }
|
||||
)
|
||||
|
||||
// Send Slack invitation even when no plan is configured
|
||||
await inviteToSlack(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
|
|
@ -193,6 +264,9 @@ export default defineEventHandler(async (event) => {
|
|||
{ new: true }
|
||||
)
|
||||
|
||||
// Send Slack invitation even when subscription setup fails
|
||||
await inviteToSlack(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
|
|
@ -234,6 +308,9 @@ export default defineEventHandler(async (event) => {
|
|||
{ new: true }
|
||||
)
|
||||
|
||||
// Send Slack invitation for paid tier members
|
||||
await inviteToSlack(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
|
|
@ -260,6 +337,9 @@ export default defineEventHandler(async (event) => {
|
|||
{ new: true }
|
||||
)
|
||||
|
||||
// Send Slack invitation even when subscription fetch fails
|
||||
await inviteToSlack(member)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
subscription: {
|
||||
|
|
|
|||
100
server/api/members/cancel-subscription.post.js
Normal file
100
server/api/members/cancel-subscription.post.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// Cancel member subscription
|
||||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
const HELCIM_API_BASE = "https://api.helcim.com/v2";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await connectDB();
|
||||
const config = useRuntimeConfig(event);
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
// Decode JWT token
|
||||
let decoded;
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
// Get member
|
||||
const member = await Member.findById(decoded.memberId);
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Member not found",
|
||||
});
|
||||
}
|
||||
|
||||
// If already on free tier, nothing to cancel
|
||||
if (member.contributionTier === "0" || !member.helcimSubscriptionId) {
|
||||
return {
|
||||
success: true,
|
||||
message: "No active subscription to cancel",
|
||||
member,
|
||||
};
|
||||
}
|
||||
|
||||
const helcimToken =
|
||||
config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN;
|
||||
|
||||
try {
|
||||
// Cancel Helcim subscription
|
||||
const response = await fetch(
|
||||
`${HELCIM_API_BASE}/subscriptions/${member.helcimSubscriptionId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"api-token": helcimToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error(
|
||||
"Failed to cancel Helcim subscription:",
|
||||
response.status,
|
||||
errorText,
|
||||
);
|
||||
// Continue anyway - we'll update the member record
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error canceling Helcim subscription:", error);
|
||||
// Continue anyway - we'll update the member record
|
||||
}
|
||||
|
||||
// Update member status
|
||||
member.status = "cancelled";
|
||||
member.contributionTier = "0";
|
||||
member.helcimSubscriptionId = null;
|
||||
member.paymentMethod = "none";
|
||||
member.subscriptionEndDate = new Date();
|
||||
await member.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Subscription cancelled successfully",
|
||||
member,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error cancelling subscription:", error);
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || "Failed to cancel subscription",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -1,9 +1,74 @@
|
|||
// server/api/members/create.post.js
|
||||
import Member from '../../models/member.js'
|
||||
import { connectDB } from '../../utils/mongoose.js'
|
||||
import { getSlackService } from '../../utils/slack.ts'
|
||||
// Simple payment check function to avoid import issues
|
||||
const requiresPayment = (contributionValue) => contributionValue !== '0'
|
||||
|
||||
// Function to invite member to Slack
|
||||
async function inviteToSlack(member) {
|
||||
try {
|
||||
const slackService = getSlackService()
|
||||
if (!slackService) {
|
||||
console.warn('Slack service not configured, skipping invitation')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`Processing Slack invitation for ${member.email}...`)
|
||||
|
||||
const inviteResult = await slackService.inviteUserToSlack(
|
||||
member.email,
|
||||
member.name
|
||||
)
|
||||
|
||||
if (inviteResult.success) {
|
||||
// Update member record based on the actual result
|
||||
if (inviteResult.status === 'existing_user_added_to_channel' ||
|
||||
inviteResult.status === 'user_already_in_channel' ||
|
||||
inviteResult.status === 'new_user_invited_to_workspace') {
|
||||
member.slackInviteStatus = 'sent'
|
||||
member.slackUserId = inviteResult.userId
|
||||
member.slackInvited = true
|
||||
} else {
|
||||
// Manual invitation required
|
||||
member.slackInviteStatus = 'pending'
|
||||
member.slackInvited = false
|
||||
}
|
||||
await member.save()
|
||||
|
||||
// Send notification to vetting channel
|
||||
await slackService.notifyNewMember(
|
||||
member.name,
|
||||
member.email,
|
||||
member.circle,
|
||||
member.contributionTier,
|
||||
inviteResult.status
|
||||
)
|
||||
|
||||
console.log(`Successfully processed Slack invitation for ${member.email}: ${inviteResult.status}`)
|
||||
} else {
|
||||
// Update member record to reflect failed invitation
|
||||
member.slackInviteStatus = 'failed'
|
||||
await member.save()
|
||||
|
||||
console.error(`Failed to process Slack invitation for ${member.email}: ${inviteResult.error}`)
|
||||
// Don't throw error - member creation should still succeed
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during Slack invitation process:', error)
|
||||
|
||||
// Update member record to reflect failed invitation
|
||||
try {
|
||||
member.slackInviteStatus = 'failed'
|
||||
await member.save()
|
||||
} catch (saveError) {
|
||||
console.error('Failed to update member Slack status:', saveError)
|
||||
}
|
||||
|
||||
// Don't throw error - member creation should still succeed
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Ensure database is connected
|
||||
await connectDB()
|
||||
|
|
@ -23,6 +88,9 @@ export default defineEventHandler(async (event) => {
|
|||
const member = new Member(body)
|
||||
await member.save()
|
||||
|
||||
// Send Slack invitation for new members
|
||||
await inviteToSlack(member)
|
||||
|
||||
// TODO: Process payment with Helcim if not free tier
|
||||
if (requiresPayment(body.contributionTier)) {
|
||||
// Payment processing will be added here
|
||||
|
|
|
|||
115
server/api/members/directory.get.js
Normal file
115
server/api/members/directory.get.js
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
// Check if user is authenticated
|
||||
const token = getCookie(event, "auth-token");
|
||||
let isAuthenticated = false;
|
||||
let currentMemberId = null;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
currentMemberId = decoded.memberId;
|
||||
isAuthenticated = true;
|
||||
} catch (err) {
|
||||
// Invalid token, treat as public
|
||||
isAuthenticated = false;
|
||||
}
|
||||
}
|
||||
|
||||
const query = getQuery(event);
|
||||
const search = query.search || "";
|
||||
const circle = query.circle || "";
|
||||
const skills = query.skills ? query.skills.split(",") : [];
|
||||
|
||||
// Build query
|
||||
const dbQuery = {
|
||||
showInDirectory: true,
|
||||
status: "active",
|
||||
};
|
||||
|
||||
// Filter by circle if specified
|
||||
if (circle) {
|
||||
dbQuery.circle = circle;
|
||||
}
|
||||
|
||||
// Search by name or bio
|
||||
if (search) {
|
||||
dbQuery.$or = [
|
||||
{ name: { $regex: search, $options: "i" } },
|
||||
{ bio: { $regex: search, $options: "i" } },
|
||||
];
|
||||
}
|
||||
|
||||
// Filter by skills
|
||||
if (skills.length > 0) {
|
||||
dbQuery.skills = { $in: skills };
|
||||
}
|
||||
|
||||
try {
|
||||
const members = await Member.find(dbQuery)
|
||||
.select(
|
||||
"name pronouns timeZone avatar studio bio skills location socialLinks offering lookingFor privacy circle createdAt"
|
||||
)
|
||||
.sort({ createdAt: -1 })
|
||||
.lean();
|
||||
|
||||
// Filter fields based on privacy settings
|
||||
const filteredMembers = members.map((member) => {
|
||||
const privacy = member.privacy || {};
|
||||
const filtered = {
|
||||
_id: member._id,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
createdAt: member.createdAt,
|
||||
};
|
||||
|
||||
// Helper function to check if field should be visible
|
||||
const isVisible = (field) => {
|
||||
const privacySetting = privacy[field] || "members";
|
||||
if (privacySetting === "public") return true;
|
||||
if (privacySetting === "members" && isAuthenticated) return true;
|
||||
if (privacySetting === "private") return false;
|
||||
return false;
|
||||
};
|
||||
|
||||
// Add fields based on privacy settings
|
||||
if (isVisible("avatar")) filtered.avatar = member.avatar;
|
||||
if (isVisible("pronouns")) filtered.pronouns = member.pronouns;
|
||||
if (isVisible("timeZone")) filtered.timeZone = member.timeZone;
|
||||
if (isVisible("studio")) filtered.studio = member.studio;
|
||||
if (isVisible("bio")) filtered.bio = member.bio;
|
||||
if (isVisible("skills")) filtered.skills = member.skills;
|
||||
if (isVisible("location")) filtered.location = member.location;
|
||||
if (isVisible("socialLinks")) filtered.socialLinks = member.socialLinks;
|
||||
if (isVisible("offering")) filtered.offering = member.offering;
|
||||
if (isVisible("lookingFor")) filtered.lookingFor = member.lookingFor;
|
||||
|
||||
return filtered;
|
||||
});
|
||||
|
||||
// Get unique skills for filter options
|
||||
const allSkills = members
|
||||
.flatMap((m) => m.skills || [])
|
||||
.filter((skill, index, self) => self.indexOf(skill) === index)
|
||||
.sort();
|
||||
|
||||
return {
|
||||
members: filteredMembers,
|
||||
totalCount: filteredMembers.length,
|
||||
filters: {
|
||||
availableSkills: allSkills,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Directory fetch error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: "Failed to fetch member directory",
|
||||
});
|
||||
}
|
||||
});
|
||||
60
server/api/members/my-events.get.js
Normal file
60
server/api/members/my-events.get.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import Event from "../../models/event";
|
||||
import Member from "../../models/member";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event);
|
||||
const { memberId } = query;
|
||||
|
||||
if (!memberId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Member ID is required",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Verify member exists
|
||||
const member = await Member.findById(memberId);
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Member not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Find all events where the user is registered
|
||||
// Filter out cancelled events and only show future events
|
||||
const now = new Date();
|
||||
|
||||
const events = await Event.find({
|
||||
"registrations.memberId": memberId,
|
||||
isCancelled: { $ne: true },
|
||||
startDate: { $gte: now },
|
||||
})
|
||||
.select(
|
||||
"title slug description startDate endDate location featureImage maxAttendees registeredCount",
|
||||
)
|
||||
.sort({ startDate: 1 })
|
||||
.limit(10);
|
||||
|
||||
console.log(
|
||||
`Found ${events.length} registered events for member ${memberId}`,
|
||||
);
|
||||
|
||||
return {
|
||||
events,
|
||||
count: events.length,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error fetching member events:", error);
|
||||
|
||||
if (error.statusCode) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to fetch registered events",
|
||||
});
|
||||
}
|
||||
});
|
||||
117
server/api/members/profile.patch.js
Normal file
117
server/api/members/profile.patch.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
let memberId;
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readBody(event);
|
||||
|
||||
// Define allowed profile fields
|
||||
const allowedFields = [
|
||||
"pronouns",
|
||||
"timeZone",
|
||||
"avatar",
|
||||
"studio",
|
||||
"bio",
|
||||
"skills",
|
||||
"location",
|
||||
"socialLinks",
|
||||
"offering",
|
||||
"lookingFor",
|
||||
"showInDirectory",
|
||||
"helcimCustomerId",
|
||||
];
|
||||
|
||||
// Define privacy fields
|
||||
const privacyFields = [
|
||||
"pronounsPrivacy",
|
||||
"timeZonePrivacy",
|
||||
"avatarPrivacy",
|
||||
"studioPrivacy",
|
||||
"bioPrivacy",
|
||||
"skillsPrivacy",
|
||||
"locationPrivacy",
|
||||
"socialLinksPrivacy",
|
||||
"offeringPrivacy",
|
||||
"lookingForPrivacy",
|
||||
];
|
||||
|
||||
// Build update object
|
||||
const updateData = {};
|
||||
|
||||
allowedFields.forEach((field) => {
|
||||
if (body[field] !== undefined) {
|
||||
updateData[field] = body[field];
|
||||
}
|
||||
});
|
||||
|
||||
// Handle privacy settings
|
||||
privacyFields.forEach((privacyField) => {
|
||||
if (body[privacyField] !== undefined) {
|
||||
const baseField = privacyField.replace("Privacy", "");
|
||||
updateData[`privacy.${baseField}`] = body[privacyField];
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const member = await Member.findByIdAndUpdate(
|
||||
memberId,
|
||||
{ $set: updateData },
|
||||
{ new: true, runValidators: true },
|
||||
);
|
||||
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: "Member not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Return sanitized member data
|
||||
return {
|
||||
id: member._id,
|
||||
email: member.email,
|
||||
name: member.name,
|
||||
circle: member.circle,
|
||||
contributionTier: member.contributionTier,
|
||||
pronouns: member.pronouns,
|
||||
timeZone: member.timeZone,
|
||||
avatar: member.avatar,
|
||||
studio: member.studio,
|
||||
bio: member.bio,
|
||||
skills: member.skills,
|
||||
location: member.location,
|
||||
socialLinks: member.socialLinks,
|
||||
offering: member.offering,
|
||||
lookingFor: member.lookingFor,
|
||||
showInDirectory: member.showInDirectory,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Profile update error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
message: "Failed to update profile",
|
||||
});
|
||||
}
|
||||
});
|
||||
354
server/api/members/update-contribution.post.js
Normal file
354
server/api/members/update-contribution.post.js
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
// Update member's contribution tier
|
||||
import jwt from "jsonwebtoken";
|
||||
import {
|
||||
getHelcimPlanId,
|
||||
requiresPayment,
|
||||
isValidContributionValue,
|
||||
} from "../../config/contributions.js";
|
||||
import Member from "../../models/member.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
const HELCIM_API_BASE = "https://api.helcim.com/v2";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
await connectDB();
|
||||
const config = useRuntimeConfig(event);
|
||||
const body = await readBody(event);
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
// Decode JWT token
|
||||
let decoded;
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
// Validate contribution tier
|
||||
if (
|
||||
!body.contributionTier ||
|
||||
!isValidContributionValue(body.contributionTier)
|
||||
) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Invalid contribution tier",
|
||||
});
|
||||
}
|
||||
|
||||
// Get member
|
||||
const member = await Member.findById(decoded.memberId);
|
||||
if (!member) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Member not found",
|
||||
});
|
||||
}
|
||||
|
||||
const oldTier = member.contributionTier;
|
||||
const newTier = body.contributionTier;
|
||||
|
||||
// If same tier, nothing to do
|
||||
if (oldTier === newTier) {
|
||||
return {
|
||||
success: true,
|
||||
message: "Already on this tier",
|
||||
member,
|
||||
};
|
||||
}
|
||||
|
||||
const helcimToken =
|
||||
config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN;
|
||||
const oldRequiresPayment = requiresPayment(oldTier);
|
||||
const newRequiresPayment = requiresPayment(newTier);
|
||||
|
||||
// Case 1: Moving from free to paid tier
|
||||
if (!oldRequiresPayment && newRequiresPayment) {
|
||||
// Check if member has Helcim customer ID with saved payment method
|
||||
if (!member.helcimCustomerId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage:
|
||||
"Please use the subscription creation flow to upgrade to a paid tier",
|
||||
data: { requiresPaymentSetup: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Try to fetch customer info from Helcim to check for saved cards
|
||||
const helcimToken =
|
||||
config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN;
|
||||
|
||||
try {
|
||||
const customerResponse = await fetch(
|
||||
`${HELCIM_API_BASE}/customers/${member.helcimCustomerId}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"api-token": helcimToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!customerResponse.ok) {
|
||||
throw new Error("Failed to fetch customer info");
|
||||
}
|
||||
|
||||
const customerData = await customerResponse.json();
|
||||
const customerCode = customerData.customerCode;
|
||||
|
||||
if (!customerCode) {
|
||||
throw new Error("No customer code found");
|
||||
}
|
||||
|
||||
// Check if customer has saved cards
|
||||
const cardsResponse = await fetch(
|
||||
`${HELCIM_API_BASE}/card-terminals?customerId=${member.helcimCustomerId}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"api-token": helcimToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
let hasCards = false;
|
||||
if (cardsResponse.ok) {
|
||||
const cardsData = await cardsResponse.json();
|
||||
hasCards = cardsData.cards && cardsData.cards.length > 0;
|
||||
}
|
||||
|
||||
if (!hasCards) {
|
||||
throw new Error("No saved payment methods");
|
||||
}
|
||||
|
||||
// Create new subscription with saved payment method
|
||||
const newPlanId = getHelcimPlanId(newTier);
|
||||
|
||||
if (!newPlanId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Plan not configured for tier ${newTier}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Generate idempotency key
|
||||
const chars =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let idempotencyKey = "";
|
||||
for (let i = 0; i < 25; i++) {
|
||||
idempotencyKey += chars.charAt(
|
||||
Math.floor(Math.random() * chars.length),
|
||||
);
|
||||
}
|
||||
|
||||
// Get tier amount
|
||||
const { getContributionTierByValue } = await import(
|
||||
"../../config/contributions.js"
|
||||
);
|
||||
const tierInfo = getContributionTierByValue(newTier);
|
||||
|
||||
const subscriptionResponse = await fetch(
|
||||
`${HELCIM_API_BASE}/subscriptions`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
"api-token": helcimToken,
|
||||
"idempotency-key": idempotencyKey,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
subscriptions: [
|
||||
{
|
||||
dateActivated: new Date().toISOString().split("T")[0],
|
||||
paymentPlanId: parseInt(newPlanId),
|
||||
customerCode: customerCode,
|
||||
recurringAmount: parseFloat(tierInfo.amount),
|
||||
paymentMethod: "card",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!subscriptionResponse.ok) {
|
||||
const errorText = await subscriptionResponse.text();
|
||||
console.error("Failed to create subscription:", errorText);
|
||||
throw new Error(`Failed to create subscription: ${errorText}`);
|
||||
}
|
||||
|
||||
const subscriptionData = await subscriptionResponse.json();
|
||||
const subscription = subscriptionData.data?.[0];
|
||||
|
||||
if (!subscription) {
|
||||
throw new Error("No subscription returned in response");
|
||||
}
|
||||
|
||||
// Update member record
|
||||
member.contributionTier = newTier;
|
||||
member.helcimSubscriptionId = subscription.id;
|
||||
member.paymentMethod = "card";
|
||||
member.status = "active";
|
||||
await member.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Successfully upgraded to paid tier",
|
||||
member,
|
||||
subscription: {
|
||||
subscriptionId: subscription.id,
|
||||
status: subscription.status,
|
||||
nextBillingDate: subscription.nextBillingDate,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating subscription with saved payment:", error);
|
||||
// If we can't use saved payment, require new payment setup
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage:
|
||||
"Payment information required. You'll be redirected to complete payment setup.",
|
||||
data: { requiresPaymentSetup: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2: Moving from paid to free tier (cancel subscription)
|
||||
if (oldRequiresPayment && !newRequiresPayment) {
|
||||
if (member.helcimSubscriptionId) {
|
||||
try {
|
||||
// Cancel Helcim subscription
|
||||
const response = await fetch(
|
||||
`${HELCIM_API_BASE}/subscriptions/${member.helcimSubscriptionId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"api-token": helcimToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
"Failed to cancel Helcim subscription:",
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error canceling Helcim subscription:", error);
|
||||
// Continue anyway - we'll update the member record
|
||||
}
|
||||
}
|
||||
|
||||
// Update member to free tier
|
||||
member.contributionTier = newTier;
|
||||
member.helcimSubscriptionId = null;
|
||||
member.paymentMethod = "none";
|
||||
await member.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Successfully downgraded to free tier",
|
||||
member,
|
||||
};
|
||||
}
|
||||
|
||||
// Case 3: Moving between paid tiers
|
||||
if (oldRequiresPayment && newRequiresPayment) {
|
||||
const newPlanId = getHelcimPlanId(newTier);
|
||||
|
||||
if (!newPlanId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Plan not configured for tier ${newTier}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!member.helcimSubscriptionId) {
|
||||
// No subscription exists - they need to go through payment flow
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage:
|
||||
"Payment information required. You'll be redirected to complete payment setup.",
|
||||
data: { requiresPaymentSetup: true },
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
// Update subscription plan in Helcim
|
||||
const response = await fetch(
|
||||
`${HELCIM_API_BASE}/subscriptions/${member.helcimSubscriptionId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
"api-token": helcimToken,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
paymentPlanId: parseInt(newPlanId),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error(
|
||||
"Failed to update Helcim subscription:",
|
||||
response.status,
|
||||
errorText,
|
||||
);
|
||||
throw new Error(`Failed to update subscription: ${errorText}`);
|
||||
}
|
||||
|
||||
const subscriptionData = await response.json();
|
||||
|
||||
// Update member record
|
||||
member.contributionTier = newTier;
|
||||
await member.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Successfully updated contribution level",
|
||||
member,
|
||||
subscription: subscriptionData,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error updating Helcim subscription:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: error.message || "Failed to update subscription",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Case 4: Moving between free tiers (shouldn't happen but handle it)
|
||||
member.contributionTier = newTier;
|
||||
await member.save();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Successfully updated contribution level",
|
||||
member,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error updating contribution tier:", error);
|
||||
throw createError({
|
||||
statusCode: error.statusCode || 500,
|
||||
statusMessage: error.message || "Failed to update contribution tier",
|
||||
});
|
||||
}
|
||||
});
|
||||
68
server/api/slack/test-bot.get.ts
Normal file
68
server/api/slack/test-bot.get.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { WebClient } from '@slack/web-api'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
if (!config.slackBotToken) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Slack bot token not configured'
|
||||
}
|
||||
}
|
||||
|
||||
const client = new WebClient(config.slackBotToken)
|
||||
|
||||
try {
|
||||
// Test basic API access
|
||||
const authTest = await client.auth.test()
|
||||
console.log('Auth test result:', authTest)
|
||||
|
||||
// Test if admin API is available
|
||||
let adminApiAvailable = false
|
||||
let adminError = null
|
||||
|
||||
try {
|
||||
// Try to call admin.users.list to test admin API access
|
||||
await client.admin.users.list({ limit: 1 })
|
||||
adminApiAvailable = true
|
||||
} catch (error: any) {
|
||||
adminError = error.data?.error || error.message
|
||||
console.log('Admin API test failed:', adminError)
|
||||
}
|
||||
|
||||
// Test channel access if channel ID is configured
|
||||
let channelAccess = false
|
||||
let channelError = null
|
||||
|
||||
if (config.slackVettingChannelId) {
|
||||
try {
|
||||
const channelInfo = await client.conversations.info({
|
||||
channel: config.slackVettingChannelId
|
||||
})
|
||||
channelAccess = !!channelInfo.channel
|
||||
} catch (error: any) {
|
||||
channelError = error.data?.error || error.message
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
botInfo: {
|
||||
user: authTest.user,
|
||||
team: authTest.team,
|
||||
url: authTest.url
|
||||
},
|
||||
adminApiAvailable,
|
||||
adminError: adminApiAvailable ? null : adminError,
|
||||
channelAccess,
|
||||
channelError: channelAccess ? null : channelError,
|
||||
channelId: config.slackVettingChannelId || 'Not configured'
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.data?.error || error.message || 'Unknown error'
|
||||
}
|
||||
}
|
||||
})
|
||||
59
server/api/updates/[id].delete.js
Normal file
59
server/api/updates/[id].delete.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
let memberId;
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, "id");
|
||||
|
||||
try {
|
||||
const update = await Update.findById(id);
|
||||
|
||||
if (!update) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Update not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user is the author
|
||||
if (update.author.toString() !== memberId) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: "You can only delete your own updates",
|
||||
});
|
||||
}
|
||||
|
||||
await Update.findByIdAndDelete(id);
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (error.statusCode) throw error;
|
||||
console.error("Delete update error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to delete update",
|
||||
});
|
||||
}
|
||||
});
|
||||
60
server/api/updates/[id].get.js
Normal file
60
server/api/updates/[id].get.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const id = getRouterParam(event, "id");
|
||||
const token = getCookie(event, "auth-token");
|
||||
let memberId = null;
|
||||
|
||||
// Check if user is authenticated
|
||||
if (token) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
// Token invalid, continue as non-member
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const update = await Update.findById(id).populate("author", "name avatar");
|
||||
|
||||
if (!update) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Update not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Check privacy permissions
|
||||
if (update.privacy === "private") {
|
||||
// Only author can view private updates
|
||||
if (!memberId || update.author._id.toString() !== memberId) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: "You don't have permission to view this update",
|
||||
});
|
||||
}
|
||||
} else if (update.privacy === "members") {
|
||||
// Must be authenticated to view members-only updates
|
||||
if (!memberId) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: "You must be a member to view this update",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return update;
|
||||
} catch (error) {
|
||||
if (error.statusCode) throw error;
|
||||
console.error("Get update error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to fetch update",
|
||||
});
|
||||
}
|
||||
});
|
||||
68
server/api/updates/[id].patch.js
Normal file
68
server/api/updates/[id].patch.js
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
let memberId;
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, "id");
|
||||
const body = await readBody(event);
|
||||
|
||||
try {
|
||||
const update = await Update.findById(id);
|
||||
|
||||
if (!update) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "Update not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user is the author
|
||||
if (update.author.toString() !== memberId) {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: "You can only edit your own updates",
|
||||
});
|
||||
}
|
||||
|
||||
// Update allowed fields
|
||||
if (body.content !== undefined) update.content = body.content;
|
||||
if (body.images !== undefined) update.images = body.images;
|
||||
if (body.privacy !== undefined) update.privacy = body.privacy;
|
||||
if (body.commentsEnabled !== undefined)
|
||||
update.commentsEnabled = body.commentsEnabled;
|
||||
|
||||
await update.save();
|
||||
await update.populate("author", "name avatar");
|
||||
|
||||
return update;
|
||||
} catch (error) {
|
||||
if (error.statusCode) throw error;
|
||||
console.error("Update edit error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to update",
|
||||
});
|
||||
}
|
||||
});
|
||||
56
server/api/updates/index.get.js
Normal file
56
server/api/updates/index.get.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
let memberId = null;
|
||||
|
||||
// Check if user is authenticated
|
||||
if (token) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
// Token invalid, continue as non-member
|
||||
}
|
||||
}
|
||||
|
||||
const query = getQuery(event);
|
||||
const limit = parseInt(query.limit) || 20;
|
||||
const skip = parseInt(query.skip) || 0;
|
||||
|
||||
try {
|
||||
// Build privacy filter
|
||||
let privacyFilter;
|
||||
if (!memberId) {
|
||||
// Not authenticated - only show public updates
|
||||
privacyFilter = { privacy: "public" };
|
||||
} else {
|
||||
// Authenticated member - show public and members-only updates
|
||||
privacyFilter = { privacy: { $in: ["public", "members"] } };
|
||||
}
|
||||
|
||||
const updates = await Update.find(privacyFilter)
|
||||
.populate("author", "name avatar")
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.skip(skip);
|
||||
|
||||
const total = await Update.countDocuments(privacyFilter);
|
||||
|
||||
return {
|
||||
updates,
|
||||
total,
|
||||
hasMore: skip + limit < total,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Get updates error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to fetch updates",
|
||||
});
|
||||
}
|
||||
});
|
||||
57
server/api/updates/index.post.js
Normal file
57
server/api/updates/index.post.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
let memberId;
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readBody(event);
|
||||
|
||||
if (!body.content || !body.content.trim()) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Content is required",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const update = await Update.create({
|
||||
author: memberId,
|
||||
content: body.content,
|
||||
images: body.images || [],
|
||||
privacy: body.privacy || "members",
|
||||
commentsEnabled: body.commentsEnabled ?? true,
|
||||
});
|
||||
|
||||
// Populate author details
|
||||
await update.populate("author", "name avatar");
|
||||
|
||||
return update;
|
||||
} catch (error) {
|
||||
console.error("Create update error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to create update",
|
||||
});
|
||||
}
|
||||
});
|
||||
53
server/api/updates/my-updates.get.js
Normal file
53
server/api/updates/my-updates.get.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../models/update.js";
|
||||
import { connectDB } from "../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (!token) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Not authenticated",
|
||||
});
|
||||
}
|
||||
|
||||
let memberId;
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
memberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
const query = getQuery(event);
|
||||
const limit = parseInt(query.limit) || 20;
|
||||
const skip = parseInt(query.skip) || 0;
|
||||
|
||||
try {
|
||||
const updates = await Update.find({ author: memberId })
|
||||
.populate("author", "name avatar")
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.skip(skip);
|
||||
|
||||
const total = await Update.countDocuments({ author: memberId });
|
||||
|
||||
return {
|
||||
updates,
|
||||
total,
|
||||
hasMore: skip + limit < total,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Get my updates error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to fetch updates",
|
||||
});
|
||||
}
|
||||
});
|
||||
76
server/api/updates/user/[id].get.js
Normal file
76
server/api/updates/user/[id].get.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import jwt from "jsonwebtoken";
|
||||
import Update from "../../../models/update.js";
|
||||
import Member from "../../../models/member.js";
|
||||
import { connectDB } from "../../../utils/mongoose.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const userId = getRouterParam(event, "id");
|
||||
const token = getCookie(event, "auth-token");
|
||||
let currentMemberId = null;
|
||||
|
||||
// Check if user is authenticated
|
||||
if (token) {
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
currentMemberId = decoded.memberId;
|
||||
} catch (err) {
|
||||
// Token invalid, continue as non-member
|
||||
}
|
||||
}
|
||||
|
||||
const query = getQuery(event);
|
||||
const limit = parseInt(query.limit) || 20;
|
||||
const skip = parseInt(query.skip) || 0;
|
||||
|
||||
try {
|
||||
// Verify the user exists
|
||||
const user = await Member.findById(userId);
|
||||
if (!user) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: "User not found",
|
||||
});
|
||||
}
|
||||
|
||||
// Build privacy filter
|
||||
let privacyFilter;
|
||||
if (!currentMemberId) {
|
||||
// Not authenticated - only show public updates
|
||||
privacyFilter = { author: userId, privacy: "public" };
|
||||
} else if (currentMemberId === userId) {
|
||||
// Viewing own updates - show all
|
||||
privacyFilter = { author: userId };
|
||||
} else {
|
||||
// Authenticated member viewing another's updates - show public and members-only
|
||||
privacyFilter = { author: userId, privacy: { $in: ["public", "members"] } };
|
||||
}
|
||||
|
||||
const updates = await Update.find(privacyFilter)
|
||||
.populate("author", "name avatar")
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limit)
|
||||
.skip(skip);
|
||||
|
||||
const total = await Update.countDocuments(privacyFilter);
|
||||
|
||||
return {
|
||||
updates,
|
||||
total,
|
||||
hasMore: skip + limit < total,
|
||||
user: {
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
avatar: user.avatar,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.statusCode) throw error;
|
||||
console.error("Get user updates error:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to fetch user updates",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -4,68 +4,65 @@
|
|||
// Central configuration for Ghost Guild Contribution Levels and Helcim Plans
|
||||
export const CONTRIBUTION_TIERS = {
|
||||
FREE: {
|
||||
value: '0',
|
||||
value: "0",
|
||||
amount: 0,
|
||||
label: '$0 - I need support right now',
|
||||
tier: 'free',
|
||||
label: "$0 - I need support right now",
|
||||
tier: "free",
|
||||
helcimPlanId: null, // No Helcim plan needed for free tier
|
||||
features: [
|
||||
'Access to basic resources',
|
||||
'Community forum access'
|
||||
]
|
||||
features: ["Access to basic resources", "Community forum access"],
|
||||
},
|
||||
SUPPORTER: {
|
||||
value: '5',
|
||||
value: "5",
|
||||
amount: 5,
|
||||
label: '$5 - I can contribute a little',
|
||||
tier: 'supporter',
|
||||
label: "$5 - I can contribute a little",
|
||||
tier: "supporter",
|
||||
helcimPlanId: 20162,
|
||||
features: [
|
||||
'All Free Membership benefits',
|
||||
'Priority community support',
|
||||
'Early access to events'
|
||||
]
|
||||
"All Free Membership benefits",
|
||||
"Priority community support",
|
||||
"Early access to events",
|
||||
],
|
||||
},
|
||||
MEMBER: {
|
||||
value: '15',
|
||||
value: "15",
|
||||
amount: 15,
|
||||
label: '$15 - I can sustain the community',
|
||||
tier: 'member',
|
||||
helcimPlanId: null, // TODO: Create $15/month plan in Helcim dashboard
|
||||
label: "$15 - I can sustain the community",
|
||||
tier: "member",
|
||||
helcimPlanId: 21596,
|
||||
features: [
|
||||
'All Supporter benefits',
|
||||
'Access to premium workshops',
|
||||
'Monthly 1-on-1 sessions',
|
||||
'Advanced resource library'
|
||||
]
|
||||
"All Supporter benefits",
|
||||
"Access to premium workshops",
|
||||
"Monthly 1-on-1 sessions",
|
||||
"Advanced resource library",
|
||||
],
|
||||
},
|
||||
ADVOCATE: {
|
||||
value: '30',
|
||||
value: "30",
|
||||
amount: 30,
|
||||
label: '$30 - I can support others too',
|
||||
tier: 'advocate',
|
||||
helcimPlanId: null, // TODO: Create $30/month plan in Helcim dashboard
|
||||
label: "$30 - I can support others too",
|
||||
tier: "advocate",
|
||||
helcimPlanId: 21597,
|
||||
features: [
|
||||
'All Member benefits',
|
||||
'Weekly group mentoring',
|
||||
'Access to exclusive events',
|
||||
'Direct messaging with experts'
|
||||
]
|
||||
"All Member benefits",
|
||||
"Weekly group mentoring",
|
||||
"Access to exclusive events",
|
||||
"Direct messaging with experts",
|
||||
],
|
||||
},
|
||||
CHAMPION: {
|
||||
value: '50',
|
||||
value: "50",
|
||||
amount: 50,
|
||||
label: '$50 - I want to sponsor multiple members',
|
||||
tier: 'champion',
|
||||
helcimPlanId: null, // TODO: Create $50/month plan in Helcim dashboard
|
||||
label: "$50 - I want to sponsor multiple members",
|
||||
tier: "champion",
|
||||
helcimPlanId: 21598,
|
||||
features: [
|
||||
'All Advocate benefits',
|
||||
'Personal mentoring sessions',
|
||||
'VIP event access',
|
||||
'Custom project support',
|
||||
'Annual strategy session'
|
||||
]
|
||||
}
|
||||
"All Advocate benefits",
|
||||
"Personal mentoring sessions",
|
||||
"VIP event access",
|
||||
"Custom project support",
|
||||
"Annual strategy session",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
// Get all contribution options as an array (useful for forms)
|
||||
|
|
@ -75,12 +72,12 @@ export const getContributionOptions = () => {
|
|||
|
||||
// Get valid contribution values for validation
|
||||
export const getValidContributionValues = () => {
|
||||
return Object.values(CONTRIBUTION_TIERS).map(tier => tier.value);
|
||||
return Object.values(CONTRIBUTION_TIERS).map((tier) => tier.value);
|
||||
};
|
||||
|
||||
// Get contribution tier by value
|
||||
export const getContributionTierByValue = (value) => {
|
||||
return Object.values(CONTRIBUTION_TIERS).find(tier => tier.value === value);
|
||||
return Object.values(CONTRIBUTION_TIERS).find((tier) => tier.value === value);
|
||||
};
|
||||
|
||||
// Get Helcim plan ID for a contribution tier
|
||||
|
|
@ -102,10 +99,12 @@ export const isValidContributionValue = (value) => {
|
|||
|
||||
// Get contribution tier by Helcim plan ID
|
||||
export const getContributionTierByHelcimPlan = (helcimPlanId) => {
|
||||
return Object.values(CONTRIBUTION_TIERS).find(tier => tier.helcimPlanId === helcimPlanId);
|
||||
return Object.values(CONTRIBUTION_TIERS).find(
|
||||
(tier) => tier.helcimPlanId === helcimPlanId,
|
||||
);
|
||||
};
|
||||
|
||||
// Get paid tiers only (excluding free tier)
|
||||
export const getPaidContributionTiers = () => {
|
||||
return Object.values(CONTRIBUTION_TIERS).filter(tier => tier.amount > 0);
|
||||
return Object.values(CONTRIBUTION_TIERS).filter((tier) => tier.amount > 0);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import mongoose from 'mongoose'
|
||||
import mongoose from "mongoose";
|
||||
|
||||
const eventSchema = new mongoose.Schema({
|
||||
title: { type: String, required: true },
|
||||
|
|
@ -9,14 +9,14 @@ const eventSchema = new mongoose.Schema({
|
|||
featureImage: {
|
||||
url: String, // Cloudinary URL
|
||||
publicId: String, // Cloudinary public ID for transformations
|
||||
alt: String // Alt text for accessibility
|
||||
alt: String, // Alt text for accessibility
|
||||
},
|
||||
startDate: { type: Date, required: true },
|
||||
endDate: { type: Date, required: true },
|
||||
eventType: {
|
||||
type: String,
|
||||
enum: ['community', 'workshop', 'social', 'showcase'],
|
||||
default: 'community'
|
||||
enum: ["community", "workshop", "social", "showcase"],
|
||||
default: "community",
|
||||
},
|
||||
// Online-first location handling
|
||||
location: {
|
||||
|
|
@ -24,14 +24,15 @@ const eventSchema = new mongoose.Schema({
|
|||
required: true,
|
||||
// This will typically be a Slack channel or video conference link
|
||||
validate: {
|
||||
validator: function(v) {
|
||||
validator: function (v) {
|
||||
// Must be either a valid URL or a Slack channel reference
|
||||
const urlPattern = /^https?:\/\/.+/;
|
||||
const slackPattern = /^#[a-zA-Z0-9-_]+$/;
|
||||
return urlPattern.test(v) || slackPattern.test(v);
|
||||
},
|
||||
message: 'Location must be a valid URL (video conference link) or Slack channel (starting with #)'
|
||||
}
|
||||
message:
|
||||
"Location must be a valid URL (video conference link) or Slack channel (starting with #)",
|
||||
},
|
||||
},
|
||||
isOnline: { type: Boolean, default: true }, // Default to online-first
|
||||
// Visibility and status controls
|
||||
|
|
@ -46,97 +47,110 @@ const eventSchema = new mongoose.Schema({
|
|||
description: String, // Series description
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['workshop_series', 'recurring_meetup', 'multi_day', 'course', 'tournament'],
|
||||
default: 'workshop_series'
|
||||
enum: [
|
||||
"workshop_series",
|
||||
"recurring_meetup",
|
||||
"multi_day",
|
||||
"course",
|
||||
"tournament",
|
||||
],
|
||||
default: "workshop_series",
|
||||
},
|
||||
position: Number, // Order within the series (e.g., 1 = first event, 2 = second, etc.)
|
||||
totalEvents: Number, // Total planned events in the series
|
||||
isSeriesEvent: { type: Boolean, default: false } // Flag to identify series events
|
||||
isSeriesEvent: { type: Boolean, default: false }, // Flag to identify series events
|
||||
},
|
||||
// Event pricing for public attendees (deprecated - use tickets instead)
|
||||
pricing: {
|
||||
isFree: { type: Boolean, default: true },
|
||||
publicPrice: { type: Number, default: 0 }, // Price for non-members
|
||||
currency: { type: String, default: 'CAD' },
|
||||
paymentRequired: { type: Boolean, default: false }
|
||||
currency: { type: String, default: "CAD" },
|
||||
paymentRequired: { type: Boolean, default: false },
|
||||
},
|
||||
// Ticket configuration
|
||||
tickets: {
|
||||
enabled: { type: Boolean, default: false },
|
||||
public: {
|
||||
available: { type: Boolean, default: false },
|
||||
name: { type: String, default: 'Public Ticket' },
|
||||
name: { type: String, default: "Public Ticket" },
|
||||
description: String,
|
||||
price: { type: Number, default: 0 },
|
||||
quantity: Number, // null = unlimited
|
||||
sold: { type: Number, default: 0 },
|
||||
earlyBirdPrice: Number,
|
||||
earlyBirdDeadline: Date
|
||||
}
|
||||
earlyBirdDeadline: Date,
|
||||
},
|
||||
},
|
||||
// Circle targeting
|
||||
targetCircles: [{
|
||||
type: String,
|
||||
enum: ['community', 'founder', 'practitioner'],
|
||||
required: false
|
||||
}],
|
||||
targetCircles: [
|
||||
{
|
||||
type: String,
|
||||
enum: ["community", "founder", "practitioner"],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
maxAttendees: Number,
|
||||
registrationRequired: { type: Boolean, default: false },
|
||||
registrationDeadline: Date,
|
||||
agenda: [String],
|
||||
speakers: [{
|
||||
name: String,
|
||||
role: String,
|
||||
bio: String
|
||||
}],
|
||||
registrations: [{
|
||||
name: String,
|
||||
email: String,
|
||||
membershipLevel: String,
|
||||
isMember: { type: Boolean, default: false },
|
||||
paymentStatus: {
|
||||
type: String,
|
||||
enum: ['pending', 'completed', 'failed', 'not_required'],
|
||||
default: 'not_required'
|
||||
speakers: [
|
||||
{
|
||||
name: String,
|
||||
role: String,
|
||||
bio: String,
|
||||
},
|
||||
paymentId: String, // Helcim transaction ID
|
||||
amountPaid: { type: Number, default: 0 },
|
||||
registeredAt: { type: Date, default: Date.now }
|
||||
}],
|
||||
],
|
||||
registrations: [
|
||||
{
|
||||
memberId: { type: mongoose.Schema.Types.ObjectId, ref: "Member" }, // Reference to Member model
|
||||
name: String,
|
||||
email: String,
|
||||
membershipLevel: String,
|
||||
isMember: { type: Boolean, default: false },
|
||||
paymentStatus: {
|
||||
type: String,
|
||||
enum: ["pending", "completed", "failed", "not_required"],
|
||||
default: "not_required",
|
||||
},
|
||||
paymentId: String, // Helcim transaction ID
|
||||
amountPaid: { type: Number, default: 0 },
|
||||
registeredAt: { type: Date, default: Date.now },
|
||||
},
|
||||
],
|
||||
createdBy: { type: String, required: true },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
updatedAt: { type: Date, default: Date.now }
|
||||
})
|
||||
updatedAt: { type: Date, default: Date.now },
|
||||
});
|
||||
|
||||
// Generate slug from title
|
||||
function generateSlug(title) {
|
||||
return title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
// Pre-save hook to generate slug
|
||||
eventSchema.pre('save', async function(next) {
|
||||
eventSchema.pre("save", async function (next) {
|
||||
try {
|
||||
if (this.isNew || this.isModified('title')) {
|
||||
let baseSlug = generateSlug(this.title)
|
||||
let slug = baseSlug
|
||||
let counter = 1
|
||||
|
||||
if (this.isNew || this.isModified("title")) {
|
||||
let baseSlug = generateSlug(this.title);
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
|
||||
// Ensure slug is unique
|
||||
while (await this.constructor.findOne({ slug, _id: { $ne: this._id } })) {
|
||||
slug = `${baseSlug}-${counter}`
|
||||
counter++
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
counter++;
|
||||
}
|
||||
|
||||
this.slug = slug
|
||||
}
|
||||
next()
|
||||
} catch (error) {
|
||||
console.error('Error in pre-save hook:', error)
|
||||
next(error)
|
||||
}
|
||||
})
|
||||
|
||||
export default mongoose.models.Event || mongoose.model('Event', eventSchema)
|
||||
this.slug = slug;
|
||||
}
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error("Error in pre-save hook:", error);
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default mongoose.models.Event || mongoose.model("Event", eventSchema);
|
||||
|
|
|
|||
|
|
@ -1,46 +1,125 @@
|
|||
// server/models/member.js
|
||||
import mongoose from 'mongoose'
|
||||
import { resolve } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import mongoose from "mongoose";
|
||||
import { resolve } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url))
|
||||
const __dirname = fileURLToPath(new URL(".", import.meta.url));
|
||||
|
||||
// Import configs using dynamic imports to avoid build issues
|
||||
const getValidCircleValues = () => ['community', 'founder', 'practitioner']
|
||||
const getValidContributionValues = () => ['0', '5', '15', '30', '50']
|
||||
const getValidCircleValues = () => ["community", "founder", "practitioner"];
|
||||
const getValidContributionValues = () => ["0", "5", "15", "30", "50"];
|
||||
|
||||
const memberSchema = new mongoose.Schema({
|
||||
email: { type: String, required: true, unique: true },
|
||||
name: { type: String, required: true },
|
||||
circle: {
|
||||
type: String,
|
||||
circle: {
|
||||
type: String,
|
||||
enum: getValidCircleValues(),
|
||||
required: true
|
||||
required: true,
|
||||
},
|
||||
contributionTier: {
|
||||
type: String,
|
||||
enum: getValidContributionValues(),
|
||||
required: true
|
||||
required: true,
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['pending_payment', 'active', 'suspended', 'cancelled'],
|
||||
default: 'pending_payment'
|
||||
enum: ["pending_payment", "active", "suspended", "cancelled"],
|
||||
default: "pending_payment",
|
||||
},
|
||||
helcimCustomerId: String,
|
||||
helcimSubscriptionId: String,
|
||||
paymentMethod: {
|
||||
type: String,
|
||||
enum: ['card', 'bank', 'none'],
|
||||
default: 'none'
|
||||
enum: ["card", "bank", "none"],
|
||||
default: "none",
|
||||
},
|
||||
subscriptionStartDate: Date,
|
||||
subscriptionEndDate: Date,
|
||||
nextBillingDate: Date,
|
||||
slackInvited: { type: Boolean, default: false },
|
||||
slackInviteStatus: {
|
||||
type: String,
|
||||
enum: ["pending", "sent", "failed", "accepted"],
|
||||
default: "pending",
|
||||
},
|
||||
slackUserId: String,
|
||||
|
||||
// Profile fields
|
||||
pronouns: String,
|
||||
timeZone: String,
|
||||
avatar: String,
|
||||
studio: String,
|
||||
bio: String,
|
||||
skills: [String],
|
||||
location: String,
|
||||
socialLinks: {
|
||||
mastodon: String,
|
||||
linkedin: String,
|
||||
website: String,
|
||||
other: String,
|
||||
},
|
||||
offering: String,
|
||||
lookingFor: String,
|
||||
showInDirectory: { type: Boolean, default: true },
|
||||
|
||||
// Privacy settings for profile fields
|
||||
privacy: {
|
||||
pronouns: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
timeZone: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
avatar: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "public",
|
||||
},
|
||||
studio: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
bio: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
skills: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
location: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
socialLinks: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
offering: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
lookingFor: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
},
|
||||
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
lastLogin: Date
|
||||
})
|
||||
lastLogin: Date,
|
||||
});
|
||||
|
||||
// Check if model already exists to prevent re-compilation in development
|
||||
export default mongoose.models.Member || mongoose.model('Member', memberSchema)
|
||||
export default mongoose.models.Member || mongoose.model("Member", memberSchema);
|
||||
|
|
|
|||
50
server/models/update.js
Normal file
50
server/models/update.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import mongoose from "mongoose";
|
||||
|
||||
const updateSchema = new mongoose.Schema({
|
||||
author: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "Member",
|
||||
required: true,
|
||||
},
|
||||
content: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
images: [
|
||||
{
|
||||
url: String,
|
||||
publicId: String,
|
||||
alt: String,
|
||||
},
|
||||
],
|
||||
privacy: {
|
||||
type: String,
|
||||
enum: ["public", "members", "private"],
|
||||
default: "members",
|
||||
},
|
||||
commentsEnabled: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
createdAt: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
},
|
||||
updatedAt: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
},
|
||||
});
|
||||
|
||||
// Update the updatedAt timestamp on save
|
||||
updateSchema.pre("save", function (next) {
|
||||
this.updatedAt = Date.now();
|
||||
next();
|
||||
});
|
||||
|
||||
// Indexes for performance
|
||||
updateSchema.index({ createdAt: -1 }); // For sorting by date
|
||||
updateSchema.index({ privacy: 1, createdAt: -1 }); // Compound index for filtering and sorting
|
||||
updateSchema.index({ author: 1 }); // For author lookups
|
||||
|
||||
export default mongoose.models.Update || mongoose.model("Update", updateSchema);
|
||||
233
server/utils/slack.ts
Normal file
233
server/utils/slack.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import { WebClient } from "@slack/web-api";
|
||||
|
||||
export class SlackService {
|
||||
private client: WebClient;
|
||||
private vettingChannelId: string;
|
||||
|
||||
constructor(botToken: string, vettingChannelId: string) {
|
||||
this.client = new WebClient(botToken);
|
||||
this.vettingChannelId = vettingChannelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invite user to workspace and channel (using proper admin and conversation scopes)
|
||||
*/
|
||||
async inviteUserToSlack(
|
||||
email: string,
|
||||
realName: string
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
userId?: string;
|
||||
status?: string;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
// First, check if user already exists in workspace
|
||||
const existingUser = await this.findUserByEmail(email);
|
||||
|
||||
if (existingUser) {
|
||||
// User exists, invite them to the vetting channel
|
||||
try {
|
||||
await this.client.conversations.invite({
|
||||
channel: this.vettingChannelId,
|
||||
users: existingUser,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`Successfully invited existing user ${email} to vetting channel`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
userId: existingUser,
|
||||
status: "existing_user_added_to_channel",
|
||||
};
|
||||
} catch (error: any) {
|
||||
if (error.data?.error === "already_in_channel") {
|
||||
return {
|
||||
success: true,
|
||||
userId: existingUser,
|
||||
status: "user_already_in_channel",
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// User doesn't exist, try to invite to workspace using admin API
|
||||
try {
|
||||
const inviteResponse = await this.client.admin.users.invite({
|
||||
email: email,
|
||||
real_name: realName,
|
||||
channel_ids: [this.vettingChannelId],
|
||||
is_restricted: true, // Single-channel guest
|
||||
is_ultra_restricted: false,
|
||||
});
|
||||
|
||||
if (inviteResponse.ok && inviteResponse.user) {
|
||||
console.log(
|
||||
`Successfully invited ${email} to workspace as single-channel guest`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
userId: inviteResponse.user.id,
|
||||
status: "new_user_invited_to_workspace",
|
||||
};
|
||||
} else {
|
||||
throw new Error(`Admin invite failed: ${inviteResponse.error}`);
|
||||
}
|
||||
} catch (adminError: any) {
|
||||
console.log(
|
||||
`Admin API not available or failed: ${
|
||||
adminError.data?.error || adminError.message
|
||||
}`
|
||||
);
|
||||
|
||||
// Fall back to manual process
|
||||
return {
|
||||
success: true,
|
||||
status: "manual_invitation_required",
|
||||
error: `Admin API unavailable: ${
|
||||
adminError.data?.error || adminError.message
|
||||
}`,
|
||||
};
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(`Failed to process invitation for ${email}:`, error);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error.data?.error || error.message || "Unknown error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find user in workspace by email
|
||||
*/
|
||||
private async findUserByEmail(email: string): Promise<string | null> {
|
||||
try {
|
||||
const response = await this.client.users.lookupByEmail({ email });
|
||||
return response.user?.id || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification to the vetting channel about a new member
|
||||
*/
|
||||
async notifyNewMember(
|
||||
memberName: string,
|
||||
memberEmail: string,
|
||||
circle: string,
|
||||
contributionTier: string,
|
||||
invitationStatus: string = "manual_invitation_required"
|
||||
): Promise<void> {
|
||||
try {
|
||||
let statusMessage = "";
|
||||
let actionMessage = "";
|
||||
|
||||
switch (invitationStatus) {
|
||||
case "existing_user_added_to_channel":
|
||||
statusMessage =
|
||||
"✅ Existing user automatically added to this channel.";
|
||||
actionMessage = "Ready for vetting!";
|
||||
break;
|
||||
case "user_already_in_channel":
|
||||
statusMessage = "✅ User is already in this channel.";
|
||||
actionMessage = "Ready for vetting!";
|
||||
break;
|
||||
case "new_user_invited_to_workspace":
|
||||
statusMessage =
|
||||
"🎉 User successfully invited to workspace as single-channel guest.";
|
||||
actionMessage = "Ready for vetting!";
|
||||
break;
|
||||
case "manual_invitation_required":
|
||||
statusMessage = "📧 User needs to be manually invited to join Slack.";
|
||||
actionMessage = `Please vet this new member before inviting them to other channels.`;
|
||||
break;
|
||||
default:
|
||||
statusMessage = "⚠️ Invitation status unknown.";
|
||||
actionMessage = "Manual review required.";
|
||||
}
|
||||
|
||||
await this.client.chat.postMessage({
|
||||
channel: this.vettingChannelId,
|
||||
text: `New Ghost Guild member: ${memberName}`,
|
||||
blocks: [
|
||||
{
|
||||
type: "header",
|
||||
text: {
|
||||
type: "plain_text",
|
||||
text: "New Ghost Guild Member Registration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
fields: [
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*Name:*\n${memberName}`,
|
||||
},
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*Email:*\n${memberEmail}`,
|
||||
},
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*Circle:*\n${circle}`,
|
||||
},
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*Contribution:*\n$${contributionTier}/month`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Status:* ${statusMessage}\n*Action:* ${actionMessage}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "divider",
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to send Slack notification:", error);
|
||||
// Don't throw - this is non-critical
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the Slack channel exists and bot has access
|
||||
*/
|
||||
async verifyChannelAccess(): Promise<boolean> {
|
||||
try {
|
||||
const response = await this.client.conversations.info({
|
||||
channel: this.vettingChannelId,
|
||||
});
|
||||
return response.ok && !!response.channel;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get configured Slack service instance
|
||||
*/
|
||||
export function getSlackService(): SlackService | null {
|
||||
const config = useRuntimeConfig();
|
||||
|
||||
if (!config.slackBotToken || !config.slackVettingChannelId) {
|
||||
console.warn(
|
||||
"Slack integration not configured - missing bot token or channel ID"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
return new SlackService(config.slackBotToken, config.slackVettingChannelId);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue