Backend build for FinancialProfileForm

This commit is contained in:
Josh 2025-04-01 13:33:37 +00:00
parent f14910a0df
commit 2a008a8658
3 changed files with 83 additions and 11 deletions

View File

@ -360,6 +360,63 @@ app.post('/api/premium/career-history', authenticatePremiumUser, async (req, res
}
});
app.get('/api/premium/financial-profile', authenticatePremiumUser, async (req, res) => {
try {
const row = await db.get(`SELECT * FROM financial_profile WHERE user_id = ?`, [req.userId]);
res.json(row || {});
} catch (error) {
console.error('Error fetching financial profile:', error);
res.status(500).json({ error: 'Failed to fetch financial profile' });
}
});
app.post('/api/premium/financial-profile', authenticatePremiumUser, async (req, res) => {
const {
currentSalary, additionalIncome, monthlyExpenses, monthlyDebtPayments,
retirementSavings, retirementContribution, emergencyFund,
inCollege, expectedGraduation, partTimeIncome, tuitionPaid, collegeLoanTotal
} = req.body;
try {
// Upsert-style logic: Check if exists
const existing = await db.get(`SELECT id FROM financial_profile WHERE user_id = ?`, [req.userId]);
if (existing) {
await db.run(`
UPDATE financial_profile SET
current_salary = ?, additional_income = ?, monthly_expenses = ?, monthly_debt_payments = ?,
retirement_savings = ?, retirement_contribution = ?, emergency_fund = ?,
in_college = ?, expected_graduation = ?, part_time_income = ?, tuition_paid = ?, college_loan_total = ?,
updated_at = CURRENT_TIMESTAMP
WHERE user_id = ?
`, [
currentSalary, additionalIncome, monthlyExpenses, monthlyDebtPayments,
retirementSavings, retirementContribution, emergencyFund,
inCollege ? 1 : 0, expectedGraduation, partTimeIncome, tuitionPaid, collegeLoanTotal,
req.userId
]);
} else {
await db.run(`
INSERT INTO financial_profile (
id, user_id, current_salary, additional_income, monthly_expenses, monthly_debt_payments,
retirement_savings, retirement_contribution, emergency_fund, in_college, expected_graduation,
part_time_income, tuition_paid, college_loan_total
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, [
uuidv4(), req.userId, currentSalary, additionalIncome, monthlyExpenses, monthlyDebtPayments,
retirementSavings, retirementContribution, emergencyFund,
inCollege ? 1 : 0, expectedGraduation, partTimeIncome, tuitionPaid, collegeLoanTotal
]);
}
res.status(200).json({ message: 'Financial profile saved.' });
} catch (error) {
console.error('Error saving financial profile:', error);
res.status(500).json({ error: 'Failed to save financial profile.' });
}
});
// Retrieve career history
app.get('/api/premium/career-history', authenticatePremiumUser, async (req, res) => {
try {

View File

@ -1,5 +1,7 @@
import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from 'react-router-dom';
import authFetch from '../utils/authFetch.js';
export default function FinancialProfileForm() {
const location = useLocation();
@ -27,23 +29,36 @@ export default function FinancialProfileForm() {
useEffect(() => {
console.log("✅ selectedCareer in useEffect:", selectedCareer);
}, [selectedCareer]);
// Fetch existing data on mount
useEffect(() => {
async function fetchProfile() {
try {
const res = await fetch(`/api/premium/financial-profile?user_id=${userId}`);
if (res.ok) {
const data = await res.json();
async function fetchFinancialProfile() {
try {
const res = await authFetch("/api/premium/financial-profile", {
method: "GET",
headers: {
"Authorization": `Bearer ${localStorage.getItem('token')}`
}
});
if (res.ok) {
const data = await res.json();
if (data && Object.keys(data).length > 0) {
setFormData((prev) => ({ ...prev, ...data }));
} else {
console.log("No existing financial profile. Starting fresh.");
}
} catch (err) {
console.error("Failed to fetch financial profile", err);
} else {
console.warn("Response not OK when fetching financial profile:", res.status);
}
} catch (err) {
console.error("Failed to fetch financial profile", err);
}
}
fetchFinancialProfile();
}, [userId]);
fetchProfile();
}, [userId]);
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
@ -56,7 +71,7 @@ export default function FinancialProfileForm() {
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await fetch("/api/premium/financial-profile", {
const res = await authFetch("/api/premium/financial-profile", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_id: userId, ...formData })

Binary file not shown.