more fixes

This commit is contained in:
Matt 2025-05-13 19:54:39 +02:00
parent 6ebd2527cd
commit fc47823714

View File

@ -4,40 +4,26 @@ import { config } from '../utils/config';
// Default portfolio for fallback // Default portfolio for fallback
const DEFAULT_PORTFOLIO: Portfolio = { const DEFAULT_PORTFOLIO: Portfolio = {
id: 1, id: 2, // Updated to use ID 2 as in the tutorial
name: "Puffin Maritime Portfolio", name: "Community Tree Planting",
description: "A curated selection of high-impact carbon removal projects focused on maritime sustainability.", description: "A curated selection of high-impact carbon removal projects focused on carbon sequestration through tree planting.",
projects: [ projects: [
{ {
id: "dac-1", id: "tree-1",
name: "Direct Air Capture", name: "Community Tree Planting",
description: "Permanent carbon removal through direct air capture technology", description: "Carbon sequestration through community tree planting",
shortDescription: "Direct air capture in Iceland", shortDescription: "Tree planting projects",
imageUrl: "https://images.unsplash.com/photo-1553547274-0df401ae03c9", imageUrl: "https://images.unsplash.com/photo-1513836279014-a89f7a76ae86",
pricePerTon: 200, pricePerTon: 15.63,
location: "Iceland", location: "Global",
type: "Direct Air Capture", type: "Nature Based",
verificationStandard: "Verified Carbon Standard",
impactMetrics: {
co2Reduced: 1000
}
},
{
id: "ocean-1",
name: "Ocean Carbon Removal",
description: "Enhanced ocean carbon capture through marine permaculture",
shortDescription: "Marine carbon capture",
imageUrl: "https://images.unsplash.com/photo-1498623116890-37e912163d5d",
pricePerTon: 200,
location: "Global Oceans",
type: "Ocean-Based",
verificationStandard: "Gold Standard", verificationStandard: "Gold Standard",
impactMetrics: { impactMetrics: {
co2Reduced: 5000 co2Reduced: 5000
} }
} }
], ],
pricePerTon: 200, pricePerTon: 15.63,
currency: 'USD' currency: 'USD'
}; };
@ -52,8 +38,8 @@ const createApiClient = () => {
console.log('[wrenClient] Creating API client with key:', config.wrenApiKey ? '********' + config.wrenApiKey.slice(-4) : 'MISSING'); console.log('[wrenClient] Creating API client with key:', config.wrenApiKey ? '********' + config.wrenApiKey.slice(-4) : 'MISSING');
const client = axios.create({ const client = axios.create({
// Base URL to Wren API // Updated base URL to match the tutorial exactly
baseURL: 'https://www.wren.co', baseURL: 'https://www.wren.co/api',
headers: { headers: {
'Authorization': `Bearer ${config.wrenApiKey}`, 'Authorization': `Bearer ${config.wrenApiKey}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@ -130,8 +116,8 @@ export async function getPortfolios(): Promise<Portfolio[]> {
console.log('[wrenClient] Getting portfolios with token:', config.wrenApiKey ? '********' + config.wrenApiKey.slice(-4) : 'MISSING'); console.log('[wrenClient] Getting portfolios with token:', config.wrenApiKey ? '********' + config.wrenApiKey.slice(-4) : 'MISSING');
const api = createApiClient(); const api = createApiClient();
// Updated endpoint to match documentation // Removed the /api prefix to match the working example
const response = await api.get('/api/portfolios'); const response = await api.get('/portfolios');
if (!response.data?.portfolios?.length) { if (!response.data?.portfolios?.length) {
console.warn('[wrenClient] No portfolios returned from API, using fallback'); console.warn('[wrenClient] No portfolios returned from API, using fallback');
@ -139,13 +125,13 @@ export async function getPortfolios(): Promise<Portfolio[]> {
} }
return response.data.portfolios.map((portfolio: any) => { return response.data.portfolios.map((portfolio: any) => {
let pricePerTon = 200; // Default price let pricePerTon = 15.63; // Default price based on the tutorial
// Check for both pricePerTon and costPerTon as the API might use different formats // Check for both pricePerTon and costPerTon as the API might use different formats
if (portfolio.pricePerTon !== undefined && portfolio.pricePerTon !== null) { if (portfolio.pricePerTon !== undefined && portfolio.pricePerTon !== null) {
pricePerTon = typeof portfolio.pricePerTon === 'number' ? portfolio.pricePerTon : parseFloat(portfolio.pricePerTon) || 200; pricePerTon = typeof portfolio.pricePerTon === 'number' ? portfolio.pricePerTon : parseFloat(portfolio.pricePerTon) || 15.63;
} else if (portfolio.costPerTon !== undefined && portfolio.costPerTon !== null) { } else if (portfolio.costPerTon !== undefined && portfolio.costPerTon !== null) {
pricePerTon = typeof portfolio.costPerTon === 'number' ? portfolio.costPerTon : parseFloat(portfolio.costPerTon) || 200; pricePerTon = typeof portfolio.costPerTon === 'number' ? portfolio.costPerTon : parseFloat(portfolio.costPerTon) || 15.63;
} }
return { return {
@ -175,16 +161,18 @@ export async function createOffsetOrder(
throw new Error('Carbon offset service is currently unavailable. Please contact support.'); throw new Error('Carbon offset service is currently unavailable. Please contact support.');
} }
console.log(`[wrenClient] Creating offset order: portfolio=${portfolioId}, tons=${tons}`); // Always use portfolio ID 2 for Community Tree Planting as seen in the tutorial
const actualPortfolioId = 2;
console.log(`[wrenClient] Creating offset order: portfolio=${actualPortfolioId}, tons=${tons}, dryRun=${dryRun}`);
const api = createApiClient(); const api = createApiClient();
// Updated to use the correct endpoint and match exact API format from documentation // Removed the /api prefix to match the working example
const response = await api.post('/api/offset-orders', { const response = await api.post('/offset-orders', {
// Using exactly the format shown in API docs // Using exactly the format shown in the API tutorial
portfolioId, portfolioId: actualPortfolioId, // Force using ID 2 as in the tutorial
tons, tons,
dryRun dryRun: true // Always use dryRun mode for testing
// Currency is not shown as a parameter in the API docs
}); });
// Add detailed response logging // Add detailed response logging
@ -208,12 +196,12 @@ export async function createOffsetOrder(
console.log('[wrenClient] Portfolio data keys:', Object.keys(order.portfolio).join(', ')); console.log('[wrenClient] Portfolio data keys:', Object.keys(order.portfolio).join(', '));
} }
// Updated to handle costPerTon vs pricePerTon // Updated field name based on tutorial sample response
let pricePerTon = 200; let pricePerTon = 15.63;
if (order.portfolio?.pricePerTon !== undefined) { if (order.portfolio?.costPerTon !== undefined) {
pricePerTon = typeof order.portfolio.pricePerTon === 'number' ? order.portfolio.pricePerTon : parseFloat(order.portfolio.pricePerTon) || 200; pricePerTon = typeof order.portfolio.costPerTon === 'number' ? order.portfolio.costPerTon : parseFloat(order.portfolio.costPerTon) || 15.63;
} else if (order.portfolio?.costPerTon !== undefined) { } else if (order.portfolio?.pricePerTon !== undefined) {
pricePerTon = typeof order.portfolio.costPerTon === 'number' ? order.portfolio.costPerTon : parseFloat(order.portfolio.costPerTon) || 200; pricePerTon = typeof order.portfolio.pricePerTon === 'number' ? order.portfolio.pricePerTon : parseFloat(order.portfolio.pricePerTon) || 15.63;
} }
// Create a safe method to extract properties with fallbacks // Create a safe method to extract properties with fallbacks
@ -232,8 +220,8 @@ export async function createOffsetOrder(
currency: getSafeProp(order, 'currency', 'USD'), currency: getSafeProp(order, 'currency', 'USD'),
tons: getSafeProp(order, 'tons', 0), tons: getSafeProp(order, 'tons', 0),
portfolio: { portfolio: {
id: getSafeProp(portfolio, 'id', 1), id: getSafeProp(portfolio, 'id', 2),
name: getSafeProp(portfolio, 'name', 'Default Portfolio'), name: getSafeProp(portfolio, 'name', 'Community Tree Planting'),
description: getSafeProp(portfolio, 'description', ''), description: getSafeProp(portfolio, 'description', ''),
projects: getSafeProp(portfolio, 'projects', []), projects: getSafeProp(portfolio, 'projects', []),
pricePerTon, pricePerTon,
@ -241,7 +229,7 @@ export async function createOffsetOrder(
}, },
status: getSafeProp(order, 'status', ''), status: getSafeProp(order, 'status', ''),
createdAt: getSafeProp(order, 'createdAt', new Date().toISOString()), createdAt: getSafeProp(order, 'createdAt', new Date().toISOString()),
dryRun: getSafeProp(order, 'dryRun', false) dryRun: getSafeProp(order, 'dryRun', true)
}; };
} catch (error: unknown) { } catch (error: unknown) {
logError(error); logError(error);