diff --git a/data/bookbob_appointment.txt b/data/bookbob_appointment.txt index 7cdb268ba6..9591bd4c5f 100644 --- a/data/bookbob_appointment.txt +++ b/data/bookbob_appointment.txt @@ -1,2 +1,5 @@ +Name: Patrick|NRIC: S9089078U|Date: 08-11-2024|Time: 09:00 Name: John Doe|NRIC: S1234567A|Date: 18-11-2024|Time: 18:00 +Name: Yusof|NRIC: S9089079U|Date: 19-11-2024|Time: 09:00 Name: Helen Smith|NRIC: S7654321A|Date: 19-11-2024|Time: 18:00 +Name: Yusof|NRIC: S9089079U|Date: 19-11-2024|Time: 18:30 diff --git a/data/bookbob_data.txt b/data/bookbob_data.txt index 864ef982f9..87d4b86493 100644 --- a/data/bookbob_data.txt +++ b/data/bookbob_data.txt @@ -1 +1,4 @@ -Name: John Doe | NRIC: S1234567A | Phone Number: 98765432 | Date_Of_Birth: | Home Address: | Allergy: [] | Sex: | Medical History: [] | Visit: [01-10-2024 15:30, Diagnosis: [], Medications: [], 21-10-2024 15:48, Diagnosis: [], Medications: []]; +Name: Patricia | NRIC: S908909U | Phone Number: | Date_Of_Birth: | Home Address: | Allergy: [] | Sex: | Medical History: [] | Visit: [01-01-2025 16:00, Diagnosis: [Cough], Medications: [Cough syrup, Lozenges], 01-01-2025 16:00, Diagnosis: [Gastric, Runny Nose], Medications: [Cetirizine, Panadol], 07-11-2024 16:00, Diagnosis: [Asthma], Medications: []]; +Name: Aaron Chia | NRIC: T0989087I | Phone Number: 90890765 | Date_Of_Birth: | Home Address: Yio Chu Kang, 650987 | Allergy: [] | Sex: Male | Medical History: [] | Visit: [07-07-2025 10:00, Diagnosis: [], Medications: [], 09-08-2025 10:00, Diagnosis: [Asthma], Medications: [Albuterol]]; +Name: John Doe | NRIC: S9876543A | Phone Number: 91234567 | Date_Of_Birth: | Home Address: | Allergy: [] | Sex: | Medical History: [] | Visit: [01-11-2024 14:30, Diagnosis: [Fever], Medications: [Paracetamol]]; +Name: Jane Smith | NRIC: S8765432B | Phone Number: 92345678 | Date_Of_Birth: | Home Address: | Allergy: [] | Sex: | Medical History: [] | Visit: [01-11-2024 15:30, Diagnosis: [Cough], Medications: [Cough Syrup]]; diff --git a/docs/AfterAppointment.puml b/docs/AfterAppointment.puml index 335d306ff5..bbcf4010b8 100644 --- a/docs/AfterAppointment.puml +++ b/docs/AfterAppointment.puml @@ -5,8 +5,8 @@ object ":Main" as Main object " :CommandHandler" as CommandHandler object " in:Scanner" as Scanner object " appointment:Appointment " as Appointment { -name = John Doe -nric = S123A +name = "John Doe" +nric = "S123A" date = 18-11-2024 time = 18:00 } diff --git a/docs/AfterExecutionOD.png b/docs/AfterExecutionOD.png index f45d647b8b..579b608095 100644 Binary files a/docs/AfterExecutionOD.png and b/docs/AfterExecutionOD.png differ diff --git a/docs/DeveloperGuide.md b/docs/DeveloperGuide.md index 641df49b99..6e18b8221e 100644 --- a/docs/DeveloperGuide.md +++ b/docs/DeveloperGuide.md @@ -8,7 +8,6 @@ layout: default ## Table of Contents 1. [Design & Implementation](#design--implementation) - [Architecture](#architecture) - - [Managing Patient Visits and Records](#1-managing-patient-visits-and-records) - [Adding New Visits for Existing Patients](#a-adding-new-visits-for-existing-patients) - [Adding New Patient to the Patient Records](#b-adding-new-patient-to-the-patient-records) - [Appointment Feature](#c-appointment-feature) @@ -165,6 +164,7 @@ class and records it within the `AppointmentRecord` class. The appointment recor > The Sequence Diagram for the execution of appointment command: ![img.png](NewAppointmentSD.png) + --- ## Appendix A : Product Scope ### Target user profile diff --git a/docs/NewAppointment.puml b/docs/NewAppointment.puml index c7378c482e..c1b71f2b08 100644 --- a/docs/NewAppointment.puml +++ b/docs/NewAppointment.puml @@ -2,28 +2,44 @@ 'https://plantuml.com/sequence-diagram actor Doctor -Doctor -> Main ++ -Main -> Record ** -Main -> AppointmentRecord ** -Main -> FileHandler ++ : initFile(records) -FileHandler -> Main -- : -Main -> FileHandler ++ : initFile(appointmentRecords) -FileHandler -> Main -- : -Main -> CommandHandler ** : -Doctor -> Main : appointment("John Doe, S123A, 18-11-2024, 18:00") -Main -> CommandHandler ++: commandHandler.appointment("John Doe, S123A, 18-11-2024, 18:00") -CommandHandler -> AppointmentRecord ++ : appointmentRecord.checkAvailability("18-11-2024, 18:00") -AppointmentRecord -> CommandHandler -- : nextAvailableTime +Doctor -> ":Main" ++ +":Main" -> ":Record" ** +activate ":Record" +":Record" --> ":Main" -- : record:Record +":Main" -> ":AppointmentRecord" ** +activate ":AppointmentRecord" +":AppointmentRecord" --> ":Main" -- : appointmentRecord:AppointmentRecord +":Main" -> ":FileHandler" ++ : initFile(records) +":FileHandler" --> ":Main" -- : +":Main" -> ":FileHandler" ++ : initFile(appointmentRecords) +":FileHandler" --> ":Main" -- : +":Main" -> ":CommandHandler" ** : +activate ":CommandHandler" +":CommandHandler" --> ":Main" --: commandHandler:CommandHandler +Doctor -> ":Main" : appointment("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":Main" -> ":CommandHandler" ++: commandHandler.appointment("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":CommandHandler" -> ":CommandHandler" ++: commandHandler.extractName("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":CommandHandler" --> ":CommandHandler" --: name = "John Doe" +":CommandHandler" -> ":CommandHandler" ++: commandHandler.extractNric("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":CommandHandler" --> ":CommandHandler" --: nric = "S123A"" +":CommandHandler" --> ":CommandHandler" ++: commandHandler.extractDate("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":CommandHandler" --> ":CommandHandler" --: date = "18-11-2024"" +":CommandHandler" -> ":CommandHandler" ++: commandHandler.extractTime("n/John Doe, ic/S123A, date/18-11-2024, time/18:00") +":CommandHandler" --> ":CommandHandler" --: time = "18:00" +":CommandHandler" -> ":AppointmentRecord" ++ : appointmentRecord.checkAvailability("18-11-2024, 18:00") +":AppointmentRecord" --> ":CommandHandler" -- : nextAvailableTime group alt [nextAvailableTime == "18:00"] - CommandHandler -> Appointment ** - CommandHandler -> Appointment ++ : new Appointment("John Doe", "S123A", "18-11-2024", "18:00") - Appointment -> CommandHandler -- : appointment + ":CommandHandler" -> ":Appointment" ** + activate ":Appointment" + ":CommandHandler" -> ":Appointment" : new Appointment("John Doe", "S123A", "18-11-2024", "18:00") + ":Appointment" --> ":CommandHandler" -- : appointment - CommandHandler -> AppointmentRecord ++ : appointmentRecords.addAppointment(appointment) - AppointmentRecord -> CommandHandler -- + ":CommandHandler" -> ":AppointmentRecord" ++ : appointmentRecords.addAppointment(appointment) + ":AppointmentRecord" --> ":CommandHandler" -- else end -CommandHandler -> FileHandler ++ : FileHandler.autosave(appointmentRecords) -FileHandler -> CommandHandler -- - +":CommandHandler" -> ":FileHandler" ++ : FileHandler.autosave(appointmentRecords) +":FileHandler" --> ":CommandHandler" -- +":CommandHandler" --> ":Main" -- +deactivate ":Main" @enduml \ No newline at end of file diff --git a/docs/NewAppointmentSD.png b/docs/NewAppointmentSD.png index 794a62834e..7e727b1525 100644 Binary files a/docs/NewAppointmentSD.png and b/docs/NewAppointmentSD.png differ diff --git a/docs/team/johndoe.md b/docs/team/johndoe.md deleted file mode 100644 index ab75b391b8..0000000000 --- a/docs/team/johndoe.md +++ /dev/null @@ -1,6 +0,0 @@ -# John Doe - Project Portfolio Page - -## Overview - - -### Summary of Contributions diff --git a/src/main/java/bookbob/entity/Appointment.java b/src/main/java/bookbob/entity/Appointment.java index 981067e7af..e12e827992 100644 --- a/src/main/java/bookbob/entity/Appointment.java +++ b/src/main/java/bookbob/entity/Appointment.java @@ -5,7 +5,7 @@ import java.time.format.DateTimeFormatter; //@@author G13nd0n -public class Appointment implements Comparable { +public class Appointment implements Comparable, OutputConversion { private String patientName; private String patientNric; private LocalTime time; @@ -67,4 +67,19 @@ public int compareTo(Appointment other) { return 1; } } + + //@@author G13nd0n + @Override + public String convertPatientToOutputText() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + String patientName = this.getPatientName(); + String patientNric = this.getPatientNric(); + String date = this.getDate().format(formatter); + String time = this.getTime().toString(); + String output = ""; + output += "Name: " + patientName + "|" + "NRIC: " + patientNric + "|" + + "Date: " + date + "|" + "Time: " + time; + + return output; + } } diff --git a/src/main/java/bookbob/entity/AppointmentRecord.java b/src/main/java/bookbob/entity/AppointmentRecord.java index 60cf4889c5..79148b82cb 100644 --- a/src/main/java/bookbob/entity/AppointmentRecord.java +++ b/src/main/java/bookbob/entity/AppointmentRecord.java @@ -1,15 +1,20 @@ package bookbob.entity; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Scanner; //@@author G13nd0n -public class AppointmentRecord { +public class AppointmentRecord implements FileOperation { private List appointments; private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -20,7 +25,38 @@ public AppointmentRecord() { //@@author G13nd0n public void addAppointment(Appointment appointment) { - appointments.add(appointment); + LocalDate availableDate = appointment.getDate(); + LocalTime availableTime = appointment.getTime(); + LocalTime nextAvailableTime= this.checkAvailability(availableDate, availableTime); + if (nextAvailableTime == availableTime) { + appointments.add(appointment); + + System.out.println("Appointment on " + appointment.getDate().format(formatter) + " " + + appointment.getTime() + " with Patient " + appointment.getPatientName() + ", " + + appointment.getPatientNric() + " has been added."); + } else { + System.out.println("There is already an appointment at the given timeslot. " + + "The next available timeslot is: " + nextAvailableTime.toString()); + } + this.sort(); + } + + //@@author G13nd0n + public void addAppointment(String name, String nric, String date, String time) { + LocalDate availableDate = LocalDate.parse(date, formatter); + LocalTime availableTime = LocalTime.parse(time); + LocalTime nextAvailableTime= this.checkAvailability(availableDate, availableTime); + if (nextAvailableTime == availableTime) { + Appointment appointment = new Appointment(name, nric, date, time); + appointments.add(appointment); + + System.out.println("Appointment on " + appointment.getDate().format(formatter) + " " + + appointment.getTime() + " with Patient " + appointment.getPatientName() + ", " + + appointment.getPatientNric() + " has been added."); + } else { + System.out.println("There is already an appointment at the given timeslot. " + + "The next available timeslot is: " + nextAvailableTime.toString()); + } this.sort(); } @@ -28,16 +64,18 @@ public void addAppointment(Appointment appointment) { public List findAppointments(String input) { List results = new ArrayList<>(); String[] inputs = input.split("/"); + String filters = inputs[0]; String details = inputs[1]; - if (inputs[0].equals("n")) { + + if (filters.equals("n")) { for (int i = 0; i < appointments.size(); i++) { Appointment appointment = appointments.get(i); String patientName = appointment.getPatientName(); - if (patientName.equals(details)) { + if (patientName.contains(details)) { results.add(appointment); } } - } else if (inputs[0].equals("ic")) { + } else if (filters.equals("ic")) { for (int i = 0; i < appointments.size(); i++) { Appointment appointment = appointments.get(i); String nric = appointment.getPatientNric(); @@ -45,7 +83,7 @@ public List findAppointments(String input) { results.add(appointment); } } - } else if (inputs[0].equals("date")){ + } else if (filters.equals("date")){ for (int i = 0; i < appointments.size(); i++) { Appointment appointment = appointments.get(i); String date = appointment.getDate().format(formatter); @@ -53,7 +91,7 @@ public List findAppointments(String input) { results.add(appointment); } } - } else if (inputs[0].equals("time")) { + } else if (filters.equals("time")) { for (int i = 0; i < appointments.size(); i++) { Appointment appointment = appointments.get(i); String time = appointment.getTime().toString(); @@ -84,7 +122,7 @@ public void setAppointments(List appointments) { //@@author G13nd0n public void appointmentNotice() { if (appointments.size() == 0) { - System.out.println("No appointments scheduled for today"); + noAppointmentMessage(); return; } @@ -92,7 +130,7 @@ public void appointmentNotice() { LocalDate today = LocalDate.now(); if (firstAppointmentDate.isAfter(today)) { - System.out.println("No appointments scheduled for today"); + noAppointmentMessage(); return; } System.out.println("Appointment scheduled for today:"); @@ -105,6 +143,11 @@ public void appointmentNotice() { } } + //@@author G13nd0n + private static void noAppointmentMessage() { + System.out.println("No appointments scheduled for today"); + } + //@@author G13nd0n public LocalTime checkAvailability(LocalDate date, LocalTime time) { LocalTime nextAvailableTime = time; @@ -114,26 +157,142 @@ public LocalTime checkAvailability(LocalDate date, LocalTime time) { LocalDate appointmentDate = appointment.getDate(); LocalTime appointmentTime = appointment.getTime(); LocalTime appointmentEndTime = appointmentTime.plusMinutes(consultationDuration); - if (appointmentDate.equals(date) && appointmentTime.equals(nextAvailableTime)) { - nextAvailableTime = appointmentEndTime; - endTime = appointmentEndTime.plusMinutes(consultationDuration); - break; - } else if (appointmentDate.isAfter(date)) { + if (appointmentDate.isAfter(date)) { break; } else if (appointmentDate.isBefore(date)) { continue; - } else if (appointmentDate.equals(date) && appointmentTime.isBefore(nextAvailableTime) + } else if (appointmentTime.equals(nextAvailableTime)) { + nextAvailableTime = appointmentEndTime; + break; + } else if (appointmentTime.isBefore(nextAvailableTime) && appointmentEndTime.isAfter(nextAvailableTime)) { nextAvailableTime = appointmentEndTime; endTime = appointmentEndTime.plusMinutes(consultationDuration); - } else if (appointmentDate.equals(date) && appointmentEndTime.isBefore(nextAvailableTime)) { + } else if (appointmentEndTime.isBefore(nextAvailableTime)) { continue; - } else if (appointmentDate.equals(date) && appointmentTime.isBefore(endTime)) { + } else if (appointmentEndTime.equals(nextAvailableTime)) { + nextAvailableTime = appointmentEndTime; + } else if (appointmentTime.isBefore(endTime)) { nextAvailableTime = appointmentEndTime; endTime = appointmentEndTime.plusMinutes(consultationDuration); } } return nextAvailableTime; } + + //@@author G13nd0n + @Override + public void initFile(String appointmentFilePath) { + try { + String directoryName = "data"; + String currentDirectory = System.getProperty("user.dir"); + String directory = currentDirectory + File.separator + directoryName; + File directoryFile = new File(directory); + + if(directoryFile.mkdirs()) { //directory was not created + File file = new File(appointmentFilePath); + file.createNewFile(); //create new data file + } else { //directory already created + File file = new File(appointmentFilePath); + if (file.createNewFile()) { //file was not created + } else { + this.retrieveData(appointmentFilePath); + } + } + } catch(Exception e){ + e.printStackTrace(); + } + } + + //@@author G13nd0n + @Override + public void autosave(String appointmentFilePath) throws IOException, IOException { + List appointments = this.getAppointments(); + FileWriter fw = new FileWriter(appointmentFilePath); + for (Appointment appointment : appointments) { + String toWrite = appointment.convertPatientToOutputText(); + fw.write(toWrite + "\n"); + } + fw.close(); + } + + //@@author G13nd0n + @Override + public void retrieveData(String appointmentFilePath) { + try { + File file = new File(appointmentFilePath); + Scanner reader = new Scanner(file); + while (reader.hasNextLine()) { + String line = reader.nextLine(); + String[] data = line.split("\\|"); + String name = data[0].substring(6).trim(); + String nric = data[1].substring(6).trim(); + String date = data[2].substring(6).trim(); + String time = data[3].substring(6).trim(); + Appointment appointment = new Appointment(name, nric, date, time); + this.addAppointment(appointment); + } + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + public void listAppointments() { + if (appointments.isEmpty()) { + System.out.println("No appointments found."); + return; + } + for (Appointment appointment : appointments) { + System.out.println(appointment); + } + } + + public void removePastAppointments() { + LocalDate today = LocalDate.now(); + LocalTime now = LocalTime.now(); + List updatedAppointments = new ArrayList(); + for (int i = 0; i < appointments.size(); i++) { + Appointment currentAppointment = appointments.get(i); + LocalDate appointmentDate = currentAppointment.getDate(); + LocalTime appointmentTime = currentAppointment.getTime(); + if (appointmentDate.isAfter(today)) { + updatedAppointments.add(currentAppointment); + } else if (appointmentDate.isEqual(today) && appointmentTime.isAfter(now)) { + updatedAppointments.add(currentAppointment); + } + } + } + + public void deleteAppointment(String nric, String date, String time) { + String patientName = ""; + int initialAppointmentSize = appointments.size(); + + for (int i = 0; i < initialAppointmentSize; i++) { + Appointment appointment = appointments.get(i); + patientName = appointment.getPatientName(); + String patientNric = appointment.getPatientNric(); + String patientDate = appointment.getDate().format(formatter); + String patientTime = appointment.getTime().toString(); + if (!patientNric.equals(nric)) { + continue; + } + if (!patientDate.equals(date)) { + continue; + } + if (!patientTime.equals(time)) { + continue; + } + appointments.remove(i); + break; + } + + if (appointments.size() == initialAppointmentSize) { + System.out.println("Patient with " + nric + " do not have appointment on the given date and time."); + return; + } + System.out.println("Appointment on " + date + " " + time + " with Patient " + patientName + ", " + + nric + " has been deleted."); + + } } diff --git a/src/main/java/bookbob/entity/FileOperation.java b/src/main/java/bookbob/entity/FileOperation.java new file mode 100644 index 0000000000..f4e3e946f0 --- /dev/null +++ b/src/main/java/bookbob/entity/FileOperation.java @@ -0,0 +1,10 @@ +package bookbob.entity; + +import java.io.IOException; + +//@@author coraleaf0602 +public interface FileOperation { + void initFile(String filePath); + void autosave(String filePath) throws IOException; + void retrieveData(String filePath); +} diff --git a/src/main/java/bookbob/entity/OutputConversion.java b/src/main/java/bookbob/entity/OutputConversion.java new file mode 100644 index 0000000000..3e7b54ab2a --- /dev/null +++ b/src/main/java/bookbob/entity/OutputConversion.java @@ -0,0 +1,5 @@ +package bookbob.entity; + +public interface OutputConversion { + String convertPatientToOutputText(); +} diff --git a/src/main/java/bookbob/entity/Patient.java b/src/main/java/bookbob/entity/Patient.java index 732d4bdefe..4072b9e548 100644 --- a/src/main/java/bookbob/entity/Patient.java +++ b/src/main/java/bookbob/entity/Patient.java @@ -2,7 +2,7 @@ import java.util.ArrayList; -public class Patient { +public class Patient implements OutputConversion { private String name; private String nric; private String sex; @@ -124,4 +124,16 @@ public String toString() { ", DOB: " + getDateOfBirth() + ", Allergy: " + getAllergies() + ", Sex: " + getSex() + ", Medical History: " + getMedicalHistories(); } + + //@@author PrinceCatt + @Override + public String convertPatientToOutputText() { + String output = ""; + output += "Name: " + this.getName() + " | " + "NRIC: " + this.getNric() + " | " + + "Phone Number: " + this.getPhoneNumber() + " | " + "Date_Of_Birth: " + this.getDateOfBirth() + + " | " + "Home Address: " + this.getHomeAddress() + " | " + "Allergy: " + this.getAllergies() + + " | " + "Sex: " + this.getSex() + " | " + "Medical History: " + this.getMedicalHistories() + + " | " + "Visit: " + this.getVisits() + ";"; + return output; + } } diff --git a/src/main/java/bookbob/entity/Records.java b/src/main/java/bookbob/entity/Records.java index 83aefbb303..2bc7804ca4 100644 --- a/src/main/java/bookbob/entity/Records.java +++ b/src/main/java/bookbob/entity/Records.java @@ -1,8 +1,14 @@ package bookbob.entity; +import bookbob.functions.FileHandler; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; import java.util.ArrayList; +import java.util.Scanner; -public class Records { +public class Records implements FileOperation{ private final ArrayList patients; // default constructor: empty @@ -12,12 +18,150 @@ public Records() { } // add a patient to records + //@@author G13nd0n public void addPatient(Patient patient) { patients.add(patient); } - // getter + //@@author G13nd0n + public void addPatient(String name, String nric, ArrayList visits, String sex, String dateOfBirth, + String phoneNumber, String homeAddress, ArrayList allergies, + ArrayList medicalHistories) { + Patient patient = new Patient(name, nric, visits); + patient.setSex(sex); + patient.setDateOfBirth(dateOfBirth); + patient.setPhoneNumber(phoneNumber); + patient.setHomeAddress(homeAddress); + patient.setAllergies(allergies); + patient.setMedicalHistories(medicalHistories); + patients.add(patient); + System.out.println("Patient " + name + " with NRIC " + nric + " added."); + } + public ArrayList getPatients() { return patients; } + + //@@author PrinceCatt + @Override + public void initFile(String filePath) { + try { + String directoryName = "data"; + String currentDirectory = System.getProperty("user.dir"); + String directory = currentDirectory + File.separator + directoryName; + File directoryFile = new File(directory); + + if (directoryFile.mkdirs()) { //directory was not created + File file = new File(filePath); + file.createNewFile(); //create new data file + } else { //directory already created + File file = new File(filePath); + if(file.createNewFile()) { //file was not created + } else { + this.retrieveData(filePath); + } + } + } catch(Exception e){ + e.printStackTrace(); + } + } + + //@@author PrinceCatt + @Override + public void autosave(String filePath) throws IOException { + ArrayList patients = this.getPatients(); + FileWriter fw = new FileWriter(filePath); + for (Patient currPatient : patients) { + String toWrite = currPatient.convertPatientToOutputText(); + fw.write(toWrite + "\n"); + } + fw.close(); + } + + //@@author PrinceCatt + @Override + public void retrieveData(String filePath) { + try { + File file = new File(filePath); + Scanner reader = new Scanner(file); + + while (reader.hasNextLine()) { + String line = reader.nextLine(); + String[] data = line.split("\\|"); + + if (data.length < 9) { + continue; + } + + // Parse basic patient information + String name = data[0].substring(6).trim(); + String nric = data[1].substring(6).trim(); + String phoneNumber = data[2].substring(15).trim(); + String dateOfBirth = data[3].substring(16).trim(); + String homeAddress = data[4].substring(15).trim(); + //@@author kaboomzxc + String sex = data[6].substring(5).trim(); + ArrayList allergies = FileHandler.parseList(data[5].substring(9).trim()); + ArrayList medicalHistories = FileHandler.parseList(data[7].substring(17).trim()); + + // Parse visits + ArrayList visits = new ArrayList<>(); + String visitsString = data[8].trim(); + + // Extract the content between the outer-most brackets + int firstBracket = visitsString.indexOf("["); + int lastBracket = visitsString.lastIndexOf("]"); + + if (firstBracket != -1 && lastBracket != -1) { + visitsString = visitsString.substring(firstBracket + 1, lastBracket); + + // Split into individual visits by looking for date pattern + String[] visitParts = visitsString.split("(?<=\\]),\\s*(?=\\d{2}-\\d{2}-\\d{4})"); + + for (String visitPart : visitParts) { + Visit visit = FileHandler.parseVisitInputString("[" + visitPart + "]"); + if (visit != null) { + visits.add(visit); + } + } + } + + Patient patient = new Patient(name, nric, phoneNumber, dateOfBirth, homeAddress, + allergies, sex, medicalHistories, visits); + this.addPatient(patient); + } + reader.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void delete(String nric) { + assert nric != null : "Please provide a valid NRIC"; + + double initialSize = patients.size(); + if (patients.isEmpty()) { + System.out.println("No patients found."); + return; + } + try { + Integer.parseInt(nric.substring(1, 2)); + } catch (NumberFormatException e){ + System.out.println("Please provide the NRIC of the patient, not the name."); + return; + } + for (int i = 0; i < patients.size(); i++) { + Patient patient = patients.get(i); + if (patient.getNric().equals(nric)) { + patients.remove(i); + System.out.println("Patient " + patient.getName() + ", " + nric + ", has been deleted."); + break; + } + } + + if (patients.size() == initialSize) { + System.out.println("Patient with " + nric + " not found"); + + } + } } diff --git a/src/main/java/bookbob/functions/CommandHandler.java b/src/main/java/bookbob/functions/CommandHandler.java index 761cf970d3..4d8698a342 100644 --- a/src/main/java/bookbob/functions/CommandHandler.java +++ b/src/main/java/bookbob/functions/CommandHandler.java @@ -7,8 +7,6 @@ import bookbob.entity.Visit; import java.io.IOException; -import java.time.LocalDate; -import java.time.LocalTime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; @@ -57,43 +55,41 @@ public void help() { | | TIME format: HH:mm | m/Paracetamol,Ibuprofen | +-------------+---------------------------------------+---------------------------------+ | Edit Visit | editVisit ic/NRIC | editVisit ic/S7209876Y | - | | date/VISIT_DATE_AND_TIME | date/06-11-2024 14:00 | - | | [newDate/NEW_DATE] [d/DIAGNOSIS] | newDate/08-11-2024 14:00 | + | | date/VISIT_DATE_TIME | date/06-11-2024 14:00 | + | | [newDate/NEW_DATE_TIME] [d/DIAGNOSIS]| newDate/08-11-2024 14:00 | | | [m/MEDICATION] | d/Asthma m/Panadol, Antibiotics | | | DATE format: dd-mm-yyyy | | | | TIME format: HH:mm | | +-------------+---------------------------------------+---------------------------------+ | List | list | list | +-------------+---------------------------------------+---------------------------------+ - | Find | find n/NAME OR | find n/John Doe | - | | find ic/NRIC OR | find ic/S1234 | - | | find p/PHONE_NUMBER OR | find p/91234567 | - | | find d/DIAGNOSIS OR | find d/Fever | - | | find m/MEDICATION OR | find m/Panadol | - | | find ha/HOME_ADDRESS OR | find ha/NUS PGPR | + | Find | find n/NAME OR | find n/John Doe | + | | find ic/NRIC OR | find ic/S1234 | + | | find p/PHONE_NUMBER OR | find p/91234567 | + | | find ha/HOME_ADDRESS OR | find ha/NUS PGPR | | | find dob/DATE_OF_BIRTH OR | find dob/01011990 | - | | find al/ALLERGY OR | find al/Peanuts | - | | find find s/SEX OR | find find s/Female | + | | find al/ALLERGY OR | find al/Peanuts | + | | find s/SEX OR | find s/Female | | | find mh/MEDICAL_HISTORY | find mh/Diabetes | +-------------+---------------------------------------+---------------------------------+ | Delete | delete NRIC | delete S9534567A | +-------------+---------------------------------------+---------------------------------+ - | Add | appointment n/NAME ic/NRIC | add n/James Ho ic/S9534567A | - | Appointment | date/DATE time/TIME | date/01-04-2025 time/12:00 | - | | DATE format: dd-mm-yyyy | | + | Add | appointment n/NAME ic/NRIC | appointment n/James Ho | + | Appointment | date/DATE time/TIME | ic/S9534567A date/01-04-2025 | + | | DATE format: dd-mm-yyyy | time/12:00 | | | TIME format: HH:mm | | +-------------+---------------------------------------+---------------------------------+ - | List | listAppointments | list | + | List | listAppointments | listAppointments | | Appointment | | | +-------------+---------------------------------------+---------------------------------+ | Find | findAppointment n/NAME OR | findAppointment n/John Doe | - | Appointment | findAppointment ic/NRIC OR | findAppointment ic/S1234 | + | Appointment | findAppointment ic/NRIC OR | findAppointment ic/S1234567A | | | findAppointment date/DATE OR | findAppointment date/01-04-2025 | | | findAppointment time/TIME OR | findAppointment time/12:00 | | | DATE format: dd-mm-yyyy | | | | TIME format: HH:mm | | +-------------+---------------------------------------+---------------------------------+ - | Delete | deleteAppointment NRIC | deleteAppointment S9534567A | + | Delete | deleteAppointment ic/NRIC | deleteAppointment ic/S9534567A | | Appointment | date/DATE time/TIME | date/01-04-2025 time/12:00 | | | DATE format: dd-mm-yyyy | | | | TIME format: HH:mm | | @@ -107,7 +103,7 @@ public void help() { | Find | findMedication medication | findMedication Panadol | | Medication | | | +-------------+---------------------------------------+---------------------------------+ - | Save | save(automatic) | | + | Save | save (automatic) | | +-------------+---------------------------------------+---------------------------------+ | Retrieve/ | retrieve or import | | | Import | (automatic) | | @@ -118,150 +114,23 @@ public void help() { //@@author yentheng0110 public void add(String input, Records records) throws IOException { - String name = ""; - String nric = ""; - String sex = ""; - String dateOfBirth = ""; - String phoneNumber = ""; - String homeAddress = ""; + String name = extractName(input); + String nric = extractNric(input); + String sex = extractGender(input); + String dateOfBirth = extractDateOfBirth(input); + String phoneNumber = extractPhoneNumber(input); + String homeAddress = extractHomeAddress(input); + ArrayList diagnoses = extractDiagnoses(input); + ArrayList medications = extractMedications(input); + ArrayList allergies = extractAllergies(input); + ArrayList medicalHistories = extractMedicalHistories(input); ArrayList visits = new ArrayList<>(); - ArrayList diagnoses = new ArrayList<>(); - ArrayList medications = new ArrayList<>(); - ArrayList allergies = new ArrayList<>(); - ArrayList medicalHistories = new ArrayList<>(); - - // Extract name (a mandatory field) - int nameStart = input.indexOf("n/"); - - assert nameStart != -1 : "Please provide a valid patient name."; - - if (nameStart == -1) { - System.out.println("Please provide the patient's name."); - return; - } - - int nameEnd = findNextFieldStart(input, nameStart + 2); - name = input.substring(nameStart + 2, nameEnd).trim(); - - // Extract nric (a mandatory field) - int nricStart = input.indexOf("ic/"); - - assert nricStart != -1 : "Please provide a valid patient NRIC."; - - if (nricStart == -1) { - System.out.println("Please provide the patient's NRIC."); - return; - } - - int nricEnd = findNextFieldStart(input, nricStart + 3); - nric = input.substring(nricStart + 3, nricEnd).trim(); - - // Extract sex - int sexStart = input.indexOf("s/"); - if (sexStart != -1) { - int sexEnd = findNextFieldStart(input, sexStart + 2); - sex = input.substring(sexStart + 2, sexEnd).trim(); - } - - // Extract date of birth - int dobStart = input.indexOf("dob/"); - if (dobStart != -1) { - int dobEnd = findNextFieldStart(input, dobStart + 4); - dateOfBirth = input.substring(dobStart + 4, dobEnd).trim(); - } - - // Extract phone number - int phoneStart = input.indexOf("p/"); - if (phoneStart != -1) { - int phoneEnd = findNextFieldStart(input, phoneStart + 2); - phoneNumber = input.substring(phoneStart + 2, phoneEnd).trim(); - } - - // Extract home address - int homeAddressStart = input.indexOf("ha/"); - if (homeAddressStart != -1) { - int homeAddressEnd = findNextFieldStart(input, homeAddressStart + 3); - homeAddress = input.substring(homeAddressStart + 3, homeAddressEnd).trim(); - } + LocalDateTime visitDate = extractVisitDateTime(input); - // Extract the first visit date of the patient - int visitStart = input.indexOf("v/"); - LocalDateTime visitDate = null; - - assert visitStart != -1 : "Please provide a date for the patient's visit"; - - if (visitStart == -1) { - System.out.println("Please provide a date for the patient's visit."); - return; - } - - int visitEnd = findNextFieldStart(input, visitStart + 2); - String visitDateString = input.substring(visitStart + 2, visitEnd).trim(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); - - try { - visitDate = LocalDateTime.parse(visitDateString, formatter); - } catch (DateTimeParseException e) { - throw new IllegalArgumentException("Invalid visit date format. Please use 'dd-MM-yyyy HH:mm' format."); - } - - // Add the visit date, diagnoses and medications to a Visit object Visit visit = new Visit(visitDate, diagnoses, medications); visits.add(visit); - // Extract diagnoses (split by comma) - int diagnosisStart = input.indexOf("d/"); - if (diagnosisStart != -1) { - int diagnosisEnd = findNextFieldStart(input, diagnosisStart + 2); - String diagnosisInput = input.substring(diagnosisStart + 2, diagnosisEnd).trim(); - String[] diagnosisArray = diagnosisInput.split(",\\s*"); - for (String diagnosis : diagnosisArray) { - diagnoses.add(diagnosis.trim()); - } - } - - // Extract medications (split by comma) - int medicationStart = input.indexOf("m/"); - if (medicationStart != -1) { - int medicationEnd = findNextFieldStart(input, medicationStart + 2); - String medicationInput = input.substring(medicationStart + 2, medicationEnd).trim(); - String[] medsArray = medicationInput.split(",\\s*"); - for (String med : medsArray) { - medications.add(med.trim()); - } - } - - // Extract allergies (split by comma) - int allergyStart = input.indexOf("al/"); - if (allergyStart != -1) { - int allergyEnd = findNextFieldStart(input, allergyStart + 3); - String allergyInput = input.substring(allergyStart + 3, allergyEnd).trim(); - String[] allergiesArray = allergyInput.split(",\\s*"); - for (String allergy : allergiesArray) { - allergies.add(allergy.trim()); - } - } - - // Extract medical histories (split by comma) - int medicalHistoryStart = input.indexOf("mh/"); - if (medicalHistoryStart != -1) { - int medicalHistoryEnd = findNextFieldStart(input, medicalHistoryStart + 3); - String medicalHistoryInput = input.substring(medicalHistoryStart + 3, medicalHistoryEnd).trim(); - String[] medicalHistoriesArray = medicalHistoryInput.split(",\\s*"); - for (String medicalHistory : medicalHistoriesArray) { - medicalHistories.add(medicalHistory.trim()); - } - } - - Patient patient = new Patient(name, nric, visits); - patient.setSex(sex); - patient.setDateOfBirth(dateOfBirth); - patient.setPhoneNumber(phoneNumber); - patient.setHomeAddress(homeAddress); - patient.setAllergies(allergies); - patient.setMedicalHistories(medicalHistories); - records.addPatient(patient); - System.out.println("Patient " + name + " with NRIC " + nric + " added."); + records.addPatient(name, nric, visits, sex, dateOfBirth, phoneNumber, homeAddress, allergies, medicalHistories); FileHandler.autosave(records); } @@ -281,7 +150,7 @@ private int findNextFieldStart(String input, int currentIndex) { return nextIndex; } - //@@author yentheng0110 and kaboomzxc + //@@author yentheng0110 public void list(Records records) { List patients = records.getPatients(); if (patients.isEmpty()) { @@ -290,7 +159,6 @@ public void list(Records records) { } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); - for (Patient patient : patients) { // Print patient information System.out.println("Name: " + patient.getName() + ", NRIC: " + patient.getNric() + @@ -298,6 +166,7 @@ public void list(Records records) { ", DOB: " + patient.getDateOfBirth() + ", Allergies: " + patient.getAllergies() + ", Sex: " + patient.getSex() + ", Medical Histories: " + patient.getMedicalHistories()); + //@@author kaboomzxc // Print all visits for (Visit visit : patient.getVisits()) { System.out.println(" Visit Date: " + visit.getVisitDate().format(formatter) + @@ -312,123 +181,50 @@ public void list(Records records) { //@@author yentheng0110 public void edit(String input, Records records) throws IOException { // Extract NRIC from the input command - int nricStart = input.indexOf("ic/"); - assert nricStart != -1 : "Please provide a valid patient NRIC in the records."; - if (nricStart == -1) { - System.out.println("Please provide a valid patient NRIC in the records."); - return; - } - int nricEnd = findNextFieldStart(input, nricStart + 3); - String nric = input.substring(nricStart + 3, nricEnd).trim(); - + String nric = extractNric(input); Patient patientToBeEdited = null; // Search for the patient with matching name and NRIC - for (Patient patient : records.getPatients()) { - if (patient.getNric().trim().replaceAll("\\s+", "") - .equalsIgnoreCase(nric.replaceAll("\\s+", "").trim())) { - patientToBeEdited = patient; - break; - } - } + patientToBeEdited = extractPatient(records, nric, patientToBeEdited); if (patientToBeEdited == null) { System.out.println("No patient found."); return; } - records.getPatients().remove(patientToBeEdited); - String[] parts = input.split("/to", 2); if (parts.length < 2) { System.out.println("No fields provided to update."); return; } - String updates = parts[1].trim(); // Get everything after "/to" - // Extract optional fields for updating if provided by the user - int nameStart = updates.indexOf("n/"); - String newName = null; - if (nameStart != -1) { - int nameEnd = findNextFieldStart(updates, nameStart + 2); - newName = updates.substring(nameStart + 2, nameEnd).trim(); - } - - int newNRICStart = updates.indexOf("newic/"); - String newNRIC = null; - if (newNRICStart != -1) { - int newNRICEnd = findNextFieldStart(updates, newNRICStart + 6); - newNRIC = updates.substring(newNRICStart + 6, newNRICEnd).trim(); - } - - int sexStart = updates.indexOf("s/"); - String newSex = null; - if (sexStart != -1) { - int sexEnd = findNextFieldStart(updates, sexStart + 2); - newSex = updates.substring(sexStart + 2, sexEnd).trim(); - } - - int dobStart = updates.indexOf("dob/"); - String newDob = null; - if (dobStart != -1) { - int dobEnd = findNextFieldStart(updates, dobStart + 4); - newDob = updates.substring(dobStart + 4, dobEnd).trim(); - } - - int phoneStart = updates.indexOf("p/"); - String newPhone = null; - if (phoneStart != -1) { - int phoneEnd = findNextFieldStart(updates, phoneStart + 2); - newPhone = updates.substring(phoneStart + 2, phoneEnd).trim(); - } - - int homeAddressStart = updates.indexOf("ha/"); - String newHomeAddress = null; - if (homeAddressStart != -1) { - int homeAddressEnd = findNextFieldStart(updates, homeAddressStart + 3); - newHomeAddress = updates.substring(homeAddressStart + 3, homeAddressEnd).trim(); - } - - int allergyStart = updates.indexOf("al/"); - ArrayList newAllergies = new ArrayList<>(); - if (allergyStart != -1) { - int allergyEnd = findNextFieldStart(updates, allergyStart + 3); - String allergiesUpdatedInput = updates.substring(allergyStart + 3, allergyEnd).trim(); - String[] updatedAllergies = allergiesUpdatedInput.split(",\\s*"); - for (String allergy : updatedAllergies) { - newAllergies.add(allergy.trim()); - } - } - - int medicalHistoryStart = updates.indexOf("mh/"); - ArrayList newMedicalHistories = new ArrayList<>(); - if (medicalHistoryStart != -1) { - int medicalHistoryEnd = findNextFieldStart(updates, medicalHistoryStart + 3); - String medicalHistoriesUpdatedInput = updates.substring(medicalHistoryStart + 3, medicalHistoryEnd).trim(); - String[] updatedMedicalHistories = medicalHistoriesUpdatedInput.split(",\\s*"); - for (String medicalHistory : updatedMedicalHistories) { - newMedicalHistories.add(medicalHistory.trim()); - } - } + String newName = extractNewName(updates); + String newNRIC = extractNewNric(updates); + String newSex = extractGender(updates); + String newDob = extractDateOfBirth(updates); + String newPhone = extractPhoneNumber(updates); + String newHomeAddress = extractHomeAddress(updates); + ArrayList newAllergies = extractAllergies(updates); + ArrayList newMedicalHistories = extractMedicalHistories(updates); // Update patient details only if new values are provided - if (newName != null) { + if (!newName.isEmpty()) { patientToBeEdited.setName(newName); } - if (newNRIC != null) { + if (!newNRIC.isEmpty()) { patientToBeEdited.setNric(newNRIC); } - if (newSex != null) { + if (!newSex.isEmpty()) { patientToBeEdited.setSex(newSex); } - if (newDob != null) { + if (!newDob.isEmpty()) { patientToBeEdited.setDateOfBirth(newDob); } - if (newPhone != null) { + if (!newPhone.isEmpty()) { patientToBeEdited.setPhoneNumber(newPhone); } - if (newHomeAddress != null) { + if (!newHomeAddress.isEmpty()) { patientToBeEdited.setHomeAddress(newHomeAddress); } if (!newAllergies.isEmpty()) { @@ -437,7 +233,6 @@ public void edit(String input, Records records) throws IOException { if (!newMedicalHistories.isEmpty()) { patientToBeEdited.setMedicalHistories(newMedicalHistories); } - // Confirm the updated details System.out.println("Patient record updated successfully."); System.out.println("Updated patient details:"); @@ -450,25 +245,10 @@ public void edit(String input, Records records) throws IOException { //@@author yentheng0110 public void editVisit(String input, Records records) throws IOException { // Extract NRIC from input command - int nricStart = input.indexOf("ic/"); - assert nricStart != -1 : "Please provide a valid patient NRIC in the records."; - if (nricStart == -1) { - System.out.println("Please provide a valid patient NRIC."); - return; - } - int nricEnd = findNextFieldStart(input, nricStart + 3); - String nric = input.substring(nricStart + 3, nricEnd).trim(); + String nric = extractNric(input); Patient patient = null; - - // Search for the patient by NRIC - for (Patient p : records.getPatients()) { - if (p.getNric().trim().replaceAll("\\s+", "") - .equalsIgnoreCase(nric.replaceAll("\\s+", "").trim())) { - patient = p; - break; - } - } + patient = extractPatient(records, nric, patient); if (patient == null) { System.out.println("No patient found with the given NRIC."); @@ -476,15 +256,9 @@ public void editVisit(String input, Records records) throws IOException { } // Extract visit date from input command - int dateStart = input.indexOf("date/"); - assert dateStart != -1 : "Please provide a valid visit date."; - if (dateStart == -1) { - System.out.println("Please provide a valid visit date."); - return; - } - int dateEnd = findNextFieldStart(input, dateStart + 5); + String date = extractDate(input); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); - LocalDateTime visitDate = LocalDateTime.parse(input.substring(dateStart + 5, dateEnd).trim(), formatter); + LocalDateTime visitDate = LocalDateTime.parse(date, formatter); Visit visitToBeEdited = null; @@ -501,38 +275,22 @@ public void editVisit(String input, Records records) throws IOException { return; } - // Extract optional updates for visit - int newDateStart = input.indexOf("newDate/"); + // Extract optional updates for visit\ LocalDateTime newDate = null; + int newDateStart = input.indexOf("newDate/"); if (newDateStart != -1) { int newDateEnd = findNextFieldStart(input, newDateStart + 8); newDate = LocalDateTime.parse(input.substring(newDateStart + 8, newDateEnd).trim(), formatter); visitToBeEdited.setVisitDate(newDate); } - int diagnosesStart = input.indexOf("d/"); - ArrayList newDiagnoses = new ArrayList<>(); - if (diagnosesStart != -1) { - int diagnosesEnd = findNextFieldStart(input, diagnosesStart + 2); - String diagnosesInput = input.substring(diagnosesStart + 2, diagnosesEnd).trim(); - String[] diagnosesArray = diagnosesInput.split(",\\s*"); - for (String diagnosis : diagnosesArray) { - newDiagnoses.add(diagnosis.trim()); - } - visitToBeEdited.setDiagnoses(newDiagnoses); - } + ArrayList newDiagnoses = extractDiagnoses(input); + visitToBeEdited.setDiagnoses(newDiagnoses); + int medicationStart = input.indexOf("m/"); - ArrayList newMedications = new ArrayList<>(); - if (medicationStart != -1) { - int medicationEnd = findNextFieldStart(input, medicationStart + 2); - String medicationsInput = input.substring(medicationStart + 2, medicationEnd).trim(); - String[] medicationsArray = medicationsInput.split(",\\s*"); - for (String medication : medicationsArray) { - newMedications.add(medication.trim()); - } - visitToBeEdited.setMedications(newMedications); - } + ArrayList newMedications = extractMedications(input); + visitToBeEdited.setMedications(newMedications); // Confirm the updated visit details System.out.println("Visit record updated successfully."); @@ -545,32 +303,7 @@ public void editVisit(String input, Records records) throws IOException { // @@author G13nd0n public void delete(String nric, Records records) throws IOException { - assert nric != null : "Please provide a valid NRIC"; - - List patients = records.getPatients(); - double initialSize = patients.size(); - if (patients.isEmpty()) { - System.out.println("No patients found."); - return; - } - try { - Integer.parseInt(nric.substring(1, 2)); - } catch (NumberFormatException e){ - System.out.println("Please provide the NRIC of the patient, not the name."); - return; - } - for (int i = 0; i < patients.size(); i++) { - Patient patient = patients.get(i); - if (patient.getNric().equals(nric)) { - patients.remove(i); - System.out.println("Patient " + patient.getName() + ", " + nric + ", has been deleted."); - break; - } - } - - if (patients.size() == initialSize) { - System.out.println("Patient with " + nric + " not found"); - } + records.delete(nric); FileHandler.autosave(records); } @@ -599,7 +332,8 @@ public void find(String input, Records records) { if (searchParams.isEmpty()) { logger.log(Level.WARNING, "No valid search parameters provided."); System.out.println("Invalid search parameters. Please use the format: " - + "find n/NAME ic/NRIC [p/PHONE] [ha/ADDRESS] [dob/DOB] [al/ALLERGY] [s/SEX] [mh/MEDICAL_HISTORY]"); + + "find [n/NAME] [ic/NRIC] [p/PHONE] [ha/ADDRESS] [dob/DOB] [al/ALLERGY] [s/SEX] " + + "[mh/MEDICAL_HISTORY]"); return; } @@ -610,6 +344,7 @@ public void find(String input, Records records) { displayResults(matchedPatients); } + //@@author kaboomzxc private Map extractSearchParams(String input) { Map params = new HashMap<>(); String[] parts = input.split("\\s+"); @@ -631,10 +366,12 @@ private Map extractSearchParams(String input) { return params; } + //@@author kaboomzxc private boolean isValidSearchKey(String key) { return Arrays.asList("n", "ic", "p", "ha", "dob", "al", "s", "mh").contains(key); } + //@@author kaboomzxc private boolean matchesSearchCriteria(Patient patient, Map searchParams) { logger.log(Level.FINE, "Checking if patient matches search criteria: {0}", patient); @@ -670,7 +407,8 @@ private boolean matchesSearchCriteria(Patient patient, Map searc logger.log(Level.FINE, "Patient {0} matches criteria: {1}", new Object[]{patient.getNric(), matches}); return matches; } - + + //@@author kaboomzxc private void displayResults(List patients) { if (patients.isEmpty()) { System.out.println("No matching patients found."); @@ -684,112 +422,27 @@ private void displayResults(List patients) { //@@author G13nd0n public void appointment(String input, AppointmentRecord appointmentRecord) throws IOException { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - String name = ""; - String nric = ""; - String date = ""; - String time = ""; - - int nameStart = input.indexOf("n/"); - int nricStart = input.indexOf("ic/"); - int dateStart = input.indexOf("date/"); - int timeStart = input.indexOf("time/"); - - int nameEnd = findNextFieldStart(input, nameStart + 2); - name = input.substring(nameStart + 2, nameEnd).trim(); - int nricEnd = findNextFieldStart(input, nricStart + 2); - nric = input.substring(nricStart + 3, nricEnd).trim(); - int dateEnd = findNextFieldStart(input, dateStart + 2); - date = input.substring(dateStart + 5, dateEnd).trim(); - int timeEnd = findNextFieldStart(input, timeStart + 2); - time = input.substring(timeStart + 5, timeEnd).trim(); - LocalDate availableDate = LocalDate.parse(date, formatter); - LocalTime availableTime = LocalTime.parse(time); - - LocalTime nextAvailableTime= appointmentRecord.checkAvailability(availableDate, availableTime); - - if (nextAvailableTime == availableTime) { - Appointment appointment = new Appointment(name, nric, date, time); - appointmentRecord.addAppointment(appointment); - - System.out.println("Appointment on " + appointment.getDate().format(formatter) + " " + - appointment.getTime() + " with Patient " + appointment.getPatientName() + ", " + - appointment.getPatientNric() + " has been added."); - } else { - System.out.println("There is already an appointment at the given timeslot. " + - "The next available timeslot is: " + nextAvailableTime.toString()); - } + String name = extractName(input); + String nric = extractNric(input);; + String date = extractDate(input); + String time = extractTime(input); + appointmentRecord.addAppointment(name, nric, date, time); FileHandler.autosave(appointmentRecord); } //@@author G13nd0n public void deleteAppointment(String input, AppointmentRecord appointmentRecord) throws IOException { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - String nric = ""; - String date = ""; - String time = ""; - - int nricStart = input.indexOf("ic/"); - int dateStart = input.indexOf("date/"); - int timeStart = input.indexOf("time/"); - - if (nricStart == -1 || dateStart == -1 || timeStart == -1) { - throw new IllegalArgumentException(); - } - - assert nricStart != -1 : "Please provide a valid NRIC"; - assert dateStart != -1 : "Please provide a valid date"; - assert timeStart != -1 : "Please provide a valid time"; - - int nricEnd = findNextFieldStart(input, nricStart + 2); - nric = input.substring(nricStart + 3, nricEnd).trim(); - int dateEnd = findNextFieldStart(input, dateStart + 2); - date = input.substring(dateStart + 5, dateEnd).trim(); - int timeEnd = findNextFieldStart(input, timeStart + 2); - time = input.substring(timeStart + 5, timeEnd).trim(); - List appointments = appointmentRecord.getAppointments(); - String patientName = ""; - int initialAppointmentSize = appointments.size(); - - for (int i = 0; i < initialAppointmentSize; i++) { - Appointment appointment = appointments.get(i); - patientName = appointment.getPatientName(); - String patientNric = appointment.getPatientNric(); - String patientDate = appointment.getDate().format(formatter); - String patientTime = appointment.getTime().toString(); - if (!patientNric.equals(nric)) { - continue; - } - if (!patientDate.equals(date)) { - continue; - } - if (!patientTime.equals(time)) { - continue; - } - appointments.remove(i); - break; - } - appointmentRecord.setAppointments(appointments); - if (appointments.size() == initialAppointmentSize) { - System.out.println("Patient with " + nric + " do not have appointment on the given date and time."); - return; - } - System.out.println("Appointment on " + date + " " + time + " with Patient " + patientName + ", " + - nric + " has been deleted."); - + String nric = extractNric(input); + String date = extractDate(input); + String time = extractTime(input); + appointmentRecord.deleteAppointment(nric, date, time); FileHandler.autosave(appointmentRecord); } //@@author G13nd0n public void listAppointments(AppointmentRecord appointmentRecord) { - List appointments = appointmentRecord.getAppointments(); - if (appointments.isEmpty()) { - System.out.println("No appointments found."); - return; - } - for (Appointment appointment : appointments) { - System.out.println(appointment); - } + appointmentRecord.listAppointments(); } //@@author G13nd0n @@ -806,21 +459,7 @@ public void findAppointment(String input, AppointmentRecord appointmentRecord) { //@@author G13nd0n public void removePastAppointments(AppointmentRecord appointmentRecord) throws IOException { - LocalDate today = LocalDate.now(); - LocalTime now = LocalTime.now(); - List appointments = appointmentRecord.getAppointments(); - List updatedAppointments = new ArrayList(); - for (int i = 0; i < appointments.size(); i++) { - Appointment currentAppointment = appointments.get(i); - LocalDate appointmentDate = currentAppointment.getDate(); - LocalTime appointmentTime = currentAppointment.getTime(); - if (appointmentDate.isAfter(today)) { - updatedAppointments.add(currentAppointment); - } else if (appointmentDate.isEqual(today) && appointmentTime.isAfter(now)) { - updatedAppointments.add(currentAppointment); - } - } - appointmentRecord.setAppointments(updatedAppointments); + appointmentRecord.removePastAppointments(); FileHandler.autosave(appointmentRecord); } @@ -828,13 +467,10 @@ public void removePastAppointments(AppointmentRecord appointmentRecord) throws I public void addVisit(String input, Records records) throws IOException { try { // Extract NRIC first (mandatory field) - int nricStart = input.indexOf("ic/"); - if (nricStart == -1) { - System.out.println("Please provide the patient's NRIC."); + String nric = extractNric(input); + if (nric.isEmpty()) { return; } - int nricEnd = findNextFieldStart(input, nricStart + 3); - String nric = input.substring(nricStart + 3, nricEnd).trim(); // Find the patient with matching NRIC Patient targetPatient = null; @@ -851,13 +487,10 @@ public void addVisit(String input, Records records) throws IOException { } // Extract visit date (mandatory field) - int visitStart = input.indexOf("v/"); - if (visitStart == -1) { - System.out.println("Please provide the visit date and time."); + String visitDateString = extractVisitDate(input); + if (visitDateString == null) { return; } - int visitEnd = findNextFieldStart(input, visitStart + 2); - String visitDateString = input.substring(visitStart + 2, visitEnd).trim(); // Parse visit date DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); @@ -870,28 +503,10 @@ public void addVisit(String input, Records records) throws IOException { } // Extract medications (optional, can be multiple) - ArrayList medications = new ArrayList<>(); - int medicationStart = input.indexOf("m/"); - if (medicationStart != -1) { - int medicationEnd = findNextFieldStart(input, medicationStart + 2); - String medicationInput = input.substring(medicationStart + 2, medicationEnd).trim(); - if (!medicationInput.isEmpty()) { - String[] medsArray = medicationInput.split(",\\s*"); - medications.addAll(Arrays.asList(medsArray)); - } - } + ArrayList medications = extractMedications(input); // Extract diagnoses (optional, can be multiple) - ArrayList diagnoses = new ArrayList<>(); - int diagnosisStart = input.indexOf("d/"); - if (diagnosisStart != -1) { - int diagnosisEnd = findNextFieldStart(input, diagnosisStart + 2); - String diagnosisInput = input.substring(diagnosisStart + 2, diagnosisEnd).trim(); - if (!diagnosisInput.isEmpty()) { - String[] diagnosisArray = diagnosisInput.split(",\\s*"); - diagnoses.addAll(Arrays.asList(diagnosisArray)); - } - } + ArrayList diagnoses = extractDiagnoses(input); // Create new visit with the collected data Visit newVisit = new Visit(visitDate, diagnoses, medications); @@ -980,4 +595,229 @@ public void findVisitByMedication(String medication, Records records) { System.out.println("No patient found with medication: " + medication); } } + + //@@author G13nd0n + private LocalDateTime extractVisitDateTime(String input) { + LocalDateTime visitDate = null; + String visitDateString = extractVisitDate(input); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); + try { + visitDate = LocalDateTime.parse(visitDateString, formatter); + } catch (DateTimeParseException e) { + throw new IllegalArgumentException("Invalid visit date format. Please use 'dd-MM-yyyy HH:mm' format."); + } + return visitDate; + } + + //@@author G13nd0n + private ArrayList extractMedicalHistories(String input) { + int lengthOfMedicalHistoriesIndicator = 3; + ArrayList medicalHistories = new ArrayList<>(); + int medicalHistoryStart = input.indexOf("mh/"); + if (medicalHistoryStart != -1) { + int medicalHistoryEnd = findNextFieldStart(input, medicalHistoryStart + + lengthOfMedicalHistoriesIndicator); + String medicalHistoryInput = input.substring(medicalHistoryStart + lengthOfMedicalHistoriesIndicator, + medicalHistoryEnd).trim(); + String[] medicalHistoriesArray = medicalHistoryInput.split(",\\s*"); + for (String medicalHistory : medicalHistoriesArray) { + medicalHistories.add(medicalHistory.trim()); + } + } + return medicalHistories; + } + + //@@author G13nd0n + private ArrayList extractAllergies(String input) { + int lengthOfAllergiesIndicator = 3; + ArrayList allergies = new ArrayList<>(); + int allergyStart = input.indexOf("al/"); + if (allergyStart != -1) { + int allergyEnd = findNextFieldStart(input, allergyStart + lengthOfAllergiesIndicator); + String allergyInput = input.substring(allergyStart + lengthOfAllergiesIndicator, allergyEnd).trim(); + String[] allergiesArray = allergyInput.split(",\\s*"); + for (String allergy : allergiesArray) { + allergies.add(allergy.trim()); + } + } + return allergies; + } + + //@@author G13nd0n + private ArrayList extractMedications(String input) { + int lengthOfMedicationIndicator = 2; + ArrayList medications = new ArrayList<>(); + int medicationStart = input.indexOf("m/"); + if (medicationStart != -1) { + int medicationEnd = findNextFieldStart(input, medicationStart + lengthOfMedicationIndicator); + String medicationInput = input.substring(medicationStart + lengthOfMedicationIndicator, + medicationEnd).trim(); + String[] medsArray = medicationInput.split(",\\s*"); + for (String med : medsArray) { + medications.add(med.trim()); + } + } + return medications; + } + + //@@author G13nd0n + private ArrayList extractDiagnoses(String input) { + int lengthOfDiagnosesIndicator = 2; + ArrayList diagnoses = new ArrayList<>(); + int diagnosisStart = input.indexOf("d/"); + if (diagnosisStart != -1) { + int diagnosisEnd = findNextFieldStart(input, diagnosisStart + lengthOfDiagnosesIndicator); + String diagnosisInput = input.substring(diagnosisStart + lengthOfDiagnosesIndicator, diagnosisEnd).trim(); + String[] diagnosisArray = diagnosisInput.split(",\\s*"); + for (String diagnosis : diagnosisArray) { + diagnoses.add(diagnosis.trim()); + } + } + return diagnoses; + } + + //@@author G13nd0n + private String extractHomeAddress(String input) { + int lengthOfHomeAdressIndicator = 3; + String homeAddress = ""; + int homeAddressStart = input.indexOf("ha/"); + if (homeAddressStart != -1) { + int homeAddressEnd = findNextFieldStart(input, homeAddressStart + lengthOfHomeAdressIndicator); + homeAddress = input.substring(homeAddressStart + lengthOfHomeAdressIndicator, homeAddressEnd).trim(); + } + return homeAddress; + } + + //@@author G13nd0n + private String extractPhoneNumber(String input) { + int lengthOfPhoneNumberIndicator = 2; + String phoneNumber = ""; + int phoneStart = input.indexOf("p/"); + if (phoneStart != -1) { + int phoneEnd = findNextFieldStart(input, phoneStart + lengthOfPhoneNumberIndicator); + phoneNumber = input.substring(phoneStart + lengthOfPhoneNumberIndicator, phoneEnd).trim(); + } + return phoneNumber; + } + + //@@author G13nd0n + private String extractDateOfBirth(String input) { + int lengthOfDateOfBirthIndicator = 4; + String dateOfBirth = ""; + int dobStart = input.indexOf("dob/"); + if (dobStart != -1) { + int dobEnd = findNextFieldStart(input, dobStart + lengthOfDateOfBirthIndicator); + dateOfBirth = input.substring(dobStart + lengthOfDateOfBirthIndicator, dobEnd).trim(); + } + return dateOfBirth; + } + + //@@author G13nd0n + private String extractGender(String input) { + int lengthOfGenderIndicator = 2; + String sex = ""; + int sexStart = input.indexOf("s/"); + if (sexStart != -1) { + int sexEnd = findNextFieldStart(input, sexStart + lengthOfGenderIndicator); + sex = input.substring(sexStart + lengthOfGenderIndicator, sexEnd).trim(); + } + return sex; + } + + //@@author G13nd0n + private String extractTime(String input) { + int lengthOfTimeIndicator = 5; + int timeStart = input.indexOf("time/"); + if (timeStart == -1) { + System.out.println("Please provide the time"); + } + int timeEnd = findNextFieldStart(input, timeStart + lengthOfTimeIndicator); + String time = input.substring(timeStart + lengthOfTimeIndicator, timeEnd).trim(); + return time; + } + + //@@author G13nd0n + private String extractDate(String input) { + int lengthOfDateIndicator = 5; + int dateStart = input.indexOf("date/"); + if (dateStart == -1) { + System.out.println("Please provide the date"); + } + int dateEnd = findNextFieldStart(input, dateStart + lengthOfDateIndicator); + String date = input.substring(dateStart + lengthOfDateIndicator, dateEnd).trim(); + return date; + } + + //@@author G13nd0n + private String extractNric(String input) { + int lengthOfNricIndicator = 3; + int nricStart = input.indexOf("ic/"); + if (nricStart == -1) { + System.out.println("Please provide the patient's NRIC."); + return ""; + } + int nricEnd = findNextFieldStart(input, nricStart + lengthOfNricIndicator); + String nric = input.substring(nricStart + lengthOfNricIndicator, nricEnd).trim(); + return nric; + } + + //@@author G13nd0n + private String extractNewNric(String updates) { + int lenghtOfNewNricIndicator = 6; + String newNRIC = ""; + int newNRICStart = updates.indexOf("newic/"); + if (newNRICStart != -1) { + int newNRICEnd = findNextFieldStart(updates, newNRICStart + lenghtOfNewNricIndicator); + newNRIC = updates.substring(newNRICStart + lenghtOfNewNricIndicator, newNRICEnd).trim(); + } + return newNRIC; + } + + //@@author G13nd0n + private String extractName(String input) { + int lengthOfNameIndicator = 2; + int nameStart = input.indexOf("n/"); + if (nameStart == -1) { + System.out.println("Please provide the patient's name"); + } + int nameEnd = findNextFieldStart(input, nameStart + lengthOfNameIndicator); + String name = input.substring(nameStart + lengthOfNameIndicator, nameEnd).trim(); + return name; + } + + private String extractNewName(String input) { + int lengthOfNameIndicator = 2; + int nameStart = input.indexOf("n/"); + if (nameStart == -1) { + return ""; + } + int nameEnd = findNextFieldStart(input, nameStart + lengthOfNameIndicator); + String name = input.substring(nameStart + lengthOfNameIndicator, nameEnd).trim(); + return name; + } + + //@@author G13nd0n + private static Patient extractPatient(Records records, String nric, Patient patientToBeEdited) { + for (Patient patient : records.getPatients()) { + if (patient.getNric().trim().replaceAll("\\s+", "") + .equalsIgnoreCase(nric.replaceAll("\\s+", "").trim())) { + patientToBeEdited = patient; + break; + } + } + return patientToBeEdited; + } + + private String extractVisitDate(String input) { + int lengthOfVisitIndicator = 2; + int visitStart = input.indexOf("v/"); + if (visitStart == -1) { + System.out.println("Please provide the visit date and time."); + return null; + } + int visitEnd = findNextFieldStart(input, visitStart + lengthOfVisitIndicator); + String visitDateString = input.substring(visitStart + lengthOfVisitIndicator, visitEnd).trim(); + return visitDateString; + } + } diff --git a/src/main/java/bookbob/functions/FileHandler.java b/src/main/java/bookbob/functions/FileHandler.java index 940c2d4424..b30b556956 100644 --- a/src/main/java/bookbob/functions/FileHandler.java +++ b/src/main/java/bookbob/functions/FileHandler.java @@ -1,207 +1,41 @@ package bookbob.functions; -import bookbob.entity.Patient; import bookbob.entity.Records; import bookbob.entity.AppointmentRecord; -import bookbob.entity.Appointment; +import bookbob.entity.FileOperation; import bookbob.entity.Visit; + import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; -import java.util.List; -import java.util.Scanner; -import java.util.logging.Level; import java.util.logging.Logger; public class FileHandler { - private static final Logger logger = Logger.getLogger(FileHandler.class.getName()); private static String filePath = "data" + File.separator + "bookbob_data.txt"; private static String appointmentFilePath = "data" + File.separator + "bookbob_appointment.txt"; - //@@author PrinceCatt - public static void initFile(Records records){ - try { - String directoryName = "data"; - String currentDirectory = System.getProperty("user.dir"); - String directory = currentDirectory + File.separator + directoryName; - File directoryFile = new File(directory); - - if (directoryFile.mkdirs()) { //directory was not created - File file = new File(filePath); - file.createNewFile(); //create new data file - } else { //directory already created - logger.log(Level.INFO, "Directory exists"); - File file = new File(filePath); - if(file.createNewFile()) { //file was not created - logger.log(Level.INFO, "Directory exists, creating new file"); - } else { - retrieveData(records); - } - } - } catch(Exception e){ - logger.log(Level.WARNING, "Error initialising file", e); - e.printStackTrace(); - } - } - - public static void initFile(AppointmentRecord appointmentRecord){ - try { - String directoryName = "data"; - String currentDirectory = System.getProperty("user.dir"); - String directory = currentDirectory + File.separator + directoryName; - File directoryFile = new File(directory); - - if(directoryFile.mkdirs()) { //directory was not created - File file = new File(filePath); - file.createNewFile(); //create new data file - } else { //directory already created - logger.log(Level.INFO, "Directory for appointments exists"); - File file = new File(appointmentFilePath); - if (file.createNewFile()) { //file was not created - logger.log(Level.INFO, "Directory for appointments exists, creating new file"); - } else { - retrieveData(appointmentRecord); - } - } - } catch(Exception e){ - logger.log(Level.WARNING, "Error initializing file", e); - e.printStackTrace(); - } - } - - //@@author PrinceCatt - public static String convertPatientToOutputText(Patient patient) { - String output = ""; - output += "Name: " + patient.getName() + " | " + "NRIC: " + patient.getNric() + " | " - + "Phone Number: " + patient.getPhoneNumber() + " | " + "Date_Of_Birth: " + patient.getDateOfBirth() - + " | " + "Home Address: " + patient.getHomeAddress() + " | " + "Allergy: " + patient.getAllergies() - + " | " + "Sex: " + patient.getSex() + " | " + "Medical History: " + patient.getMedicalHistories() - + " | " + "Visit: " + patient.getVisits() + ";"; - return output; - } - - - public static String convertPatientToOutputText(Appointment appointment) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - String patientName = appointment.getPatientName(); - String patientNric = appointment.getPatientNric(); - String date = appointment.getDate().format(formatter); - String time = appointment.getTime().toString(); - String output = ""; - output += "Name: " + patientName + "|" + "NRIC: " + patientNric + "|" - + "Date: " + date + "|" + "Time: " + time; - - return output; - } - - //@@author PrinceCatt - public static void autosave(Records records) throws IOException { - ArrayList patients = records.getPatients(); - FileWriter fw = new FileWriter(filePath); - for (Patient currPatient : patients) { - String toWrite = convertPatientToOutputText(currPatient); - fw.write(toWrite + "\n"); - } - fw.close(); - logger.log(Level.INFO, "Autosaved successfully"); - } - - public static void autosave(AppointmentRecord appointmentRecord) throws IOException { - List appointments = appointmentRecord.getAppointments(); - FileWriter fw = new FileWriter(appointmentFilePath); - for (Appointment appointment : appointments) { - String toWrite = convertPatientToOutputText(appointment); - fw.write(toWrite + "\n"); - } - fw.close(); - logger.log(Level.INFO, "Autosaved appointments successfully"); - } - - //@@author PrinceCatt and kaboomzxc - public static void retrieveData(Records records) { - try { - File file = new File(filePath); - Scanner reader = new Scanner(file); - - while (reader.hasNextLine()) { - String line = reader.nextLine(); - String[] data = line.split("\\|"); - - if (data.length < 9) { - continue; - } - - // Parse basic patient information - String name = data[0].substring(6).trim(); - String nric = data[1].substring(6).trim(); - String phoneNumber = data[2].substring(15).trim(); - String dateOfBirth = data[3].substring(16).trim(); - String homeAddress = data[4].substring(15).trim(); - String sex = data[6].substring(5).trim(); - ArrayList allergies = parseList(data[5].substring(9).trim()); - ArrayList medicalHistories = parseList(data[7].substring(17).trim()); - - // Parse visits - ArrayList visits = new ArrayList<>(); - String visitsString = data[8].trim(); - - // Extract the content between the outer-most brackets - int firstBracket = visitsString.indexOf("["); - int lastBracket = visitsString.lastIndexOf("]"); - - if (firstBracket != -1 && lastBracket != -1) { - visitsString = visitsString.substring(firstBracket + 1, lastBracket); - - // Split into individual visits by looking for date pattern - String[] visitParts = visitsString.split("(?<=\\]),\\s*(?=\\d{2}-\\d{2}-\\d{4})"); - - for (String visitPart : visitParts) { - Visit visit = parseVisitInputString("[" + visitPart + "]"); - if (visit != null) { - visits.add(visit); - } - } - } - - Patient patient = new Patient(name, nric, phoneNumber, dateOfBirth, homeAddress, - allergies, sex, medicalHistories, visits); - records.addPatient(patient); - } - reader.close(); - } catch (Exception e) { - e.printStackTrace(); + public static void initFile(FileOperation fileOperation) { + if (fileOperation instanceof AppointmentRecord) { + fileOperation.initFile(appointmentFilePath); + } else if (fileOperation instanceof Records) { + fileOperation.initFile(filePath); } } - public static void retrieveData(AppointmentRecord appointmentRecord){ - try { - File file = new File(appointmentFilePath); - Scanner reader = new Scanner(file); - while (reader.hasNextLine()) { - String line = reader.nextLine(); - String[] data = line.split("\\|"); - String name = data[0].substring(6).trim(); - String nric = data[1].substring(6).trim(); - String date = data[2].substring(6).trim(); - String time = data[3].substring(6).trim(); - Appointment appointment = new Appointment(name, nric, date, time); - appointmentRecord.addAppointment(appointment); - } - logger.log(Level.INFO, "Retrieved successfully"); - } catch (FileNotFoundException e) { - logger.log(Level.WARNING, "File not found", e); - throw new RuntimeException(e); + public static void autosave(FileOperation fileOperation) throws IOException { + if (fileOperation instanceof AppointmentRecord) { + fileOperation.autosave(appointmentFilePath); + } else if (fileOperation instanceof Records) { + fileOperation.autosave(filePath); } } - + //@@author yentheng0110 and kaboomzxc - private static ArrayList parseList(String input) { + public static ArrayList parseList(String input) { ArrayList list = new ArrayList<>(); // Remove any number of surrounding brackets String content = input.replaceAll("^\\[+|\\]+$", ""); @@ -212,7 +46,7 @@ private static ArrayList parseList(String input) { return list; } - + //@@author coraleaf0602 public static Visit parseVisitInputString(String visitString) { try { int visitStartIndex = visitString.indexOf("["); @@ -238,6 +72,7 @@ public static Visit parseVisitInputString(String visitString) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); LocalDateTime visitDateTime = LocalDateTime.parse(dateTimeString, formatter); + //@@author kaboomzxc // Parse diagnoses and medications ArrayList diagnosisList = new ArrayList<>(); ArrayList medicationsList = new ArrayList<>(); @@ -269,6 +104,7 @@ public static Visit parseVisitInputString(String visitString) { } } } + //@@author coraleaf0602 return new Visit(visitDateTime, diagnosisList, medicationsList); } catch (Exception e) { return null; diff --git a/src/test/java/bookbob/MainTest.java b/src/test/java/bookbob/MainTest.java new file mode 100644 index 0000000000..4ccef7826e --- /dev/null +++ b/src/test/java/bookbob/MainTest.java @@ -0,0 +1,546 @@ +package bookbob; + +import bookbob.entity.Records; +import bookbob.entity.AppointmentRecord; +import bookbob.functions.CommandHandler; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class MainTest { + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + private final PrintStream standardOut = System.out; + private Records records; + private AppointmentRecord appointmentRecord; + private CommandHandler commandHandler; + private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + private final String TODAY = LocalDate.now().format(formatter); + private final String TOMORROW = LocalDate.now().plusDays(1).format(formatter); + private final String YESTERDAY = LocalDate.now().minusDays(1).format(formatter); + + + //@@author kaboomzxc + @BeforeEach + void setUp() throws IOException { + System.setOut(new PrintStream(outputStreamCaptor)); + records = new Records(); + appointmentRecord = new AppointmentRecord(); + commandHandler = new CommandHandler(); + } + + @AfterEach + void tearDown() { + System.setOut(standardOut); + } + + //@@author kaboomzxc + // Test different command combinations + @Test + void testMultipleCommandSequences() { + String input = "add n/John Doe ic/S9876543A p/91234567 d/Fever m/Paracetamol v/01-11-2024 14:30\n" + + "add n/Jane Smith ic/S8765432B p/92345678 d/Cough m/Cough Syrup v/01-11-2024 15:30\n" + + "list\n" + + "findVisit S9876543A\n" + + "findDiagnosis Fever\n" + + "findMedication Paracetamol\n" + + "appointment n/John Doe ic/S9876543A date/02-11-2024 time/14:30\n" + + "listAppointments\n" + + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Patient John Doe with NRIC S9876543A added")); + assertTrue(output.contains("Patient Jane Smith with NRIC S8765432B added")); + assertTrue(output.contains("Appointment on 02-11-2024 14:30")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test all error conditions in addVisit + @Test + void testAddVisitErrors() { + String input = "addVisit\n" + // Missing all parameters + "addVisit ic/S9876543A\n" + // Missing visit date + "addVisit v/01-11-2024 14:30\n" + // Missing NRIC + "addVisit ic/S9876543A v/invalid-date\n" + // Invalid date format + "addVisit ic/INVALID v/01-11-2024 14:30\n" + // Invalid NRIC format + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Please provide the patient's NRIC")); + assertTrue(output.contains("Please provide the visit date")); + assertTrue(output.contains("Invalid date format")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test all error conditions in editVisit + @Test + void testEditVisitErrors() { + String input = "add n/John Doe ic/S9876543A v/01-11-2024 14:30\n" + + "editVisit\n" + // Missing all parameters + "editVisit ic/S9876543A\n" + // Missing date + "editVisit date/01-11-2024 14:30\n" + // Missing NRIC + "editVisit ic/S9876543A date/invalid-date\n" + // Invalid date + "editVisit ic/INVALID date/01-11-2024 14:30\n" + // Invalid NRIC + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Please provide the patient's NRIC")); + assertTrue(output.contains("Please provide a valid visit date")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test all error conditions in appointment + @Test + void testAppointmentErrors() { + String input = "appointment\n" + // Missing all parameters + "appointment n/John Doe\n" + // Missing NRIC + "appointment n/John Doe ic/S9876543A\n" + // Missing date and time + "appointment n/John Doe ic/S9876543A date/01-11-2024\n" + // Missing time + "appointment n/John Doe ic/S9876543A date/invalid time/14:30\n" + // Invalid date + "appointment n/John Doe ic/S9876543A date/01-11-2024 time/invalid\n" + // Invalid time + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Please provide the patient's name")); + assertTrue(output.contains("Please provide the patient's NRIC")); + assertTrue(output.contains("Please provide the date")); + assertTrue(output.contains("Please provide the time")); + assertTrue(output.contains("Error in adding appointment")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test appointment time slot validation + @Test + void testAppointmentTimeSlotValidation() { + String input = "appointment n/John Doe ic/S9876543A date/01-11-2024 time/14:30\n" + + "appointment n/Jane Smith ic/S8765432B date/01-11-2024 time/14:30\n" + // Same time slot + "appointment n/Bob Wilson ic/S7654321C date/01-11-2024 time/14:45\n" + // Within 30 min + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("There is already an appointment at the given timeslot")); + assertTrue(output.contains("The next available timeslot is:")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test find command with various criteria + @Test + void testFindWithMultipleCriteria() { + String input = "add n/John Doe ic/S9876543A p/91234567 d/Fever m/Paracetamol " + + "ha/123 Main St dob/01-01-1990 v/01-11-2024 14:30 al/Peanuts s/Male mh/Asthma\n" + + "find n/John\n" + + "find ic/S987\n" + + "find p/91234567\n" + + "find ha/Main\n" + + "find dob/01-01-1990\n" + + "find al/Peanuts\n" + + "find s/Male\n" + + "find mh/Asthma\n" + + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Matching patients")); + assertEquals(8, output.split("Matching patients").length - 1); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test deleteAppointment with various conditions + @Test + void testDeleteAppointmentScenarios() { + String input = "appointment n/John Doe ic/S9876543A date/01-11-2024 time/14:30\n" + + "deleteAppointment ic/S9876543A date/01-11-2024 time/14:30\n" + // Valid deletion + "deleteAppointment ic/INVALID date/01-11-2024 time/14:30\n" + // Invalid NRIC + "deleteAppointment ic/S9876543A date/invalid time/14:30\n" + // Invalid date + "deleteAppointment ic/S9876543A date/01-11-2024 time/invalid\n" + // Invalid time + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("has been deleted")); + assertTrue(output.contains("Error in deleting appointment")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test input validation edge cases + @Test + void testInputValidationEdgeCases() { + String input = "add n/ ic/S9876543A v/01-11-2024 14:30\n" + // Empty name + "add n/John Doe ic/ v/01-11-2024 14:30\n" + // Empty NRIC + "add n/John Doe ic/S9876543A v/ \n" + // Empty visit date + "add n/John Doe ic/S9876543A v/01-11-2024 14:30 p/ \n" + // Empty phone + "add n/John Doe ic/S9876543A v/01-11-2024 14:30 ha/ \n" + // Empty address + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Please provide")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + // Test concurrent operations + @Test + void testConcurrentOperations() { + String input = "add n/John Doe ic/S9876543A v/01-11-2024 14:30\n" + + "appointment n/John Doe ic/S9876543A date/01-11-2024 time/14:30\n" + + "list\n" + + "listAppointments\n" + + "findVisit S9876543A\n" + + "findAppointment n/John\n" + + "exit\n"; + provideInput(input); + + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Patient John Doe")); + assertTrue(output.contains("Appointment on 01-11-2024 14:30")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + private void provideInput(String data) { + ByteArrayInputStream testIn = new ByteArrayInputStream(data.getBytes()); + System.setIn(testIn); + } + + //@@author kaboomzxc + @Test + void testAddCommandAllFields() { + String input = "add n/John Doe ic/S9876543A p/91234567 d/Fever,Cough m/Paracetamol,Syrup " + + "ha/123 Main St dob/01-01-1990 v/01-11-2024 14:30 al/Peanuts s/Male mh/Asthma\n" + + "add n/Jane Smith ic/S8765432B p/92345678 v/01-11-2024 15:30\n" + // Minimal fields + "add n/Bob Wilson ic/S7654321C v/01-11-2024 16:30 d/Flu\n" + // With diagnosis + "add n/Alice Brown ic/S6543210D v/01-11-2024 17:30 m/Ibuprofen\n" + // With medication + "list\n" + + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Patient John Doe with NRIC S9876543A added")); + assertTrue(output.contains("Fever, Cough")); + assertTrue(output.contains("Patient Jane Smith with NRIC S8765432B added")); + assertTrue(output.contains("Patient Bob Wilson with NRIC S7654321C added")); + assertTrue(output.contains("Patient Alice Brown with NRIC S6543210D added")); + assertTrue(output.contains("Ibuprofen")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testEditCommandAllFieldVariations() { + String input = "add n/John Doe ic/S9876543A v/01-11-2024 14:30 p/91234567\n" + + "edit ic/S9876543A /to n/James Doe\n" + + "edit ic/S9876543A /to newic/S9876543B\n" + + "edit ic/S9876543B /to p/98765432\n" + + "edit ic/S9876543B /to ha/New Address\n" + + "edit ic/S9876543B /to dob/01-01-1991\n" + + "edit ic/S9876543B /to al/Peanuts,Dust\n" + + "edit ic/S9876543B /to s/Male\n" + + "edit ic/S9876543B /to mh/Asthma,Diabetes\n" + + "list\n" + + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Patient record updated successfully")); + assertTrue(output.contains("James Doe")); + assertTrue(output.contains("S9876543B")); + assertTrue(output.contains("98765432")); + assertTrue(output.contains("New Address")); + assertTrue(output.contains("01-01-1991")); + assertTrue(output.contains("Peanuts, Dust")); + assertTrue(output.contains("Male")); + assertTrue(output.contains("Asthma, Diabetes")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testVisitOperationsComplexScenarios() { + String input = "add n/John Doe ic/S9876543A v/01-11-2024 14:30\n" + + "addVisit ic/S9876543A v/02-11-2024 14:30 d/Fever m/Paracetamol\n" + + "addVisit ic/S9876543A v/03-11-2024 14:30 d/Cold m/Syrup\n" + + "editVisit ic/S9876543A date/02-11-2024 14:30 d/Severe Fever\n" + + "editVisit ic/S9876543A date/03-11-2024 14:30 m/Strong Syrup\n" + + "findVisit S9876543A\n" + + "findDiagnosis Severe Fever\n" + + "findMedication Strong Syrup\n" + + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Visit added successfully")); + assertTrue(output.contains("Visit record updated successfully")); + assertTrue(output.contains("Severe Fever")); + assertTrue(output.contains("Strong Syrup")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testDateTimeValidations() { + String input = "add n/John Doe ic/S9876543A v/32-13-2024 14:30\n" + // Invalid date + "add n/John Doe ic/S9876543A v/01-11-2024 25:00\n" + // Invalid hour + "add n/John Doe ic/S9876543A v/01-11-2024 14:60\n" + // Invalid minute + "appointment n/John Doe ic/S9876543A date/32-13-2024 time/14:30\n" + // Invalid date + "appointment n/John Doe ic/S9876543A date/01-11-2024 time/25:00\n" + // Invalid hour + "editVisit ic/S9876543A date/32-13-2024 14:30\n" + // Invalid date + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Invalid") || output.contains("Error")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testSearchOperationsAllCriteria() { + String input = "add n/John Doe ic/S9876543A p/91234567 d/Fever m/Paracetamol " + + "ha/123 Main St dob/01-01-1990 v/01-11-2024 14:30 al/Peanuts s/Male mh/Asthma\n" + + "find n/John\n" + + "find ic/S987\n" + + "find p/91234567\n" + + "find d/Fever\n" + + "find m/Paracetamol\n" + + "find ha/Main\n" + + "find dob/01-01-1990\n" + + "find al/Peanuts\n" + + "find s/Male\n" + + "find mh/Asthma\n" + + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertEquals(10, output.split("Matching patients").length - 1); + assertTrue(output.contains("John Doe")); + assertTrue(output.contains("S9876543A")); + assertTrue(output.contains("91234567")); + assertTrue(output.contains("Main St")); + assertTrue(output.contains("Peanuts")); + assertTrue(output.contains("Male")); + assertTrue(output.contains("Asthma")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testDeleteOperationsComplexScenarios() { + String input = "add n/John Doe ic/S9876543A v/01-11-2024 14:30\n" + + "addVisit ic/S9876543A v/02-11-2024 14:30 d/Fever m/Paracetamol\n" + + "appointment n/John Doe ic/S9876543A date/03-11-2024 time/14:30\n" + + "add n/Jane Smith ic/S8765432B v/01-11-2024 15:30\n" + + "delete S9876543A\n" + // Delete first patient + "list\n" + + "delete S8765432B\n" + // Delete second patient + "list\n" + + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("has been deleted")); + assertTrue(output.contains("No patients found")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testInvalidCommandsAndErrors() { + String input = "invalidcommand\n" + + "add n/John Doe\n" + // Missing required fields + "edit ic/nonexistent /to n/New Name\n" + // Nonexistent patient + "editVisit ic/nonexistent date/01-11-2024 14:30\n" + // Nonexistent patient + "addVisit ic/nonexistent v/01-11-2024 14:30\n" + // Nonexistent patient + "find invalidformat\n" + // Invalid find format + "findVisit nonexistent\n" + // Nonexistent patient + "findDiagnosis nonexistent\n" + // Nonexistent diagnosis + "findMedication nonexistent\n" + // Nonexistent medication + "delete nonexistent\n" + // Nonexistent patient + "help\n" + // Valid help command + "exit\n"; + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Unknown command")); + assertTrue(output.contains("Please provide")); + assertTrue(output.contains("No patient found")); + assertTrue(output.contains("Action")); + assertTrue(output.contains("Format")); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + //@@author kaboomzxc + @Test + void testCheckAvailabilityAllBranches() { + String input = String.format( + "appointment n/P1 ic/S1111111A date/%s time/09:00\n" + // Initial appointment + "appointment n/P2 ic/S2222222B date/%s time/09:00\n" + // Same time (should get next slot) + "appointment n/P3 ic/S3333333C date/%s time/09:15\n" + // During first appointment + "appointment n/P4 ic/S4444444D date/%s time/09:00\n" + // Different day + "appointment n/P5 ic/S5555555E date/%s time/09:00\n" + // Previous day + "appointment n/P6 ic/S6666666F date/%s time/09:45\n" + // Clear slot + "appointment n/P7 ic/S7777777G date/%s time/09:25\n" + // Overlapping end + "listAppointments\nexit\n", + TODAY, TODAY, TODAY, TOMORROW, YESTERDAY, TODAY, TODAY); + + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("next available timeslot")); + assertTrue(output.contains("Appointment on " + TODAY + " 09:00")); + assertTrue(output.contains("Appointment on " + TODAY + " 09:45")); + assertTrue(output.contains("Appointment on " + TOMORROW + " 09:00")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + //@@author kaboomzxc + @Test + void testCompletePatientLifecycle() { + String input = "add n/John Doe ic/S1234567A p/91234567 d/Fever m/Paracetamol v/01-11-2024 14:30\n" + + "addVisit ic/S1234567A v/02-11-2024 14:30 d/Followup,Check m/None\n" + + "editVisit ic/S1234567A date/02-11-2024 14:30 newDate/03-11-2024 14:30\n" + + "edit ic/S1234567A /to p/98765432 ha/New Address\n" + + "appointment n/John Doe ic/S1234567A date/04-11-2024 time/14:30\n" + + "list\n" + + "listAppointments\n" + + "delete S1234567A\n" + + "exit\n"; + + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Patient record updated successfully")); + assertTrue(output.contains("Visit record updated successfully")); + assertTrue(output.contains("has been deleted")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testAppointmentTimeBoundaries() { + String input = String.format( + "appointment n/P1 ic/S1111111A date/%s time/00:00\n" + // Start of day + "appointment n/P2 ic/S2222222B date/%s time/23:30\n" + // End of day + "appointment n/P3 ic/S3333333C date/%s time/23:45\n" + // Very end of day + "listAppointments\nexit\n", + TODAY, TODAY, TODAY); + + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("00:00")); + assertTrue(output.contains("23:30")); + assertTrue(output.contains("The next available timeslot")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //@@author kaboomzxc + @Test + void testDateFormatHandling() { + String input = "add n/John Doe ic/S1234567A v/2024-11-01 14:30\n" + // Wrong date format + "add n/John Doe ic/S1234567A v/01-11-2024 24:00\n" + // Invalid time + "appointment n/John ic/S1234567A date/2024-11-01 time/14:30\n" + // Wrong date format + "appointment n/John ic/S1234567A date/01-11-2024 time/24:00\n" + // Invalid time + "exit\n"; + + provideInput(input); + try { + Main.main(new String[]{}); + String output = outputStreamCaptor.toString(); + assertTrue(output.contains("Invalid")); + assertTrue(output.contains("Error")); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/test/java/bookbob/entity/AppointmentRecordTest.java b/src/test/java/bookbob/entity/AppointmentRecordTest.java index a05c3073e1..20e3f4e9b7 100644 --- a/src/test/java/bookbob/entity/AppointmentRecordTest.java +++ b/src/test/java/bookbob/entity/AppointmentRecordTest.java @@ -14,9 +14,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AppointmentRecordTest { + private final Appointment firstAppointment = new Appointment("John Doe", "S1234567A", + "18-11-2024", "18:00"); + private final Appointment secondAppointment = new Appointment("Helen Smith", "S7654321A", + "18-11-2024", "19:00"); + private final AppointmentRecord appointmentRecord = new AppointmentRecord(); private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); private final PrintStream standardOut = System.out; - private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @BeforeEach public void setUp() { @@ -31,20 +36,14 @@ public void tearDown_for_helpCommand() { //@@author G13nd0n @Test void addAppointment_oneAppointment_oneAppointments() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); assertEquals(1, appointmentRecord.getAppointments().size()); } //@@author G13nd0n @Test void checkAvailability_unavailableTime_nextAvailableTime() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); LocalTime time = appointmentRecord.checkAvailability(LocalDate.parse("2024-11-18"), LocalTime.parse("18:00")); assertEquals(LocalTime.parse("18:30"), time); @@ -53,10 +52,7 @@ void checkAvailability_unavailableTime_nextAvailableTime() { //@@author G13nd0n @Test void checkAvailability_availableTime_nextAvailableTime() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); LocalTime time = appointmentRecord.checkAvailability(LocalDate.parse("2024-11-18"), LocalTime.parse("18:30")); assertEquals(LocalTime.parse("18:30"), time); @@ -65,13 +61,8 @@ void checkAvailability_availableTime_nextAvailableTime() { //@@author G13nd0n @Test void checkAvailability_selectedTimeBetween2Appointment_nextAvailableTime() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - Appointment second = new Appointment("Helen Smith", "S7654321A", "18-11-2024", - "19:00"); - appointmentRecord.addAppointment(first); - appointmentRecord.addAppointment(second); + appointmentRecord.addAppointment(firstAppointment); + appointmentRecord.addAppointment(secondAppointment); LocalTime time = appointmentRecord.checkAvailability(LocalDate.parse("2024-11-18"), LocalTime.parse("18:40")); assertEquals(LocalTime.parse("19:30"), time); @@ -80,10 +71,7 @@ void checkAvailability_selectedTimeBetween2Appointment_nextAvailableTime() { //@@author G13nd0n @Test void checkAvailability_selectedTimeDuringAppointment_nextAvailableTime() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); LocalTime time = appointmentRecord.checkAvailability(LocalDate.parse("2024-11-18"), LocalTime.parse("18:20")); assertEquals(LocalTime.parse("18:30"), time); @@ -92,26 +80,57 @@ void checkAvailability_selectedTimeDuringAppointment_nextAvailableTime() { //@@author G13nd0n @Test void checkAvailability_sameTimeDifferentDate_nextAvailableTime() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); LocalTime time = appointmentRecord.checkAvailability(LocalDate.parse("2024-11-19"), LocalTime.parse("18:00")); assertEquals(LocalTime.parse("18:00"), time); } + @Test + void findAppointments_name_noAppointments() { + List appointmentList = appointmentRecord.findAppointments("n/Smith"); + assertEquals(0, appointmentList.size()); + } + + @Test + void findAppointments_name_oneAppointments() { + Appointment third = new Appointment ("Will Smith", "S9876543A", "11-04-2025", + "00:00"); + appointmentRecord.addAppointment(firstAppointment); + appointmentRecord.addAppointment(secondAppointment); + appointmentRecord.addAppointment(third); + List appointmentList = appointmentRecord.findAppointments("n/Will Smith"); + assertEquals(1, appointmentList.size()); + } + + @Test + void findAppointments_nric_oneAppointment() { + appointmentRecord.addAppointment(firstAppointment); + appointmentRecord.addAppointment(secondAppointment); + List appointmentList = appointmentRecord.findAppointments("ic/S1234567A"); + assertEquals(1, appointmentList.size()); + } + + //@@author G13nd0n + @Test + void findAppointments_date_twoAppointments() { + Appointment third = new Appointment ("Will Smith", "S9876543A", "11-04-2025", + "00:00"); + appointmentRecord.addAppointment(firstAppointment); + appointmentRecord.addAppointment(secondAppointment); + appointmentRecord.addAppointment(third); + List appointmentList = appointmentRecord.findAppointments("date/18-11-2024"); + assertEquals(2, appointmentList.size()); + } + //@@author G13nd0n @Test void findAppointments_time_twoAppointments() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); Appointment second = new Appointment("Helen Smith", "S7654321A", "19-11-2024", "18:00"); Appointment third = new Appointment ("Will Smith", "S9876543A", "11-04-2025", "00:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); appointmentRecord.addAppointment(second); appointmentRecord.addAppointment(third); List appointmentList = appointmentRecord.findAppointments("time/18:00"); @@ -121,15 +140,12 @@ void findAppointments_time_twoAppointments() { //@@author G13nd0n @Test void setAppointment_twoAppointments_twoAppointments() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); AppointmentRecord updatedRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); Appointment second = new Appointment("Helen Smith", "S7654321A", "19-11-2024", "18:00"); Appointment third = new Appointment ("Will Smith", "S9876543A", "11-04-2025", "00:00"); - appointmentRecord.addAppointment(first); + appointmentRecord.addAppointment(firstAppointment); updatedRecord.addAppointment(second); updatedRecord.addAppointment(third); appointmentRecord.setAppointments(updatedRecord.getAppointments()); @@ -139,7 +155,6 @@ void setAppointment_twoAppointments_twoAppointments() { //author G13nd0n @Test void testAppointmentNotice_noInput_noAppointment() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); appointmentRecord.appointmentNotice(); String expected = "No appointments scheduled for today"; assertEquals(expected, outputStreamCaptor.toString().trim().replace(System.lineSeparator(), @@ -149,10 +164,9 @@ void testAppointmentNotice_noInput_noAppointment() { //author G13nd0n @Test void testAppointmentNotice_appointmentAfterToday_noAppointment() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - appointmentRecord.addAppointment(first); + String date = LocalDate.now().plusDays(1).format(formatter); + Appointment tomorrow = new Appointment("Mary Ong", "S3456789A", date, "18:00"); + appointmentRecord.addAppointment(tomorrow); appointmentRecord.appointmentNotice(); String expected = "No appointments scheduled for today"; assertEquals(expected, outputStreamCaptor.toString().trim().replace(System.lineSeparator(), @@ -162,15 +176,15 @@ void testAppointmentNotice_appointmentAfterToday_noAppointment() { //author G13nd0n @Test void testAppointmentNotice_appointmentToday_oneAppointment() { - AppointmentRecord appointmentRecord = new AppointmentRecord(); String date = LocalDate.now().format(formatter); - Appointment first = new Appointment("John Doe", "S1234567A", date, - "18:00"); - appointmentRecord.addAppointment(first); + Appointment todayAppointment = new Appointment("Steven Lim", "S9876543A", + date, "18:00"); + appointmentRecord.addAppointment(todayAppointment); appointmentRecord.appointmentNotice(); String expected = "Appointment scheduled for today:\n" + "Appointment on " + date +" 18:00 with " + - "Patient John Doe, S1234567A."; + "Patient Steven Lim, S9876543A."; assertEquals(expected, outputStreamCaptor.toString().trim().replace(System.lineSeparator(), "\n")); } + } diff --git a/src/test/java/bookbob/entity/AppointmentTest.java b/src/test/java/bookbob/entity/AppointmentTest.java index c23cec77fe..8a1e59e05a 100644 --- a/src/test/java/bookbob/entity/AppointmentTest.java +++ b/src/test/java/bookbob/entity/AppointmentTest.java @@ -8,99 +8,82 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AppointmentTest { + private final Appointment firstAppointment = new Appointment("John Doe", "S1234567A", + "18-11-2024", "18:00"); + private final Appointment secondAppointment = new Appointment("Helen Smith", "S7654321A", + "18-11-2024", "18:30"); + private final Appointment thirdAppointment = new Appointment("Will Ferrel", "S9876543A", + "18-11-2024", "19:00"); + private final Appointment fourthAppointment = new Appointment("Tom Hanks", "S3456789A", + "19-11-2024", "18:00"); //@@author G13nd0n @Test void testNameGetter_noInput_name() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - String name = first.getPatientName(); + String name = firstAppointment.getPatientName(); assertEquals("John Doe", name); } //@@author G13nd0n @Test void testNricGetter_noInput_nric() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - String nric = first.getPatientNric(); - + String nric = firstAppointment.getPatientNric(); assertEquals("S1234567A", nric); } //@@author G13nd0n @Test void testDateGetter_noInput_date() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - LocalDate date = first.getDate(); - + LocalDate date = firstAppointment.getDate(); assertEquals(LocalDate.parse("2024-11-18"), date); } //@@author G13nd0n @Test void testTimeGetter_noInput_time() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - LocalTime time = first.getTime(); - + LocalTime time = firstAppointment.getTime(); assertEquals(LocalTime.parse("18:00"), time); } //@@author G13nd0n @Test void testConsultationDurationGetter_noInput_duration() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - long duration = first.getConsultationDuration(); + long duration = firstAppointment.getConsultationDuration(); assertEquals(30, duration); } //@@author G13nd0n @Test - void compareTo_firstBeforeSecond_negativeOne() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); - Appointment second = new Appointment("Helen Smith", "S7654321A", "18-11-2024", - "18:30"); - int result = first.compareTo(second); - + void compareTo_firstAppointmentBeforeSecondAppointmentInTime_negativeOne() { + int result = firstAppointment.compareTo(secondAppointment); assertEquals(-1, result); } //@@author G13nd0n @Test void compareTo_twoInputs_one() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "19:00"); - Appointment second = new Appointment("Helen Smith", "S7654321A", "18-11-2024", - "18:30"); - int result = first.compareTo(second); - + int result = thirdAppointment.compareTo(secondAppointment); assertEquals(1, result); } //@@author G13nd0n @Test - void compareTo_differenceInDate_negativeOne() { - Appointment first = new Appointment("John Doe", "S1234567A", "17-11-2024", - "18:00"); - Appointment second = new Appointment("Helen Smith", "S7654321A", "18-11-2024", - "18:30"); - int result = first.compareTo(second); - + void compareTo_firstAppointmentBeforeFourthAppointmentInDay_negativeOne() { + int result = firstAppointment.compareTo(fourthAppointment); assertEquals(-1, result); } //@@author G13nd0n @Test - void toString_noInput_string() { - Appointment first = new Appointment("John Doe", "S1234567A", "18-11-2024", - "18:00"); + void compareTo_fourthAppointmentAfterFirstAppointmentInDay_negativeOne() { + int result = fourthAppointment.compareTo(firstAppointment); + assertEquals(1, result); + } + //@@author G13nd0n + @Test + void toString_noInput_string() { String result ="Appointment on 18-11-2024 18:00 with Patient John Doe, S1234567A."; - - assertEquals(result, first.toString()); + assertEquals(result, firstAppointment.toString()); } } diff --git a/src/test/java/bookbob/functions/CommandHandlerTest.java b/src/test/java/bookbob/functions/CommandHandlerTest.java index ae82084f98..c2f61fad5e 100644 --- a/src/test/java/bookbob/functions/CommandHandlerTest.java +++ b/src/test/java/bookbob/functions/CommandHandlerTest.java @@ -66,43 +66,41 @@ void helpCommand_noInput_outputsCommandHelp() { "| | TIME format: HH:mm | m/Paracetamol,Ibuprofen |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + "| Edit Visit | editVisit ic/NRIC | editVisit ic/S7209876Y |\n" + - "| | date/VISIT_DATE_AND_TIME | date/06-11-2024 14:00 |\n" + - "| | [newDate/NEW_DATE] [d/DIAGNOSIS] | newDate/08-11-2024 14:00 |\n" + + "| | date/VISIT_DATE_TIME | date/06-11-2024 14:00 |\n" + + "| | [newDate/NEW_DATE_TIME] [d/DIAGNOSIS]| newDate/08-11-2024 14:00 |\n" + "| | [m/MEDICATION] | d/Asthma m/Panadol, Antibiotics |\n" + "| | DATE format: dd-mm-yyyy | |\n" + "| | TIME format: HH:mm | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + "| List | list | list |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + - "| Find | find n/NAME OR | find n/John Doe |\n" + - "| | find ic/NRIC OR | find ic/S1234 |\n" + - "| | find p/PHONE_NUMBER OR | find p/91234567 |\n" + - "| | find d/DIAGNOSIS OR | find d/Fever |\n" + - "| | find m/MEDICATION OR | find m/Panadol |\n" + - "| | find ha/HOME_ADDRESS OR | find ha/NUS PGPR |\n" + + "| Find | find n/NAME OR | find n/John Doe |\n" + + "| | find ic/NRIC OR | find ic/S1234 |\n" + + "| | find p/PHONE_NUMBER OR | find p/91234567 |\n" + + "| | find ha/HOME_ADDRESS OR | find ha/NUS PGPR |\n" + "| | find dob/DATE_OF_BIRTH OR | find dob/01011990 |\n" + - "| | find al/ALLERGY OR | find al/Peanuts |\n" + - "| | find find s/SEX OR | find find s/Female |\n" + + "| | find al/ALLERGY OR | find al/Peanuts |\n" + + "| | find s/SEX OR | find s/Female |\n" + "| | find mh/MEDICAL_HISTORY | find mh/Diabetes |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + "| Delete | delete NRIC | delete S9534567A |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + - "| Add | appointment n/NAME ic/NRIC | add n/James Ho ic/S9534567A |\n" + - "| Appointment | date/DATE time/TIME | date/01-04-2025 time/12:00 |\n" + - "| | DATE format: dd-mm-yyyy | |\n" + + "| Add | appointment n/NAME ic/NRIC | appointment n/James Ho |\n" + + "| Appointment | date/DATE time/TIME | ic/S9534567A date/01-04-2025 |\n" + + "| | DATE format: dd-mm-yyyy | time/12:00 |\n" + "| | TIME format: HH:mm | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + - "| List | listAppointments | list |\n" + + "| List | listAppointments | listAppointments |\n" + "| Appointment | | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + "| Find | findAppointment n/NAME OR | findAppointment n/John Doe |\n" + - "| Appointment | findAppointment ic/NRIC OR | findAppointment ic/S1234 |\n" + + "| Appointment | findAppointment ic/NRIC OR | findAppointment ic/S1234567A |\n" + "| | findAppointment date/DATE OR | findAppointment date/01-04-2025 |\n" + "| | findAppointment time/TIME OR | findAppointment time/12:00 |\n" + "| | DATE format: dd-mm-yyyy | |\n" + "| | TIME format: HH:mm | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + - "| Delete | deleteAppointment NRIC | deleteAppointment S9534567A |\n" + + "| Delete | deleteAppointment ic/NRIC | deleteAppointment ic/S9534567A |\n" + "| Appointment | date/DATE time/TIME | date/01-04-2025 time/12:00 |\n" + "| | DATE format: dd-mm-yyyy | |\n" + "| | TIME format: HH:mm | |\n" + @@ -116,7 +114,7 @@ void helpCommand_noInput_outputsCommandHelp() { "| Find | findMedication medication | findMedication Panadol |\n" + "| Medication | | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + - "| Save | save(automatic) | |\n" + + "| Save | save (automatic) | |\n" + "+-------------+---------------------------------------+---------------------------------+\n" + "| Retrieve/ | retrieve or import | |\n" + "| Import | (automatic) | |\n" + diff --git a/src/test/java/bookbob/functions/FileHandlerTest.java b/src/test/java/bookbob/functions/FileHandlerTest.java index 7747739506..b10f21cda2 100644 --- a/src/test/java/bookbob/functions/FileHandlerTest.java +++ b/src/test/java/bookbob/functions/FileHandlerTest.java @@ -41,7 +41,7 @@ void testTextConverterFullInformationRecords() throws IOException { Patient patient = new Patient("John", "S9765432T", "87658976", "06071997", "Bukit Gombak", allergies, "Male", medicalHistory, visits); - String output = fileHandler.convertPatientToOutputText(patient); + String output = patient.convertPatientToOutputText(); assertEquals(output, "Name: John | NRIC: S9765432T | Phone Number: 87658976 | " + "Date_Of_Birth: 06071997 | Home Address: Bukit Gombak | Allergy: [Peanuts] " + "| Sex: Male | Medical History: [History of gastritis] | Visit: " + @@ -58,7 +58,7 @@ void testTextConverterPartialInformationRecords() { ArrayList visits = new ArrayList<>(); visits.add(new Visit(visitDateTime)); Patient patient = new Patient("John", "S9765432T", visits); - String output = fileHandler.convertPatientToOutputText(patient); + String output = patient.convertPatientToOutputText(); assertEquals(output, "Name: John | NRIC: S9765432T | Phone Number: | " + "Date_Of_Birth: | Home Address: | Allergy: [] | Sex: | Medical History: [] | " + "Visit: [21-10-2024 15:48, Diagnosis: [], Medications: []];"); @@ -72,7 +72,7 @@ void testTextConverterAppointmentRecords() { String date = "21-10-2024"; String time = "15:48"; Appointment appointment = new Appointment(name, nric, date, time); - String output = fileHandler.convertPatientToOutputText(appointment); + String output = appointment.convertPatientToOutputText(); assertEquals(output, "Name: John|NRIC: S9765432T|Date: 21-10-2024|Time: 15:48"); }