Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions apps/backend/lambdas/expenditures/db-types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* This file was generated by kysely-codegen.
* Please do not edit it manually.
*/

import type { ColumnType } from "kysely";

export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
? ColumnType<S, I | undefined, U>
: ColumnType<T, T | undefined, T>;

export type Numeric = ColumnType<string, number | string, number | string>;

export type Timestamp = ColumnType<Date, Date | string, Date | string>;

export interface BranchDonors {
contact_email: string | null;
contact_name: string | null;
created_at: Generated<Timestamp | null>;
donor_id: Generated<number>;
organization: string;
}

export interface BranchExpenditures {
amount: Numeric;
category: string | null;
created_at: Generated<Timestamp | null>;
description: string | null;
entered_by: number | null;
expenditure_id: Generated<number>;
project_id: number;
spent_on: Generated<Timestamp>;
}

export interface BranchProjectDonations {
amount: Numeric;
donated_at: Generated<Timestamp | null>;
donation_id: Generated<number>;
donor_id: number;
project_id: number;
}

export interface BranchProjectMemberships {
hours: Numeric | null;
membership_id: Generated<number>;
project_id: number;
role: string;
start_date: Timestamp | null;
user_id: number;
}

export interface BranchProjects {
created_at: Generated<Timestamp | null>;
currency: Generated<string | null>;
end_date: Timestamp | null;
name: string;
project_id: Generated<number>;
start_date: Timestamp | null;
total_budget: Numeric | null;
}

export interface BranchUsers {
created_at: Generated<Timestamp | null>;
email: string;
is_admin: Generated<boolean | null>;
name: string;
user_id: Generated<number>;
}

export interface DB {
"branch.donors": BranchDonors;
"branch.expenditures": BranchExpenditures;
"branch.project_donations": BranchProjectDonations;
"branch.project_memberships": BranchProjectMemberships;
"branch.projects": BranchProjects;
"branch.users": BranchUsers;
}
19 changes: 19 additions & 0 deletions apps/backend/lambdas/expenditures/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Kysely, PostgresDialect } from 'kysely'
import { Pool } from 'pg'
import type { DB } from './db-types'


const db = new Kysely<DB>({
dialect: new PostgresDialect({
pool: new Pool({
host: process.env.DB_HOST ?? 'localhost',
port: Number(process.env.DB_PORT ?? 5432),
user: process.env.DB_USER ?? 'branch_dev',
password: process.env.DB_PASSWORD ?? 'password',
database: process.env.DB_NAME ?? 'branch_db',
ssl: false,
}),
}),
})

export default db
174 changes: 174 additions & 0 deletions apps/backend/lambdas/expenditures/dev-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { handler } from './handler';
import { loadOpenApiSpec, getSwaggerHtml } from './swagger-utils';
import * as http from 'http';
import * as fs from 'fs';
import * as path from 'path';
import { URL } from 'url';
import { APIGatewayProxyEvent } from 'aws-lambda';

const HANDLER_NAME = 'expenditures';
const BASE_PATH = `/${HANDLER_NAME}`;

// Check if shared server exists, if not create it
const SHARED_SERVER_PORT = 3000;
const LOCK_FILE = path.join(__dirname, '..', '.dev-server.lock');

async function startOrJoinServer() {
// Try to register this handler with existing server
try {
const response = await fetch(`http://localhost:${SHARED_SERVER_PORT}/_register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
handlerName: HANDLER_NAME,
handlerPath: __dirname
})
});

if (response.ok) {
console.log(`Registered ${HANDLER_NAME} with existing dev server`);
console.log(`Handler available at: http://localhost:${SHARED_SERVER_PORT}${BASE_PATH}`);
console.log(`Swagger UI: http://localhost:${SHARED_SERVER_PORT}${BASE_PATH}/swagger`);
return;
}
} catch (err) {
// Server doesn't exist, we'll create it
}

// Create the shared server
const handlers = new Map();

const server = http.createServer(async (req, res) => {
try {
const chunks = [] as Buffer[];
req.on('data', (c) => chunks.push(c));
req.on('end', async () => {
const bodyRaw = Buffer.concat(chunks).toString('utf8');
const fullUrl = new URL(req.url || '/', `http://localhost:${SHARED_SERVER_PORT}`);

// Handle registration endpoint
if (fullUrl.pathname === '/_register' && req.method === 'POST') {
const { handlerName, handlerPath } = JSON.parse(bodyRaw);
try {
const handlerModule = require(path.join(handlerPath, 'handler.ts'));
const swaggerUtils = require(path.join(handlerPath, 'swagger-utils.ts'));
handlers.set(handlerName, { handler: handlerModule.handler, swaggerUtils, handlerPath });
res.statusCode = 200;
res.end('OK');
console.log(`Registered handler: ${handlerName}`);
} catch (err) {
res.statusCode = 500;
res.end('Failed to load handler');
}
return;
}

// Handle root route - show available handlers
if (fullUrl.pathname === '/' && req.method === 'GET') {
const handlerList = Array.from(handlers.keys()).map(name =>
`<li><a href="/${name}">${name}</a> - <a href="/${name}/swagger">Swagger UI</a></li>`
).join('');

const html = `<!DOCTYPE html>
<html><head><title>Lambda Dev Server</title></head>
<body>
<h1>Lambda Development Server</h1>
<h2>Available Handlers:</h2>
<ul>${handlerList}</ul>
</body></html>`;

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}

// Route to specific handler
const pathParts = fullUrl.pathname.split('/').filter(Boolean);
const handlerName = pathParts[0];

if (!handlers.has(handlerName)) {
res.statusCode = 404;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: `Handler '${handlerName}' not found` }));
return;
}

const { handler: handlerFn, swaggerUtils } = handlers.get(handlerName);
const handlerPath = '/' + pathParts.slice(1).join('/');

// Handle Swagger routes for this handler
if (handlerPath === '/swagger.json' && req.method === 'GET') {
const spec = swaggerUtils.loadOpenApiSpec();
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(spec));
return;
}
if (handlerPath === '/swagger' && req.method === 'GET') {
const html = swaggerUtils.getSwaggerHtml(`/${handlerName}/swagger.json`);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}

// Create Lambda event (compatible with both API Gateway and Function URL formats)
const event = {
// API Gateway format
body: bodyRaw || null,
headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : (v ?? '')])) as Record<string, string>,
httpMethod: (req.method || 'GET').toUpperCase(),
isBase64Encoded: false,
multiValueHeaders: {},
multiValueQueryStringParameters: null,
path: handlerPath || '/',
pathParameters: null,
queryStringParameters: Object.fromEntries(fullUrl.searchParams.entries()),
requestContext: {
// Function URL format
http: {
method: (req.method || 'GET').toUpperCase(),
path: handlerPath || '/',
protocol: 'HTTP/1.1',
sourceIp: '127.0.0.1'
}
} as any,
resource: handlerPath || '/',
stageVariables: null,
// Function URL format
rawPath: handlerPath || '/',
rawQueryString: fullUrl.search.slice(1) || ''
};

const result = await handlerFn(event);
res.statusCode = result.statusCode || 200;
if (result.headers) {
for (const [k, v] of Object.entries(result.headers)) res.setHeader(k, String(v));
}
res.end(result.body);
});
} catch (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Server error' }));
}
});

server.listen(SHARED_SERVER_PORT, () => {
console.log(`Lambda Dev Server started on http://localhost:${SHARED_SERVER_PORT}`);
console.log(`Available handlers will be listed at http://localhost:${SHARED_SERVER_PORT}`);

// Register this handler
handlers.set(HANDLER_NAME, {
handler,
swaggerUtils: { loadOpenApiSpec, getSwaggerHtml },
handlerPath: __dirname
});

console.log(`Handler '${HANDLER_NAME}' available at: http://localhost:${SHARED_SERVER_PORT}${BASE_PATH}`);
console.log(`Swagger UI: http://localhost:${SHARED_SERVER_PORT}${BASE_PATH}/swagger`);
});
}

startOrJoinServer().catch(console.error);
109 changes: 109 additions & 0 deletions apps/backend/lambdas/expenditures/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import db from './db';
import { ExpenditureValidationUtils } from './validation-utils';

export const handler = async (event: any): Promise<APIGatewayProxyResult> => {
try {
// Support both API Gateway and Lambda Function URL events
// API Gateway: event.path, event.httpMethod
// Function URL: event.rawPath, event.requestContext.http.method
const rawPath = event.rawPath || event.path || '/';
const normalizedPath = rawPath.replace(/\/$/, '');
const method = (event.requestContext?.http?.method || event.httpMethod || 'GET').toUpperCase();

// Health check
if ((normalizedPath.endsWith('/health') || normalizedPath === '/health') && method === 'GET') {
return json(200, { ok: true, timestamp: new Date().toISOString() });
}

// >>> ROUTES-START (do not remove this marker)
// CLI-generated routes will be inserted here

// POST /expenditures
if ((normalizedPath === '/expenditures' || normalizedPath === '' || normalizedPath === '/') && method === 'POST') {
const body = event.body ? JSON.parse(event.body) as Record<string, unknown> : {};

// Validate input
const validationResult = ExpenditureValidationUtils.validateExpenditureInput(body);
if (validationResult instanceof Error) {
return json(400, { message: validationResult.message });
}

const { projectID, enteredBy, amount, category, description, spentOn } = validationResult;

// Check if project exists
const project = await db
.selectFrom('branch.projects')
.where('project_id', '=', projectID)
.selectAll()
.executeTakeFirst();

if (!project) {
return json(404, { message: 'Project not found' });
}

// Check if enteredBy user exists (if provided)
if (enteredBy !== undefined && enteredBy !== null) {
const user = await db
.selectFrom('branch.users')
.where('user_id', '=', enteredBy)
.selectAll()
.executeTakeFirst();

if (!user) {
return json(404, { message: 'User not found' });
}
}

// Insert expenditure
try {
await db
.insertInto('branch.expenditures')
.values({
project_id: projectID,
entered_by: enteredBy ?? null,
amount,
category: category ?? null,
description: description ?? null,
spent_on: spentOn ? new Date(spentOn) : new Date(),
})
.executeTakeFirst();
} catch (err) {
console.error('Database insert error:', err);
return json(500, { message: 'Failed to create expenditure' });
}

return json(201, {
ok: true,
route: 'POST /expenditures',
body: {
projectID,
enteredBy: enteredBy ?? null,
amount,
category: category ?? null,
description: description ?? null,
spentOn: spentOn ?? new Date().toISOString().split('T')[0],
},
});
}
// <<< ROUTES-END

return json(404, { message: 'Not Found', path: normalizedPath, method });
} catch (err) {
console.error('Lambda error:', err);
return json(500, { message: 'Internal Server Error' });
}
};

function json(statusCode: number, body: unknown): APIGatewayProxyResult {
return {
statusCode,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,Authorization',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS'
},
body: JSON.stringify(body)
};
}
Loading