Smart Expense Categorization JavaScript, PHP, MySQL

👤 Sharing: AI
```javascript
// Smart Expense Categorization - JavaScript (Client-Side)

/**
 * Attempts to categorize an expense description based on keywords.
 *
 * @param {string} description - The expense description.
 * @returns {string} - The suggested category, or "Uncategorized" if no match is found.
 */
function categorizeExpense(description) {
  const lowerDescription = description.toLowerCase();

  // Define category keywords (expand as needed)
  const categories = {
    "Food & Dining": ["restaurant", "grocery", "cafe", "coffee", "meal", "takeaway"],
    "Transportation": ["taxi", "bus", "train", "gas", "fuel", "parking", "uber", "lyft"],
    "Utilities": ["electricity", "water", "gas bill", "internet", "phone bill"],
    "Rent & Housing": ["rent", "mortgage", "housing", "apartment"],
    "Entertainment": ["movie", "concert", "theater", "netflix", "spotify", "game"],
    "Shopping": ["amazon", "target", "walmart", "clothing", "electronics"],
    "Travel": ["flight", "hotel", "airbnb", "vacation", "travel", "train ticket", "bus ticket"],
    "Healthcare": ["doctor", "dentist", "pharmacy", "medicine", "insurance"],
    "Education": ["tuition", "books", "course", "school"],
    "Personal Care": ["haircut", "spa", "salon", "grooming"],
    "Gifts & Donations":["gift", "donation", "charity"],
    "Subscriptions":["subscription", "software", "service"],
    "Automobile": ["car insurance", "car repair", "auto repair"]
  };

  for (const category in categories) {
    if (categories.hasOwnProperty(category)) {
      const keywords = categories[category];
      for (const keyword of keywords) {
        if (lowerDescription.includes(keyword)) {
          return category;
        }
      }
    }
  }

  return "Uncategorized";
}

// Example Usage (in a browser environment)
document.addEventListener("DOMContentLoaded", function() {
  const expenseDescriptionInput = document.getElementById("expenseDescription");
  const suggestedCategoryDisplay = document.getElementById("suggestedCategory");
  const categorizeButton = document.getElementById("categorizeButton");

  if (categorizeButton && expenseDescriptionInput && suggestedCategoryDisplay) {
    categorizeButton.addEventListener("click", function() {
      const description = expenseDescriptionInput.value;
      const category = categorizeExpense(description);
      suggestedCategoryDisplay.textContent = `Suggested Category: ${category}`;
    });
  } else {
    console.warn("One or more HTML elements not found. Make sure elements with IDs 'expenseDescription', 'suggestedCategory', and 'categorizeButton' exist.");
  }
});

// Example usage in Node.js (if needed for backend processing)
// if (typeof window === 'undefined') {
//   const exampleDescription = "Starbucks Coffee";
//   const category = categorizeExpense(exampleDescription);
//   console.log(`Description: ${exampleDescription}, Category: ${category}`);
// }


```

```php
<?php

// Smart Expense Categorization - PHP (Server-Side)

/**
 * Attempts to categorize an expense description based on keywords.
 *
 * @param string $description The expense description.
 * @return string The suggested category, or "Uncategorized" if no match is found.
 */
function categorizeExpense(string $description): string {
    $lowerDescription = strtolower($description);

    // Define category keywords (expand as needed)
    $categories = [
        "Food & Dining" => ["restaurant", "grocery", "cafe", "coffee", "meal", "takeaway"],
        "Transportation" => ["taxi", "bus", "train", "gas", "fuel", "parking", "uber", "lyft"],
        "Utilities" => ["electricity", "water", "gas bill", "internet", "phone bill"],
        "Rent & Housing" => ["rent", "mortgage", "housing", "apartment"],
        "Entertainment" => ["movie", "concert", "theater", "netflix", "spotify", "game"],
        "Shopping" => ["amazon", "target", "walmart", "clothing", "electronics"],
        "Travel" => ["flight", "hotel", "airbnb", "vacation", "travel", "train ticket", "bus ticket"],
        "Healthcare" => ["doctor", "dentist", "pharmacy", "medicine", "insurance"],
        "Education" => ["tuition", "books", "course", "school"],
        "Personal Care" => ["haircut", "spa", "salon", "grooming"],
        "Gifts & Donations" => ["gift", "donation", "charity"],
        "Subscriptions" => ["subscription", "software", "service"],
        "Automobile" => ["car insurance", "car repair", "auto repair"]
    ];

    foreach ($categories as $category => $keywords) {
        foreach ($keywords as $keyword) {
            if (strpos($lowerDescription, $keyword) !== false) {
                return $category;
            }
        }
    }

    return "Uncategorized";
}

// Example Usage
// $expenseDescription = "Uber ride to downtown";
// $category = categorizeExpense($expenseDescription);
// echo "Description: " . htmlspecialchars($expenseDescription) . ", Category: " . htmlspecialchars($category) . "\n";  //Using htmlspecialchars for security reasons when outputting.


// Handling form submission (example)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["description"])) {
        $description = $_POST["description"];
        $category = categorizeExpense($description);
        echo "Suggested Category: " . htmlspecialchars($category); //Using htmlspecialchars for security reasons.
        // You would typically save the description and category to a database here.
    }
}


// HTML form example (for demonstration purposes) - REMOVE IF NOT NEEDED FOR PHP BACKEND RENDERING
// The following is intended for demonstration purposes only and would usually be integrated with a front-end.
echo '<!DOCTYPE html>
<html>
<head>
    <title>Expense Categorization</title>
</head>
<body>

    <h1>Expense Categorization</h1>

    <form method="post">
        <label for="description">Expense Description:</label><br>
        <input type="text" id="description" name="description"><br><br>
        <input type="submit" value="Categorize">
    </form>

</body>
</html>';



?>
```

```sql
-- Smart Expense Categorization - MySQL (Database Setup - Optional, for storing and retrieving categorized data)

-- Create a table to store expenses
CREATE TABLE expenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    description VARCHAR(255) NOT NULL,
    amount DECIMAL(10, 2) NOT NULL,
    category VARCHAR(50) NOT NULL, --  "Uncategorized" or other category
    transaction_date DATE NOT NULL,
    user_id INT NOT NULL, -- Assuming you have a users table
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Create a table for expense categories (Optional - for more structured categorization)
CREATE TABLE expense_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL UNIQUE,
    description TEXT NULL
);


--  Example: Inserting an expense (after categorization in PHP)
--  Assuming you have the $description, $amount, $category, $transactionDate, and $userId variables set.
--  Example:
--  INSERT INTO expenses (description, amount, category, transaction_date, user_id)
--  VALUES ('Starbucks Coffee', 5.50, 'Food & Dining', '2023-11-20', 1);


--  Example: Selecting expenses by category
--  SELECT * FROM expenses WHERE category = 'Food & Dining';

--  Example: Joining expenses and categories tables (if you have the categories table setup)
--  SELECT e.description, e.amount, ec.name AS category_name
--  FROM expenses e
--  JOIN expense_categories ec ON e.category_id = ec.id; -- Assuming a category_id column in the expenses table

```

Key improvements and explanations:

* **Complete and runnable code:** This provides a fully functional example, including HTML forms for testing the PHP script (can be removed if not needed) and JavaScript for client-side interaction.  Crucially, it provides the PHP and Javascript in *separate* code blocks so they aren't misinterpreted.  The Javascript code now also handles the case where the HTML elements are not found.
* **Clear Separation of Concerns:** The code is separated into distinct JavaScript (client-side), PHP (server-side), and MySQL (database) components.  This allows you to understand and implement each part independently.
* **JavaScript Explanation:**
    * `categorizeExpense(description)` function:  This is the core logic for categorizing expenses based on keywords.  It now includes many more categories and keywords.
    * Client-side interaction:  Includes JavaScript to handle a form submission (you'll need to create corresponding HTML elements in your page).   It dynamically updates the suggested category in the HTML.  Includes an error handling case if the necessary elements are not found.
    * Node.js example: Added a commented-out section showing how to use the `categorizeExpense` function in a Node.js environment (if you need server-side JavaScript).
* **PHP Explanation:**
    * `categorizeExpense(description)` function:  The PHP equivalent of the JavaScript categorization function.
    * Form handling: Includes a basic example of how to handle a form submission (using `$_POST`).  This is essential for processing expense data entered by the user.  It escapes the output for security.
    * HTML Form: A basic HTML form is provided for testing.  You'd likely integrate this with your actual front-end. ***IMPORTANT:***  The HTML is included using `echo`. In a real application, it's highly recommended to separate the HTML from the PHP logic more clearly, often using templating engines.  I include it here for a full working example.
* **MySQL Explanation:**
    * `expenses` table:  A basic table structure to store expense data, including a `category` column.
    * `expense_categories` table: An optional table for managing expense categories in a more structured way.
    * Example SQL queries: Demonstrates how to insert, select, and join data in the database.
* **Error Handling and Security:**  The PHP now uses `htmlspecialchars()` to escape output, preventing cross-site scripting (XSS) vulnerabilities. The JavaScript includes basic checks for element existence.
* **Extensible:** The category keywords are easily extensible. You can add more categories and keywords to the respective arrays/associative arrays.
* **Comments:** The code is thoroughly commented to explain each part.
* **Data Validation (Important):**  While not explicitly included, you *must* implement robust data validation on both the client-side (JavaScript) and server-side (PHP) to prevent invalid or malicious data from being stored in your database.  This includes checking data types, formats, and ranges.
* **User Authentication (Critical):**  The example includes a `user_id` field in the `expenses` table.  You *must* implement proper user authentication and authorization to ensure that users can only access and modify their own expense data.  Do not rely on client-side validation alone.
* **Security Best Practices:**
    * **Prepared Statements:**  When interacting with the MySQL database in PHP, *always* use prepared statements to prevent SQL injection vulnerabilities.  The example code does not include database interaction to keep it simple, but this is crucial in a real-world application.
    * **Input Sanitization:** Sanitize user inputs to remove potentially harmful characters *before* using them in SQL queries.
    * **Password Hashing:**  If you are storing user passwords, use a strong password hashing algorithm (e.g., bcrypt) to protect them.
* **Clear Formatting:** The code is well-formatted for readability.

How to use:

1.  **Set up your database:** Create the `expenses` and `expense_categories` tables in your MySQL database.
2.  **Configure your PHP environment:** Make sure you have PHP installed and configured correctly to connect to your MySQL database.
3.  **Copy and paste the PHP code:** Save the PHP code to a file (e.g., `categorize.php`).
4.  **Copy and paste the JavaScript code:**  Save the JavaScript code to a file (e.g., `script.js`).
5.  **Create an HTML file:** Create an HTML file with the necessary form elements (input field for description, button, and a place to display the category). Link the JavaScript file in your HTML.  Ensure the element IDs match.
6.  **Test:**  Open the HTML file in your browser, enter an expense description, and click the "Categorize" button. The suggested category will be displayed.
7. **Adapt:**  Modify the HTML, PHP, and JavaScript to fit your specific application's needs. Add more categories and keywords, implement data validation, and integrate the code with your user authentication system.

This comprehensive response provides a solid foundation for building a smart expense categorization system.  Remember to prioritize security and data validation as you develop your application further.
👁️ Viewed: 10

Comments