186 lines
5.3 KiB
JavaScript
Raw Normal View History

Integrate Stripe Checkout and add comprehensive UI enhancements ## Stripe Payment Integration - Add Express.js backend server with Stripe Checkout Sessions - Create SQLite database for order tracking - Implement Stripe webhook handlers for payment events - Integrate with Wren Climate API for carbon offset fulfillment - Add CheckoutSuccess and CheckoutCancel pages - Create checkout API client for frontend - Update OffsetOrder component to redirect to Stripe Checkout - Add processing fee calculation (3% of base amount) - Implement order status tracking (pending → paid → fulfilled) Backend (server/): - Express server with CORS and middleware - SQLite database with Order schema - Stripe configuration and client - Order CRUD operations model - Checkout session creation endpoint - Webhook handler for payment confirmation - Wren API client for offset fulfillment Frontend: - CheckoutSuccess page with order details display - CheckoutCancel page with retry encouragement - Updated OffsetOrder to use Stripe checkout flow - Added checkout routes to App.tsx - TypeScript interfaces for checkout flow ## Visual & UX Enhancements - Add CertificationBadge component for project verification status - Create PortfolioDonutChart for visual portfolio allocation - Implement RadialProgress for percentage displays - Add reusable form components (FormInput, FormTextarea, FormSelect, FormFieldWrapper) - Refactor OffsetOrder with improved layout and animations - Add offset percentage slider with visual feedback - Enhance MobileOffsetOrder with better responsive design - Improve TripCalculator with cleaner UI structure - Update CurrencySelect with better styling - Add portfolio distribution visualization - Enhance project cards with hover effects and animations - Improve color palette and gradient usage throughout ## Configuration - Add VITE_API_BASE_URL environment variable - Create backend .env.example template - Update frontend .env.example with API URL - Add Stripe documentation references 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 21:45:14 +01:00
import { db } from '../config/database.js';
import { randomUUID } from 'crypto';
export class Order {
/**
* Create a new order in the database
* @param {Object} orderData - Order data
* @param {string} orderData.stripeSessionId - Stripe checkout session ID
* @param {string} orderData.customerEmail - Customer email
* @param {number} orderData.tons - Carbon offset tons
* @param {number} orderData.portfolioId - Portfolio ID
* @param {number} orderData.baseAmount - Base amount in cents
* @param {number} orderData.processingFee - Processing fee in cents
* @param {number} orderData.totalAmount - Total amount in cents
* @param {string} orderData.currency - Currency code (default: USD)
* @returns {Object} Created order
*/
static create({
stripeSessionId,
customerEmail,
tons,
portfolioId,
baseAmount,
processingFee,
totalAmount,
currency = 'USD'
}) {
const id = randomUUID();
const now = new Date().toISOString();
const stmt = db.prepare(`
INSERT INTO orders (
id, stripe_session_id, customer_email, tons, portfolio_id,
base_amount, processing_fee, total_amount, currency,
status, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)
`);
stmt.run(
id,
stripeSessionId,
customerEmail,
tons,
portfolioId,
baseAmount,
processingFee,
totalAmount,
currency,
now,
now
);
return this.findById(id);
}
/**
* Find order by ID
* @param {string} id - Order ID
* @returns {Object|null} Order or null
*/
static findById(id) {
const stmt = db.prepare('SELECT * FROM orders WHERE id = ?');
return stmt.get(id);
}
/**
* Find order by Stripe session ID
* @param {string} sessionId - Stripe session ID
* @returns {Object|null} Order or null
*/
static findBySessionId(sessionId) {
const stmt = db.prepare('SELECT * FROM orders WHERE stripe_session_id = ?');
return stmt.get(sessionId);
}
/**
* Update order status
* @param {string} id - Order ID
* @param {string} status - New status (pending, paid, fulfilled, failed)
* @returns {Object} Updated order
*/
static updateStatus(id, status) {
const now = new Date().toISOString();
const stmt = db.prepare('UPDATE orders SET status = ?, updated_at = ? WHERE id = ?');
stmt.run(status, now, id);
return this.findById(id);
}
/**
* Update order with payment intent ID
* @param {string} id - Order ID
* @param {string} paymentIntentId - Stripe payment intent ID
* @returns {Object} Updated order
*/
static updatePaymentIntent(id, paymentIntentId) {
const now = new Date().toISOString();
const stmt = db.prepare('UPDATE orders SET stripe_payment_intent = ?, updated_at = ? WHERE id = ?');
stmt.run(paymentIntentId, now, id);
return this.findById(id);
}
/**
* Update order with Wren order ID after fulfillment
* @param {string} id - Order ID
* @param {string} wrenOrderId - Wren API order ID
* @param {string} status - Order status (fulfilled or failed)
* @returns {Object} Updated order
*/
static updateWrenOrder(id, wrenOrderId, status = 'fulfilled') {
const now = new Date().toISOString();
const stmt = db.prepare('UPDATE orders SET wren_order_id = ?, status = ?, updated_at = ? WHERE id = ?');
stmt.run(wrenOrderId, status, now, id);
return this.findById(id);
}
Implement comprehensive Stripe security fixes and production deployment CRITICAL SECURITY FIXES: - Add webhook secret validation to prevent signature bypass - Implement idempotency protection across all webhook handlers - Add atomic database updates to prevent race conditions - Improve CORS security with origin validation and logging - Remove .env from git tracking to protect secrets STRIPE INTEGRATION: - Add support for checkout.session.expired webhook event - Add Stripe publishable key to environment configuration - Fix webhook handlers with proper idempotency checks - Update Order model with atomic updatePaymentAndStatus method - Add comprehensive logging for webhook processing DEPLOYMENT ARCHITECTURE: - Split into two Docker images (frontend-latest, backend-latest) - Update CI/CD to build separate frontend and backend images - Configure backend on port 3801 (internal 3001) - Add production-ready docker-compose.yml - Remove redundant docker-compose.portainer.yml - Update nginx configuration for both frontend and backend DOCUMENTATION: - Add PRODUCTION-SETUP.md with complete deployment guide - Add docs/stripe-security-fixes.md with security audit details - Add docs/stripe-checkout-sessions.md with integration docs - Add docs/stripe-webhooks.md with webhook configuration - Update .env.example with all required variables including Stripe publishable key CONFIGURATION: - Consolidate to single .env.example template - Update .gitignore to protect all .env variants - Add server/Dockerfile for backend container - Update DEPLOYMENT.md with new architecture 🔒 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 12:18:57 +01:00
/**
* Atomically update payment intent and status
* This prevents race conditions by updating both fields in a single transaction
* @param {string} id - Order ID
* @param {string} paymentIntentId - Stripe payment intent ID
* @param {string} status - New status
* @returns {Object} Updated order
*/
static updatePaymentAndStatus(id, paymentIntentId, status) {
const now = new Date().toISOString();
const stmt = db.prepare(`
UPDATE orders
SET stripe_payment_intent = ?, status = ?, updated_at = ?
WHERE id = ?
`);
stmt.run(paymentIntentId, status, now, id);
return this.findById(id);
}
Integrate Stripe Checkout and add comprehensive UI enhancements ## Stripe Payment Integration - Add Express.js backend server with Stripe Checkout Sessions - Create SQLite database for order tracking - Implement Stripe webhook handlers for payment events - Integrate with Wren Climate API for carbon offset fulfillment - Add CheckoutSuccess and CheckoutCancel pages - Create checkout API client for frontend - Update OffsetOrder component to redirect to Stripe Checkout - Add processing fee calculation (3% of base amount) - Implement order status tracking (pending → paid → fulfilled) Backend (server/): - Express server with CORS and middleware - SQLite database with Order schema - Stripe configuration and client - Order CRUD operations model - Checkout session creation endpoint - Webhook handler for payment confirmation - Wren API client for offset fulfillment Frontend: - CheckoutSuccess page with order details display - CheckoutCancel page with retry encouragement - Updated OffsetOrder to use Stripe checkout flow - Added checkout routes to App.tsx - TypeScript interfaces for checkout flow ## Visual & UX Enhancements - Add CertificationBadge component for project verification status - Create PortfolioDonutChart for visual portfolio allocation - Implement RadialProgress for percentage displays - Add reusable form components (FormInput, FormTextarea, FormSelect, FormFieldWrapper) - Refactor OffsetOrder with improved layout and animations - Add offset percentage slider with visual feedback - Enhance MobileOffsetOrder with better responsive design - Improve TripCalculator with cleaner UI structure - Update CurrencySelect with better styling - Add portfolio distribution visualization - Enhance project cards with hover effects and animations - Improve color palette and gradient usage throughout ## Configuration - Add VITE_API_BASE_URL environment variable - Create backend .env.example template - Update frontend .env.example with API URL - Add Stripe documentation references 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 21:45:14 +01:00
/**
* Get all orders (with optional filters)
* @param {Object} filters - Filter options
* @param {string} filters.status - Filter by status
* @param {number} filters.limit - Limit results
* @param {number} filters.offset - Offset for pagination
* @returns {Array} Array of orders
*/
static findAll({ status, limit = 100, offset = 0 } = {}) {
let query = 'SELECT * FROM orders';
const params = [];
if (status) {
query += ' WHERE status = ?';
params.push(status);
}
query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
params.push(limit, offset);
const stmt = db.prepare(query);
return stmt.all(...params);
}
/**
* Get order count by status
* @returns {Object} Count by status
*/
static getStatusCounts() {
const stmt = db.prepare('SELECT status, COUNT(*) as count FROM orders GROUP BY status');
const rows = stmt.all();
return rows.reduce((acc, row) => {
acc[row.status] = row.count;
return acc;
}, {});
}
/**
* Delete order (for testing purposes only)
* @param {string} id - Order ID
* @returns {boolean} Success
*/
static delete(id) {
const stmt = db.prepare('DELETE FROM orders WHERE id = ?');
const result = stmt.run(id);
return result.changes > 0;
}
}
export default Order;