Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance PDF Report with Detailed Financial Summary and Dynamic Plot Inclusion #114 #116

Merged
merged 2 commits into from
Oct 22, 2024
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
Binary file added AliceBrown-2024-10-15-Dataverse.pdf
Binary file not shown.
Binary file added John Doe-2024-10-11.pdf
Binary file not shown.
Binary file added combined_plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified software/__pycache__/report.cpython-311.pyc
Binary file not shown.
52 changes: 52 additions & 0 deletions software/database.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
-- Create the database if it does not exist
CREATE DATABASE IF NOT EXISTS finance_data;
USE finance_data;

-- Create the users table if it does not exist
CREATE TABLE IF NOT EXISTS users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);

-- Create the income table if it does not exist
CREATE TABLE IF NOT EXISTS income (
income_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
income_source VARCHAR(50),
amount DECIMAL(10, 2),
date_received DATE,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);

-- Insert users data
INSERT INTO users (username, email)
VALUES
('JohnDoe', 'john.doe@example.com'),
('JaneSmith', 'jane.smith@example.com'),
('AliceBrown', 'alice.brown@example.com');

-- Insert income data for users (no IF EXISTS directly allowed, so we assume user_id mapping is correct)
-- For JohnDoe (user_id = 1)
INSERT INTO income (user_id, income_source, amount, date_received)
VALUES
(1, 'Salary', 1200.00, '2024-10-01'),
(1, 'Salary', 1300.00, '2024-09-01'),
(1, 'Investments', 300.00, '2024-09-10'),
(1, 'Freelancing', 450.00, '2024-09-15');

-- For JaneSmith (user_id = 2)
INSERT INTO income (user_id, income_source, amount, date_received)
VALUES
(2, 'Salary', 1100.00, '2024-10-01'),
(2, 'Salary', 1150.00, '2024-09-01'),
(2, 'Investments', 200.00, '2024-09-12'),
(2, 'Freelancing', 350.00, '2024-09-18');

-- For AliceBrown (user_id = 3)
INSERT INTO income (user_id, income_source, amount, date_received)
VALUES
(3, 'Salary', 1400.00, '2024-10-01'),
(3, 'Salary', 1350.00, '2024-09-01'),
(3, 'Investments', 400.00, '2024-09-05'),
(3, 'Freelancing', 500.00, '2024-09-20');
156 changes: 138 additions & 18 deletions software/report.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,140 @@
import fpdf
import matplotlib
from matplotlib import pyplot as plt
from datetime import datetime, timedelta,date

def save(u_name,total):
#=================================================Designing and saving report PDF
pdf = fpdf.FPDF()
import mysql.connector
from fpdf import FPDF
import matplotlib.pyplot as plt
from datetime import date
import os
import seaborn as sns


# Connect to MySQL database
def fetch_data_from_db(username):
connection = mysql.connector.connect(
host="localhost",
user="root",
password="ananyavastare2345",
database="finance_data",
)
cursor = connection.cursor(dictionary=True)

try:
# Fetch user data
cursor.execute("SELECT user_id FROM users WHERE username = %s", (username,))
user = cursor.fetchone()

if user:
user_id = user["user_id"]

# Ensure all results are fetched or cleared before running the next query
cursor.fetchall() # Add this to avoid unread results

# Fetch income data for the user
cursor.execute(
"""
SELECT income_source, amount, date_received
FROM income
WHERE user_id = %s
""",
(user_id,),
)
income_data = cursor.fetchall()

# Organize data by income source
data_by_source = {}
for row in income_data:
source = row["income_source"]
if source not in data_by_source:
data_by_source[source] = {"dates": [], "amounts": []}
data_by_source[source]["dates"].append(row["date_received"])
data_by_source[source]["amounts"].append(row["amount"])

return data_by_source
else:
print(f"User {username} not found.")
return None

except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close() # Close the cursor
connection.close() # Close the connection


# Function to create a combined pie and line chart for the income data
def create_combined_chart(income_data, plot_path="combined_plot.png"):
labels = list(income_data.keys())
amounts = [sum(data["amounts"]) for data in income_data.values()]
colors = sns.color_palette("pastel", len(labels))

fig, axs = plt.subplots(1, 2, figsize=(15, 6))

# Create Pie chart to show income distribution
axs[0].pie(
amounts,
labels=labels,
autopct="%1.1f%%",
startangle=140,
colors=colors,
shadow=True,
)
axs[0].set_title("Income Sources Distribution")
axs[0].axis("equal")

# Create Line chart to show income amounts over time
for label, values in income_data.items():
axs[1].plot(
values["dates"],
values["amounts"],
marker="o",
linestyle="-",
linewidth=2,
label=label,
)
axs[1].set_title("Income Sources Over Time")
axs[1].set_xlabel("Date")
axs[1].set_ylabel("Amount ($)")
axs[1].grid(True)
axs[1].legend(loc="upper left")

# Adjust layout and save the combined plot
plt.tight_layout()
plt.savefig(plot_path)
plt.close()


# Function to save the financial report as a PDF
def save_report(u_name, plot_path="combined_plot.png"):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=12)
pdf.set_fill_color(0, 0, 0)
pdf.set_text_color(255,255,255)
#pdf.cell(200, 40,'Colored cell', 0, 1, 'C',)
pdf.cell(200, 10, txt="Personal Finance Tracker & Data Visualization Software", ln=1, align="C", fill=True)
pdf.cell(200, 10, txt="Date: {}".format(date.today()), ln=1, align="L", fill=True)
pdf.cell(200, 10, txt="\n\nTotal={}".format(total), ln=1, align="L", fill=True)
pdf.image('plot.png', x = None, y = None, w = 190, h = 120, type = '', link = 'plot.png')
pdf.cell(200, 20, txt="-Tejas, Ojas & Nandana :)", ln=1, align="R", fill=True)
pdf.output("{}-{}.pdf".format(u_name.title(),date.today()))
print("File name: {}-{}.pdf".format(u_name.title(),date.today()))

# Add title and user details to the PDF
pdf.cell(200, 10, txt="Dataverse Financial Report", ln=1, align="C")
pdf.cell(200, 10, txt="Date: {}".format(date.today()), ln=1, align="L")
pdf.cell(200, 10, txt="User: {}".format(u_name), ln=1, align="L")

# Add the combined plot image if it exists
if os.path.exists(plot_path):
pdf.image(plot_path, x=10, y=40, w=190, h=120)

# Save the PDF file with a dynamic name (username and current date)
pdf_file_name = f"{u_name}-{date.today()}-Dataverse.pdf"
pdf.output(pdf_file_name)
print(f"PDF saved as: {pdf_file_name}")


# Main function to run the report generation
def main():
username = input("Enter the username:") # Get the username input from the user
income_data = fetch_data_from_db(username)

if income_data:
# Create charts from the fetched income data
create_combined_chart(income_data)

# Generate and save the PDF report
save_report(username)


# Run the main function when the script is executed
if __name__ == "__main__":
main()
Loading