0% found this document useful (0 votes)
6 views32 pages

Healthcare Management App Code

The document contains code snippets for a health management application, including a login page, backend API service, and various functionalities for managing healthcare records, food diet entries, notes, and reminders. It also includes an AI chat system for health-related queries. The application utilizes React for the frontend and Express with PostgreSQL for the backend, implementing features such as user authentication and data storage.

Uploaded by

dev.unity.cc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views32 pages

Healthcare Management App Code

The document contains code snippets for a health management application, including a login page, backend API service, and various functionalities for managing healthcare records, food diet entries, notes, and reminders. It also includes an AI chat system for health-related queries. The application utilizes React for the frontend and Express with PostgreSQL for the backend, implementing features such as user authentication and data storage.

Uploaded by

dev.unity.cc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Sample Output

SAMPLE CODING

Login Page Code

import React, { useState } from 'react';


import { useNavigate } from 'react-router-dom';

import { Button } from '@/components/ui/button';

import { Input } from '@/components/ui/input';

import { useAuth } from '@/contexts/AuthContext';

const Login = () => {

const [loading, setLoading] = useState(false);

const [email, setEmail] = useState('');

const [password, setPassword] = useState('');

const { signInWithGoogle, signInWithEmail } = useAuth();

const navigate = useNavigate();

const handleGoogleSignIn = async () => {

try {

setLoading(true);

await signInWithGoogle();

navigate('/dashboard');

} catch (error) {

[Link]('Login error:', error);

} finally {

setLoading(false);

};

const handleLogin = async (e: [Link]) => {

[Link]();

try {
setLoading(true);

await signInWithEmail(email, password);

navigate('/dashboard');

} catch (error) {

[Link]('Login error:', error);

} finally {

setLoading(false);

};

Backend API Service Code

import axios from 'axios';

const API_BASE_URL = '[Link]

interface HealthcareRecord {

id?: number;

user_id?: string;

type: string;

value: string;

unit?: string;

notes?: string;

created_at?: string;

class BackendApiService {
private currentUserId: string | null = null;

async getHealthcareRecords(): Promise<{ success: boolean; data: HealthcareRecord[] }> {

try {

const response = await [Link](`${API_BASE_URL}/healthcare`, {

params: { user_id: [Link] }

});

return { success: true, data: [Link] };

} catch (error) {

[Link]('Error fetching healthcare records:', error);

return { success: false, data: [] };

async createHealthcareRecord(record: Omit<HealthcareRecord, 'id' | 'created_at'>) {

try {

const response = await [Link](`${API_BASE_URL}/healthcare`, {

...record,

user_id: [Link]

});

return { success: true, data: [Link] };

} catch (error) {

[Link]('Error creating healthcare record:', error);

return { success: false };

}
Server Backend Code

const express = require('express');

const { Pool } = require('pg');

const cors = require('cors');

require('dotenv').config();

const app = express();

const PORT = [Link] || 3001;

[Link](cors());

[Link]([Link]());

const pool = new Pool({

connectionString: [Link].DATABASE_URL,

ssl: {

rejectUnauthorized: false

});

async function initDB() {

try {

await [Link](`

CREATE TABLE IF NOT EXISTS healthcare_records (

id SERIAL PRIMARY KEY,


user_id VARCHAR(255),

type VARCHAR(100) NOT NULL,

value VARCHAR(255) NOT NULL,

unit VARCHAR(50),

notes TEXT,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

`);

[Link]('Database tables initialized successfully');

} catch (error) {

[Link]('Error initializing database:', error);

[Link]('/api/healthcare', async (req, res) => {

try {

const { user_id } = [Link];

const result = await [Link](

'SELECT * FROM healthcare_records WHERE user_id = $1 ORDER BY created_at DESC',

[user_id]

);

[Link]([Link]);

} catch (error) {

[Link]('Error fetching healthcare records:', error);

[Link](500).json({ error: 'Failed to fetch healthcare records' });

});
[Link]('/api/healthcare', async (req, res) => {

try {

const { user_id, type, value, unit, notes } = [Link];

const result = await [Link](

'INSERT INTO healthcare_records (user_id, type, value, unit, notes) VALUES ($1, $2, $3, $4, $5) RETURNING *',

[user_id, type, value, unit, notes]

);

[Link](201).json([Link][0]);

} catch (error) {

[Link]('Error creating healthcare record:', error);

[Link](500).json({ error: 'Failed to create healthcare record' });

});

[Link](PORT, async () => {

[Link](`Server running on port ${PORT}`);

await initDB();

});

Health Care Tracking Code

// Health record interface

interface HealthRecord {

type: string;

value: string;

unit: string;
notes: string;

// Add health record function

const addHealthRecord = async (record) => {

try {

const response = await [Link]('/api/healthcare', {

user_id: [Link],

type: [Link],

value: [Link],

unit: [Link],

notes: [Link]

});

return [Link];

} catch (error) {

[Link]('Error adding health record:', error);

};

// Get health records

const getHealthRecords = async () => {

try {

const response = await [Link]('/api/healthcare', {

params: { user_id: [Link] }

});

return [Link];

} catch (error) {
[Link]('Error fetching records:', error);

};

Food Diet Management Code

// Food entry interface

interface FoodEntry {

meal_type: string;

food_name: string;

calories: number;

protein: number;

carbs: number;

fat: number;

// Add food entry

const addFoodEntry = async (food) => {

try {

const response = await [Link]('/api/food-diet', {

user_id: [Link],

meal_type: food.meal_type,

food_name: food.food_name,

calories: [Link],

protein: [Link],

carbs: [Link],

fat: [Link]
});

return [Link];

} catch (error) {

[Link]('Error adding food entry:', error);

};

// Calculate daily nutrition

const getDailyNutrition = async (date) => {

try {

const records = await [Link]('/api/food-diet', {

params: { user_id: [Link] }

});

const totalCalories = [Link]((sum, item) =>

sum + ([Link] || 0), 0

);

return { totalCalories, records: [Link] };

} catch (error) {

[Link]('Error calculating nutrition:', error);

};

Database Operations

// Create healthcare table


CREATE TABLE healthcare_records (

id SERIAL PRIMARY KEY,

user_id VARCHAR(255),

type VARCHAR(100) NOT NULL,

value VARCHAR(255) NOT NULL,

unit VARCHAR(50),

notes TEXT,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

// Create food diet table

CREATE TABLE food_diet_records (

id SERIAL PRIMARY KEY,

user_id VARCHAR(255),

meal_type VARCHAR(50) NOT NULL,

food_name VARCHAR(255) NOT NULL,

calories INTEGER,

protein DECIMAL(5,2),

carbs DECIMAL(5,2),

fat DECIMAL(5,2),

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

// Insert health record

INSERT INTO healthcare_records (user_id, type, value, unit, notes)

VALUES ($1, $2, $3, $4, $5);


// Select user records

SELECT * FROM healthcare_records

WHERE user_id = $1

ORDER BY created_at DESC;

Notes Management Code

// Note interface

interface Note {

id: number;

title: string;

content: string;

user_id: string;

created_at: string;

// Create new note

const createNote = async (noteData) => {

try {

const response = await [Link]('/api/notes', {

user_id: [Link],

title: [Link],

content: [Link]

});

return { success: true, data: [Link] };

} catch (error) {

[Link]('Error creating note:', error);


return { success: false };

};

// Get all notes

const getNotes = async () => {

try {

const response = await [Link]('/api/notes', {

params: { user_id: [Link] }

});

return { success: true, data: [Link] };

} catch (error) {

[Link]('Error fetching notes:', error);

return { success: false, data: [] };

};

// Update note

const updateNote = async (id, noteData) => {

try {

const response = await [Link](`/api/notes/${id}`, {

title: [Link],

content: [Link],

user_id: [Link]

});

return { success: true, data: [Link] };

} catch (error) {
[Link]('Error updating note:', error);

return { success: false };

};

// Delete note

const deleteNote = async (id) => {

try {

await [Link](`/api/notes/${id}`, {

params: { user_id: [Link] }

});

return { success: true };

} catch (error) {

[Link]('Error deleting note:', error);

return { success: false };

};

Reminder System Code

// Reminder interface

interface Reminder {

id: string;

title: string;

message: string;

time: string;

enabled: boolean;
type: 'workout' | 'medication' | 'health';

// Set reminder

const setReminder = (reminder) => {

const reminders = [Link]([Link]('reminders') || '[]');

const newReminder = {

...reminder,

id: [Link]().toString(),

enabled: true

};

[Link](newReminder);

[Link]('reminders', [Link](reminders));

return newReminder;

};

// Get active reminders

const getActiveReminders = () => {

const reminders = [Link]([Link]('reminders') || '[]');

return [Link](r => [Link]);

};

// Check reminder notifications

const checkReminders = () => {

const now = new Date();

const currentTime = [Link]() + ':' + [Link]().toString().padStart(2, '0');


const activeReminders = getActiveReminders();

[Link](reminder => {

if ([Link] === currentTime) {

showNotification([Link], [Link]);

});

};

// Show notification

const showNotification = (title, message) => {

if ([Link] === 'granted') {

new Notification(title, {

body: message,

icon: '/[Link]'

});

};

Database Schema

// Create notes table

CREATE TABLE notes (

id SERIAL PRIMARY KEY,

user_id VARCHAR(255),

title VARCHAR(255) NOT NULL,

content TEXT,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,


updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

// Notes API endpoints

[Link]('/api/notes', async (req, res) => {

const { user_id } = [Link];

const result = await [Link](

'SELECT * FROM notes WHERE user_id = $1 ORDER BY created_at DESC',

[user_id]

);

[Link]([Link]);

});

[Link]('/api/notes', async (req, res) => {

const { user_id, title, content } = [Link];

const result = await [Link](

'INSERT INTO notes (user_id, title, content) VALUES ($1, $2, $3) RETURNING *',

[user_id, title, content]

);

[Link](201).json([Link][0]);

});

[Link]('/api/notes/:id', async (req, res) => {

const { id } = [Link];

const { user_id } = [Link];

await [Link]('DELETE FROM notes WHERE id = $1 AND user_id = $2', [id, user_id]);

[Link]({ message: 'Note deleted successfully' });


});

AI Chat System Code

AI Chat System Code

// Chat message interface

interface ChatMessage {

id: string;

role: 'user' | 'assistant';

content: string;

timestamp: Date;

// Health context interface

interface HealthContext {

healthRecords: any[];

foodEntries: any[];

workoutHistory: any[];

userProfile: {

age?: number;

gender?: string;

conditions?: string[];

};

}
AI Integration Code

import { Groq } from 'groq-sdk';

const groq = new Groq({

apiKey: [Link].GROQ_API_KEY,

dangerouslyAllowBrowser: true,

});

class HealthChatAI {

private conversationHistory: ChatMessage[] = [];

async sendMessage(userMessage: string, healthContext?: HealthContext) {

try {

// Add user message to history

const userChatMessage: ChatMessage = {

id: `user-${[Link]()}`,

role: 'user',

content: userMessage,

timestamp: new Date()

};

[Link](userChatMessage);

// Generate AI response

const completion = await [Link]({


messages: [

role: "system",

content: "You are a helpful health and wellness assistant."

},

role: "user",

content: userMessage

],

model: "deepseek-r1-distill-llama-70b",

temperature: 0.7,

max_tokens: 1000

});

const aiContent = [Link][0]?.message?.content || "I'm sorry, I couldn't process that.";

const aiChatMessage: ChatMessage = {

id: `ai-${[Link]()}`,

role: 'assistant',

content: aiContent,

timestamp: new Date()

};

[Link](aiChatMessage);

return aiChatMessage;
} catch (error) {

[Link]('AI Chat error:', error);

return [Link](userMessage);

clearHistory() {

[Link] = [];

Chat Component Code

const AIChat = () => {

const [messages, setMessages] = useState<ChatMessage[]>([]);

const [inputMessage, setInputMessage] = useState("");

const [isLoading, setIsLoading] = useState(false);

const sendMessage = async () => {

if (![Link]() || isLoading) return;

setIsLoading(true);

try {

// Add user message

const userMessage: ChatMessage = {

id: `user-${[Link]()}`,

role: 'user',
content: inputMessage,

timestamp: new Date()

};

setMessages(prev => [...prev, userMessage]);

setInputMessage("");

// Get AI response

const aiResponse = await [Link](inputMessage, healthContext);

setMessages(prev => [...prev, aiResponse]);

} catch (error) {

[Link]('Chat error:', error);

} finally {

setIsLoading(false);

};

return (

<div className="chat-container">

<div className="messages">

{[Link]((message) => (

<div key={[Link]} className={`message ${[Link]}`}>

<div className="content">{[Link]}</div>

</div>

))}

</div>
<div className="input-area">

<input

value={inputMessage}

onChange={(e) => setInputMessage([Link])}

placeholder="Ask a health question..."

onKeyDown={(e) => [Link] === 'Enter' && sendMessage()}

/>

<button onClick={sendMessage} disabled={isLoading}>

{isLoading ? 'Sending...' : 'Send'}

</button>

</div>

</div>

);

};

Quick Questions Feature

const quickQuestions = [

text: "How can I improve my heart health?",

❤️
icon: " "

},

text: "What foods boost brain function?",

🧠
icon: " "

},
{

text: "Best exercises for weight loss?",

💪
icon: " "

];

// Render quick questions

{[Link]((question, index) => (

<button

key={index}

onClick={() => sendMessage([Link])}

className="quick-question-btn"

>

{[Link]} {[Link]}

</button>

))}

Local Storage Integration

// Save chat history

const saveChatHistory = (messages: ChatMessage[]) => {

[Link]('ai_chat_history', [Link](messages));

};

// Load chat history

const loadChatHistory = (): ChatMessage[] => {

const saved = [Link]('ai_chat_history');


return saved ? [Link](saved) : [];

};

// Get health context from user data

const getHealthContext = (): HealthContext => {

const healthRecords = [Link]([Link]('health_records') || '[]');

const foodEntries = [Link]([Link]('food_entries') || '[]');

const workouts = [Link]([Link]('strength_workouts') || '[]');

return {

healthRecords,

foodEntries,

workoutHistory: workouts,

userProfile: {}

};

};

You might also like