Text : Working with Header - Detail Form in Next JS

 JS Code : 

"use client";
import axios from "axios";
import { useState, useEffect } from "react";

const Invoice = () => {
  const [patientsList, setPatientsList] = useState([]);
  const [medicinesList, setMedicinesList] = useState([]);
  //header state vars
  const [patientId, setPatientId] = useState("");
  const [invoiceDate, setInvoiceDate] = useState("");
  const [invoiceTotal, setInvoiceTotal] = useState(0);
  //details state vars
  const [medicineId, setMedicineId] = useState("");
  const [qty, setQty] = useState(1);
  const [price, setPrice] = useState(0);
  const [amount, setAmount] = useState(0);
  //list for the details
  const [detailsList, setDetailsList] = useState([]);

  const getPatients = async () => {
    const url = "http://localhost/hospital/api/patients.php";
    const response = await axios.get(url, {
      params: { operation: "getPatients", json: "" },
    });
    setPatientsList(response.data);
  };

  const getMedicines = async () => {
    const url = "http://localhost/hospital/api/medicines.php";
    const response = await axios.get(url, {
      params: { operation: "getMedicines", json: "" },
    });
    setMedicinesList(response.data);
  };

  const getMedicineDetails = async (medId) => {
    const url = "http://localhost/hospital/api/medicines.php";
    const response = await axios.get(url, {
      params: {
        operation: "getMedicineDetails",
        json: JSON.stringify({ medId: medId }),
      },
    });

    setPrice(response.data[0].med_price);
    setAmount(qty * response.data[0].med_price);
    //details row
    const row = {
      medId: medicineId,
      medName: response.data[0].med_name,
      qty: qty,
      price: response.data[0].med_price,
      amount: qty * response.data[0].med_price,
    };
    setDetailsList([...detailsList, row]);
  };

  const computeInvoiceTotal = () => {
    const total = detailsList.reduce((accumulator, currentItem) => {
      return accumulator + currentItem.amount;
    }, 0);

    setInvoiceTotal(total);
  };

  const submit = async () => {
    const url = "http://localhost/hospital/api/invoice.php";
    const jsonData = {
      header: {patientId: patientId, date:invoiceDate, total:invoiceTotal },
      detail: detailsList
    };

    const formData = new FormData();
    formData.append("operation", "saveInvoice");
    formData.append("json", JSON.stringify(jsonData));

    const response = await axios({
      url: url,
      method: "POST",
      data: formData
    })

    if(response.data == 1){
      alert("You have successfully created a new invoice.");
    }else{
      alert("There was an error creating a new invoice");
    }

  };

  useEffect(() => {
    getPatients();
    getMedicines();
  }, []);

  useEffect(() => {
    if (medicineId) {
      getMedicineDetails(medicineId);
    }
  }, [medicineId]);

  useEffect(() => {
    computeInvoiceTotal();
  }, [detailsList]);

  return (
    <>
      <h1>Working with a Header - Detail Form</h1>
      <h4>Invoice Header</h4>
      Patient :
      <select value={patientId} onChange={(e) => setPatientId(e.target.value)}>
        {patientsList.map((patient, index) => {
          return (
            <option value={patient.patient_id} key={index}>
              {patient.patient_name}
            </option>
          );
        })}
      </select>
      <br />
      Date :
      <input
        type="date"
        value={invoiceDate}
        onChange={(e) => setInvoiceDate(e.target.value)}
      />
      <h4>Invoice Detail</h4>
      Qty:
      <input
        type="number"
        value={qty}
        onChange={(e) => {
          setQty(e.target.value);
        }}
      />
      - Medicine -
      <select
        value={medicineId}
        onChange={(e) => setMedicineId(e.target.value)}
      >
        {medicinesList.map((medicine, index) => {
          return (
            <option value={medicine.med_id} key={index}>
              {medicine.med_name}
            </option>
          );
        })}
      </select>
      <label> - Price - {price}</label>
      <label> - Amount - {amount}</label>
      <table>
        <thead>
          <tr>
            <th style={{ display: "none" }}>MedId</th>
            <th>Medicine</th>
            <th>Qty</th>
            <th>Price</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          {detailsList.map((row, index) => {
            return (
              <tr>
                <td style={{ display: "none" }}>{row.medId}</td>
                <td>{row.medName}</td>
                <td>{row.qty}</td>
                <td>{row.price}</td>
                <td>{row.amount}</td>
              </tr>
            );
          })}
          <tr>
            <td colspan="3">TOTAL</td>
            <td>{invoiceTotal}</td>
          </tr>
        </tbody>
      </table>
      <button onClick={submit}>Submit</button>
    </>
  );
};

export default Invoice;



PHP Code : 

Invoice

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

class Invoice{
  function saveInvoice($json){
    include "connection.php";
    $json = json_decode($json, true);

    $header = $json['header'];
    $detail = $json['detail'];

    try{
      $conn->beginTransaction();
      //save the header/master
      $sql = "INSERT INTO tblinvoicemaster(invM_patientId, invM_date, invM_total) ";
      $sql .= " VALUES(:patientId, :date, :total)";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":patientId", $header['patientId']);
      $stmt->bindParam(":date", $header['date']);
      $stmt->bindParam(":total", $header['total']);
      $stmt->execute();
      if($stmt->rowCount() > 0){
        //get the newly added auto increment id
        //to be used in the detail table
        $newId = $conn->lastInsertId();
        //save the detail
        $sql = "INSERT INTO tblinvoicedetail(invD_invoiceId, invD_medicineId, ";
        $sql .= "invD_qty, invD_price, invD_amount) VALUES (:invoiceId, :medId, :qty, ";
        $sql .= ":price, :amount)";
        $stmt = $conn->prepare($sql);
        foreach($detail as $row){
          $stmt->bindParam(":invoiceId", $newId);
          $stmt->bindParam(":medId", $row['medId']);
          $stmt->bindParam(":qty", $row['qty']);
          $stmt->bindParam(":price", $row['price']);
          $stmt->bindParam(":amount", $row['amount']);
          $stmt->execute();
        }
      }

      $conn->commit();
      return 1;
    } catch(PDOException $e){
      $conn->rollBack();
      return 0;
    }  
  }
}

//submitted by the client - operation and json
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
  $operation = $_GET['operation'];
  $json = $_GET['json'];
}else if($_SERVER['REQUEST_METHOD'] == 'POST'){
  $operation = $_POST['operation'];
  $json = $_POST['json'];
}

$invoice = new Invoice();
switch($operation){
  case "saveInvoice":
    echo $invoice->saveInvoice($json);
    break;
    }
?>
 


Patients


<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  class Patient {

    function getPatientDetails($json){
      include "connection.php";
      $json = json_decode($json, true);
 
      $sql = "SELECT * FROM tblpatients WHERE patient_id = :patientId";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":patientId", $json['patientId']);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($conn); unset($stmt);
      return json_encode($returnValue);
    }

    function getPatients($json){
      include "connection.php";
      $json = json_decode($json, true);
 
      $sql = "SELECT * FROM tblpatients ORDER BY patient_name";
      $stmt = $conn->prepare($sql);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($conn); unset($stmt);
      return json_encode($returnValue);
    }


  }

  //submitted by the client - operation and json
  if ($_SERVER['REQUEST_METHOD'] == 'GET'){
    $operation = $_GET['operation'];
    $json = $_GET['json'];
  }else if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $operation = $_POST['operation'];
    $json = $_POST['json'];
  }

  $patient = new Patient();
  switch($operation){
    case "getPatientDetails":
      echo $patient->getPatientDetails($json);
      break;
    case "getPatients":
      echo $patient->getPatients($json);
      break;
    }

?>


Medicines


<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  class Medicine {
    function getMedicineDetails($json){
      include "connection.php";
      $json = json_decode($json, true);
 
      $sql = "SELECT * FROM tblmedicines WHERE med_id = :medId";
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(":medId", $json['medId']);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($conn); unset($stmt);
      return json_encode($returnValue);
    }

    function getMedicines($json){
      include "connection.php";
      $json = json_decode($json, true);
 
      $sql = "SELECT * FROM tblmedicines ORDER BY med_name";
      $stmt = $conn->prepare($sql);
      $stmt->execute();
      $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
      unset($conn); unset($stmt);
      return json_encode($returnValue);
    }


  }

  //submitted by the client - operation and json
  if ($_SERVER['REQUEST_METHOD'] == 'GET'){
    $operation = $_GET['operation'];
    $json = $_GET['json'];
  }else if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $operation = $_POST['operation'];
    $json = $_POST['json'];
  }

  $medicine = new Medicine();
  switch($operation){
    case "getMedicineDetails":
      echo $medicine->getMedicineDetails($json);
      break;
    case "getMedicines":
      echo $medicine->getMedicines($json);
      break;
      }

?>








No comments:

Post a Comment

IMAGE : OPTIMIZING API END POINTS USING CLASSES IN PHP

 BACK END users.php   TEXT VERSION connection.php   TEXT VERSION FRONT END main.dart (LOGIN PAGE) register.dart   TEXT VERSION