Skip to content
Snippets Groups Projects
section.js 11.5 KiB
Newer Older
  • Learn to ignore specific revisions
  • // Imports
    import * as Auth from "/services/auth/auth.js";
    import * as Common from "/services/common/common.js";
    import * as Messages from "/services/messages/messages.js";
    import { Delete } from "/services/common/delete.js";
    
    // DOM elements
    
    // local variables
    let current_user;
    
    export async function mount(where, parent) {
      const sectionComponent = new Section(parent);
      await sectionComponent.mount(where);
      return sectionComponent;
    }
    
    class Section {
      constructor(parent) {
        this.parent = parent;
      }
    
      async mount(where) {
        const mountpoint = where;
        document.getElementById(mountpoint).innerHTML = /* HTML */ `
          <header class="card-header">
            <p class="card-header-title" id="section-title">
              Sections
            </p>
            <button id="section-new" class="button is-success" disabled>
              <span class="icon is-small">
                <i class="fas fa-plus"></i>
              </span>
            </button>
          </header>
          <div class="card-content">
            <div id="section-list" class="content">
              Sélectionner une circonscription.
            </div>
          </div>
        `;
        current_user = await Auth.GetUser();
        this.mountModal("section-modal");
        this.handleDom();
      }
    
      handleDom() {
        let sectionHandler = this;
        document
          .getElementById(`section-new`)
          .addEventListener("click", function () {
            sectionHandler.newSection(sectionHandler.area);
          });
    
        document
          .getElementById(`section-modal-close`)
          .addEventListener("click", function () {
            Common.toggleModal("section-modal", "section-modal-card");
          });
        document
          .getElementById(`section-modal-cancel`)
          .addEventListener("click", function () {
            Common.toggleModal("section-modal", "section-modal-card");
          });
        document
          .getElementById(`section-modal-save`)
          .addEventListener("click", async function () {
            await sectionHandler.saveSection();
          });
        document
          .getElementById(`section-modal-save-section`)
          .addEventListener("click", async function () {
            await sectionHandler.saveSection();
            await new Promise((r) => setTimeout(r, 800));
            sectionHandler.newSection(sectionHandler.area);
          });
        document
          .getElementById(`section-modal-save-desk`)
          .addEventListener("click", async function () {
            let section = await sectionHandler.saveSection();
            await new Promise((r) => setTimeout(r, 800));
            sectionHandler.parent.deskHandler.section = section;
            sectionHandler.parent.deskHandler.newDesk(section);
          });
      }
    
      mountModal(where) {
        const mountpoint = where;
        document.getElementById(mountpoint).innerHTML = /* HTML */ `
          <div class="modal-background"></div>
          <div class="modal-card" id="section-modal-card">
            <header class="modal-card-head">
              <p class="modal-card-title">
                Ajout/modification d'une section
              </p>
              <button
                class="delete"
                aria-label="close"
                id="section-modal-close"
              ></button>
            </header>
            <section class="modal-card-body">
              <div class="field">
                <label>Id</label>
                <div class="control">
                  <input
                    class="input"
                    type="number"
                    id="section-modal-id"
                    disabled
                  />
                </div>
              </div>
              <div class="field">
                <label>Nom</label>
                <div class="control">
                  <input class="input" type="text" id="section-modal-name" />
                </div>
              </div>
            </section>
            <footer class="modal-card-foot">
              <button id="section-modal-save" class="button is-success">
                Sauvegarder
              </button>
              <button id="section-modal-save-section" class="button is-success">
                Sauvegarder <br />
                (ajouter section)
              </button>
              <button id="section-modal-save-desk" class="button is-success">
                Sauvegarder <br />
                (ajouter bureau)
              </button>
              <button id="section-modal-cancel" class="button">Annuler</button>
            </footer>
          </div>
        `;
      }
    
      async displaySections() {
        let sectionHandler = this;
        let sections = await this.updateSections();
        const markup = sections
          .map((section) => this.sectionTemplate(section))
          .join("");
        document.getElementById("section-list").innerHTML = markup;
        document.getElementById("section-new").removeAttribute("disabled");
        document.getElementById("section-title").innerHTML =
          "Sections de&nbsp;<em> " + this.area.Name + "</em>";
    
        sections.map((section) => {
          document
            .getElementById(`sections-section-edit-${section.ID}`)
            .addEventListener("click", function () {
              sectionHandler.editSection(section);
            });
          document
            .getElementById(`sections-section-delete-${section.ID}`)
            .addEventListener("click", function () {
              new Delete(() => {
                sectionHandler.deleteSection(section);
              });
            });
          document
            .getElementById(`sections-section-${section.ID}`)
            .addEventListener("click", function () {
              sectionHandler.activateSection(section);
              sectionHandler.parent.deskHandler.section = section;
              sectionHandler.parent.deskHandler.displayDesks();
              document.getElementById("desk-new").setAttribute("disabled", "true");
            });
        });
      }
    
      emptySections() {
        this.area = null;
        document.getElementById("section-title").innerHTML = "Sections";
        document.getElementById("section-list").innerHTML =
          "Veuillez sélectionner une circonscription";
      }
    
      sectionTemplate(section) {
        return /* HTML */ `<div class="card card-list">
          <div id="sections-section-${section.ID}" class="card-content">
            <div class="content">
              <nav class="level">
                <div class="level-left">
                  ${section.Name}
                </div>
                <div class="level-right">
                  <a
                    id="sections-section-edit-${section.ID}"
                    class="button is-link is-small"
                    title="Modifier"
                  >
                    <span class="icon is-small">
                      <i class="fas fa-pen"></i>
                    </span>
                  </a>
                  <a
                    id="sections-section-delete-${section.ID}"
                    class="button is-danger is-small"
                    title="Supprimer"
                  >
                    <span class="icon is-small">
                      <i class="fas fa-times"></i>
                    </span>
                  </a>
                </div>
              </nav>
            </div>
          </div>
        </div>`;
      }
    
    
      async activateSection(sectionToActivate) {
    
        this.parent.deskHandler.emptyDesks();
        let sections = await this.updateSections();
        sections.forEach((section) => {
          document
            .getElementById(`sections-section-${section.ID}`)
            .classList.remove("active-card");
        });
        document
    
          .getElementById(`sections-section-${sectionToActivate.ID}`)
    
          .classList.add("active-card");
      }
    
      newSection(area) {
        this.method = "POST";
        this.area = area;
        document.getElementById("section-modal-id").value = null;
        document.getElementById("section-modal-name").value = area.Name;
        Common.toggleModal("section-modal", "section-modal-card");
      }
    
      editSection(section) {
        this.method = "PUT";
        document.getElementById("section-modal-id").value = section.ID;
        document.getElementById("section-modal-name").value = section.Name;
        Common.toggleModal("section-modal", "section-modal-card");
      }
    
      async saveSection() {
        let section;
        if (this.method == "POST")
          document.getElementById("section-modal-id").value = null;
    
        try {
          const response = await fetch(
            "/api/Section/" + document.getElementById("section-modal-id").value,
            {
              method: this.method,
              headers: new Headers({
                "XSRF-Token": current_user.xsrftoken,
              }),
              body: JSON.stringify({
                ID: parseInt(document.getElementById("section-modal-id").value),
                AreaID: this.area.ID,
                Name: document.getElementById("section-modal-name").value,
              }),
            }
          );
          if (response.status !== 200) {
            throw new Error(
              `Section could not be updated or created (status ${response.status})`
            );
          }
          section = await response.json();
          await this.displaySections();
        } catch (e) {
          Messages.Show("is-warning", e.message);
          console.error(e);
        }
        Common.toggleModal("section-modal", "section-modal-card");
        this.activateSection(section);
        this.parent.deskHandler.section = section;
        this.parent.deskHandler.displayDesks();
        return section;
      }
    
      async updateSections() {
        let sectionHandler = this;
        try {
          const response = await fetch("/api/Section/", {
            method: "GET",
            headers: new Headers({
              "XSRF-Token": current_user.xsrftoken,
            }),
          });
          if (response.status !== 200) {
            throw new Error(
              `Sections could not be fetched (status ${response.status})`
            );
          }
          let sections = await response.json();
          return sections.filter(function (section) {
            return section.AreaID == sectionHandler.area.ID;
          });
        } catch (e) {
          Messages.Show("is-warning", e.message);
          console.error(e);
        }
      }
    
      async deleteSection(section) {
        try {
          const response = await fetch("/api/Section/" + section.ID, {
            method: "delete",
            headers: new Headers({
              "XSRF-Token": current_user.xsrftoken,
            }),
          });
          if (response.status !== 200) {
            throw new Error(
              `Section could not be deleted (status ${response.status})`
            );
          }
        } catch (e) {
          Messages.Show("is-warning", e.message);
          console.error(e);
        }
        this.displaySections();
        this.parent.deskHandler.emptyDesks();
        document.getElementById("desk-new").setAttribute("disabled", "true");
      }
    
    
      async cloneSections(areaCloned, areaToClone) {
        let sectionHandler = this;
        await areaToClone.Sections.forEach(async (sectionToClone) => {
          try {
            sectionToClone = await sectionHandler.getSection(sectionToClone.ID);
            const response = await fetch("/api/Section/", {
              method: "POST",
              headers: new Headers({
                "XSRF-Token": current_user.xsrftoken,
              }),
              body: JSON.stringify({
                ID: null,
                AreaID: areaCloned.ID,
                Name: sectionToClone.Name,
              }),
            });
            if (response.status !== 200) {
              throw new Error(
                `Section could not be cloned (status ${response.status})`
              );
            }
            let sectionCloned = await response.json();
            await sectionHandler.parent.deskHandler.cloneDesks(
              sectionCloned,
              sectionToClone
            );
          } catch (e) {
            Messages.Show("is-warning", e.message);
            console.error(e);
          }
        });
      }
    
      async getSection(id) {
        try {
          const response = await fetch("/api/Section/" + id, {
            method: "GET",
            headers: new Headers({
              "XSRF-Token": current_user.xsrftoken,
            }),
          });
          if (response.status !== 200) {
            throw new Error(
              `Section could not be fetched (status ${response.status})`
            );
          }
          return await response.json();
        } catch (e) {
          Messages.Show("is-warning", e.message);
          console.error(e);
        }
      }