Skip to content
Snippets Groups Projects
client.ts 10.8 KiB
Newer Older
„Sophia's avatar
„Sophia committed
// Funktion, die die aktive Seite anzeigt und alle anderen ausblendet
function showPage(pageId: string): void {
  // Alle Seiten ausblenden
  const pages: NodeListOf<HTMLDivElement> = document.querySelectorAll('.page');
  pages.forEach((page: HTMLDivElement) => {
    page.classList.remove('active');
  });

  // Die ausgewählte Seite anzeigen
  const activePage: HTMLElement | null = document.getElementById(pageId);
  if (activePage) {
    activePage.classList.add('active');
  } else {
    console.error(`Seite mit der ID "${pageId}" wurde nicht gefunden.`);
  }
}

// Event-Listener für die Initialisierung beim Laden der Seite
document.addEventListener('DOMContentLoaded', () => {
  showPage('reisen'); // Standardmäßig die Seite "Reisen" anzeigen
});

„Sophia's avatar
„Sophia committed
interface User {
„Sophia's avatar
„Sophia committed
  user_id: number;
  firstName: string;
  lastName: string;
  eMail: string;
  adress: string;
  role: string;
„Sophia's avatar
„Sophia committed
}

let modalEl: bootstrap.Modal

document.addEventListener("DOMContentLoaded", (): void => {
  modalEl = new bootstrap.Modal("#edit-user-modal");

Sarah Gloger's avatar
Sarah Gloger committed
  // --- Initialisierung der Benutzeranzeige ---
  readUsers();
„Sophia's avatar
„Sophia committed

Sarah Gloger's avatar
Sarah Gloger committed
  // --- Registrierungsformular Eventhandler ---
„Sophia's avatar
„Sophia committed
  document.getElementById("add-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
    event.preventDefault();
„Sophia's avatar
„Sophia committed
    const firstNameEl: HTMLInputElement = document.getElementById("add-user-first-name") as HTMLInputElement;
    const lastNameEl: HTMLInputElement = document.getElementById("add-user-last-name") as HTMLInputElement;
Sarah Gloger's avatar
Sarah Gloger committed
    const eMailEl: HTMLInputElement = document.getElementById("add-user-email") as HTMLInputElement;
    const passwordEl: HTMLInputElement = document.getElementById("add-user-password") as HTMLInputElement;
    const repeatPasswordEl: HTMLInputElement = document.getElementById("add-user-repeatPassword") as HTMLInputElement;
„Sophia's avatar
„Sophia committed

    const firstName: string = firstNameEl.value;
    const lastName: string = lastNameEl.value;
Sarah Gloger's avatar
Sarah Gloger committed
    const eMail: string = eMailEl.value;
    const password: string = passwordEl.value;
    const repeatPassword: string = repeatPasswordEl.value;
„Sophia's avatar
„Sophia committed

Sarah Gloger's avatar
Sarah Gloger committed
    // Check, if any given value is empty
    if (!firstName || !lastName || !eMail || !password || !repeatPassword) {
      addMessage("Bitte alle Felder ausfüllen!");
      return;
    }
„Sophia's avatar
„Sophia committed

Sarah Gloger's avatar
Sarah Gloger committed
    // Validate passwords match
    if (password !== repeatPassword) {
      addMessage("Passwörter stimmen nicht überein!");
„Sophia's avatar
„Sophia committed
      return;
    }

Sarah Gloger's avatar
Sarah Gloger committed
    // Send user data to server
„Sophia's avatar
„Sophia committed
    const res: Response = await fetch('/user', {
Sarah Gloger's avatar
Sarah Gloger committed
      method: 'POST',
„Sophia's avatar
„Sophia committed
      headers: {
Sarah Gloger's avatar
Sarah Gloger committed
        "Content-type": "application/json",
„Sophia's avatar
„Sophia committed
      },
Sarah Gloger's avatar
Sarah Gloger committed
      body: JSON.stringify({ firstName, lastName, eMail, password, repeatPassword }),
„Sophia's avatar
„Sophia committed
    });
    const data: any = await res.json();

    addMessage(data.message);

Sarah Gloger's avatar
Sarah Gloger committed
    if (res.ok) {
      // Clear the input fields
      firstNameEl.value = "";
      lastNameEl.value = "";
      eMailEl.value = "";
      passwordEl.value = "";
      repeatPasswordEl.value = "";
    }
„Sophia's avatar
„Sophia committed
  });

  document.getElementById("edit-user-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
    event.preventDefault();
    let idEl: HTMLInputElement = document.getElementById("edit-user-id") as HTMLInputElement;
„Sophia's avatar
„Sophia committed
    let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement;
    let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement;
„Sophia's avatar
„Sophia committed

    // Read the user's id from the hidden field.
    let userId: number = parseInt(idEl.value);
„Sophia's avatar
„Sophia committed
    let firstName: string = firstNameEl.value;
    let lastName: string = lastNameEl.value;
„Sophia's avatar
„Sophia committed

    const res: Response = await fetch('/user/' + userId, {
      method: 'put',
      headers: {
        "Content-type": "application/json"
      },
„Sophia's avatar
„Sophia committed
      body: JSON.stringify({ firstName, lastName }),
„Sophia's avatar
„Sophia committed
    });
    const data: any = await res.json();
    addMessage(data.message);

    // Hide the modal window
    modalEl.hide();

    // Update the html
    readUsers();
  });

Sarah Gloger's avatar
Sarah Gloger committed
  document.getElementById("dropdown-anmelden")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
„Sophia's avatar
„Sophia committed
    event.preventDefault();
Sarah Gloger's avatar
Sarah Gloger committed
    const eMailInput: HTMLInputElement = document.getElementById('exampleDropdownFormEmail2') as HTMLInputElement;
    const passwordInput: HTMLInputElement = document.getElementById('exampleDropdownFormPassword2') as HTMLInputElement;
„Sophia's avatar
„Sophia committed

Sarah Gloger's avatar
Sarah Gloger committed
    const eMail: string = eMailInput.value;
„Sophia's avatar
„Sophia committed
    const password: string = passwordInput.value;

    const response: Response = await fetch('http://localhost:8080/login', {
        method: "POST",
        headers: {
          "Content-type": "application/json"
        },
Sarah Gloger's avatar
Sarah Gloger committed
        body: JSON.stringify({eMail, password}),
„Sophia's avatar
„Sophia committed
      }
    );

    if (response.status === 400 || response.status === 401) {
      const data: any = await response.json();
      addMessage(data.message);
    } else if (response.status === 200) {
      const data: any = await response.json();
      addMessage(data.message);
      showLoggedInStatus(data.user);
    } else {
      console.warn(`Unhandled response code (${response.status}).`)
    }
  });

  document.getElementById("logout-form")!.addEventListener("submit", async (event: SubmitEvent): Promise<void> => {
    event.preventDefault();
    await fetch('http://localhost:8080/logout', {
        method: "POST",
      }
    );
    showLoggedOutStatus()
  });
});


/**
 * Gets and displays all users
 */
async function readUsers(): Promise<void> {
  const res: Response = await fetch('/users', {
      method: "GET"
    }
  );
  const data: any = await res.json();
  renderList(data.userList);
}

/**
 * Displays the logged in username
 */
function showLoggedInStatus(user: User): void {
Sarah Gloger's avatar
Sarah Gloger committed
  const eMail: HTMLElement = document.getElementById('current-user-email')!;
  eMail.innerHTML = `Hello ${user.firstName}`;
„Sophia's avatar
„Sophia committed

  readUsers();
}

/**
 * Resets the site to the logged-out state.
 * Clears user list, shows login form, hides logout form-
 */
function showLoggedOutStatus(): void {
Sarah Gloger's avatar
Sarah Gloger committed
  const eMail: HTMLElement = document.getElementById('current-user-email')!;
  eMail.innerHTML = ``;
„Sophia's avatar
„Sophia committed

  const addUserForm: HTMLElement = document.getElementById('add-user-container')!;
  addUserForm.classList.add("d-none"); // hide content area

  const contentArea: HTMLElement = document.getElementById('user-list-container')!;
  contentArea.classList.add("d-none"); // hide content area

  const login: HTMLElement = document.getElementById('login-container')!;
  login.classList.remove("d-none"); // show login

  const logout: HTMLElement = document.getElementById('logout-container')!;
  logout.classList.add("d-none"); // hide logout

  (document.getElementById('add-user-form') as HTMLFormElement).reset();
}

Sarah Gloger's avatar
Sarah Gloger committed
/// für ADMIN wieder relevant
„Sophia's avatar
„Sophia committed
/**
 * 1) Clears the user table.
 * 2) Adds all users to the table.
 */
function renderList(userList: User[]): void {
  let userListEl: HTMLElement = document.getElementById("user-list")!;

  // Remove all entries from the table
  userListEl.replaceChildren();

  for (let user of userList) {
    // The new table row
    let tr: HTMLTableRowElement = document.createElement("tr");

    // ID cell
„Sophia's avatar
„Sophia committed
    let tdUser_id: HTMLTableCellElement = document.createElement("td");
    tdUser_id.textContent = user.user_id.toString();
„Sophia's avatar
„Sophia committed

    // Given name cell
„Sophia's avatar
„Sophia committed
    let tdFirstName: HTMLTableCellElement = document.createElement("td");
    tdFirstName.textContent = user.firstName;
„Sophia's avatar
„Sophia committed

    // Family name cell
„Sophia's avatar
„Sophia committed
    let tdLastName: HTMLTableCellElement = document.createElement("td");
    tdLastName.textContent = user.lastName;

    // email cell
    let tdEmail: HTMLTableCellElement = document.createElement("td");
    tdEmail.textContent = user.eMail;

    // adress cell
    let tdAdress: HTMLTableCellElement = document.createElement("td");
    tdAdress.textContent = user.adress;
„Sophia's avatar
„Sophia committed

„Sophia's avatar
„Sophia committed
    // role cell
    let tdRole: HTMLTableCellElement = document.createElement("td");
    tdRole.textContent = user.role;
„Sophia's avatar
„Sophia committed

    // Buttons cell
    let tdButtons: HTMLTableCellElement = document.createElement("td");

    // Delete button
    let deleteButton: HTMLButtonElement = document.createElement("button");
    deleteButton.className = "btn btn-danger";
    deleteButton.addEventListener("click", async () => {
„Sophia's avatar
„Sophia committed
      const res: Response = await fetch('/user/' + user.user_id, {
„Sophia's avatar
„Sophia committed
        method: 'DELETE'
      });
      const data: any = await res.json();
      addMessage(data.message);
      readUsers();
    });

    // Delete button icon
    let deleteButtonIcon: HTMLElement = document.createElement("i");
    deleteButtonIcon.className = "fa-solid fa-trash";
    deleteButton.append(deleteButtonIcon);

    // Edit button
    let editButton: HTMLButtonElement = document.createElement("button");
    editButton.className = "btn btn-primary ms-3";
    editButton.addEventListener("click", () => {
      showEditModal(user);
    });

    // Edit button icon
    let editButtonIcon: HTMLElement = document.createElement("i");
    editButtonIcon.className = "fa-solid fa-pen";
    editButton.append(editButtonIcon);

    // Adds the buttons to the button cell
    tdButtons.append(deleteButton, editButton);

    // Add the cells to the table row
„Sophia's avatar
„Sophia committed
    tr.append(tdUser_id, tdFirstName, tdLastName, tdEmail,tdAdress, tdRole, tdButtons);
„Sophia's avatar
„Sophia committed

    // Add the table row to the table
    userListEl.append(tr);
  }
}

/**
 * 1) Fills the modal window with the given user's data.
 * 2) Opens the modal window.
 */
function showEditModal(user: User): void {
„Sophia's avatar
„Sophia committed
  let user_idEl: HTMLInputElement = document.getElementById("edit-user-user_id") as HTMLInputElement;
  let firstNameEl: HTMLInputElement = document.getElementById("edit-user-first-name") as HTMLInputElement;
  let lastNameEl: HTMLInputElement = document.getElementById("edit-user-last-name") as HTMLInputElement;
„Sophia's avatar
„Sophia committed

  // Write the user's id into the hidden field.
„Sophia's avatar
„Sophia committed
  user_idEl.value = user.user_id.toString();
„Sophia's avatar
„Sophia committed

  // Write the user's data into the text fields.
„Sophia's avatar
„Sophia committed
  firstNameEl.value = user.firstName;
  lastNameEl.value = user.lastName;
„Sophia's avatar
„Sophia committed

  // Show the modal window.
  modalEl.show();
}

/**
 * Creates a new alert message.
 */
function addMessage(message: string): void {
  const messagesEl: HTMLElement = document.getElementById('messages')!;

  // The alert element
  let alertEl: HTMLElement = document.createElement('div');
  alertEl.classList.add('alert', 'alert-warning', 'alert-dismissible', 'fade', 'show');
  alertEl.setAttribute('role', 'alert');
  alertEl.textContent = message;

  // Close button
  let buttonEl: HTMLElement = document.createElement("button");
  // btn-close changes the button into an 'X' icon.
  buttonEl.className = "btn-close";
  // data-bs-dismiss enables the button to automatically close the alert on click.
  buttonEl.setAttribute("data-bs-dismiss", "alert");

  // Add the close button to the alert.
  alertEl.appendChild(buttonEl);

  // Convert to Bootstrap Alert type
  const alert: bootstrap.Alert = new bootstrap.Alert(alertEl);

  // Add message to DOM
  messagesEl.appendChild(alertEl);

  // Auto-remove message after 5 seconds (5000ms)
  setTimeout(() => {
    alert.close();
  }, 5000);
}
„Sophia's avatar
„Sophia committed