Skip to content

Commit

Permalink
feat: fix settings
Browse files Browse the repository at this point in the history
  • Loading branch information
benjaminshafii committed Jan 9, 2025
1 parent ce3aa16 commit 50d7867
Show file tree
Hide file tree
Showing 18 changed files with 10,492 additions and 9,910 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
"pnpm": "^8.0.0"
},
"workspaces": [
"packages/*",
"pipes/*"
"packages/*"
],
"dependencies": {
"@hookform/resolvers": "^3.9.1",
Expand Down
Binary file modified pipes/auto-pay/bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions pipes/auto-pay/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-switch": "^1.1.2",
"@radix-ui/react-toast": "^1.2.3",
"@radix-ui/react-toggle-group": "^1.1.1",
"@radix-ui/react-tooltip": "^1.1.5",
"@screenpipe/browser": "0.1.12",
"@screenpipe/js": "^1.0.1",
Expand Down
File renamed without changes.
53 changes: 53 additions & 0 deletions pipes/auto-pay/src/app/api/createMercuryPayment/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import axios, { AxiosError } from 'axios';
import { getAutoPaySettings } from '@/lib/auto-pay-settings';
import { NextResponse } from 'next/server';
import type { MercuryPaymentInfo, MercuryPaymentResponse } from '@/types/mercury';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const MERCURY_API_URL = 'https://api.mercury.com/api/v1';

export async function POST(request: Request) {
try {
const { paymentInfo } = await request.json() as { paymentInfo: MercuryPaymentInfo };
const { mercuryApiKey, mercuryAccountId } = await getAutoPaySettings();

if (!mercuryApiKey || !mercuryAccountId) {
throw new Error('Missing Mercury API configuration');
}

console.log('0xHypr', 'Creating Mercury payment', paymentInfo);

// Create the payment using Mercury's API
const paymentResponse = await axios.post<MercuryPaymentResponse>(
`${MERCURY_API_URL}/account/${mercuryAccountId}/payments`,
paymentInfo,
{
headers: {
Authorization: `Bearer ${mercuryApiKey}`,
'Content-Type': 'application/json',
},
}
);

console.log('0xHypr', 'Mercury payment created:', paymentResponse.data);

return NextResponse.json({
success: true,
payment: paymentResponse.data,
paymentId: paymentResponse.data.id,
mercuryUrl: paymentResponse.data.mercuryUrl,
});
} catch (error) {
const axiosError = error as AxiosError;
console.error(
'0xHypr Error creating Mercury payment:',
axiosError.response?.data || axiosError
);
return NextResponse.json(
axiosError.response?.data || { message: axiosError.message },
{ status: axiosError.response?.status || 500 }
);
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
import { NextApiRequest, NextApiResponse } from 'next';
import axios, { AxiosError } from 'axios';
import { v4 as uuidv4 } from 'uuid';
import type { PaymentInfo } from '@/types/wise';
import { getAutoPaySettings } from '@/lib/auto-pay-settings';
import { NextResponse } from 'next/server';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(request: Request) {
const { wiseApiKey, wiseProfileId, enableProduction } =
await getAutoPaySettings();

const WISE_API_URL = enableProduction
? 'https://api.transferwise.com'
: 'https://api.sandbox.transferwise.tech';
try {
const { paymentInfo } = req.body as { paymentInfo: PaymentInfo };

// Create a quote using v3 authenticated quotes endpoint
const { paymentInfo } = await request.json() as { paymentInfo: PaymentInfo };

// Create a quote using v3 authenticated quotes endpoint
console.log('0xHypr', 'Creating quote');
Expand Down Expand Up @@ -120,19 +115,11 @@ export default async function handler(

// Create transfer with the improved logic
console.log('0xHypr', 'Creating transfer');
// print quoteResponse.data
// random number between 1000 and 9999
console.log('0xHypr', 'Quote ID:', quoteResponse.data);
const transferData = {
targetAccount: recipientResponse.data.id,
quoteUuid: quoteResponse.data.id,
customerTransactionId: uuidv4(),
details: {
// reference: paymentInfo.referenceNote || "Auto payment",
// transferPurpose: "verification.transfers.purpose.pay.bills",
// transferPurposeSubTransferPurpose: "verification.sub.transfers.purpose.pay.bills",
// sourceOfFunds: "verification.source.of.funds.other"
},
details: {},
originator: {
type: 'ACCOUNT',
id: '1234567890',
Expand Down Expand Up @@ -173,7 +160,7 @@ export default async function handler(
console.log('0xHypr', 'Transfer funded');
}

return res.status(200).json({
return NextResponse.json({
success: true,
transfer: transferResponse.data,
transferId: transferResponse.data.id,
Expand All @@ -184,8 +171,9 @@ export default async function handler(
'0xHypr Error creating transfer:',
axiosError.response?.data || axiosError
);
return res
.status(axiosError.response?.status || 500)
.json(axiosError.response?.data || { message: axiosError.message });
return NextResponse.json(
axiosError.response?.data || { message: axiosError.message },
{ status: axiosError.response?.status || 500 }
);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import { NextApiRequest, NextApiResponse } from 'next';
import axios from 'axios';
import { getAutoPaySettings } from '@/lib/auto-pay-settings';
import { NextResponse } from 'next/server';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

interface FundTransferRequest {
transferId: string;
}

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}

export async function POST(request: Request) {
try {
const { transferId } = req.body as FundTransferRequest;
const { transferId } = await request.json() as FundTransferRequest;
const { wiseApiKey, wiseProfileId, enableProduction } =
await getAutoPaySettings();
// Get Wise API token and profile ID from environment variables
Expand Down Expand Up @@ -43,15 +39,18 @@ export default async function handler(
}
);

return res.status(200).json({
return NextResponse.json({
success: true,
payment: fundResponse.data,
});
} catch (err) {
console.error('Failed to fund transfer:', err);
return res.status(500).json({
error: 'Failed to fund transfer',
details: err instanceof Error ? err.message : 'Unknown error',
});
return NextResponse.json(
{
error: 'Failed to fund transfer',
details: err instanceof Error ? err.message : 'Unknown error',
},
{ status: 500 }
);
}
}
}
80 changes: 11 additions & 69 deletions pipes/auto-pay/src/app/api/settings/route.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,13 @@
import { getAutoPaySettings } from '@/lib/auto-pay-settings';
import { pipe } from '@screenpipe/js';
import { NextResponse } from 'next/server';
import { promises as fs } from 'fs';
import path from 'path';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

async function updatePipeConfig(settings: any) {
try {
const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();
const pipeConfigPath = path.join(screenpipeDir, 'pipes', 'auto-pay', 'pipe.json');
const settingsPath = path.join(screenpipeDir, 'pipes', 'auto-pay', 'settings.json');

console.log('0xHypr', 'updating pipe config at:', pipeConfigPath);

let config: any = {};
let persistedSettings: any = {};

try {
const content = await fs.readFile(pipeConfigPath, 'utf8');
config = JSON.parse(content);
} catch (err) {
console.log('0xHypr', 'no existing config found, creating new one');
config = {
name: 'auto-pay-pipe',
version: '0.1.0',
fields: []
};
}

try {
const settingsContent = await fs.readFile(settingsPath, 'utf8');
persistedSettings = JSON.parse(settingsContent);
} catch (err) {
console.log('0xHypr', 'no existing settings found, creating new one');
persistedSettings = {};
}

// Merge new settings with persisted settings
const updatedSettings = { ...persistedSettings, ...settings };
await fs.writeFile(settingsPath, JSON.stringify(updatedSettings, null, 2));

// Update pipe config if needed
await fs.writeFile(pipeConfigPath, JSON.stringify(config, null, 2));

console.log('0xHypr', 'updated pipe config successfully');
} catch (err) {
console.error('failed to update pipe config:', err);
throw err;
}
}

export async function GET() {
console.log('0xHypr', 'shello');
console.log('0xHypr', 'shello');
if (!pipe) {
return NextResponse.json({ error: 'pipe not found' }, { status: 500 });
}
Expand All @@ -68,22 +23,10 @@ export async function GET() {

console.log('0xHypr', { settingsPath })
try {
// const settingsContent = await fs.readFile(settingsPath, 'utf8');
// const persistedSettings = JSON.parse(settingsContent);
// console.log('0xHypr', { persistedSettings })

// Merge with current settings
const rawSettings = await settingsManager.getAll();
const namespaceSettings = await settingsManager.getNamespaceSettings('auto-pay');
const customSettings = {
wiseApiKey: namespaceSettings?.wiseApiKey || process.env.WISE_API_KEY,
wiseProfileId: namespaceSettings?.wiseProfileId || process.env.WISE_PROFILE_ID,
enableProduction: namespaceSettings?.enableProduction || process.env.NEXT_PUBLIC_USE_PRODUCTION === 'true',
mercuryApiKey: namespaceSettings?.mercuryApiKey || process.env.MERCURY_API_KEY,
mercuryAccountId: namespaceSettings?.mercuryAccountId || process.env.MERCURY_ACCOUNT_ID
}
console.log('0xHypr', { customSettings })
const customSettings = await getAutoPaySettings();

console.log('0xHypr', { customSettings })
console.log('0xHypr', { rawSettings })

return NextResponse.json({
Expand All @@ -93,7 +36,6 @@ export async function GET() {
'auto-pay': {
...(rawSettings.customSettings?.['auto-pay'] || {}),
...customSettings,
// ...persistedSettings,
},
},
});
Expand All @@ -118,16 +60,13 @@ export async function PUT(request: Request) {
const body = await request.json();
const { key, value, isPartialUpdate, reset, namespace } = body;

// Handle auto-pay namespace updates
if (namespace === 'auto-pay' && isPartialUpdate) {
await updatePipeConfig(value);
}

if (reset) {
if (namespace) {
if (key) {
// Reset single key in namespace
await settingsManager.setCustomSetting(namespace, key, undefined);
} else {
// Reset entire namespace
await settingsManager.updateNamespaceSettings(namespace, {});
}
} else {
Expand All @@ -142,7 +81,7 @@ export async function PUT(request: Request) {

if (namespace) {
if (isPartialUpdate) {
const currentSettings = (await settingsManager.getNamespaceSettings(namespace)) || {};
const currentSettings = await settingsManager.getNamespaceSettings(namespace) || {};
await settingsManager.updateNamespaceSettings(namespace, {
...currentSettings,
...value,
Expand All @@ -161,6 +100,9 @@ export async function PUT(request: Request) {
return NextResponse.json({ success: true });
} catch (error) {
console.error('failed to update settings:', error);
return NextResponse.json({ error: 'failed to update settings' }, { status: 500 });
return NextResponse.json(
{ error: 'failed to update settings' },
{ status: 500 }
);
}
}
Loading

0 comments on commit 50d7867

Please sign in to comment.