Proyectos de Subversion Moodle

Rev

Rev 1225 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Add bulk actions to the users list report
18
 *
19
 * @module     core_admin/bulk_user_actions
20
 * @copyright  2024 Marina Glancy
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
 
361 ariadna 24
import * as reportSelectors from "core_reportbuilder/local/selectors";
25
import * as tableEvents from "core_table/local/dynamic/events";
26
import * as FormChangeChecker from "core_form/changechecker";
27
import * as CustomEvents from "core/custom_interaction_events";
28
import jQuery from "jquery";
1 efrain 29
 
30
const Selectors = {
361 ariadna 31
  bulkActionsForm: "form#user-bulk-action-form",
32
  userReportWrapper: '[data-region="report-user-list-wrapper"]',
33
  checkbox:
34
    'input[type="checkbox"][data-togglegroup="report-select-all"][data-toggle="slave"]',
35
  masterCheckbox:
36
    'input[type="checkbox"][data-togglegroup="report-select-all"][data-toggle="master"]',
37
  checkedRows:
38
    '[data-togglegroup="report-select-all"][data-toggle="slave"]:checked',
1226 ariadna 39
  filtersForm: 'form#filters-form', // Seleccionamos el formulario de filtros
1 efrain 40
};
41
 
42
/**
1226 ariadna 43
 * Función para resetear los filtros
1 efrain 44
 */
1226 ariadna 45
const resetFilters = () => {
46
  const filterForm = document.querySelector(Selectors.filtersForm); // Asegúrate de que el selector coincide con los filtros
47
  if (!filterForm) return;
48
 
49
  // Crear un objeto FormData que contendrá todos los valores del formulario
50
  const formData = new FormData(filterForm);
51
 
52
  // Iterar sobre cada elemento de input en el formulario
53
  filterForm.querySelectorAll("input, select").forEach((element) => {
54
    if (element.type === "checkbox" || element.type === "radio") {
55
      // Si es un checkbox o radio, desmarcarlo
56
      element.checked = false;
57
    } else {
58
      // Si es un input de texto o select, limpiar el valor
59
      element.value = "";
60
    }
61
 
62
    // Opcional: para asegurarse de que los valores del FormData también se reseteen
63
    formData.set(element.name, "");
64
  });
65
 
66
  // Si hay algún elemento select, deseleccionar la opción seleccionada
67
  filterForm.querySelectorAll("select").forEach((select) => {
68
    select.selectedIndex = -1; // Deseleccionar la opción seleccionada
69
  });
70
};
71
 
72
/**
73
 * Initialize module
74
 */
1 efrain 75
export const init = () => {
361 ariadna 76
  const userBulkForm = document.querySelector(Selectors.bulkActionsForm);
77
  const userReport = userBulkForm
78
    ?.closest(Selectors.userReportWrapper)
79
    ?.querySelector(reportSelectors.regions.report);
80
  if (!userBulkForm || !userReport) {
81
    return;
82
  }
83
  const actionSelect = userBulkForm.querySelector("select");
84
  CustomEvents.define(actionSelect, [CustomEvents.events.accessibleChange]);
1 efrain 85
 
361 ariadna 86
  jQuery(actionSelect).on(CustomEvents.events.accessibleChange, (event) => {
87
    if (event.target.value && `${event.target.value}` !== "0") {
88
      const e = new Event("submit", { cancelable: true });
89
      userBulkForm.dispatchEvent(e);
90
      if (!e.defaultPrevented) {
91
        FormChangeChecker.markFormSubmitted(userBulkForm);
92
        userBulkForm.submit();
93
      }
1 efrain 94
    }
361 ariadna 95
  });
1 efrain 96
 
1226 ariadna 97
  // Cada vez que los checkboxes en el informe cambien, actualizamos la lista de usuarios en los valores del formulario
98
  // y habilitamos/deshabilitamos el select de acciones.
361 ariadna 99
  const updateUserIds = () => {
100
    const selectedUsers = [
101
      ...userReport.querySelectorAll(Selectors.checkedRows),
102
    ];
103
    const selectedUserIds = selectedUsers.map((check) => parseInt(check.value));
104
    userBulkForm.querySelector('[name="userids"]').value =
105
      selectedUserIds.join(",");
1 efrain 106
 
1226 ariadna 107
    // Deshabilitar el selector de acción si no se seleccionan usuarios, y resetear la selección actual.
361 ariadna 108
    actionSelect.disabled = selectedUsers.length === 0;
109
    if (actionSelect.disabled) {
110
      actionSelect.value = "0";
111
    }
1 efrain 112
 
361 ariadna 113
    const selectedUsersNames = selectedUsers.map(
114
      (check) => document.querySelector(`label[for="${check.id}"]`).textContent
115
    );
1226 ariadna 116
    // Agregar los ids y nombres de los usuarios a los atributos de datos del formulario para que estén disponibles desde
117
    // otros módulos JS que escuchen el evento de submit del formulario.
361 ariadna 118
    userBulkForm.data = {
119
      userids: selectedUserIds,
120
      usernames: selectedUsersNames,
1 efrain 121
    };
361 ariadna 122
  };
1 efrain 123
 
361 ariadna 124
  updateUserIds();
1 efrain 125
 
361 ariadna 126
  document.addEventListener("change", (event) => {
1226 ariadna 127
    // Cuando los checkboxes son marcados junto a usuarios individuales o el toggle maestro (Seleccionar todo/nada).
361 ariadna 128
    if (
129
      (event.target.matches(Selectors.checkbox) ||
130
        event.target.matches(Selectors.masterCheckbox)) &&
131
      userReport.contains(event.target)
132
    ) {
133
      updateUserIds();
134
    }
135
  });
1 efrain 136
 
361 ariadna 137
  document.addEventListener(tableEvents.tableContentRefreshed, (event) => {
1226 ariadna 138
    // Cuando el contenido del informe se actualiza (es decir, se cambia la página, se aplican filtros, etc.).
361 ariadna 139
    if (userReport.contains(event.target)) {
140
      updateUserIds();
1226 ariadna 141
      resetFilters(); // Restablecer los filtros después de cada actualización de la tabla
361 ariadna 142
    }
143
  });
1225 ariadna 144
};