Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router";
import axios from "axios";
import "./BillingModule.css";

const BillingModule = () => {
  const [expenses, setExpenses] = useState([]);
  const [expenseType, setExpenseType] = useState("");
  const [amount, setAmount] = useState("");
  const [grossTotal, setGrossTotal] = useState(0);
  const [objectId, setObjectId] = useState("");
  const [name, setName] = useState("");

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const params = new URLSearchParams(location.search);
    setObjectId(params.get("objectId"));
    setName(params.get("name"));
  }, [location.search]);

  const handleAddExpense = () => {
    if (expenseType && amount) {
      const newExpense = {
        expenseType,
        amount: parseFloat(amount),
      };

      setExpenses([...expenses, newExpense]);
      setExpenseType("");
      setAmount("");
    }
  };

  const handleDeleteExpense = (index) => {
    const updatedExpenses = [...expenses];
    updatedExpenses.splice(index, 1);
    setExpenses(updatedExpenses);
  };

  const calculateGrossTotal = () => {
    const total = expenses.reduce((acc, expense) => acc + expense.amount, 0);
    setGrossTotal(total);
  };

  const handleFinish = async () => {
    const expensesArray = [];
  
    // Add expenses to the array
    expenses.forEach((expense) => {
      const { expenseType, amount } = expense;
      expensesArray.push({ expenseType, amount });
    });
  
    const data = {
      name,
      objectId,
      expenses: expensesArray,
      grossTotal,
    };
  
    console.log("Post Data:", data); // Print the post data in the console
  
    try {
      const response = await axios.post("/api/admin/billing", data);
      if (response.status === 200) {
        navigate("/success");
      } else {
        throw new Error("Failed to complete the process");
      }
    } catch (error) {
      console.error(error);
    }
  };
  

  return (
    <div className="billing-container">
      {objectId && name ? (
        <div>
          <h1 className="hospital-name">SEVASADAN LIFELINE</h1>
          <h2 className="patient-info">Patient Name: {name}</h2>
          <h2 className="patient-info">Patient ID: {objectId}</h2>
        </div>
      ) : (
        <p>No patient information found.</p>
      )}
      <div className="add-expense">
        <h3>Add Expense</h3>
        <div className="input-group">
          <label htmlFor="expenseType">Expense Type:</label>
          <input
            type="text"
            id="expenseType"
            value={expenseType}
            onChange={(e) => setExpenseType(e.target.value)}
          />
        </div>
        <div className="input-group">
          <label htmlFor="amount">Amount:</label>
          <input
            type="number"
            id="amount"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
          />
        </div>
        <button className="add-expense-btn" onClick={handleAddExpense}>
          Add Expense
        </button>
      </div>
      <div className="expense-list">
        <h3>Expenses</h3>
        <table className="expense-table">
          <thead>
            <tr>
              <th>Expense Type</th>
              <th>Amount</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {expenses.map((expense, index) => (
              <tr key={index}>
                <td>{expense.expenseType}</td>
                <td>{expense.amount}</td>
                <td>
                  <button
                    className="delete-expense-btn"
                    onClick={() => handleDeleteExpense(index)}
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="gross-total">
        <h3>Gross Total: {grossTotal}</h3>
        <button className="calculate-total-btn" onClick={calculateGrossTotal}>
          Calculate Gross Total
        </button>
      </div>
      <button className="finish-btn" onClick={handleFinish}>
        Finish
      </button>
    </div>
  );
};

export default BillingModule;
const billingSchema = new mongoose.Schema({
  name: String,
  objectId: String,
  expenses: [{ expenseType: String, amount: Number }],
  grossTotal: Number,
});

const Billing = mongoose.model("Billing", billingSchema);<pre>import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router";
import axios from "axios";
import "./BillingModule.css";

const BillingModule = () => {
  const [expenses, setExpenses] = useState([]);
  const [expenseType, setExpenseType] = useState("");
  const [amount, setAmount] = useState("");
  const [grossTotal, setGrossTotal] = useState(0);
  const [objectId, setObjectId] = useState("");
  const [name, setName] = useState("");

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const params = new URLSearchParams(location.search);
    setObjectId(params.get("objectId"));
    setName(params.get("name"));
  }, [location.search]);

  const handleAddExpense = () => {
    if (expenseType && amount) {
      const newExpense = {
        expenseType,
        amount: parseFloat(amount),
      };

      setExpenses([...expenses, newExpense]);
      setExpenseType("");
      setAmount("");
    }
  };

  const handleDeleteExpense = (index) => {
    const updatedExpenses = [...expenses];
    updatedExpenses.splice(index, 1);
    setExpenses(updatedExpenses);
  };

  const calculateGrossTotal = () => {
    const total = expenses.reduce((acc, expense) => acc + expense.amount, 0);
    setGrossTotal(total);
  };

  const handleFinish = async () => {
    const expensesArray = [];
  
    // Add expenses to the array
    expenses.forEach((expense) => {
      const { expenseType, amount } = expense;
      expensesArray.push({ expenseType, amount });
    });
  
    const data = {
      name,
      objectId,
      expenses: expensesArray,
      grossTotal,
    };
  
    console.log("Post Data:", data); // Print the post data in the console
  
    try {
      const response = await axios.post("/api/admin/billing", data);
      if (response.status === 200) {
        navigate("/success");
      } else {
        throw new Error("Failed to complete the process");
      }
    } catch (error) {
      console.error(error);
    }
  };
  

  return (
    <div className="billing-container">
      {objectId && name ? (
        <div>
          <h1 className="hospital-name">SEVASADAN LIFELINE</h1>
          <h2 className="patient-info">Patient Name: {name}</h2>
          <h2 className="patient-info">Patient ID: {objectId}</h2>
        </div>
      ) : (
        <p>No patient information found.</p>
      )}
      <div className="add-expense">
        <h3>Add Expense</h3>
        <div className="input-group">
          <label htmlFor="expenseType">Expense Type:</label>
          <input
            type="text"
            id="expenseType"
            value={expenseType}
            onChange={(e) => setExpenseType(e.target.value)}
          />
        </div>
        <div className="input-group">
          <label htmlFor="amount">Amount:</label>
          <input
            type="number"
            id="amount"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
          />
        </div>
        <button className="add-expense-btn" onClick={handleAddExpense}>
          Add Expense
        </button>
      </div>
      <div className="expense-list">
        <h3>Expenses</h3>
        <table className="expense-table">
          <thead>
            <tr>
              <th>Expense Type</th>
              <th>Amount</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {expenses.map((expense, index) => (
              <tr key={index}>
                <td>{expense.expenseType}</td>
                <td>{expense.amount}</td>
                <td>
                  <button
                    className="delete-expense-btn"
                    onClick={() => handleDeleteExpense(index)}
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="gross-total">
        <h3>Gross Total: {grossTotal}</h3>
        <button className="calculate-total-btn" onClick={calculateGrossTotal}>
          Calculate Gross Total
        </button>
      </div>
      <button className="finish-btn" onClick={handleFinish}>
        Finish
      </button>
    </div>
  );
};

export default BillingModule;


What I have tried:

I checked all the apis endpoint and made sure that server is running correctly
Posted
Updated 24-May-23 21:30pm
v2
Comments
Richard Deeming 25-May-23 3:29am    
A 500 error means something went wrong in your server-side code.

Which means that the server is not "running correctly".

You'll need to debug your code and check any event logs to try to find out what the actual problem is; "error 500" is just a generic "something went wrong" message, and doesn't give anyone enough information to diagnose the problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900