| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762 |
- /**
- * Page User management
- */
-
- 'use strict';
-
- // Datatable (js)
- document.addEventListener('DOMContentLoaded', function (e) {
- let borderColor, bodyBg, headingColor;
-
- borderColor = config.colors.borderColor;
- bodyBg = config.colors.bodyBg;
- headingColor = config.colors.headingColor;
-
- // Variable declaration for table
- const dt_user_table = document.querySelector('.datatables-users'),
- userView = baseUrl + 'app/user/view/account',
- offCanvasForm = document.getElementById('offcanvasAddUser');
-
- // Select2 initialization
- var select2 = $('.select2');
- if (select2.length) {
- var $this = select2;
- $this.wrap('<div class="position-relative"></div>').select2({
- placeholder: 'Select Country',
- dropdownParent: $this.parent()
- });
- }
-
- // ajax setup
- $.ajaxSetup({
- headers: {
- 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
- }
- });
-
- // Users datatable
- if (dt_user_table) {
- const dt_user = new DataTable(dt_user_table, {
- processing: true,
- serverSide: true,
- ajax: {
- url: baseUrl + 'user-list',
- dataSrc: function (json) {
- // Ensure recordsTotal and recordsFiltered are numeric and not undefined/null
- if (typeof json.recordsTotal !== 'number') {
- json.recordsTotal = 0;
- }
- if (typeof json.recordsFiltered !== 'number') {
- json.recordsFiltered = 0;
- }
-
- // Fallback for empty data to avoid pagination NaN issue
- json.data = Array.isArray(json.data) ? json.data : [];
-
- return json.data;
- }
- },
- columns: [
- // columns according to JSON
- { data: 'id' },
- { data: 'id' },
- { data: 'name' },
- { data: 'email' },
- { data: 'email_verified_at' },
- { data: 'action' }
- ],
- columnDefs: [
- {
- // For Responsive
- className: 'control',
- searchable: false,
- orderable: false,
- responsivePriority: 2,
- targets: 0,
- render: function (data, type, full, meta) {
- return '';
- }
- },
- {
- searchable: false,
- orderable: false,
- targets: 1,
- render: function (data, type, full, meta) {
- return `<span>${full.fake_id}</span>`;
- }
- },
- {
- // User full name
- targets: 2,
- responsivePriority: 4,
- render: function (data, type, full, meta) {
- const { name } = full; // Destructuring to get 'name' from the 'full' object
-
- // For Avatar badge
- const stateNum = Math.floor(Math.random() * 6);
- const states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
- const state = states[stateNum];
-
- // Extract initials from the name
- const initials = (name.match(/\b\w/g) || []).shift() + (name.match(/\b\w/g) || []).pop();
- const initialsUpper = initials.toUpperCase();
-
- // Create avatar badge using template literals
- const avatar = `<span class="avatar-initial rounded-circle bg-label-${state}">${initialsUpper}</span>`;
-
- // Create full output for row using template literals
- const rowOutput = `
- <div class="d-flex justify-content-start align-items-center user-name">
- <div class="avatar-wrapper">
- <div class="avatar avatar-sm me-4">
- ${avatar}
- </div>
- </div>
- <div class="d-flex flex-column">
- <a href="${userView}" class="text-truncate text-heading">
- <span class="fw-medium">${name}</span>
- </a>
- </div>
- </div>
- `;
-
- // Return the final output as HTML string
- return rowOutput;
- }
- },
- {
- // User email
- targets: 3,
- render: function (data, type, full, meta) {
- const email = full['email'];
-
- return '<span class="user-email">' + email + '</span>';
- }
- },
- {
- // email verify
- targets: 4,
- className: 'text-center',
- render: function (data, type, full, meta) {
- const verified = full['email_verified_at'];
- return `${
- verified
- ? '<i class="icon-base bx fs-4 bx-check-shield text-success"></i>'
- : '<i class="icon-base bx fs-4 bx-shield-x text-danger" ></i>'
- }`;
- }
- },
- {
- // Actions
- targets: -1,
- title: 'Actions',
- searchable: false,
- orderable: false,
- render: function (data, type, full, meta) {
- return (
- '<div class="d-flex align-items-center gap-4">' +
- `<button class="btn btn-sm btn-icon edit-record" data-id="${full['id']}" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddUser"><i class="icon-base bx bx-edit icon-22px"></i></button>` +
- `<button class="btn btn-sm btn-icon delete-record" data-id="${full['id']}"><i class="icon-base bx bx-trash icon-22px"></i></button>` +
- '<button class="btn btn-sm btn-icon dropdown-toggle hide-arrow" data-bs-toggle="dropdown"><i class="icon-base bx bx-dots-vertical-rounded icon-22px"></i></button>' +
- '<div class="dropdown-menu dropdown-menu-end m-0">' +
- '<a href="' +
- userView +
- '" class="dropdown-item">View</a>' +
- '<a href="javascript:;" class="dropdown-item">Suspend</a>' +
- '</div>' +
- '</div>'
- );
- }
- }
- ],
- order: [[2, 'desc']],
- layout: {
- topStart: {
- rowClass: 'row m-3 my-0 justify-content-between',
- features: [
- {
- pageLength: {
- menu: [7, 10, 20, 50, 70, 100],
- text: '_MENU_'
- }
- }
- ]
- },
- topEnd: {
- features: [
- {
- search: {
- placeholder: 'Search User',
- text: '_INPUT_'
- }
- },
- {
- buttons: [
- {
- extend: 'collection',
- className: 'btn btn-label-secondary dropdown-toggle',
- text: '<i class="icon-base bx bx-export me-2 bx-sm"></i>Export',
- buttons: [
- {
- extend: 'print',
- title: 'Users',
- text: '<i class="icon-base bx bx-printer me-2" ></i>Print',
- className: 'dropdown-item',
- exportOptions: {
- columns: [1, 2, 3, 4, 5],
- // prevent avatar to be print
- format: {
- body: function (inner, coldex, rowdex) {
- if (inner.length <= 0) return inner;
-
- // Check if inner is HTML content
- if (inner.indexOf('<') > -1) {
- const parser = new DOMParser();
- const doc = parser.parseFromString(inner, 'text/html');
-
- // Get all text content
- let text = '';
-
- // Handle specific elements
- const userNameElements = doc.querySelectorAll('.user-name');
- if (userNameElements.length > 0) {
- userNameElements.forEach(el => {
- // Get text from nested structure
- const nameText =
- el.querySelector('.fw-medium')?.textContent ||
- el.querySelector('.d-block')?.textContent ||
- el.textContent;
- text += nameText.trim() + ' ';
- });
- } else {
- // Get regular text content
- text = doc.body.textContent || doc.body.innerText;
- }
-
- return text.trim();
- }
-
- return inner;
- }
- }
- },
- customize: function (win) {
- win.document.body.style.color = config.colors.headingColor;
- win.document.body.style.borderColor = config.colors.borderColor;
- win.document.body.style.backgroundColor = config.colors.bodyBg;
- const table = win.document.body.querySelector('table');
- table.classList.add('compact');
- table.style.color = 'inherit';
- table.style.borderColor = 'inherit';
- table.style.backgroundColor = 'inherit';
- }
- },
- {
- extend: 'csv',
- title: 'Users',
- text: '<i class="icon-base bx bx-file me-2" ></i>Csv',
- className: 'dropdown-item',
- exportOptions: {
- columns: [1, 2, 3, 4, 5],
- format: {
- body: function (inner, coldex, rowdex) {
- if (inner.length <= 0) return inner;
-
- // Parse HTML content
- const parser = new DOMParser();
- const doc = parser.parseFromString(inner, 'text/html');
-
- let text = '';
-
- // Handle user-name elements specifically
- const userNameElements = doc.querySelectorAll('.user-name');
- if (userNameElements.length > 0) {
- userNameElements.forEach(el => {
- // Get text from nested structure - try different selectors
- const nameText =
- el.querySelector('.fw-medium')?.textContent ||
- el.querySelector('.d-block')?.textContent ||
- el.textContent;
- text += nameText.trim() + ' ';
- });
- } else {
- // Handle other elements (status, role, etc)
- text = doc.body.textContent || doc.body.innerText;
- }
-
- return text.trim();
- }
- }
- }
- },
- {
- extend: 'excel',
- text: '<i class="icon-base bx bxs-file-export me-2"></i>Excel',
- className: 'dropdown-item',
- exportOptions: {
- columns: [1, 2, 3, 4, 5],
- format: {
- body: function (inner, coldex, rowdex) {
- if (inner.length <= 0) return inner;
-
- // Parse HTML content
- const parser = new DOMParser();
- const doc = parser.parseFromString(inner, 'text/html');
-
- let text = '';
-
- // Handle user-name elements specifically
- const userNameElements = doc.querySelectorAll('.user-name');
- if (userNameElements.length > 0) {
- userNameElements.forEach(el => {
- // Get text from nested structure - try different selectors
- const nameText =
- el.querySelector('.fw-medium')?.textContent ||
- el.querySelector('.d-block')?.textContent ||
- el.textContent;
- text += nameText.trim() + ' ';
- });
- } else {
- // Handle other elements (status, role, etc)
- text = doc.body.textContent || doc.body.innerText;
- }
-
- return text.trim();
- }
- }
- }
- },
- {
- extend: 'pdf',
- title: 'Users',
- text: '<i class="icon-base bx bxs-file-pdf me-2"></i>Pdf',
- className: 'dropdown-item',
- exportOptions: {
- columns: [1, 2, 3, 4, 5],
- format: {
- body: function (inner, coldex, rowdex) {
- if (inner.length <= 0) return inner;
-
- // Parse HTML content
- const parser = new DOMParser();
- const doc = parser.parseFromString(inner, 'text/html');
-
- let text = '';
-
- // Handle user-name elements specifically
- const userNameElements = doc.querySelectorAll('.user-name');
- if (userNameElements.length > 0) {
- userNameElements.forEach(el => {
- // Get text from nested structure - try different selectors
- const nameText =
- el.querySelector('.fw-medium')?.textContent ||
- el.querySelector('.d-block')?.textContent ||
- el.textContent;
- text += nameText.trim() + ' ';
- });
- } else {
- // Handle other elements (status, role, etc)
- text = doc.body.textContent || doc.body.innerText;
- }
-
- return text.trim();
- }
- }
- }
- },
- {
- extend: 'copy',
- title: 'Users',
- text: '<i class="icon-base bx bx-copy me-2" ></i>Copy',
- className: 'dropdown-item',
- exportOptions: {
- columns: [1, 2, 3, 4, 5],
- format: {
- body: function (inner, coldex, rowdex) {
- if (inner.length <= 0) return inner;
-
- // Parse HTML content
- const parser = new DOMParser();
- const doc = parser.parseFromString(inner, 'text/html');
-
- let text = '';
-
- // Handle user-name elements specifically
- const userNameElements = doc.querySelectorAll('.user-name');
- if (userNameElements.length > 0) {
- userNameElements.forEach(el => {
- // Get text from nested structure - try different selectors
- const nameText =
- el.querySelector('.fw-medium')?.textContent ||
- el.querySelector('.d-block')?.textContent ||
- el.textContent;
- text += nameText.trim() + ' ';
- });
- } else {
- // Handle other elements (status, role, etc)
- text = doc.body.textContent || doc.body.innerText;
- }
-
- return text.trim();
- }
- }
- }
- }
- ]
- },
- {
- text: '<i class="icon-base bx bx-plus icon-sm me-0 me-sm-2"></i><span class="d-none d-sm-inline-block">Add New User</span>',
- className: 'add-new btn btn-primary',
- attr: {
- 'data-bs-toggle': 'offcanvas',
- 'data-bs-target': '#offcanvasAddUser'
- }
- }
- ]
- }
- ]
- },
- bottomStart: {
- rowClass: 'row mx-3 justify-content-between',
- features: [
- {
- info: {
- text: 'Showing _START_ to _END_ of _TOTAL_ entries'
- }
- }
- ]
- },
- bottomEnd: 'paging'
- },
- displayLength: 7,
- language: {
- paginate: {
- next: '<i class="icon-base bx bx-chevron-right scaleX-n1-rtl icon-18px"></i>',
- previous: '<i class="icon-base bx bx-chevron-left scaleX-n1-rtl icon-18px"></i>',
- first: '<i class="icon-base bx bx-chevrons-left scaleX-n1-rtl icon-18px"></i>',
- last: '<i class="icon-base bx bx-chevrons-right scaleX-n1-rtl icon-18px"></i>'
- }
- },
- // For responsive popup
- responsive: {
- details: {
- display: DataTable.Responsive.display.modal({
- header: function (row) {
- const data = row.data();
- return 'Details of ' + data['name'];
- }
- }),
- type: 'column',
- renderer: function (api, rowIdx, columns) {
- const data = columns
- .map(function (col) {
- return col.title !== '' // Do not show row in modal popup if title is blank (for check box)
- ? `<tr data-dt-row="${col.rowIndex}" data-dt-column="${col.columnIndex}">
- <td>${col.title}:</td>
- <td>${col.data}</td>
- </tr>`
- : '';
- })
- .join('');
-
- if (data) {
- const div = document.createElement('div');
- div.classList.add('table-responsive');
- const table = document.createElement('table');
- div.appendChild(table);
- table.classList.add('table');
- const tbody = document.createElement('tbody');
- tbody.innerHTML = data;
- table.appendChild(tbody);
- return div;
- }
- return false;
- }
- }
- },
- initComplete: function () {
- // Remove btn-secondary from export buttons
- document.querySelectorAll('.dt-buttons .btn').forEach(btn => {
- btn.classList.remove('btn-secondary');
- });
- }
- });
-
- // Delete Record
- document.addEventListener('click', function (e) {
- if (e.target.closest('.delete-record')) {
- const deleteBtn = e.target.closest('.delete-record');
- const user_id = deleteBtn.dataset.id;
- const dtrModal = document.querySelector('.dtr-bs-modal.show');
-
- // hide responsive modal in small screen
- if (dtrModal) {
- const bsModal = bootstrap.Modal.getInstance(dtrModal);
- bsModal.hide();
- }
-
- // sweetalert for confirmation of delete
- Swal.fire({
- title: 'Are you sure?',
- text: "You won't be able to revert this!",
- icon: 'warning',
- showCancelButton: true,
- confirmButtonText: 'Yes, delete it!',
- customClass: {
- confirmButton: 'btn btn-primary me-3',
- cancelButton: 'btn btn-label-secondary'
- },
- buttonsStyling: false
- }).then(function (result) {
- if (result.value) {
- // delete the data
- fetch(`${baseUrl}user-list/${user_id}`, {
- method: 'DELETE',
- headers: {
- 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
- 'Content-Type': 'application/json'
- }
- })
- .then(response => {
- if (response.ok) {
- dt_user.draw();
-
- // success sweetalert
- Swal.fire({
- icon: 'success',
- title: 'Deleted!',
- text: 'The user has been deleted!',
- customClass: {
- confirmButton: 'btn btn-success'
- }
- });
- } else {
- throw new Error('Delete failed');
- }
- })
- .catch(error => {
- console.log(error);
- });
- } else if (result.dismiss === Swal.DismissReason.cancel) {
- Swal.fire({
- title: 'Cancelled',
- text: 'The User is not deleted!',
- icon: 'error',
- customClass: {
- confirmButton: 'btn btn-success'
- }
- });
- }
- });
- }
- });
-
- // edit record
- document.addEventListener('click', function (e) {
- if (e.target.closest('.edit-record')) {
- const editBtn = e.target.closest('.edit-record');
- const user_id = editBtn.dataset.id;
- const dtrModal = document.querySelector('.dtr-bs-modal.show');
-
- // hide responsive modal in small screen
- if (dtrModal) {
- const bsModal = bootstrap.Modal.getInstance(dtrModal);
- bsModal.hide();
- }
-
- // changing the title of offcanvas
- document.getElementById('offcanvasAddUserLabel').innerHTML = 'Edit User';
-
- // get data
- fetch(`${baseUrl}user-list/${user_id}/edit`)
- .then(response => response.json())
- .then(data => {
- document.getElementById('user_id').value = data.id;
- document.getElementById('add-user-fullname').value = data.name;
- document.getElementById('add-user-email').value = data.email;
- });
- }
- });
-
- // changing the title
- const addNewBtn = document.querySelector('.add-new');
- if (addNewBtn) {
- addNewBtn.addEventListener('click', function () {
- document.getElementById('user_id').value = ''; //resetting input field
- document.getElementById('offcanvasAddUserLabel').innerHTML = 'Add User';
- });
- }
-
- // Filter form control to default size
- setTimeout(() => {
- const elementsToModify = [
- { selector: '.dt-buttons .btn', classToRemove: 'btn-secondary' },
- { selector: '.dt-search .form-control', classToRemove: 'form-control-sm' },
- { selector: '.dt-length .form-select', classToRemove: 'form-select-sm', classToAdd: 'ms-0' },
- { selector: '.dt-length', classToAdd: 'mb-md-6 mb-0' },
- {
- selector: '.dt-layout-end',
- classToRemove: 'justify-content-between',
- classToAdd: 'd-flex gap-md-4 justify-content-md-between justify-content-center gap-0 flex-wrap mt-0'
- },
- { selector: '.dt-layout-start', classToAdd: 'mt-0' },
- { selector: '.dt-buttons', classToAdd: 'd-flex gap-4 mb-md-0 mb-6' },
- { selector: '.dt-layout-table', classToRemove: 'row mt-2' },
- { selector: '.dt-layout-full', classToRemove: 'col-md col-12', classToAdd: 'table-responsive' }
- ];
-
- // Delete record
- elementsToModify.forEach(({ selector, classToRemove, classToAdd }) => {
- document.querySelectorAll(selector).forEach(element => {
- if (classToRemove) {
- classToRemove.split(' ').forEach(className => element.classList.remove(className));
- }
- if (classToAdd) {
- classToAdd.split(' ').forEach(className => element.classList.add(className));
- }
- });
- });
- }, 100);
- }
-
- // validating form and updating user's data
- const addNewUserForm = document.getElementById('addNewUserForm');
-
- // user form validation
- if (addNewUserForm) {
- const fv = FormValidation.formValidation(addNewUserForm, {
- fields: {
- name: {
- validators: {
- notEmpty: {
- message: 'Please enter fullname'
- }
- }
- },
- email: {
- validators: {
- notEmpty: {
- message: 'Please enter your email'
- },
- emailAddress: {
- message: 'The value is not a valid email address'
- }
- }
- },
- userContact: {
- validators: {
- notEmpty: {
- message: 'Please enter your contact'
- }
- }
- },
- company: {
- validators: {
- notEmpty: {
- message: 'Please enter your company'
- }
- }
- }
- },
- plugins: {
- trigger: new FormValidation.plugins.Trigger(),
- bootstrap5: new FormValidation.plugins.Bootstrap5({
- // Use this for enabling/changing valid/invalid class
- eleValidClass: '',
- rowSelector: function (field, ele) {
- // field is the field name & ele is the field element
- return '.mb-6';
- }
- }),
- submitButton: new FormValidation.plugins.SubmitButton(),
- autoFocus: new FormValidation.plugins.AutoFocus()
- }
- }).on('core.form.valid', function () {
- // adding or updating user when form successfully validate
- const formData = new FormData(addNewUserForm);
- const formDataObj = {};
-
- // Convert FormData to URL-encoded string
- formData.forEach((value, key) => {
- formDataObj[key] = value;
- });
-
- const searchParams = new URLSearchParams();
- for (const [key, value] of Object.entries(formDataObj)) {
- searchParams.append(key, value);
- }
-
- fetch(`${baseUrl}user-list`, {
- method: 'POST',
- headers: {
- 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
- 'Content-Type': 'application/x-www-form-urlencoded'
- },
- body: searchParams.toString()
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Network response was not ok');
- }
- return response.text();
- })
- .then(status => {
- // Refresh DataTable
- dt_user_table && new DataTable(dt_user_table).draw();
-
- // Hide offcanvas
- const offcanvasInstance = bootstrap.Offcanvas.getInstance(offCanvasForm);
- offcanvasInstance && offcanvasInstance.hide();
-
- // sweetalert
- Swal.fire({
- icon: 'success',
- title: `Successfully ${status}!`,
- text: `User ${status} Successfully.`,
- customClass: {
- confirmButton: 'btn btn-success'
- }
- });
- })
- .catch(err => {
- // Hide offcanvas
- const offcanvasInstance = bootstrap.Offcanvas.getInstance(offCanvasForm);
- offcanvasInstance && offcanvasInstance.hide();
-
- Swal.fire({
- title: 'Duplicate Entry!',
- text: 'Your email should be unique.',
- icon: 'error',
- customClass: {
- confirmButton: 'btn btn-success'
- }
- });
- });
- });
-
- // clearing form data when offcanvas hidden
- offCanvasForm.addEventListener('hidden.bs.offcanvas', function () {
- fv.resetForm(true);
- });
- }
-
- // Phone mask initialization
- const phoneMaskList = document.querySelectorAll('.phone-mask');
-
- // Phone Number
- if (phoneMaskList) {
- phoneMaskList.forEach(function (phoneMask) {
- phoneMask.addEventListener('input', event => {
- const cleanValue = event.target.value.replace(/\D/g, '');
- phoneMask.value = formatGeneral(cleanValue, {
- blocks: [3, 3, 4],
- delimiters: [' ', ' ']
- });
- });
- registerCursorTracker({
- input: phoneMask,
- delimiter: ' '
- });
- });
- }
- });
|