Database Name: contact_manager.db (SQLite database)
SQLite is a file-based database, so you don't need to install a separate database server. The database file will be created automatically when you run the application for the first time.
First, create the following directory structure:
smart-contact-manager/
├── backend/
│ ├── app.py
│ ├── schema.sql
│ ├── config.py
│ └── requirements.txt
└── frontend/
├── public/
├── src/
│ ├── api/
│ │ └── config.js
└── package.jsonMake sure you have Python 3.8+ installed. You can check with:
python --versionCreate a virtual environment in the backend directory:
cd smart-contact-manager/backend
python -m venv venvActivate the virtual environment:
On Windows:
venv\Scripts\activateOn macOS/Linux:
source venv/bin/activateCreate a requirements.txt file with the following content:
Flask==2.2.3
Flask-Cors==3.0.10
Werkzeug==2.2.3
PyJWT==2.6.0
python-dotenv==1.0.0Install the required packages:
pip install -r requirements.txtCreate a config.py file in the backend directory:
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'your-secret-key-here'
DATABASE_PATH = os.path.join(os.path.dirname(__file__), 'contact_manager.db')
JWT_EXPIRATION_DAYS = 7
DEBUG = TrueSave the SQL schema from my previous response to schema.sql in the backend directory.
Create app.py in the backend directory:
from flask import Flask, jsonify, request, g
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
import os
from datetime import datetime, timedelta
import jwt
from functools import wraps
from config import Config
app = Flask(__name__)
CORS(app)
# Configuration
app.config.from_object(Config)
# Database helpers
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(app.config['DATABASE_PATH'])
db.row_factory = sqlite3.Row
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.executescript(f.read().decode('utf8'))
db.commit()
# Token verification decorator
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'Authorization' in request.headers:
auth_header = request.headers['Authorization']
token = auth_header.split(" ")[1] if len(auth_header.split(" ")) > 1 else None
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
db = get_db()
current_user = db.execute('SELECT * FROM users WHERE id = ?', (data['user_id'],)).fetchone()
except:
return jsonify({'message': 'Token is invalid'}), 401
return f(current_user, *args, **kwargs)
return decorated
# Authentication routes
@app.route('/api/auth/register', methods=['POST'])
def register():
data = request.get_json()
if not data or not data.get('email') or not data.get('password') or not data.get('name'):
return jsonify({'message': 'Missing required fields'}), 400
db = get_db()
# Check if user already exists
existing_user = db.execute('SELECT * FROM users WHERE email = ?', (data['email'],)).fetchone()
if existing_user:
return jsonify({'message': 'User already exists'}), 409
# Create new user
hashed_password = generate_password_hash(data['password'])
db.execute('''
INSERT INTO users (name, email, password, created_at)
VALUES (?, ?, ?, ?)
''', (
data['name'],
data['email'],
hashed_password,
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
))
db.commit()
return jsonify({'message': 'User registered successfully'}), 201
@app.route('/api/auth/login', methods=['POST'])
def login():
data = request.get_json()
if not data or not data.get('email') or not data.get('password'):
return jsonify({'message': 'Missing email or password'}), 400
db = get_db()
user = db.execute('SELECT * FROM users WHERE email = ?', (data['email'],)).fetchone()
if not user:
return jsonify({'message': 'User not found'}), 404
if check_password_hash(user['password'], data['password']):
# Generate token
token_expiry = datetime.now() + timedelta(days=app.config['JWT_EXPIRATION_DAYS'])
token = jwt.encode({
'user_id': user['id'],
'exp': token_expiry
}, app.config['SECRET_KEY'], algorithm="HS256")
return jsonify({
'token': token,
'user': {
'id': user['id'],
'name': user['name'],
'email': user['email'],
'profileImage': f"https://ui-avatars.com/api/?name={user['name'].replace(' ', '+')}&background=8B5CF6&color=fff",
}
}), 200
return jsonify({'message': 'Invalid password'}), 401
# Add more routes for contacts, messages, etc. here
# (Include the routes from the previous response)
# Initialize database if it doesn't exist
@app.before_first_request
def initialize_database():
if not os.path.exists(app.config['DATABASE_PATH']):
init_db()
# Command to initialize the database manually
@app.cli.command('init-db')
def initialize_db_command():
init_db()
print('Database initialized.')
if __name__ == '__main__':
app.run(debug=app.config['DEBUG'])Make sure you have Node.js (14+) and npm installed. You can check with:
node --version
npm --versionNavigate to the frontend directory:
cd smart-contact-manager/frontendCreate a new React app:
npx create-react-app .Install additional dependencies:
npm install axios react-router-dom chart.js react-chartjs-2Create or update src/api/config.js:
// API base URL - change this to match your backend server
export const API_URL = "http://localhost:5000";Create src/api/auth.js:
import { API_URL } from "./config";
export const register = async (userData) => {
try {
const response = await fetch(`${API_URL}/api/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Registration failed");
}
return data;
} catch (error) {
throw error;
}
};
export const login = async (credentials) => {
try {
const response = await fetch(`${API_URL}/api/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(credentials),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Login failed");
}
// Store token in localStorage
localStorage.setItem("token", data.token);
localStorage.setItem("user", JSON.stringify(data.user));
return data;
} catch (error) {
throw error;
}
};
export const logout = () => {
localStorage.removeItem("token");
localStorage.removeItem("user");
};
export const getAuthHeader = () => {
const token = localStorage.getItem("token");
return token ? { Authorization: `Bearer ${token}` } : {};
};
export const isAuthenticated = () => {
return localStorage.getItem("token") !== null;
};Create a .env file in the backend directory:
SECRET_KEY=your-super-secret-key-change-this-in-productionNavigate to the backend directory:
cd smart-contact-manager/backendActivate the virtual environment if not already activated:
On Windows:
venv\Scripts\activateOn macOS/Linux:
source venv/bin/activateInitialize the database (first time only):
flask init-dbStart the Flask server:
flask runThe server will run on http://localhost:5000
Navigate to the frontend directory:
cd smart-contact-manager/frontendStart the React development server:
npm startThe application will be available at http://localhost:3000
If you encounter CORS issues, make sure the Flask CORS is properly configured. You might need to update the CORS configuration in app.py:
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})If you have issues with the database:
Delete the database file and reinitialize:
rm contact_manager.db
flask init-dbCheck if SQLite is working properly:
sqlite3 contact_manager.db
.tables
.exitIf the frontend can't connect to the backend:
src/api/config.js matches your backend server addressFor production deployment:
DEBUG = False in config.pyUse a proper web server like Gunicorn for the backend:
pip install gunicorn
gunicorn app:appBuild the React app for production:
npm run buildThis setup provides a complete development environment for the Smart Contact Manager application with proper connections between the frontend, backend, and SQLite database. The application is ready for development and can be extended with additional features as needed.
i want mysql databse so give me all codes and tables relations and quries according t that and also give all functionalitie of project in flask with that database and connect that database and fronted backend give me final proper project and also giveme database name database table queires and setup of project with teck stack as ::
present forntend code in react and tailwind (next and .ts not allow)
backend : python flask
database :: mysql all daabse with querie
smart_contact_manager-- Create database
CREATE DATABASE IF NOT EXISTS smart_contact_manager;
USE smart_contact_manager;
-- Users table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
phone VARCHAR(20),
bio TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP
);
-- Categories table
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) UNIQUE NOT NULL
);
-- Insert default categories
INSERT INTO categories (name) VALUES
('friends'),
('family'),
('work'),
('college'),
('other');
-- Contacts table
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(100) NOT NULL,
number VARCHAR(20) NOT NULL,
email VARCHAR(100),
company VARCHAR(100),
category_id INT,
birthday DATE,
notes TEXT,
is_favorite BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL
);
-- Documents table
CREATE TABLE documents (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(100) NOT NULL,
description TEXT,
file_name VARCHAR(255) NOT NULL,
file_type VARCHAR(50),
file_size VARCHAR(20),
file_path VARCHAR(255),
icon VARCHAR(20) DEFAULT 'document',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
-- Messages table
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
contact_id INT NOT NULL,
content TEXT NOT NULL,
is_from_user BOOLEAN DEFAULT TRUE,
is_read BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (contact_id) REFERENCES contacts(id) ON DELETE CASCADE
);
-- Create indexes
CREATE INDEX idx_contacts_user_id ON contacts(user_id);
CREATE INDEX idx_documents_user_id ON documents(user_id);
CREATE INDEX idx_messages_user_contact ON messages(user_id, contact_id);smart-contact-manager/
├── backend/
│ ├── app.py
│ ├── config.py
│ ├── db_schema.sql
│ └── requirements.txt
└── frontend/
├── public/
├── src/
│ ├── api/
│ ├── components/
│ ├── pages/
│ ├── App.js
│ └── index.js
├── package.json
└── tailwind.config.jsCreate requirements.txt in the backend directory:
Flask==2.2.3
Flask-Cors==3.0.10
Werkzeug==2.2.3
PyJWT==2.6.0
python-dotenv==1.0.0
mysql-connector-python==8.0.32
python-decouple==3.8Create config.py in the backend directory:
from decouple import config
class Config:
SECRET_KEY = config('SECRET_KEY', default='your-secret-key-here')
DEBUG = config('DEBUG', default=True, cast=bool)
# MySQL Database Config
MYSQL_HOST = config('MYSQL_HOST', default='localhost')
MYSQL_USER = config('MYSQL_USER', default='root')
MYSQL_PASSWORD = config('MYSQL_PASSWORD', default='')
MYSQL_DB = config('MYSQL_DB', default='smart_contact_manager')
# JWT Config
JWT_EXPIRATION_DAYS = config('JWT_EXPIRATION_DAYS', default=7, cast=int)Create app.py in the backend directory:
from flask import Flask, jsonify, request, g
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
import mysql.connector
from mysql.connector import Error
import os
from datetime import datetime, timedelta
import jwt
from functools import wraps
from config import Config
app = Flask(__name__)
CORS(app)
# Configuration
app.config.from_object(Config)
# Database connection
def get_db():
if 'db' not in g:
g.db = mysql.connector.connect(
host=app.config['MYSQL_HOST'],
user=app.config['MYSQL_USER'],
password=app.config['MYSQL_PASSWORD'],
database=app.config['MYSQL_DB']
)
g.cursor = g.db.cursor(dictionary=True)
return g.db, g.cursor
@app.teardown_appcontext
def close_db(e=None):
db = g.pop('db', None)
cursor = g.pop('cursor', None)
if cursor:
cursor.close()
if db:
db.close()
def init_db():
try:
# Create database if it doesn't exist
conn = mysql.connector.connect(
host=app.config['MYSQL_HOST'],
user=app.config['MYSQL_USER'],
password=app.config['MYSQL_PASSWORD']
)
cursor = conn.cursor()
# Create database
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {app.config['MYSQL_DB']}")
conn.commit()
# Connect to the database
conn.database = app.config['MYSQL_DB']
# Read schema file
with open('db_schema.sql', 'r') as f:
sql_commands = f.read().split(';')
for command in sql_commands:
if command.strip():
cursor.execute(command)
conn.commit()
print("Database initialized successfully")
except Error as e:
print(f"Error initializing database: {e}")
finally:
if conn.is_connected():
cursor.close()
conn.close()
# Token verification decorator
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'Authorization' in request.headers:
auth_header = request.headers['Authorization']
token = auth_header.split(" ")[1] if len(auth_header.split(" ")) > 1 else None
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
db, cursor = get_db()
cursor.execute('SELECT * FROM users WHERE id = %s', (data['user_id'],))
current_user = cursor.fetchone()
if not current_user:
return jsonify({'message': 'User not found'}), 401
except Exception as e:
return jsonify({'message': 'Token is invalid', 'error': str(e)}), 401
return f(current_user, *args, **kwargs)
return decorated
# Authentication routes
@app.route('/api/auth/register', methods=['POST'])
def register():
data = request.get_json()
if not data or not data.get('email') or not data.get('password') or not data.get('name'):
return jsonify({'message': 'Missing required fields'}), 400
db, cursor = get_db()
# Check if user already exists
cursor.execute('SELECT * FROM users WHERE email = %s', (data['email'],))
existing_user = cursor.fetchone()
if existing_user:
return jsonify({'message': 'User already exists'}), 409
# Create new user
hashed_password = generate_password_hash(data['password'])
cursor.execute('''
INSERT INTO users (name, email, password)
VALUES (%s, %s, %s)
''', (
data['name'],
data['email'],
hashed_password
))
db.commit()
return jsonify({'message': 'User registered successfully'}), 201
@app.route('/api/auth/login', methods=['POST'])
def login():
data = request.get_json()
if not data or not data.get('email') or not data.get('password'):
return jsonify({'message': 'Missing email or password'}), 400
db, cursor = get_db()
cursor.execute('SELECT * FROM users WHERE email = %s', (data['email'],))
user = cursor.fetchone()
if not user:
return jsonify({'message': 'User not found'}), 404
if check_password_hash(user['password'], data['password']):
# Generate token
token_expiry = datetime.now() + timedelta(days=app.config['JWT_EXPIRATION_DAYS'])
token = jwt.encode({
'user_id': user['id'],
'exp': token_expiry.timestamp()
}, app.config['SECRET_KEY'], algorithm="HS256")
return jsonify({
'token': token,
'user': {
'id': user['id'],
'name': user['name'],
'email': user['email'],
'profileImage': f"https://ui-avatars.com/api/?name={user['name'].replace(' ', '+')}&background=8B5CF6&color=fff",
}
}), 200
return jsonify({'message': 'Invalid password'}), 401
# Contacts routes
@app.route('/api/contacts', methods=['GET'])
@token_required
def get_contacts(current_user):
db, cursor = get_db()
cursor.execute('''
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = %s
ORDER BY c.name
''', (current_user['id'],))
contacts = cursor.fetchall()
contact_list = []
for contact in contacts:
contact_data = {
'id': contact['id'],
'name': contact['name'],
'number': contact['number'],
'email': contact['email'],
'company': contact['company'],
'category': contact['category_name'] or 'other',
'birthday': contact['birthday'].strftime('%Y-%m-%d') if contact['birthday'] else None,
'notes': contact['notes'],
'isFavorite': bool(contact['is_favorite']),
'image': f"https://ui-avatars.com/api/?name={contact['name'].replace(' ', '+')}&background=8B5CF6&color=fff",
'createdDate': contact['created_at'].strftime('%d %b %Y')
}
contact_list.append(contact_data)
return jsonify(contact_list), 200
@app.route('/api/contacts', methods=['POST'])
@token_required
def add_contact(current_user):
data = request.get_json()
if not data or not data.get('name') or not data.get('number'):
return jsonify({'message': 'Missing required fields'}), 400
db, cursor = get_db()
# Get category_id
category_name = data.get('category', 'other')
cursor.execute('SELECT id FROM categories WHERE name = %s', (category_name,))
category = cursor.fetchone()
if not category:
# Create new category if it doesn't exist
cursor.execute('INSERT INTO categories (name) VALUES (%s)', (category_name,))
db.commit()
cursor.execute('SELECT id FROM categories WHERE name = %s', (category_name,))
category = cursor.fetchone()
cursor.execute('''
INSERT INTO contacts (
user_id, name, number, email, company,
category_id, birthday, notes, is_favorite
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
''', (
current_user['id'],
data['name'],
data['number'],
data.get('email', ''),
data.get('company', ''),
category['id'],
data.get('birthday', None),
data.get('notes', ''),
data.get('isFavorite', False)
))
db.commit()
return jsonify({'message': 'Contact added successfully'}), 201
@app.route('/api/contacts/<int:contact_id>', methods=['PUT'])
@token_required
def update_contact(current_user, contact_id):
data = request.get_json()
if not data:
return jsonify({'message': 'No data provided'}), 400
db, cursor = get_db()
# Verify contact belongs to user
cursor.execute('SELECT * FROM contacts WHERE id = %s AND user_id = %s',
(contact_id, current_user['id']))
contact = cursor.fetchone()
if not contact:
return jsonify({'message': 'Contact not found or unauthorized'}), 404
# Get category_id if provided
category_id = contact['category_id']
if 'category' in data:
category_name = data['category']
cursor.execute('SELECT id FROM categories WHERE name = %s', (category_name,))
category = cursor.fetchone()
if not category:
# Create new category if it doesn't exist
cursor.execute('INSERT INTO categories (name) VALUES (%s)', (category_name,))
db.commit()
cursor.execute('SELECT id FROM categories WHERE name = %s', (category_name,))
category = cursor.fetchone()
category_id = category['id']
# Update contact
query = '''
UPDATE contacts SET
name = %s,
number = %s,
email = %s,
company = %s,
category_id = %s,
birthday = %s,
notes = %s,
is_favorite = %s,
updated_at = NOW()
WHERE id = %s AND user_id = %s
'''
cursor.execute(query, (
data.get('name', contact['name']),
data.get('number', contact['number']),
data.get('email', contact['email']),
data.get('company', contact['company']),
category_id,
data.get('birthday', contact['birthday']),
data.get('notes', contact['notes']),
data.get('isFavorite', contact['is_favorite']),
contact_id,
current_user['id']
))
db.commit()
return jsonify({'message': 'Contact updated successfully'}), 200
@app.route('/api/contacts/<int:contact_id>', methods=['DELETE'])
@token_required
def delete_contact(current_user, contact_id):
db, cursor = get_db()
# Verify contact belongs to user
cursor.execute('SELECT * FROM contacts WHERE id = %s AND user_id = %s',
(contact_id, current_user['id']))
contact = cursor.fetchone()
if not contact:
return jsonify({'message': 'Contact not found or unauthorized'}), 404
cursor.execute('DELETE FROM contacts WHERE id = %s', (contact_id,))
db.commit()
return jsonify({'message': 'Contact deleted successfully'}), 200
# Documents routes
@app.route('/api/documents', methods=['GET'])
@token_required
def get_documents(current_user):
db, cursor = get_db()
cursor.execute('''
SELECT * FROM documents WHERE user_id = %s ORDER BY name
''', (current_user['id'],))
documents = cursor.fetchall()
document_list = []
for doc in documents:
document_data = {
'id': doc['id'],
'name': doc['name'],
'description': doc['description'],
'fileName': doc['file_name'],
'fileType': doc['file_type'],
'fileSize': doc['file_size'],
'uploadDate': doc['created_at'].strftime('%Y-%m-%d'),
'icon': doc['icon']
}
document_list.append(document_data)
return jsonify(document_list), 200
# Messages routes
@app.route('/api/messages/<int:contact_id>', methods=['GET'])
@token_required
def get_messages(current_user, contact_id):
db, cursor = get_db()
# Verify contact belongs to user
cursor.execute('SELECT * FROM contacts WHERE id = %s AND user_id = %s',
(contact_id, current_user['id']))
contact = cursor.fetchone()
if not contact:
return jsonify({'message': 'Contact not found or unauthorized'}), 404
cursor.execute('''
SELECT * FROM messages
WHERE user_id = %s AND contact_id = %s
ORDER BY created_at
''', (current_user['id'], contact_id))
messages = cursor.fetchall()
message_list = []
for msg in messages:
message_data = {
'id': msg['id'],
'sender': 'user' if msg['is_from_user'] else 'contact',
'text': msg['content'],
'timestamp': msg['created_at'].strftime('%I:%M %p') if msg['created_at'].date() == datetime.now().date() else msg['created_at'].strftime('%b %d, %Y')
}
message_list.append(message_data)
return jsonify(message_list), 200
# Calendar routes
@app.route('/api/calendar/birthdays', methods=['GET'])
@token_required
def get_birthdays(current_user):
db, cursor = get_db()
cursor.execute('''
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = %s AND c.birthday IS NOT NULL
ORDER BY MONTH(c.birthday), DAY(c.birthday)
''', (current_user['id'],))
contacts = cursor.fetchall()
birthday_list = []
for contact in contacts:
birthday_data = {
'id': contact['id'],
'name': contact['name'],
'birthday': contact['birthday'].strftime('%Y-%m-%d'),
'category': contact['category_name'] or 'other',
'image': f"https://ui-avatars.com/api/?name={contact['name'].replace(' ', '+')}&background=8B5CF6&color=fff",
}
birthday_list.append(birthday_data)
return jsonify(birthday_list), 200
# Initialize database command
@app.cli.command('init-db')
def initialize_db_command():
init_db()
print('Database initialized.')
if __name__ == '__main__':
app.run(debug=app.config['DEBUG'])Create .env file in the backend directory:
SECRET_KEY=your-super-secret-key-change-this-in-production
DEBUG=True
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=your_mysql_password
MYSQL_DB=smart_contact_manager
JWT_EXPIRATION_DAYS=7npx create-react-app frontend
cd frontend
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -pUpdate tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx}",
"./public/index.html",
],
theme: {
extend: {
colors: {
purple: {
50: "#f5f3ff",
100: "#ede9fe",
200: "#ddd6fe",
300: "#c4b5fd",
400: "#a78bfa",
500: "#8b5cf6",
600: "#7c3aed",
700: "#6d28d9",
800: "#5b21b6",
900: "#4c1d95",
},
},
},
},
plugins: [],
}Create or update src/index.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
margin: 0;
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell",
"Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #f9fafb;
}
.animate-fade-in {
animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-scale {
transition: transform 0.3s ease;
}
.animate-scale:hover {
transform: scale(1.03);
}Create src/api/config.js:
export const API_URL = "http://localhost:5000";Create src/api/auth.js:
import { API_URL } from "./config";
export const register = async (userData) => {
try {
const response = await fetch(`${API_URL}/api/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Registration failed");
}
return data;
} catch (error) {
throw error;
}
};
export const login = async (credentials) => {
try {
const response = await fetch(`${API_URL}/api/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(credentials),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Login failed");
}
// Store token in localStorage
localStorage.setItem("token", data.token);
localStorage.setItem("user", JSON.stringify(data.user));
return data;
} catch (error) {
throw error;
}
};
export const logout = () => {
localStorage.removeItem("token");
localStorage.removeItem("user");
};
export const getAuthHeader = () => {
const token = localStorage.getItem("token");
return token ? { Authorization: `Bearer ${token}` } : {};
};
export const isAuthenticated = () => {
return localStorage.getItem("token") !== null;
};Create src/api/contacts.js:
import { API_URL } from "./config";
import { getAuthHeader } from "./auth";
export const getContacts = async () => {
try {
const response = await fetch(`${API_URL}/api/contacts`, {
method: "GET",
headers: {
...getAuthHeader(),
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to fetch contacts");
}
return data;
} catch (error) {
throw error;
}
};
export const addContact = async (contactData) => {
try {
const response = await fetch(`${API_URL}/api/contacts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...getAuthHeader(),
},
body: JSON.stringify(contactData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to add contact");
}
return data;
} catch (error) {
throw error;
}
};
export const updateContact = async (contactId, contactData) => {
try {
const response = await fetch(`${API_URL}/api/contacts/${contactId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
...getAuthHeader(),
},
body: JSON.stringify(contactData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to update contact");
}
return data;
} catch (error) {
throw error;
}
};
export const deleteContact = async (contactId) => {
try {
const response = await fetch(`${API_URL}/api/contacts/${contactId}`, {
method: "DELETE",
headers: {
...getAuthHeader(),
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to delete contact");
}
return data;
} catch (error) {
throw error;
}
};CREATE DATABASE smart_contact_manager;
CREATE USER 'contact_manager'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON smart_contact_manager.* TO 'contact_manager'@'localhost';
FLUSH PRIVILEGES;db_schema.sql in the backend directorycd backend
python -m venv venvActivate the virtual environment:
venv\Scripts\activatesource venv/bin/activatepip install -r requirements.txt.env file with your MySQL credentialsflask init-dbflask runcd frontend
npm installnpm start-- Create a new user
INSERT INTO users (name, email, password) VALUES (?, ?, ?);
-- Get user by email
SELECT * FROM users WHERE email = ?;
-- Update user profile
UPDATE users SET name = ?, phone = ?, bio = ?, updated_at = NOW() WHERE id = ?;-- Get all contacts for a user
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ?
ORDER BY c.name;
-- Get favorite contacts
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ? AND c.is_favorite = TRUE
ORDER BY c.name;
-- Search contacts
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ? AND
(c.name LIKE ? OR c.email LIKE ? OR c.number LIKE ?)
ORDER BY c.name;
-- Get contacts by category
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ? AND cat.name = ?
ORDER BY c.name;
-- Get upcoming birthdays
SELECT c.*, cat.name as category_name
FROM contacts c
LEFT JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ? AND c.birthday IS NOT NULL
ORDER BY
CASE
WHEN MONTH(c.birthday) > MONTH(CURDATE()) OR
(MONTH(c.birthday) = MONTH(CURDATE()) AND DAY(c.birthday) >= DAY(CURDATE()))
THEN 0
ELSE 1
END,
MONTH(c.birthday),
DAY(c.birthday)
LIMIT 10;-- Add a new document
INSERT INTO documents (user_id, name, description, file_name, file_type, file_size, file_path, icon)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
-- Get all documents for a user
SELECT * FROM documents WHERE user_id = ? ORDER BY created_at DESC;
-- Delete a document
DELETE FROM documents WHERE id = ? AND user_id = ?;-- Get all messages between user and contact
SELECT * FROM messages
WHERE user_id = ? AND contact_id = ?
ORDER BY created_at;
-- Send a new message
INSERT INTO messages (user_id, contact_id, content, is_from_user)
VALUES (?, ?, ?, ?);
-- Mark messages as read
UPDATE messages
SET is_read = TRUE
WHERE user_id = ? AND contact_id = ? AND is_from_user = FALSE;
-- Get unread message count
SELECT COUNT(*) as unread_count
FROM messages
WHERE user_id = ? AND is_read = FALSE AND is_from_user = FALSE;-- Contact distribution by category
SELECT cat.name, COUNT(c.id) as count
FROM contacts c
JOIN categories cat ON c.category_id = cat.id
WHERE c.user_id = ?
GROUP BY cat.name;
-- Monthly contact additions
SELECT
YEAR(created_at) as year,
MONTH(created_at) as month,
COUNT(*) as count
FROM contacts
WHERE user_id = ?
GROUP BY YEAR(created_at), MONTH(created_at)
ORDER BY YEAR(created_at), MONTH(created_at);
-- Birthday distribution by month
SELECT
MONTH(birthday) as month,
COUNT(*) as count
FROM contacts
WHERE user_id = ? AND birthday IS NOT NULL
GROUP BY MONTH(birthday)
ORDER BY MONTH(birthday);Database Backup and Restore
To backup the database:
mysqldump -u root -p smart_contact_manager > backup.sqlTo restore the database:
mysql -u root -p smart_contact_manager < backup.sqlProduction Deployment
For production deployment:
DEBUG=False in the .env filenpm run buildSecurity Considerations
This setup provides a complete development environment for the Smart Contact Manager application with proper connections between the React frontend, Flask backend, and MySQL database. The application is ready for development and can be extended with additional features as needed.
the frontend which exists there in my folder access that only and give me proper flask python code to register and login the user in the my sql database having user table and then create a relation of user and contacts and after adding new contact it should get added in contacts table make this for the existing frontned remove that frontend created by you
You can send messages while the preview loads