Compare commits

...

3 Commits

Author SHA1 Message Date
James Pattinson
b8f2d12011 Square enhancements 2025-11-13 17:41:28 +00:00
James Pattinson
dac8b43915 Event editing 2025-11-12 21:04:00 +00:00
James Pattinson
9edfe6aa62 Layout tweaks 2025-11-12 20:55:24 +00:00
8 changed files with 915 additions and 183 deletions

View File

@@ -190,7 +190,8 @@ async def process_square_payment(
source_id=payment_request.source_id, source_id=payment_request.source_id,
idempotency_key=payment_request.idempotency_key, idempotency_key=payment_request.idempotency_key,
reference_id=reference_id, reference_id=reference_id,
note=payment_request.note or f"Membership payment for {tier.name} - {current_user.email}" note=payment_request.note or f"Membership payment for {tier.name} - {current_user.email}",
billing_details=payment_request.billing_details
) )
if not square_result.get('success'): if not square_result.get('success'):

View File

@@ -171,6 +171,7 @@ class SquarePaymentRequest(BaseModel):
amount: float = Field(..., gt=0, description="Payment amount in GBP") amount: float = Field(..., gt=0, description="Payment amount in GBP")
idempotency_key: Optional[str] = Field(None, description="Unique key to prevent duplicate payments") idempotency_key: Optional[str] = Field(None, description="Unique key to prevent duplicate payments")
note: Optional[str] = Field(None, description="Optional payment note") note: Optional[str] = Field(None, description="Optional payment note")
billing_details: Optional[dict] = Field(None, description="Billing address and cardholder name for AVS")
class SquarePaymentResponse(BaseModel): class SquarePaymentResponse(BaseModel):

View File

@@ -35,7 +35,8 @@ class SquareService:
idempotency_key: Optional[str] = None, idempotency_key: Optional[str] = None,
customer_id: Optional[str] = None, customer_id: Optional[str] = None,
reference_id: Optional[str] = None, reference_id: Optional[str] = None,
note: Optional[str] = None note: Optional[str] = None,
billing_details: Optional[Dict] = None
) -> Dict: ) -> Dict:
""" """
Create a payment using Square Create a payment using Square
@@ -47,6 +48,7 @@ class SquareService:
customer_id: Optional Square customer ID customer_id: Optional Square customer ID
reference_id: Optional reference ID for internal tracking reference_id: Optional reference ID for internal tracking
note: Optional note about the payment note: Optional note about the payment
billing_details: Optional billing address and cardholder name for AVS
Returns: Returns:
Dict with payment result including payment_id, status, and details Dict with payment result including payment_id, status, and details
@@ -60,19 +62,49 @@ class SquareService:
# For GBP, this is pence # For GBP, this is pence
amount_in_pence = int(amount_money * 100) amount_in_pence = int(amount_money * 100)
# Create payment - pass parameters directly as keyword arguments # Build payment parameters
result = self.client.payments.create( payment_params = {
source_id=source_id, 'source_id': source_id,
idempotency_key=idempotency_key, 'idempotency_key': idempotency_key,
amount_money={ 'amount_money': {
'amount': amount_in_pence, 'amount': amount_in_pence,
'currency': 'GBP' 'currency': 'GBP'
}, },
location_id=self.location_id, 'location_id': self.location_id
customer_id=customer_id if customer_id else None, }
reference_id=reference_id if reference_id else None,
note=note if note else None # Add billing address for AVS if provided
) if billing_details:
# Add buyer email if available
if billing_details.get('email'):
payment_params['buyer_email_address'] = billing_details.get('email')
# Build billing address for AVS
billing_address = {}
if billing_details.get('address_line_1'):
billing_address['address_line_1'] = billing_details.get('address_line_1')
if billing_details.get('address_line_2'):
billing_address['address_line_2'] = billing_details.get('address_line_2')
if billing_details.get('city'):
billing_address['locality'] = billing_details.get('city')
if billing_details.get('postal_code'):
billing_address['postal_code'] = billing_details.get('postal_code')
if billing_details.get('country'):
billing_address['country'] = billing_details.get('country')
if billing_address:
payment_params['billing_address'] = billing_address
# Add optional parameters
if customer_id:
payment_params['customer_id'] = customer_id
if reference_id:
payment_params['reference_id'] = reference_id
if note:
payment_params['note'] = note
# Create payment - pass parameters directly as keyword arguments
result = self.client.payments.create(**payment_params)
if result.errors: if result.errors:
# Payment failed - extract user-friendly error messages # Payment failed - extract user-friendly error messages

View File

@@ -4,8 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SASA Membership Portal</title> <title>SASA Membership Portal</title>
<!-- Square Web Payments SDK --> <!-- Square Web Payments SDK loaded dynamically based on environment -->
<script type="text/javascript" src="https://sandbox.web.squarecdn.com/v1/square.js"></script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>

View File

@@ -180,11 +180,23 @@ body {
.dashboard-grid { .dashboard-grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); grid-template-columns: 1fr;
gap: 20px; gap: 20px;
margin-top: 20px; margin-top: 20px;
} }
/* Desktop view: side-by-side layout */
@media (min-width: 769px) {
.dashboard-grid {
grid-template-columns: 1fr 1fr;
align-items: start;
}
.dashboard-grid > .card {
margin-bottom: 0;
}
}
/* Mobile responsive adjustments */ /* Mobile responsive adjustments */
@media (max-width: 768px) { @media (max-width: 768px) {
.dashboard-grid { .dashboard-grid {
@@ -449,3 +461,176 @@ body {
border-color: #c82333; border-color: #c82333;
color: white !important; color: white !important;
} }
/* Events Container Styles */
.events-container {
display: flex;
flex-direction: column;
gap: 16px;
}
.event-card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
background-color: #f9f9f9;
}
.event-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 12px;
}
.event-info {
flex: 1;
min-width: 0;
}
.event-title {
margin: 0 0 4px 0;
color: #0066cc;
font-size: 18px;
word-wrap: break-word;
}
.event-datetime {
margin: 0;
font-size: 14px;
color: #666;
}
.event-location {
margin: 4px 0 0 0;
font-size: 14px;
color: #666;
}
.event-rsvp-buttons {
display: flex;
gap: 8px;
flex-shrink: 0;
}
.rsvp-btn {
font-size: 12px;
padding: 8px 16px;
border: 2px solid #adb5bd;
border-radius: 4px;
background-color: transparent;
color: #6c757d;
cursor: pointer;
font-weight: normal;
transition: all 0.3s ease;
white-space: nowrap;
}
.rsvp-btn:hover:not(:disabled) {
opacity: 0.8;
}
.rsvp-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.rsvp-btn.active {
font-weight: bold;
transform: scale(1.05);
}
.rsvp-btn:not(.active) {
opacity: 0.5;
filter: grayscale(50%);
}
.rsvp-btn-attending.active {
border: 3px solid #28a745;
background-color: #28a745;
color: white;
box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}
.rsvp-btn-maybe.active {
border: 3px solid #ffc107;
background-color: #ffc107;
color: #212529;
box-shadow: 0 4px 8px rgba(255, 193, 7, 0.3);
}
.rsvp-btn-not-attending.active {
border: 3px solid #dc3545;
background-color: #dc3545;
color: white;
box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3);
}
.event-description {
margin: 0;
font-size: 14px;
line-height: 1.4;
}
.event-rsvp-status {
margin-top: 12px;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
}
.event-rsvp-status.attending {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.event-rsvp-status.maybe {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
color: #856404;
}
.event-rsvp-status.not_attending {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
/* Mobile responsive adjustments for events */
@media (max-width: 768px) {
.event-header {
flex-direction: column;
align-items: stretch;
}
.event-rsvp-buttons {
flex-direction: column;
width: 100%;
gap: 8px;
}
.rsvp-btn {
width: 100%;
padding: 12px 16px;
font-size: 14px;
}
.event-title {
font-size: 16px;
}
.event-card {
padding: 12px;
}
/* Event modal responsive */
.modal-content[style*="600px"] {
max-width: 95% !important;
}
.modal-content div[style*="grid-template-columns"] {
grid-template-columns: 1fr !important;
}
}

View File

@@ -1,13 +1,15 @@
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { authService } from '../services/membershipService'; import { authService, User } from '../services/membershipService';
interface ProfileMenuProps { interface ProfileMenuProps {
userName: string; userName: string;
userRole: string; userRole: string;
user?: User | null;
onEditProfile?: () => void;
} }
const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole }) => { const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole, user, onEditProfile }) => {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [showChangePassword, setShowChangePassword] = useState(false); const [showChangePassword, setShowChangePassword] = useState(false);
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
@@ -36,6 +38,14 @@ const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole }) => {
setIsOpen(false); setIsOpen(false);
}; };
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-GB', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
};
const dropdownStyle: React.CSSProperties = { const dropdownStyle: React.CSSProperties = {
position: 'absolute', position: 'absolute',
top: '100%', top: '100%',
@@ -44,7 +54,8 @@ const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole }) => {
border: '1px solid #ddd', border: '1px solid #ddd',
borderRadius: '4px', borderRadius: '4px',
boxShadow: '0 2px 8px rgba(0,0,0,0.1)', boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
minWidth: '160px', minWidth: '280px',
maxWidth: '320px',
zIndex: 1000, zIndex: 1000,
}; };
@@ -82,10 +93,52 @@ const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole }) => {
{isOpen && ( {isOpen && (
<div style={dropdownStyle}> <div style={dropdownStyle}>
{/* Profile Details Section */}
{user && (
<div style={{
padding: '16px',
borderBottom: '1px solid #eee',
backgroundColor: '#f9f9f9',
borderRadius: '4px 4px 0 0'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
<h4 style={{ margin: 0, fontSize: '14px', fontWeight: 'bold', color: '#333' }}>Profile Details</h4>
{onEditProfile && (
<button
onClick={() => {
onEditProfile();
setIsOpen(false);
}}
style={{
background: '#0066cc',
color: 'white',
border: 'none',
padding: '4px 8px',
borderRadius: '3px',
cursor: 'pointer',
fontSize: '11px',
fontWeight: '500'
}}
>
Edit
</button>
)}
</div>
<div style={{ fontSize: '12px', color: '#555', lineHeight: '1.6' }}>
<p style={{ margin: '4px 0' }}><strong>Name:</strong> {user.first_name} {user.last_name}</p>
<p style={{ margin: '4px 0' }}><strong>Email:</strong> {user.email}</p>
{user.phone && <p style={{ margin: '4px 0' }}><strong>Phone:</strong> {user.phone}</p>}
{user.address && <p style={{ margin: '4px 0' }}><strong>Address:</strong> {user.address}</p>}
<p style={{ margin: '4px 0' }}><strong>Member since:</strong> {formatDate(user.created_at)}</p>
</div>
</div>
)}
{/* Menu Items */}
{userRole === 'super_admin' && ( {userRole === 'super_admin' && (
<> <>
<button <button
style={{ ...menuItemStyle, borderRadius: '4px 4px 0 0' }} style={{ ...menuItemStyle, borderRadius: user ? '0' : '4px 4px 0 0' }}
onClick={() => { onClick={() => {
navigate('/membership-tiers'); navigate('/membership-tiers');
setIsOpen(false); setIsOpen(false);
@@ -116,15 +169,15 @@ const ProfileMenu: React.FC<ProfileMenuProps> = ({ userName, userRole }) => {
<button <button
style={{ style={{
...menuItemStyle, ...menuItemStyle,
borderRadius: userRole === 'super_admin' ? '0 0 4px 4px' : '4px 4px 0 0', borderRadius: '0',
borderTop: userRole === 'super_admin' ? '1px solid #eee' : 'none' borderTop: (userRole === 'super_admin' || user) ? '1px solid #eee' : 'none'
}} }}
onClick={handleChangePassword} onClick={handleChangePassword}
> >
Change Password Change Password
</button> </button>
<button <button
style={{ ...menuItemStyle, borderRadius: '0 0 4px 4px' }} style={{ ...menuItemStyle, borderRadius: '0 0 4px 4px', borderTop: '1px solid #eee' }}
onClick={handleLogout} onClick={handleLogout}
> >
Log Out Log Out

View File

@@ -18,6 +18,14 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
const [payments, setPayments] = useState<any>(null); const [payments, setPayments] = useState<any>(null);
const [squareConfig, setSquareConfig] = useState<any>(null); const [squareConfig, setSquareConfig] = useState<any>(null);
// Billing details state
const [cardholderName, setCardholderName] = useState('');
const [addressLine1, setAddressLine1] = useState('');
const [addressLine2, setAddressLine2] = useState('');
const [city, setCity] = useState('');
const [postalCode, setPostalCode] = useState('');
const [isProcessing, setIsProcessing] = useState(false);
useEffect(() => { useEffect(() => {
loadSquareConfig(); loadSquareConfig();
}, []); }, []);
@@ -28,6 +36,31 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
} }
}, [squareConfig]); }, [squareConfig]);
const loadSquareSDK = (environment: string): Promise<void> => {
return new Promise((resolve, reject) => {
// Check if Square SDK is already loaded
if (window.Square) {
resolve();
return;
}
const script = document.createElement('script');
script.type = 'text/javascript';
// Load the correct SDK based on environment
if (environment?.toLowerCase() === 'sandbox') {
script.src = 'https://sandbox.web.squarecdn.com/v1/square.js';
} else {
script.src = 'https://web.squarecdn.com/v1/square.js';
}
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load Square SDK'));
document.head.appendChild(script);
});
};
const loadSquareConfig = async () => { const loadSquareConfig = async () => {
try { try {
const response = await fetch('/api/v1/payments/config/square', { const response = await fetch('/api/v1/payments/config/square', {
@@ -36,6 +69,12 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
} }
}); });
const config = await response.json(); const config = await response.json();
console.log('Square config received:', config);
// Load the appropriate Square SDK based on environment
await loadSquareSDK(config.environment);
console.log('Square SDK loaded for environment:', config.environment);
setSquareConfig(config); setSquareConfig(config);
} catch (error) { } catch (error) {
console.error('Failed to load Square config:', error); console.error('Failed to load Square config:', error);
@@ -53,13 +92,42 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
} }
try { try {
// Determine environment - default to production if not explicitly set to sandbox
const environment = squareConfig.environment?.toLowerCase() === 'sandbox' ? 'sandbox' : 'production';
console.log('Initializing Square with environment:', environment);
console.log('Application ID:', squareConfig.application_id);
console.log('Location ID:', squareConfig.location_id);
const paymentsInstance = window.Square.payments( const paymentsInstance = window.Square.payments(
squareConfig.application_id, squareConfig.application_id,
squareConfig.location_id squareConfig.location_id,
{
environment: environment
}
); );
setPayments(paymentsInstance); setPayments(paymentsInstance);
const cardInstance = await paymentsInstance.card(); // Initialize card without postal code (we collect it separately in billing form)
const cardInstance = await paymentsInstance.card({
style: {
'.input-container': {
borderColor: '#E0E0E0',
borderRadius: '4px'
},
'.input-container.is-focus': {
borderColor: '#4CAF50'
},
'.message-text': {
color: '#999'
},
'.message-icon': {
color: '#999'
},
'input': {
fontSize: '14px'
}
}
});
await cardInstance.attach('#card-container'); await cardInstance.attach('#card-container');
setCard(cardInstance); setCard(cardInstance);
setIsLoading(false); setIsLoading(false);
@@ -76,14 +144,33 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
return; return;
} }
// Validate billing details
if (!cardholderName.trim()) {
onPaymentError('Please enter cardholder name');
return;
}
if (!addressLine1.trim()) {
onPaymentError('Please enter address line 1');
return;
}
if (!city.trim()) {
onPaymentError('Please enter city');
return;
}
if (!postalCode.trim()) {
onPaymentError('Please enter postal code');
return;
}
setIsLoading(true); setIsLoading(true);
setIsProcessing(true);
try { try {
// Tokenize the payment method // Tokenize the payment method with billing details
const result = await card.tokenize(); const result = await card.tokenize();
if (result.status === 'OK') { if (result.status === 'OK') {
// Send the token to your backend // Send the token to your backend with billing details
const response = await fetch('/api/v1/payments/square/process', { const response = await fetch('/api/v1/payments/square/process', {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -94,7 +181,15 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
source_id: result.token, source_id: result.token,
amount: amount, amount: amount,
tier_id: tierId, tier_id: tierId,
note: `Membership payment - £${amount.toFixed(2)}` note: `Membership payment - £${amount.toFixed(2)}`,
billing_details: {
cardholder_name: cardholderName,
address_line_1: addressLine1,
address_line_2: addressLine2 || undefined,
city: city,
postal_code: postalCode,
country: 'GB'
}
}) })
}); });
@@ -124,33 +219,149 @@ const SquarePayment: React.FC<SquarePaymentProps> = ({
onPaymentError(error.message || 'Payment processing failed'); onPaymentError(error.message || 'Payment processing failed');
} finally { } finally {
setIsLoading(false); setIsLoading(false);
setIsProcessing(false);
} }
}; };
return ( return (
<div style={{ maxWidth: '400px', margin: '0 auto' }}> <div style={{ maxWidth: '500px', margin: '0 auto' }}>
<div style={{ marginBottom: '20px' }}> <div style={{ marginBottom: '24px' }}>
<h4 style={{ marginBottom: '10px' }}>Card Payment</h4> <h4 style={{ marginBottom: '10px' }}>Card Payment</h4>
<p style={{ fontSize: '14px', color: '#666' }}> <p style={{ fontSize: '14px', color: '#666' }}>
Amount: <strong>£{amount.toFixed(2)}</strong> Amount: <strong>£{amount.toFixed(2)}</strong>
</p> </p>
</div> </div>
{/* Cardholder Name */}
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Cardholder Name *
</label>
<input
type="text"
value={cardholderName}
onChange={(e) => setCardholderName(e.target.value)}
placeholder="Name as it appears on card"
style={{
width: '100%',
padding: '10px 12px',
fontSize: '14px',
border: '1px solid #E0E0E0',
borderRadius: '4px',
boxSizing: 'border-box'
}}
disabled={isLoading || !card}
/>
</div>
{/* Address Line 1 */}
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Address Line 1 *
</label>
<input
type="text"
value={addressLine1}
onChange={(e) => setAddressLine1(e.target.value)}
placeholder="Street address"
style={{
width: '100%',
padding: '10px 12px',
fontSize: '14px',
border: '1px solid #E0E0E0',
borderRadius: '4px',
boxSizing: 'border-box'
}}
disabled={isLoading || !card}
/>
</div>
{/* Address Line 2 */}
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Address Line 2
</label>
<input
type="text"
value={addressLine2}
onChange={(e) => setAddressLine2(e.target.value)}
placeholder="Apartment, suite, etc. (optional)"
style={{
width: '100%',
padding: '10px 12px',
fontSize: '14px',
border: '1px solid #E0E0E0',
borderRadius: '4px',
boxSizing: 'border-box'
}}
disabled={isLoading || !card}
/>
</div>
{/* City and Postal Code */}
<div style={{ display: 'flex', gap: '12px', marginBottom: '16px' }}>
<div style={{ flex: '1' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Town/City *
</label>
<input
type="text"
value={city}
onChange={(e) => setCity(e.target.value)}
placeholder="City"
style={{
width: '100%',
padding: '10px 12px',
fontSize: '14px',
border: '1px solid #E0E0E0',
borderRadius: '4px',
boxSizing: 'border-box'
}}
disabled={isLoading || !card}
/>
</div>
<div style={{ flex: '1' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Postcode *
</label>
<input
type="text"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value.toUpperCase())}
placeholder="SW1A 1AA"
style={{
width: '100%',
padding: '10px 12px',
fontSize: '14px',
border: '1px solid #E0E0E0',
borderRadius: '4px',
boxSizing: 'border-box'
}}
disabled={isLoading || !card}
/>
</div>
</div>
{/* Card Details */}
<div style={{ marginBottom: '16px' }}>
<label style={{ display: 'block', marginBottom: '6px', fontSize: '14px', fontWeight: '500' }}>
Card Details *
</label>
<div <div
id="card-container" id="card-container"
style={{ style={{
minHeight: '200px', minHeight: '120px'
marginBottom: '20px'
}} }}
/> />
</div>
<button <button
className="btn btn-primary" className="btn btn-primary"
onClick={handlePayment} onClick={handlePayment}
disabled={isLoading || !card} disabled={isLoading || !card || isProcessing}
style={{ width: '100%' }} style={{ width: '100%', padding: '12px' }}
> >
{isLoading ? 'Processing...' : `Pay £${amount.toFixed(2)}`} {isProcessing ? 'Processing...' : `Pay £${amount.toFixed(2)}`}
</button> </button>
<div style={{ marginTop: '16px', fontSize: '12px', color: '#666', textAlign: 'center' }}> <div style={{ marginTop: '16px', fontSize: '12px', color: '#666', textAlign: 'center' }}>

View File

@@ -26,6 +26,19 @@ const Dashboard: React.FC = () => {
const [eventRSVPs, setEventRSVPs] = useState<EventRSVP[]>([]); const [eventRSVPs, setEventRSVPs] = useState<EventRSVP[]>([]);
const [eventRSVPCounts, setEventRSVPCounts] = useState<{[eventId: number]: {attending: number, maybe: number, not_attending: number}}>({}); const [eventRSVPCounts, setEventRSVPCounts] = useState<{[eventId: number]: {attending: number, maybe: number, not_attending: number}}>({});
const [rsvpLoading, setRsvpLoading] = useState<{[eventId: number]: boolean}>({}); const [rsvpLoading, setRsvpLoading] = useState<{[eventId: number]: boolean}>({});
const [showEventModal, setShowEventModal] = useState(false);
const [editingEvent, setEditingEvent] = useState<Event | null>(null);
const [eventFormData, setEventFormData] = useState({
title: '',
description: '',
event_date: '',
event_time: '',
location: '',
max_attendees: ''
});
const [showRSVPModal, setShowRSVPModal] = useState(false);
const [selectedEventForRSVP, setSelectedEventForRSVP] = useState<Event | null>(null);
const [eventRSVPList, setEventRSVPList] = useState<EventRSVP[]>([]);
useEffect(() => { useEffect(() => {
if (!authService.isAuthenticated()) { if (!authService.isAuthenticated()) {
@@ -229,6 +242,13 @@ const Dashboard: React.FC = () => {
} }
}; };
const handleFormChange = (field: string, value: string) => {
setEditFormData(prev => ({
...prev,
[field]: value
}));
};
const handleSaveUser = async () => { const handleSaveUser = async () => {
if (!selectedUser) return; if (!selectedUser) return;
@@ -317,6 +337,100 @@ const Dashboard: React.FC = () => {
} }
}; };
const handleCreateEvent = () => {
setEditingEvent(null);
setEventFormData({
title: '',
description: '',
event_date: '',
event_time: '',
location: '',
max_attendees: ''
});
setShowEventModal(true);
};
const handleEditEvent = (event: Event) => {
setEditingEvent(event);
// Convert event_date to YYYY-MM-DD format for date input
const dateObj = new Date(event.event_date);
const formattedDate = dateObj.toISOString().split('T')[0];
setEventFormData({
title: event.title,
description: event.description || '',
event_date: formattedDate,
event_time: event.event_time || '',
location: event.location || '',
max_attendees: event.max_attendees?.toString() || ''
});
setShowEventModal(true);
};
const handleEventFormChange = (field: string, value: string) => {
setEventFormData(prev => ({
...prev,
[field]: value
}));
};
const handleSaveEvent = async () => {
try {
const eventData = {
title: eventFormData.title,
description: eventFormData.description || undefined,
event_date: eventFormData.event_date,
event_time: eventFormData.event_time || undefined,
location: eventFormData.location || undefined,
max_attendees: eventFormData.max_attendees ? parseInt(eventFormData.max_attendees) : undefined
};
if (editingEvent) {
// Update existing event
await eventService.updateEvent(editingEvent.id, eventData);
} else {
// Create new event
await eventService.createEvent(eventData);
}
// Reload events
const eventsData = await eventService.getAllEvents();
setAllEvents(eventsData);
await loadEventRSVPCounts(eventsData);
// Close modal
setShowEventModal(false);
setEditingEvent(null);
} catch (error) {
console.error('Failed to save event:', error);
alert('Failed to save event. Please try again.');
}
};
const handleCloseEventModal = () => {
setShowEventModal(false);
setEditingEvent(null);
};
const handleViewRSVPs = async (event: Event) => {
setSelectedEventForRSVP(event);
try {
const rsvps = await eventService.getEventRSVPs(event.id);
setEventRSVPList(rsvps);
setShowRSVPModal(true);
} catch (error) {
console.error('Failed to load RSVPs:', error);
alert('Failed to load RSVPs. Please try again.');
}
};
const handleCloseRSVPModal = () => {
setShowRSVPModal(false);
setSelectedEventForRSVP(null);
setEventRSVPList([]);
};
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-GB', { return new Date(dateString).toLocaleDateString('en-GB', {
day: 'numeric', day: 'numeric',
@@ -352,32 +466,18 @@ const Dashboard: React.FC = () => {
<> <>
<nav className="navbar"> <nav className="navbar">
<h1>SASA Membership Portal</h1> <h1>SASA Membership Portal</h1>
<ProfileMenu userName={`${user?.first_name} ${user?.last_name}`} userRole={user?.role || ''} /> <ProfileMenu
userName={`${user?.first_name} ${user?.last_name}`}
userRole={user?.role || ''}
user={user}
onEditProfile={handleProfileEdit}
/>
</nav> </nav>
<div className="container"> <div className="container">
<h2 style={{ marginTop: '20px', marginBottom: '20px' }}>Welcome, {user?.first_name}!</h2> <h2 style={{ marginTop: '20px', marginBottom: '20px' }}>Welcome, {user?.first_name}!</h2>
<div className="dashboard-grid"> <div className="dashboard-grid">
{/* Profile Card */}
<div className="card">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
<h3>Your Profile</h3>
<button
className="btn btn-secondary"
onClick={handleProfileEdit}
style={{ fontSize: '14px', padding: '6px 12px' }}
>
Edit Profile
</button>
</div>
<p><strong>Name:</strong> {user?.first_name} {user?.last_name}</p>
<p><strong>Email:</strong> {user?.email}</p>
{user?.phone && <p><strong>Phone:</strong> {user.phone}</p>}
{user?.address && <p><strong>Address:</strong> {user.address}</p>}
<p><strong>Registered since:</strong> {user && formatDate(user.created_at)}</p>
</div>
{/* Membership Card */} {/* Membership Card */}
{activeMembership ? ( {activeMembership ? (
<div className="card"> <div className="card">
@@ -408,6 +508,67 @@ const Dashboard: React.FC = () => {
</button> </button>
</div> </div>
)} )}
{/* Upcoming Events */}
<div className="card">
<h3 style={{ marginBottom: '16px' }}>Upcoming Events</h3>
{upcomingEvents.length > 0 ? (
<div className="events-container">
{upcomingEvents.map(event => (
<div key={event.id} className="event-card">
<div className="event-header">
<div className="event-info">
<h4 className="event-title">{event.title}</h4>
<p className="event-datetime">
{formatDate(event.event_date)} at {event.event_time}
</p>
{event.location && (
<p className="event-location">
📍 {event.location}
</p>
)}
</div>
<div className="event-rsvp-buttons">
<button
className={`rsvp-btn rsvp-btn-attending ${event.rsvp_status === 'attending' ? 'active' : ''}`}
onClick={() => handleRSVP(event.id, 'attending')}
disabled={rsvpLoading[event.id]}
>
{rsvpLoading[event.id] ? '...' : 'Attending'}
</button>
<button
className={`rsvp-btn rsvp-btn-maybe ${event.rsvp_status === 'maybe' ? 'active' : ''}`}
onClick={() => handleRSVP(event.id, 'maybe')}
disabled={rsvpLoading[event.id]}
>
{rsvpLoading[event.id] ? '...' : 'Maybe'}
</button>
<button
className={`rsvp-btn rsvp-btn-not-attending ${event.rsvp_status === 'not_attending' ? 'active' : ''}`}
onClick={() => handleRSVP(event.id, 'not_attending')}
disabled={rsvpLoading[event.id]}
>
{rsvpLoading[event.id] ? '...' : 'Not Attending'}
</button>
</div>
</div>
{event.description && (
<p className="event-description">
{event.description}
</p>
)}
{event.rsvp_status && (
<div className={`event-rsvp-status ${event.rsvp_status}`}>
<strong>Your RSVP:</strong> <span style={{ textTransform: 'capitalize' }}>{event.rsvp_status.replace('_', ' ')}</span>
</div>
)}
</div>
))}
</div>
) : (
<p style={{ color: '#666' }}>No upcoming events at this time.</p>
)}
</div>
</div> </div>
{/* Payment History */} {/* Payment History */}
@@ -445,125 +606,6 @@ const Dashboard: React.FC = () => {
)} )}
</div> </div>
{/* Upcoming Events */}
<div className="card" style={{ marginTop: '20px' }}>
<h3 style={{ marginBottom: '16px' }}>Upcoming Events</h3>
{upcomingEvents.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
{upcomingEvents.map(event => (
<div key={event.id} style={{
border: '1px solid #ddd',
borderRadius: '8px',
padding: '16px',
backgroundColor: '#f9f9f9'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>
<div>
<h4 style={{ margin: '0 0 4px 0', color: '#0066cc' }}>{event.title}</h4>
<p style={{ margin: '0', fontSize: '14px', color: '#666' }}>
{formatDate(event.event_date)} at {event.event_time}
</p>
{event.location && (
<p style={{ margin: '4px 0 0 0', fontSize: '14px', color: '#666' }}>
📍 {event.location}
</p>
)}
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<button
className={`btn ${event.rsvp_status === 'attending' ? 'btn-success' : 'btn-outline-secondary'}`}
onClick={() => handleRSVP(event.id, 'attending')}
disabled={rsvpLoading[event.id]}
style={{
fontSize: '12px',
padding: '8px 16px',
opacity: rsvpLoading[event.id] ? 0.6 : event.rsvp_status ? (event.rsvp_status === 'attending' ? 1 : 0.4) : 1,
cursor: rsvpLoading[event.id] ? 'not-allowed' : 'pointer',
fontWeight: event.rsvp_status === 'attending' ? 'bold' : 'normal',
border: event.rsvp_status === 'attending' ? '3px solid #28a745' : '2px solid #adb5bd',
backgroundColor: event.rsvp_status === 'attending' ? '#28a745' : 'transparent',
color: event.rsvp_status === 'attending' ? 'white' : '#6c757d',
transform: event.rsvp_status === 'attending' ? 'scale(1.1)' : event.rsvp_status ? 'scale(0.95)' : 'scale(1)',
boxShadow: event.rsvp_status === 'attending' ? '0 4px 8px rgba(40, 167, 69, 0.3)' : 'none',
transition: 'all 0.3s ease',
filter: event.rsvp_status && event.rsvp_status !== 'attending' ? 'grayscale(50%)' : 'none'
}}
>
{rsvpLoading[event.id] ? '...' : 'Attending'}
</button>
<button
className={`btn ${event.rsvp_status === 'maybe' ? 'btn-warning' : 'btn-outline-secondary'}`}
onClick={() => handleRSVP(event.id, 'maybe')}
disabled={rsvpLoading[event.id]}
style={{
fontSize: '12px',
padding: '8px 16px',
opacity: rsvpLoading[event.id] ? 0.6 : event.rsvp_status ? (event.rsvp_status === 'maybe' ? 1 : 0.4) : 1,
cursor: rsvpLoading[event.id] ? 'not-allowed' : 'pointer',
fontWeight: event.rsvp_status === 'maybe' ? 'bold' : 'normal',
border: event.rsvp_status === 'maybe' ? '3px solid #ffc107' : '2px solid #adb5bd',
backgroundColor: event.rsvp_status === 'maybe' ? '#ffc107' : 'transparent',
color: event.rsvp_status === 'maybe' ? '#212529' : '#6c757d',
transform: event.rsvp_status === 'maybe' ? 'scale(1.1)' : event.rsvp_status ? 'scale(0.95)' : 'scale(1)',
boxShadow: event.rsvp_status === 'maybe' ? '0 4px 8px rgba(255, 193, 7, 0.3)' : 'none',
transition: 'all 0.3s ease',
filter: event.rsvp_status && event.rsvp_status !== 'maybe' ? 'grayscale(50%)' : 'none'
}}
>
{rsvpLoading[event.id] ? '...' : 'Maybe'}
</button>
<button
className={`btn ${event.rsvp_status === 'not_attending' ? 'btn-danger' : 'btn-outline-secondary'}`}
onClick={() => handleRSVP(event.id, 'not_attending')}
disabled={rsvpLoading[event.id]}
style={{
fontSize: '12px',
padding: '8px 16px',
opacity: rsvpLoading[event.id] ? 0.6 : event.rsvp_status ? (event.rsvp_status === 'not_attending' ? 1 : 0.4) : 1,
cursor: rsvpLoading[event.id] ? 'not-allowed' : 'pointer',
fontWeight: event.rsvp_status === 'not_attending' ? 'bold' : 'normal',
border: event.rsvp_status === 'not_attending' ? '3px solid #dc3545' : '2px solid #adb5bd',
backgroundColor: event.rsvp_status === 'not_attending' ? '#dc3545' : 'transparent',
color: event.rsvp_status === 'not_attending' ? 'white' : '#6c757d',
transform: event.rsvp_status === 'not_attending' ? 'scale(1.1)' : event.rsvp_status ? 'scale(0.95)' : 'scale(1)',
boxShadow: event.rsvp_status === 'not_attending' ? '0 4px 8px rgba(220, 53, 69, 0.3)' : 'none',
transition: 'all 0.3s ease',
filter: event.rsvp_status && event.rsvp_status !== 'not_attending' ? 'grayscale(50%)' : 'none'
}}
>
{rsvpLoading[event.id] ? '...' : 'Not Attending'}
</button>
</div>
</div>
{event.description && (
<p style={{ margin: '0', fontSize: '14px', lineHeight: '1.4' }}>
{event.description}
</p>
)}
{event.rsvp_status && (
<div style={{
marginTop: '12px',
padding: '8px 12px',
backgroundColor: event.rsvp_status === 'attending' ? '#d4edda' :
event.rsvp_status === 'maybe' ? '#fff3cd' : '#f8d7da',
border: `1px solid ${event.rsvp_status === 'attending' ? '#c3e6cb' :
event.rsvp_status === 'maybe' ? '#ffeaa7' : '#f5c6cb'}`,
borderRadius: '4px',
fontSize: '12px',
color: event.rsvp_status === 'attending' ? '#155724' :
event.rsvp_status === 'maybe' ? '#856404' : '#721c24'
}}>
<strong>Your RSVP:</strong> <span style={{ textTransform: 'capitalize' }}>{event.rsvp_status.replace('_', ' ')}</span>
</div>
)}
</div>
))}
</div>
) : (
<p style={{ color: '#666' }}>No upcoming events at this time.</p>
)}
</div>
{/* Admin Section */} {/* Admin Section */}
{(user?.role === 'admin' || user?.role === 'super_admin') && ( {(user?.role === 'admin' || user?.role === 'super_admin') && (
<div className="card" style={{ marginTop: '20px' }}> <div className="card" style={{ marginTop: '20px' }}>
@@ -775,7 +817,7 @@ const Dashboard: React.FC = () => {
<div style={{ marginBottom: '16px' }}> <div style={{ marginBottom: '16px' }}>
<button <button
className="btn btn-primary" className="btn btn-primary"
onClick={() => {/* TODO: Implement create event modal */}} onClick={handleCreateEvent}
style={{ fontSize: '14px', padding: '8px 16px' }} style={{ fontSize: '14px', padding: '8px 16px' }}
> >
Create New Event Create New Event
@@ -797,7 +839,11 @@ const Dashboard: React.FC = () => {
</thead> </thead>
<tbody> <tbody>
{allEvents.map(event => ( {allEvents.map(event => (
<tr key={event.id} style={{ borderBottom: '1px solid #eee' }}> <tr
key={event.id}
style={{ borderBottom: '1px solid #eee', cursor: 'pointer' }}
onClick={() => handleViewRSVPs(event)}
>
<td style={{ padding: '12px' }}> <td style={{ padding: '12px' }}>
<div> <div>
<strong>{event.title}</strong> <strong>{event.title}</strong>
@@ -833,7 +879,10 @@ const Dashboard: React.FC = () => {
<div style={{ display: 'flex', gap: '4px' }}> <div style={{ display: 'flex', gap: '4px' }}>
<button <button
className="btn btn-secondary" className="btn btn-secondary"
onClick={() => {/* TODO: Implement edit event */}} onClick={(e) => {
e.stopPropagation();
handleEditEvent(event);
}}
style={{ fontSize: '12px', padding: '4px 8px' }} style={{ fontSize: '12px', padding: '4px 8px' }}
> >
Edit Edit
@@ -841,7 +890,10 @@ const Dashboard: React.FC = () => {
{event.status === 'draft' && ( {event.status === 'draft' && (
<button <button
className="btn btn-primary" className="btn btn-primary"
onClick={() => handlePublishEvent(event.id)} onClick={(e) => {
e.stopPropagation();
handlePublishEvent(event.id);
}}
style={{ fontSize: '12px', padding: '4px 8px' }} style={{ fontSize: '12px', padding: '4px 8px' }}
> >
Publish Publish
@@ -850,7 +902,10 @@ const Dashboard: React.FC = () => {
{event.status === 'published' && ( {event.status === 'published' && (
<button <button
className="btn btn-secondary" className="btn btn-secondary"
onClick={() => handleCancelEvent(event.id)} onClick={(e) => {
e.stopPropagation();
handleCancelEvent(event.id);
}}
style={{ fontSize: '12px', padding: '4px 8px' }} style={{ fontSize: '12px', padding: '4px 8px' }}
> >
Cancel Cancel
@@ -1114,6 +1169,201 @@ const Dashboard: React.FC = () => {
</div> </div>
</div> </div>
)} )}
{/* Event Create/Edit Modal */}
{showEventModal && (
<div className="modal-overlay">
<div className="modal-content" style={{ maxWidth: '600px' }}>
<h3>{editingEvent ? 'Edit Event' : 'Create New Event'}</h3>
<div className="modal-form-group">
<label>Event Title *</label>
<input
type="text"
value={eventFormData.title}
onChange={(e) => handleEventFormChange('title', e.target.value)}
required
placeholder="Annual General Meeting"
/>
</div>
<div className="modal-form-group">
<label>Description</label>
<textarea
value={eventFormData.description}
onChange={(e) => handleEventFormChange('description', e.target.value)}
rows={4}
style={{
width: '100%',
padding: '8px',
border: '1px solid #ddd',
borderRadius: '4px',
fontSize: '16px',
resize: 'vertical'
}}
placeholder="Event details and agenda..."
/>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
<div className="modal-form-group">
<label>Event Date *</label>
<input
type="date"
value={eventFormData.event_date}
onChange={(e) => handleEventFormChange('event_date', e.target.value)}
required
/>
</div>
<div className="modal-form-group">
<label>Event Time</label>
<input
type="time"
value={eventFormData.event_time}
onChange={(e) => handleEventFormChange('event_time', e.target.value)}
/>
</div>
</div>
<div className="modal-form-group">
<label>Location</label>
<input
type="text"
value={eventFormData.location}
onChange={(e) => handleEventFormChange('location', e.target.value)}
placeholder="Swansea Airport Conference Room"
/>
</div>
<div className="modal-form-group">
<label>Max Attendees (optional)</label>
<input
type="number"
value={eventFormData.max_attendees}
onChange={(e) => handleEventFormChange('max_attendees', e.target.value)}
min="1"
placeholder="Leave blank for unlimited"
/>
</div>
<div className="modal-buttons">
<button
type="button"
onClick={handleCloseEventModal}
className="modal-btn-cancel"
>
Cancel
</button>
<button
type="button"
onClick={handleSaveEvent}
className="modal-btn-primary"
disabled={!eventFormData.title || !eventFormData.event_date}
>
{editingEvent ? 'Update Event' : 'Create Event'}
</button>
</div>
</div>
</div>
)}
{/* RSVP List Modal */}
{showRSVPModal && selectedEventForRSVP && (
<div className="modal-overlay" onClick={handleCloseRSVPModal}>
<div
className="modal-content"
style={{ maxWidth: '700px', maxHeight: '80vh', overflow: 'auto' }}
onClick={(e) => e.stopPropagation()}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
<h3 style={{ margin: 0 }}>RSVPs for {selectedEventForRSVP.title}</h3>
<button
onClick={handleCloseRSVPModal}
style={{
background: 'none',
border: 'none',
fontSize: '24px',
cursor: 'pointer',
color: '#666'
}}
>
×
</button>
</div>
<div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
<p style={{ margin: '4px 0', fontSize: '14px' }}><strong>Date:</strong> {formatDate(selectedEventForRSVP.event_date)}</p>
{selectedEventForRSVP.event_time && (
<p style={{ margin: '4px 0', fontSize: '14px' }}><strong>Time:</strong> {selectedEventForRSVP.event_time}</p>
)}
{selectedEventForRSVP.location && (
<p style={{ margin: '4px 0', fontSize: '14px' }}><strong>Location:</strong> {selectedEventForRSVP.location}</p>
)}
</div>
{eventRSVPList.length > 0 ? (
<>
<div style={{ marginBottom: '16px', display: 'flex', gap: '16px', fontSize: '14px' }}>
<div>
<strong>Attending:</strong> {eventRSVPList.filter(r => r.status === 'attending').length}
</div>
<div>
<strong>Maybe:</strong> {eventRSVPList.filter(r => r.status === 'maybe').length}
</div>
<div>
<strong>Not Attending:</strong> {eventRSVPList.filter(r => r.status === 'not_attending').length}
</div>
</div>
<div className="table-container">
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ borderBottom: '2px solid #ddd' }}>
<th style={{ padding: '12px', textAlign: 'left' }}>Name</th>
<th style={{ padding: '12px', textAlign: 'left' }}>Email</th>
<th style={{ padding: '12px', textAlign: 'left' }}>RSVP</th>
<th style={{ padding: '12px', textAlign: 'left' }}>Date</th>
</tr>
</thead>
<tbody>
{eventRSVPList.map(rsvp => {
const rsvpUser = allUsers.find(u => u.id === rsvp.user_id);
return (
<tr key={rsvp.id} style={{ borderBottom: '1px solid #eee' }}>
<td style={{ padding: '12px' }}>
{rsvpUser ? `${rsvpUser.first_name} ${rsvpUser.last_name}` : `User #${rsvp.user_id}`}
</td>
<td style={{ padding: '12px' }}>
{rsvpUser?.email || 'N/A'}
</td>
<td style={{ padding: '12px' }}>
<span className={`status-badge ${
rsvp.status === 'attending' ? 'status-active' :
rsvp.status === 'maybe' ? 'status-pending' :
'status-expired'
}`}>
{rsvp.status === 'attending' ? 'ATTENDING' :
rsvp.status === 'maybe' ? 'MAYBE' :
'NOT ATTENDING'}
</span>
</td>
<td style={{ padding: '12px', fontSize: '12px', color: '#666' }}>
{rsvp.created_at ? formatDate(rsvp.created_at) : 'N/A'}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
) : (
<p style={{ textAlign: 'center', color: '#666', padding: '20px' }}>No RSVPs yet for this event.</p>
)}
</div>
</div>
)}
</> </>
); );
}; };