Untitled

 avatar
unknown
plain_text
2 months ago
6.4 kB
3
Indexable
import json
import csv
import AdminModule as admin

GREEN = "\033[92m"
RED = "\033[91m"
BLUE = "\033[94m"
RESET = "\033[0m"

finance = {}

try:
    file = open("finance.json", "r")
    finance = json.load(file)
except FileNotFoundError:
    finance = {
        "income": 0,
        "expenses": {
            "food": 0,
            "transport": 0,
            "entertainment": 0
        },
        "remainingBalance": 0,
        "budget": 0
    }

def addExpenses(expType):
    found = False
    for key in finance["expenses"]:
        if expType == key:
            found = True
            try:
                expamount = int(input("Enter Your Expense Amount: "))
                finance["expenses"][key] += expamount
                income = finance["income"]
                finance["remainingBalance"] = income - sum(finance["expenses"].values())
                if sum(finance["expenses"].values()) > finance["budget"]:
                    print(f"{RED}Warning: You've exceeded your monthly budget!{RESET}")
                else:
                    print(f"{GREEN}Expense Successfully Added!{RESET}")
            except ValueError:
                print(f"{RED}Invalid amount entered! Please enter a number.{RESET}")
    if not found:
        print("Key is invalid")

def editExpenses():
    expType = input("Enter the Expense Type to Edit: ")
    if expType in finance["expenses"]:
        try:
            new_amount = int(input("Enter the New Expense Amount: "))
            finance["expenses"][expType] = new_amount
            finance["remainingBalance"] = finance["income"] - sum(finance["expenses"].values())
            # Check if the expenses exceed the budget after editing
            if sum(finance["expenses"].values()) > finance["budget"]:
                print(f"{RED}Warning: You've exceeded your monthly budget!{RESET}")
            else:
                print(f"{GREEN}Expense Successfully Updated!{RESET}")
        except ValueError:
            print(f"{RED}Invalid amount entered! Please enter a number.{RESET}")
    else:
        print(f"{RED}Expense type not found!{RESET}")

def setBudget():
    try:
        budget = int(input("Enter your monthly budget: "))
        finance["budget"] = budget
        print(f"{GREEN}Budget set to {budget}!{RESET}")
    except ValueError:
        print(f"{RED}Invalid amount entered! Please enter a number.{RESET}")

def loadFile():
    global finance
    try:
        with open("finance.json", "r") as file:
            finance = json.load(file)
            print(f"{GREEN}File successfully loaded!{RESET}")
    except FileNotFoundError:
        print(f"{RED}No file exists to load.{RESET}")

def saveFile():
    with open("finance.json", "w") as file:
        json.dump(finance, file, indent=4)
    print(f"{GREEN}Data saved successfully into finance.json!{RESET}")

def searchExpenses():
    expType = input("Enter keyword or amount to search for: ")
    if expType in finance["expenses"]:
            print(f"{GREEN}Category: {expType}, Amount: {finance['expenses'][expType]}{RESET}")
    else:
            print(f"{RED}No expense category {expType} found!{RESET}")

def DisplayReport():
    print(f"\n{GREEN}-- Financial Report --{RESET}")
    print(f"{BLUE}{'--------------------------------'}{RESET}")
    print(f"{GREEN}Income: {finance['income']}{RESET}")
    total_expenses = sum(finance["expenses"].values())
    print(f"{RED}Total Expenses: {total_expenses}{RESET}")
    print(f"{GREEN}Remaining Balance: {finance['remainingBalance']}{RESET}")
    if finance["budget"] > 0:
        if total_expenses > finance["budget"]:
            print(f"{RED}You have exceeded your budget!{RESET}")
        else:
            print(f"{GREEN}You are within your budget!{RESET}")
    else:
        print(f"{RED}No budget set!{RESET}")
    print(f"{BLUE}{'--------------------------------'}{RESET}")

def MonthlyReport():
    try:
        total_expenses = sum(finance["expenses"].values())
        with open("summary.csv", "w") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(["Category", "Amount"])
            writer.writerow(["Income", finance["income"]])
            for category, amount in finance["expenses"].items():
                writer.writerow([category, amount])
            writer.writerow(["Total Expenses", total_expenses])
            writer.writerow(["Remaining Balance", finance["remainingBalance"]])
            writer.writerow(["Monthly Budget", finance["budget"]])
        print(f"{GREEN}Monthly report generated successfully in summary.csv!{RESET}")
    except Exception:
        print(f"{RED}Error generating summary{RESET}")

while True:
    print(f"\n{RED} -- Welcome -- {RESET}")
    print(f"{BLUE} 1. Add Income {RESET}")
    print(f"{BLUE} 2. Add Expenses {RESET}")
    print(f"{BLUE} 3. Edit Expenses {RESET}")
    print(f"{BLUE} 4. Display Report {RESET}")
    print(f"{BLUE} 5. Generate Monthly Summary {RESET}")
    print(f"{BLUE} 6. Search Expenses {RESET}")
    print(f"{BLUE} 7. Load File {RESET}")
    print(f"{BLUE} 8. Save File {RESET}")
    print(f"{BLUE} 9. Set Monthly Budget {RESET}")
    print(f"{BLUE} 10. Admin Module {RESET}")
    choice = input(f"{GREEN} - Enter Your Choice or type 'exit': {RESET}")

    if choice == '1':
        try:
            income = int(input("Enter Your Income: "))
            finance["income"] = income
            finance["remainingBalance"] = income - sum(finance["expenses"].values())
            print(f"{GREEN}Income Successfully Added!{RESET}")
        except ValueError:
            print(f"{RED}Invalid amount entered! Please enter a number.{RESET}")

    elif choice == '2':
        expType = input("Enter Your Expense Type: ")
        addExpenses(expType)

    elif choice == '3':
        editExpenses()

    elif choice == '4':
        DisplayReport()

    elif choice == '5':
        MonthlyReport()

    elif choice == '6':
        searchExpenses()

    elif choice == '7':
        loadFile()

    elif choice == '8':
        saveFile()

    elif choice == '9':
        setBudget()

    elif choice == '10':
        admin.AdminMenu()

    elif choice == 'exit':
        print("Exiting..")
        break

    else:
        print(f"{RED}Invalid input. Try again.{RESET}")
Leave a Comment