Square enhancements

This commit is contained in:
James Pattinson
2025-11-13 17:41:28 +00:00
parent dac8b43915
commit b8f2d12011
6 changed files with 410 additions and 35 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

@@ -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

@@ -36,6 +36,9 @@ const Dashboard: React.FC = () => {
location: '', location: '',
max_attendees: '' 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()) {
@@ -410,6 +413,24 @@ const Dashboard: React.FC = () => {
setEditingEvent(null); 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',
@@ -818,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>
@@ -854,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={() => handleEditEvent(event)} onClick={(e) => {
e.stopPropagation();
handleEditEvent(event);
}}
style={{ fontSize: '12px', padding: '4px 8px' }} style={{ fontSize: '12px', padding: '4px 8px' }}
> >
Edit Edit
@@ -862,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
@@ -871,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
@@ -1233,6 +1267,103 @@ const Dashboard: React.FC = () => {
</div> </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>
)}
</> </>
); );
}; };