first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-01-25 13:06:29 -05:00
commit 346346573f
1362 changed files with 343729 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Account init js
*/
var swiper = new Swiper(".mySwiper", {
loop: 'true',
spaceBetween: 10,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
});
var removeBtns = document.getElementsByClassName("remove-item-btn");
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").remove()
});
});
+266
View File
@@ -0,0 +1,266 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: brands list init File
*/
var url = "../build/json/";
var brandList = '';
var editList = false;
var prevButton = document.getElementById('page-prev');
var nextButton = document.getElementById('page-next');
// configuration variables
var currentPage = 1;
var itemsPerPage = 15;
var getJSON = function (jsonurl, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url + jsonurl, true);
xhr.responseType = "json";
xhr.onload = function () {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
// get json
getJSON("brand-list.json", function (err, data) {
if (err !== null) {
console.log("Something went wrong: " + err);
} else {
brandList = data;
loadBrandListData(brandList, currentPage);
paginationEvents();
sortElementsById();
}
});
function loadBrandListData(datas, page) {
var pages = Math.ceil(datas.length / itemsPerPage);
if (page < 1) page = 1;
if (page > pages) page = pages;
document.getElementById("brand-list").innerHTML = "";
for (var i = (page - 1) * itemsPerPage; i < (page * itemsPerPage) && i < datas.length; i++) {
// Array.from(datas).forEach(function (listData){
document.getElementById("brand-list").innerHTML += '<div class="col">\
<div class="card brand-widget card-animate">\
<div class="card-body text-center pb-2">\
<img src="'+datas[i].companyLogo+'" alt="" class="brand-img">\
</div>\
<div class="card-footer text-center border-0">\
<h6 class="fs-17">'+datas[i].brandName+'</h6>\
<p class="mb-0"><a href="#!" class="link-success stretched-link">'+datas[i].productItems+' Items</a></p>\
</div>\
</div>\
</div>';
}
selectedPage();
// refreshCallbacks();
currentPage == 1 ? prevButton.parentNode.classList.add('disabled') : prevButton.parentNode.classList.remove('disabled');
currentPage == pages ? nextButton.parentNode.classList.add('disabled') : nextButton.parentNode.classList.remove('disabled');
// });
}
// brandLogo image
document.querySelector("#brandLogo-image-input").addEventListener("change", function () {
var preview = document.querySelector("#brandLogo-img");
var file = document.querySelector("#brandLogo-image-input").files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
var brandLogoImg = document.getElementById("brandLogo-img");
var brandNameVal = document.getElementById("brandName-input");
// create-form
var forms = document.querySelectorAll('.create-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var imgArray = window.location.href.split("#");
var logoArray = brandLogoImg.src.split("#");
var text;
if (logoArray[0] == imgArray[0]) {
text = "Please select a brand logo image";
errorMsg.innerHTML = text;
return false;
} else if (brandNameVal.value == "") {
text = "Please enter a brand name";
errorMsg.innerHTML = text;
return false;
}
if (imgArray[0] && brandNameVal.value !== "" && brandLogoImg.value !== "" && !editList) {
var newArrayId = findNextId();
var newArray = {
'id': newArrayId,
"brandName": brandNameVal.value,
"companyLogo": brandLogoImg.src,
"productItems": '0'
};
brandList.push(newArray);
sortElementsById();
}
pageEvent(brandList);
loadBrandListData(brandList, currentPage);
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("createModal-close").click();
return true;
});
});
function selectedPage() {
var pagenumLink = document.getElementById('page-num').getElementsByClassName('clickPageNumber');
for (var i = 0; i < pagenumLink.length; i++) {
if (i == currentPage - 1) {
pagenumLink[i].parentNode.classList.add("active");
} else {
pagenumLink[i].parentNode.classList.remove("active");
}
}
};
// paginationEvents
function paginationEvents() {
var numPages = function numPages() {
return Math.ceil(brandList.length / itemsPerPage);
};
function clickPage() {
document.addEventListener('click', function (e) {
if (e.target.nodeName == "A" && e.target.classList.contains("clickPageNumber")) {
currentPage = e.target.textContent;
loadBrandListData(brandList, currentPage);
}
});
};
function pageNumbers() {
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
// for each page
for (var i = 1; i < numPages() + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
prevButton.addEventListener('click', function () {
if (currentPage > 1) {
currentPage--;
loadBrandListData(brandList, currentPage);
}
});
nextButton.addEventListener('click', function () {
if (currentPage < numPages()) {
currentPage++;
loadBrandListData(brandList, currentPage);
}
});
pageNumbers();
clickPage();
selectedPage();
}
function fetchIdFromObj(member) {
return parseInt(member.id);
}
function findNextId() {
if (brandList.length === 0) {
return 0;
}
var lastElementId = fetchIdFromObj(brandList[brandList.length - 1]),
firstElementId = fetchIdFromObj(brandList[0]);
return (firstElementId >= lastElementId) ? (firstElementId + 1) : (lastElementId + 1);
}
function sortElementsById() {
var manybrandList = brandList.sort(function (a, b) {
var x = fetchIdFromObj(a);
var y = fetchIdFromObj(b);
if (x > y) {
return -1;
}
if (x < y) {
return 1;
}
return 0;
})
loadBrandListData(manybrandList, currentPage);
}
// clearFields
function clearFields() {
document.getElementById("id-field").value = ""
brandLogoImg.src = "";
brandNameVal.value = "";
document.getElementById("brandLogo-image-input").value = "";
}
document.getElementById('createModal').addEventListener('hidden.bs.modal', event => {
clearFields();
});
// pageEvent
function pageEvent(data) {
if (data.length == 0) {
document.getElementById("pagination-element").style.display = "none";
document.getElementById("noresult").classList.remove("d-none");
} else {
document.getElementById("pagination-element").style.display = "flex";
document.getElementById("noresult").classList.add("d-none");
}
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
var dataPageNum = Math.ceil(data.length / itemsPerPage)
// for each page
for (var i = 1; i < dataPageNum + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
// Search input list
var searchInputList = document.getElementById("searchInputList");
searchInputList.addEventListener("keyup", function () {
var inputVal = searchInputList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.brandName.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(brandList, inputVal);
pageEvent(filterData);
loadBrandListData(filterData, currentPage);
});
+764
View File
@@ -0,0 +1,764 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Calendar init js
*/
var start_date = document.getElementById("event-start-date");
var date_range = null;
var T_check = null;
document.addEventListener("DOMContentLoaded", function () {
flatPickrInit();
var addEvent = new bootstrap.Modal(document.getElementById('event-modal'), {
keyboard: false
});
document.getElementById('event-modal');
var modalTitle = document.getElementById('modal-title');
var formEvent = document.getElementById('form-event');
var selectedEvent = null;
var forms = document.getElementsByClassName('needs-validation');
/* initialize the calendar */
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var defaultEvents = [{
id: 1,
title: "Alfred Hurst",
start: "2023-01-04",
location: 'Atlanta, Georgia',
allDay: true,
className: "bg-info-subtle",
status: "New",
payment: "354.99",
},
{
id: 2,
title: "Tommy Carey",
start: "2023-01-30",
className: "bg-info-subtle",
location: 'Virginia Beach, Virginia',
allDay: true,
status: "New",
payment: "742.00",
},
{
id: 3,
title: "Cassius Brock",
start: "2023-02-21",
className: "bg-info-subtle",
location: 'Sacramento, California',
allDay: true,
status: "New",
payment: "150.99",
},
{
id: 4,
title: "Camilla Winters",
start: "2023-03-08",
className: "bg-info-subtle",
location: 'Fresno, California',
allDay: true,
status: "New",
payment: "96.26",
},
{
id: 5,
title: "Gabrielle Holden",
start: "2023-02-22",
className: "bg-info-subtle",
location: 'El Paso, Texas',
allDay: true,
status: "New",
payment: "229.00",
},
{
id: 6,
title: "Kristina Hooper",
start: "2023-03-21",
className: "bg-info-subtle",
location: 'Seattle, Washington',
allDay: true,
status: "New",
payment: "354.99",
},
{
id: 7,
title: "Jacques Leon",
start: "2023-03-22",
className: "bg-info-subtle",
location: 'Fort Worth, Texas',
allDay: true,
status: "New",
payment: "120.00",
},
{
id: 8,
title: "Theresa Crawford",
start: "2023-04-07",
className: "bg-info-subtle",
location: 'Atlanta, Georgia',
allDay: true,
status: "New",
payment: "81.99",
},
{
id: 9,
title: "Alina Holland",
start: "2023-04-16",
className: "bg-info-subtle",
location: 'Portland, Oregon',
allDay: true,
status: "New",
payment: "209.99",
},
{
id: 10,
title: "Edward Rogers",
start: "2023-04-22",
className: "bg-info-subtle",
location: 'Denver, Colorado',
allDay: true,
status: "New",
payment: "309.09",
},
{
id: 153,
title: 'Catherine Flores',
start: new Date(y, m, 1),
className: 'bg-success-subtle',
location: 'Charlotte, North Carolina',
allDay: true,
status: "Delivered",
extendedProps: {
department: 'All Day Event'
},
description: 'An all-day event is an event that lasts an entire day or longer',
payment: "126.99",
},
{
id: 136,
title: 'William Hendrix',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2),
allDay: true,
status: "New",
className: 'bg-info-subtle',
location: 'San Francisco, California',
extendedProps: {
department: 'Long Event'
},
description: 'Long Term Event means an incident that last longer than 12 hours.',
payment: "211.99",
},
{
id: 999,
title: 'Joan Trimble',
start: new Date(y, m, d + 22, 20, 0),
end: new Date(y, m, d + 24, 16, 0),
allDay: true,
status: "New",
className: 'bg-info-subtle',
location: 'Seattle, Washington',
extendedProps: {
department: 'Meeting with Alexis'
},
description: 'A meeting is a gathering of two or more people that has been convened for the purpose of achieving a common goal through verbal interaction, such as sharing information or reaching agreement.',
payment: "260.04",
},
{
id: 991,
title: 'Emma Harper',
start: new Date(y, m, d + 4, 16, 0),
end: new Date(y, m, d + 9, 16, 0),
allDay: true,
status: "New",
className: 'bg-info-subtle',
location: 'Las Vegas, Nevada',
extendedProps: {
department: 'Repeating Event'
},
description: 'A recurring or repeating event is simply any event that you will occur more than once on your calendar. ',
payment: "354.99",
},
{
id: 112,
title: 'Michael Burks',
start: new Date(y, m, d, 12, 30),
allDay: true,
status: "Shipped",
className: 'bg-warning-subtle',
location: 'San Antonio, Texas',
extendedProps: {
department: 'Meeting'
},
description: 'Tell how to boost website traffic',
payment: "94.69",
},
{
id: 113,
title: 'David McMillan',
start: new Date(y, m, d + 9),
end: new Date(y, m, d + 11),
allDay: true,
status: "New",
className: 'bg-info-subtle',
location: 'Phoenix, Arizona',
extendedProps: {
department: 'Lunch'
},
description: 'Strategies for Creating Your Weekly Schedule',
payment: "350.99",
},
{
id: 875,
title: 'Marian Blevins',
start: new Date(y, m, d + 1, 19, 0),
allDay: true,
status: "Cancelled",
className: 'bg-danger-subtle',
location: 'Los Angeles, California',
extendedProps: {
department: 'Birthday Party'
},
description: 'Family slumber party Bring out the blankets and pillows and have a family slumber party! Play silly party games, share special snacks and wind down the fun with a special movie.',
payment: "205.55",
},
{
id: 783,
title: 'Amy Krick',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
allDay: true,
status: "Shipped",
className: 'bg-warning-subtle',
location: 'Chicago, Illinois',
payment: "154.28",
},
{
id: 456,
title: 'Ryan Simmons',
start: new Date(y, m, d + 23, 20, 0),
end: new Date(y, m, d + 24, 16, 0),
allDay: true,
className: 'bg-info-subtle',
location: 'Los Angeles, California',
status: "New",
extendedProps: {
department: 'Discussion'
},
description: 'Tell how to boost website traffic',
payment: "180.09",
},
];
var calendarEl = document.getElementById('calendar');
function addNewEvent(info) {
document.getElementById('form-event').reset();
document.getElementById('btn-delete-event').setAttribute('hidden', true);
addEvent.show();
formEvent.classList.remove("was-validated");
formEvent.reset();
selectedEvent = null;
modalTitle.innerText = 'Add Order';
newEventData = info;
document.getElementById("edit-event-btn").setAttribute("data-id", "new-event");
document.getElementById('edit-event-btn').click();
document.getElementById("edit-event-btn").setAttribute("hidden", true);
}
function getInitialView() {
if (window.innerWidth >= 768 && window.innerWidth < 1200) {
return 'timeGridWeek';
} else if (window.innerWidth <= 768) {
return 'listMonth';
} else {
return 'dayGridMonth';
}
}
var eventCategoryChoice = new Choices("#event-category", {
searchEnabled: false
});
var calendar = new FullCalendar.Calendar(calendarEl, {
timeZone: 'local',
editable: true,
droppable: true,
selectable: true,
navLinks: true,
initialView: getInitialView(),
themeSystem: 'bootstrap',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
},
windowResize: function (view) {
var newView = getInitialView();
calendar.changeView(newView);
},
eventResize: function(info) {
var indexOfSelectedEvent = defaultEvents.findIndex(function (x) {
return x.id == info.event.id
});
if (defaultEvents[indexOfSelectedEvent]) {
defaultEvents[indexOfSelectedEvent].title = info.event.title;
defaultEvents[indexOfSelectedEvent].start = info.event.start;
defaultEvents[indexOfSelectedEvent].end = (info.event.end) ? info.event.end : null;
defaultEvents[indexOfSelectedEvent].allDay = info.event.allDay;
defaultEvents[indexOfSelectedEvent].className = info.event.classNames[0];
defaultEvents[indexOfSelectedEvent].description = (info.event._def.extendedProps.description) ? info.event._def.extendedProps.description : '';
defaultEvents[indexOfSelectedEvent].location = (info.event._def.extendedProps.location) ? info.event._def.extendedProps.location : '';
}
upcomingEvent(defaultEvents);
},
eventClick: function (info) {
document.getElementById("edit-event-btn").removeAttribute("hidden");
document.getElementById('btn-save-event').setAttribute("hidden", true);
document.getElementById("edit-event-btn").setAttribute("data-id", "edit-event");
document.getElementById("edit-event-btn").innerHTML = "Edit";
eventClicked();
flatPickrInit();
flatpicekrValueClear();
addEvent.show();
formEvent.reset();
selectedEvent = info.event;
// First Modal
document.getElementById("modal-title").innerHTML = "";
document.getElementById("event-location-tag").innerHTML = selectedEvent.extendedProps.location === undefined ? "" : selectedEvent.extendedProps.location;
document.getElementById("event-payment-tag").innerHTML = selectedEvent.extendedProps.payment === undefined ? "No Location" : '$'+selectedEvent.extendedProps.payment;
document.getElementById("event-description-tag").innerHTML = selectedEvent.extendedProps.description === undefined ? "No Description" : selectedEvent.extendedProps.description;
// Edit Modal
document.getElementById("event-title").value = selectedEvent.title;
document.getElementById("event-location").value = selectedEvent.extendedProps.location === undefined ? "No Location" : selectedEvent.extendedProps.location;
document.getElementById("event-payment").value = selectedEvent.extendedProps.payment === undefined ? "" : selectedEvent.extendedProps.payment;
document.getElementById("event-description").value = selectedEvent.extendedProps.description === undefined ? "No Description" : selectedEvent.extendedProps.description;
document.getElementById("eventid").value = selectedEvent.id;
if (selectedEvent.classNames[0]) {
eventCategoryChoice.destroy();
eventCategoryChoice = new Choices("#event-category", {
searchEnabled: false
});
eventCategoryChoice.setChoiceByValue(selectedEvent.classNames[0]);
}
var st_date = selectedEvent.start;
var ed_date = selectedEvent.end;
var date_r = function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
};
var updateDay = null
if(ed_date != null){
var endUpdateDay = new Date(ed_date);
updateDay = endUpdateDay.setDate(endUpdateDay.getDate() - 1);
}
var r_date = ed_date == null ? (str_dt(st_date)) : (str_dt(st_date)) + ' to ' + (str_dt(updateDay));
var er_date = ed_date == null ? (date_r(st_date)) : (date_r(st_date)) + ' to ' + (date_r(updateDay));
flatpickr(start_date, {
defaultDate: er_date,
altInput: true,
altFormat: "j F Y",
dateFormat: "Y-m-d",
mode: ed_date !== null ? "range" : "range",
onChange: function (selectedDates, dateStr, instance) {
var date_range = dateStr;
var dates = date_range.split("to");
},
});
document.getElementById("event-start-date-tag").innerHTML = r_date;
newEventData = null;
modalTitle.innerText = selectedEvent.title;
// formEvent.classList.add("view-event");
document.getElementById('btn-delete-event').removeAttribute('hidden');
},
dateClick: function (info) {
addNewEvent(info);
},
events: defaultEvents,
eventContent: function(arg) {
if(arg.event._def.extendedProps.status == 'New'){
arg.event._def.ui.classNames = ['bg-info-subtle']
}
return {
html: '<div class="fc-event-title fc-sticky">#TBT8'+arg.event.id+ " - " + arg.event.title+'</div>'
}
},
eventReceive: function (info) {
var newid = parseInt(info.event.id);
var newEvent = {
id: newid,
title: info.event.title,
start: info.event.start,
allDay: info.event.allDay,
className: info.event.classNames[0]
};
defaultEvents.push(newEvent);
upcomingEvent(defaultEvents);
},
eventDrop: function (info) {
var indexOfSelectedEvent = defaultEvents.findIndex(function (x) {
return x.id == info.event.id
});
if (defaultEvents[indexOfSelectedEvent]) {
defaultEvents[indexOfSelectedEvent].title = info.event.title;
defaultEvents[indexOfSelectedEvent].start = info.event.start;
defaultEvents[indexOfSelectedEvent].end = (info.event.end) ? info.event.end : null;
defaultEvents[indexOfSelectedEvent].allDay = info.event.allDay;
defaultEvents[indexOfSelectedEvent].className = info.event.classNames[0];
defaultEvents[indexOfSelectedEvent].description = (info.event._def.extendedProps.description) ? info.event._def.extendedProps.description : '';
defaultEvents[indexOfSelectedEvent].location = (info.event._def.extendedProps.location) ? info.event._def.extendedProps.location : '';
}
upcomingEvent(defaultEvents);
}
});
calendar.render();
upcomingEvent(defaultEvents);
/*Add new event*/
// Form to add new event
formEvent.addEventListener('submit', function (ev) {
ev.preventDefault();
var updatedTitle = document.getElementById("event-title").value;
var updatedCategory = document.getElementById('event-category').value;
var start_date = (document.getElementById("event-start-date").value).split("to");
var updateStartDate = new Date(start_date[0].trim());
var newdate = new Date(start_date[1]);
newdate.setDate(newdate.getDate() + 1);
var end_date = null;
var event_location = document.getElementById("event-location").value;
var event_payment = document.getElementById("event-payment").value;
var eventDescription = document.getElementById("event-description").value;
var eventid = document.getElementById("eventid").value;
var all_day = false;
if (start_date.length > 1) {
var end_date = new Date(start_date[1]);
end_date.setDate(end_date.getDate() + 1);
start_date = new Date(start_date[0]);
all_day = true;
} else {
var e_date = start_date;
start_date = new Date(start_date);
end_date = new Date(e_date);
}
var e_id = defaultEvents.length + 1;
var updateEndDate = (start_date[1]) ? newdate : new Date(start_date);
// validation
if (forms[0].checkValidity() === false) {
forms[0].classList.add('was-validated');
} else {
if (selectedEvent) {
selectedEvent.setProp("id", eventid);
selectedEvent.setProp("title", updatedTitle);
selectedEvent.setProp("classNames", [updatedCategory]);
selectedEvent.setStart(updateStartDate);
selectedEvent.setEnd(updateEndDate);
selectedEvent.setAllDay(all_day);
selectedEvent.setExtendedProp("description", eventDescription);
selectedEvent.setExtendedProp("location", event_location);
selectedEvent.setExtendedProp("payment", event_payment);
var indexOfSelectedEvent = defaultEvents.findIndex(function (x) {
return x.id == selectedEvent.id
});
if (defaultEvents[indexOfSelectedEvent]) {
defaultEvents[indexOfSelectedEvent].title = updatedTitle;
defaultEvents[indexOfSelectedEvent].start = updateStartDate;
defaultEvents[indexOfSelectedEvent].end = updateEndDate;
defaultEvents[indexOfSelectedEvent].allDay = all_day;
defaultEvents[indexOfSelectedEvent].className = updatedCategory;
defaultEvents[indexOfSelectedEvent].description = eventDescription;
defaultEvents[indexOfSelectedEvent].location = event_location;
defaultEvents[indexOfSelectedEvent].payment = event_payment;
}
calendar.render();
// default
} else {
var newEvent = {
id: e_id,
title: updatedTitle,
start: start_date,
end: end_date,
allDay: all_day,
className: updatedCategory,
description: eventDescription,
location: event_location,
payment: event_payment
};
calendar.addEvent(newEvent);
defaultEvents.push(newEvent);
}
addEvent.hide();
upcomingEvent(defaultEvents);
}
});
document.getElementById("btn-delete-event").addEventListener("click", function (e) {
if (selectedEvent) {
for (var i = 0; i < defaultEvents.length; i++) {
if (defaultEvents[i].id == selectedEvent.id) {
defaultEvents.splice(i, 1);
i--;
}
}
upcomingEvent(defaultEvents);
selectedEvent.remove();
selectedEvent = null;
addEvent.hide();
}
});
document.getElementById("btn-new-event").addEventListener("click", function (e) {
flatpicekrValueClear();
flatPickrInit();
addNewEvent();
document.getElementById("edit-event-btn").setAttribute("data-id", "new-event");
document.getElementById('edit-event-btn').click();
document.getElementById("edit-event-btn").setAttribute("hidden", true);
});
// Search product list
var searchResultList = document.getElementById("searchResultsList");
searchResultList.addEventListener("keyup", function () {
var inputVal = searchResultList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.title.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(defaultEvents, inputVal);
upcomingEvent(filterData);
});
});
function flatPickrInit() {
var config = {
enableTime: true,
noCalendar: true,
};
var date_range = flatpickr(
start_date, {
enableTime: false,
mode: "range",
minDate: "today",
onChange: function (selectedDates, dateStr, instance) {
var date_range = dateStr;
var dates = date_range.split("to");
},
});
}
function flatpicekrValueClear() {
start_date.flatpickr().clear();
}
function eventClicked() {
document.getElementById('form-event').classList.add("view-event");
document.getElementById("event-title").classList.replace("d-block", "d-none");
document.getElementById("event-category").classList.replace("d-block", "d-none");
document.getElementById("event-start-date").parentNode.classList.add("d-none");
document.getElementById("event-start-date").classList.replace("d-block", "d-none");
document.getElementById("event-location").classList.replace("d-block", "d-none");
document.getElementById("event-payment").classList.replace("d-block", "d-none");
document.getElementById("event-description").classList.replace("d-block", "d-none");
document.getElementById("event-start-date-tag").classList.replace("d-none", "d-block");
document.getElementById("event-payment-tag").classList.replace("d-none", "d-block");
document.getElementById("event-location-tag").classList.replace("d-none", "d-block");
document.getElementById("event-description-tag").classList.replace("d-none", "d-block");
document.getElementById('btn-save-event').setAttribute("hidden", true);
}
function editEvent(data) {
var data_id = data.getAttribute("data-id");
if (data_id == 'new-event') {
document.getElementById('modal-title').innerHTML = "";
document.getElementById('modal-title').innerHTML = "Add Order";
document.getElementById("btn-save-event").innerHTML = "Add Order";
eventTyped();
} else if (data_id == 'edit-event') {
data.innerHTML = "Cancel";
data.setAttribute("data-id", 'cancel-event');
document.getElementById("btn-save-event").innerHTML = "Update Order";
data.removeAttribute("hidden");
eventTyped();
} else {
data.innerHTML = "Edit";
data.setAttribute("data-id", 'edit-event');
eventClicked();
}
}
function eventTyped() {
document.getElementById('form-event').classList.remove("view-event");
document.getElementById("event-title").classList.replace("d-none", "d-block");
document.getElementById("event-category").classList.replace("d-none", "d-block");
document.getElementById("event-start-date").parentNode.classList.remove("d-none");
document.getElementById("event-start-date").classList.replace("d-none", "d-block");
document.getElementById("event-location").classList.replace("d-none", "d-block");
document.getElementById("event-payment").classList.replace("d-none", "d-block");
document.getElementById("event-description").classList.replace("d-none", "d-block");
document.getElementById("event-start-date-tag").classList.replace("d-block", "d-none")
document.getElementById("event-payment-tag").classList.replace("d-block", "d-none");;
document.getElementById("event-location-tag").classList.replace("d-block", "d-none");
document.getElementById("event-description-tag").classList.replace("d-block", "d-none");
document.getElementById('btn-save-event').removeAttribute("hidden");
}
// upcoming Event
function upcomingEvent(a) {
a.sort(function (o1, o2) {
return (new Date(o1.start)) - (new Date(o2.start));
});
document.getElementById("upcoming-event-list").innerHTML = null;
Array.from(a).forEach(function (element) {
var title = element.title;
if (element.end) {
endUpdatedDay = new Date(element.end);
var updatedDay = endUpdatedDay.setDate(endUpdatedDay.getDate() - 1);
}
var e_dt = updatedDay ? updatedDay : undefined;
if (e_dt == "Invalid Date" || e_dt == undefined) {
e_dt = null;
} else {
const newDate = new Date(e_dt).toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric' });
e_dt = new Date(newDate)
.toLocaleDateString("en-GB", {
day: "numeric",
month: "short",
year: "numeric",
})
.split(" ")
.join(" ");
}
var st_date = element.start ? str_dt(element.start) : null;
var ed_date = updatedDay ? str_dt(updatedDay) : null;
if (st_date === ed_date) {
e_dt = null;
}
var startDate = element.start;
if (startDate === "Invalid Date" || startDate === undefined) {
startDate = null;
} else {
const newDate = new Date(startDate).toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric' });
startDate = new Date(newDate)
.toLocaleDateString("en-GB", {
day: "numeric",
month: "short",
year: "numeric",
})
.split(" ")
.join(" ");
}
var end_dt = (e_dt) ? e_dt : startDate;
var description = (element.description) ? element.description : "";
var e_time_s = tConvert(getTime(element.start));
var e_time_e = tConvert(getTime(updatedDay));
if (e_time_s == e_time_e) {
var e_time_s = "Full day event";
var e_time_e = null;
}
var e_time_e = (e_time_e) ? " to " + e_time_e : "";
u_event = '<div class="card">\
<div class="card-body">\
<div class="d-flex align-items-center mb-4">\
<p class="mb-0 flex-grow-1">OrderID: <span class="fw-medium">#TBT8'+element.id+'</span></p>\
<div class="flex-shrink-0">\
'+isStatus(element.status)+'\
</div>\
</div>\
<h5 class="fs-16">'+ title +'</h5>\
<div class="d-flex justify-content-between align-items-center mb-0">\
<p class="mb-0"><i class="bi bi-calendar2-check me-1 text-muted align-middle"></i>'+startDate+'</p>\
<p class="mb-0"><i class="bi bi-box-seam me-1 text-muted align-middle"></i>'+end_dt+'</p>\
</div>\
</div>\
</div>';
document.getElementById("upcoming-event-list").innerHTML += u_event;
});
};
function getTime(params) {
params = new Date(params);
if (params.getHours() != null) {
var hour = params.getHours();
var minute = (params.getMinutes()) ? params.getMinutes() : 00;
return hour + ":" + minute;
}
}
function isStatus(val) {
switch (val) {
case "Delivered":
return ('<span class="badge bg-success-subtle text-success">' + val + "</span>");
case "Shipped":
return ('<span class="badge bg-warning-subtle text-warning">' + val + "</span>");
case "Cancelled":
return ('<span class="badge bg-danger-subtle text-danger">' + val + "</span>");
case "New":
return ('<span class="badge bg-info-subtle text-info">' + val + "</span>");
default:
return ('<span class="badge bg-info-subtle text-info">' + val + "</span>");
}
}
function tConvert(time) {
var t = time.split(":");
var hours = t[0];
var minutes = t[1];
var newformat = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return (hours + ':' + minutes + ' ' + newformat);
}
var str_dt = function formatDate(date) {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date(date),
month = '' + monthNames[(d.getMonth())],
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [day + " " + month, year].join(',');
};
+490
View File
@@ -0,0 +1,490 @@
var perPage = 10;
var editlist = false;
var options = {
valueNames: [
"id",
"discount",
"couponTitle",
"code",
"productType",
"startDate",
"endDate",
"status",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
var couponsList = new List("couponsList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
//load json records
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
couponsList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">#TB${element.id}</a>`,
discount: `<h5 class="mb-0 fs-16">${element.discount}</h5>`,
couponTitle: element.couponTitle,
code: element.code,
startDate: element.startDate,
endDate: element.endDate,
productType:isProductType(element.productType),
status: isStatus(element.status),
});
couponsList.sort('id', { order: "desc" });
refreshCallbacks();
});
couponsList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TB01</a>`);
}
xhttp.open("GET", "../build/json/coupons-list.json");
xhttp.send();
var idField = document.getElementById("id-field"),
couponTitleField = document.getElementById("couponTitle-field"),
codeField = document.getElementById("code-field"),
productTypeField = document.getElementById("productType-field"),
startDateField = document.getElementById("startdate-field"),
endDateField = document.getElementById("enddate-field"),
discountField = document.getElementById("discount-field"),
statusField = document.getElementById("status-Field")
addBtn = document.getElementById("add-btn")
editBtn = document.getElementById("edit-btn"),
removeBtns = document.getElementsByClassName("remove-item-btn"),
viewBtns = document.getElementsByClassName("view-item-btn"),
editBtns = document.getElementsByClassName("edit-item-btn");
refreshCallbacks();
var productTypeVal = new Choices(productTypeField)
var statusVal = new Choices(statusField);
document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Update Coupon";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Update Coupon";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Add Coupen";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Add Coupen";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List Order";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
}
});
//Add Coupon
var count = 13;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
if (couponTitleField.value == "") {
text = "Please enter a coupon title";
errorMsg.innerHTML = text;
return false;
}else if (codeField.value == "") {
text = "Please enter a code";
errorMsg.innerHTML = text;
return false;
}else if (productTypeField.value == "") {
text = "Please select a product type";
errorMsg.innerHTML = text;
return false;
}else if (startDateField.value == "") {
text = "Please select a start date";
errorMsg.innerHTML = text;
return false;
}else if (endDateField.value == "") {
text = "Please select a end date";
errorMsg.innerHTML = text;
return false;
}else if (discountField.value == "") {
text = "Please enter discount";
errorMsg.innerHTML = text;
return false;
}else if (statusField.value == "") {
text = "Please select a delivery status";
errorMsg.innerHTML = text;
return false;
}
if (
couponTitleField.value !== "" &&
codeField.value !== "" &&
productTypeField.value !== "" &&
startDateField.value !== "" &&
endDateField.value !== "" &&
discountField.value !== "" &&
statusField.value !== "" && !editlist
) {
couponsList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TB' + count + "</a>",
couponTitle: couponTitleField.value,
code: codeField.value,
productType: productTypeField.value,
startDate: startDateField.value,
endDate: endDateField.value,
discount: `<h5 class="mb-0 fs-16">${discountField.value}</h5>`,
status: isStatus(statusField.value),
});
couponsList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Coupon added successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
} else if (
couponTitleField.value !== "" &&
codeField.value !== "" &&
productTypeField.value !== "" &&
startDateField.value !== "" &&
endDateField.value !== "" && statusField.value !== "" &&
discountField.value !== "" && editlist
) {
var editValues = couponsList.get({
id: idField.value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TB' + idField.value + "</a>",
couponTitle: couponTitleField.value,
code: codeField.value,
productType: productTypeField.value,
startDate: startDateField.value,
endDate: endDateField.value,
discount: `<h5 class="mb-0 fs-16">${discountField.value}</h5>`,
status: isStatus(statusField.value),
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Order updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
});
function refreshCallbacks() {
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = couponsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
couponsList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Coupon deleted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
});
}
});
});
});
}
//editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = couponsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
editlist = true;
idField.value = selectedid;
couponTitleField.value = x._values.couponTitle;
codeField.value = x._values.code;
//discount
discountVal = new DOMParser().parseFromString(x._values.discount, "text/html");
discountField.value = discountVal.body.firstElementChild.innerHTML
// statusVal
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField, {
searchEnabled: false
});
val = new DOMParser().parseFromString(x._values.status, "text/html");
var statusSelec = val.body.firstElementChild.innerHTML;
statusVal.setChoiceByValue(statusSelec);
// productnameVal
if (productTypeVal) productTypeVal.destroy();
productTypeVal = new Choices(productTypeField, {
searchEnabled: false,
});
var selectedproduct = x._values.productType;
productTypeVal.setChoiceByValue(selectedproduct);
flatpickr("#startdate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.startDate,
});
flatpickr("#enddate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.endDate,
});
}
});
});
});
};
//View button
if(viewBtns){
Array.from(viewBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = couponsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
console.log("isid",selectedid)
if (selectedid == itemId) {
var codeBlock = `
<div class="offcanvas-header bg-warning-subtle">
<h5 class="offcanvas-title" id="couponDetails">${x._values.couponTitle}</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<div>
<img src="../build/images/ecommerce/offer-banner.jpg" alt="" class="img-thumbnail">
</div>
<div class="mt-3">
<div class="table-responsive">
<table class="table table-borderless">
<tr>
<td><span class="text-muted">Use Code</span></td>
<td><span class="fw-medium">${x._values.code}</span></td>
</tr>
<tr>
<td><span class="text-muted">Discount</span></td>
<td><span class="fw-medium text-uppercase">${new DOMParser().parseFromString(x._values.discount, "text/html").body.firstElementChild.innerHTML}</span></td>
</tr>
<tr>
<td><span class="text-muted">Start Date</span></td>
<td><span class="fw-medium">09 Dec, 2022</span></td>
</tr>
<tr>
<td><span class="text-muted">END Date</span></td>
<td><span class="fw-medium">${x._values.endDate}</span></td>
</tr>
<tr>
<td><span class="text-muted">Product Type</span></td>
<td><span class="fw-medium">${x._values.productType}</span></td>
</tr>
<tr>
<td><span class="text-muted">Status</span></td>
<td>${x._values.status}</td>
</tr>
</table>
</div>
</div>
</div>`;
document.getElementById('couponDetails').innerHTML = codeBlock;
}
});
});
});
}
};
function isStatus(val) {
switch (val) {
case "Active":
return (
'<span class="badge bg-success-subtle text-success text-uppercase">' +
val +
"</span>"
);
case "Expired":
return (
'<span class="badge bg-danger-subtle text-danger text-uppercase">' +
val +
"</span>"
);
}
}
function isProductType(val) {
switch (val) {
case "Headphones":
return (
val
);
case "Watch":
return (
val
);
case "Furniture":
return (
val
);
case "Clothing":
return (
val
);
case "Footwear":
return (
val
);
case "Lighting":
return (
val
);
case "Beauty & Personal Care":
return (
val
);
case "Books":
return (
val
);
case "Other Accessories":
return (
val
);
}
}
function clearFields() {
couponTitleField.value = "";
codeField.value = "";
startDateField.value = "";
endDateField.value = "";
discountField.value = "";
if (productTypeVal) productTypeVal.destroy();
productTypeVal = new Choices(productTypeField);
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField);
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
+190
View File
@@ -0,0 +1,190 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Create Product init File
*/
ClassicEditor
.create(document.querySelector('#ckeditor-classic'))
.then(function (editor) {
editor.ui.view.editable.element.style.height = '200px';
})
.catch(function (error) {
console.error(error);
});
var thumbnailArray = [];
// Dropzone has been added as a global variable.
var myDropzone = new Dropzone("div.my-dropzone", {
url: "/file/post",
addRemoveLinks: true,
removedfile: function (file) {
file.previewElement.remove();
thumbnailArray = [];
},
});
myDropzone.on("thumbnail", function (file, dataUrl) {
thumbnailArray.push(dataUrl);
});
var mockFile = { name: "Existing file!", size: 12345 };
// choices category input
var productCategoryInput = new Choices('#choices-category-input', {
searchEnabled: false,
});
var editinputValueJson = sessionStorage.getItem('editInputValue');
if (editinputValueJson) {
var editinputValueJson = JSON.parse(editinputValueJson);
document.getElementById("formAction").value = "edit";
document.getElementById("product-id-input").value = editinputValueJson.id;
productCategoryInput.setChoiceByValue(editinputValueJson.category);
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, editinputValueJson.productImg);
thumbnailArray.push(editinputValueJson.productImg)
document.getElementById("product-title-input").value = editinputValueJson.productTitle;
document.getElementById("stocks-input").value = editinputValueJson.stock;
document.getElementById("product-price-input").value = editinputValueJson.price;
document.getElementById("product-discount-input").value = editinputValueJson.discount;
document.getElementById("orders-input").value = editinputValueJson.orders;
// clothe-colors
Array.from(document.querySelectorAll(".clothe-colors li")).forEach(function (subElem) {
var nameelem = subElem.querySelector('[type="checkbox"]');
editinputValueJson.color.map(function(subItem){
if (subItem == nameelem.value) {
nameelem.setAttribute("checked", "checked");
}
})
})
// clothe-size
Array.from(document.querySelectorAll(".clothe-size li")).forEach(function (subElem) {
var nameelem = subElem.querySelector('[type="checkbox"]');
if(editinputValueJson.size){
editinputValueJson.size.map(function(subItem){
if (subItem == nameelem.value) {
nameelem.setAttribute("checked", "checked");
}
})
}
})
}
var forms = document.querySelectorAll('.needs-validation')
// date & time
var date = new Date().toUTCString().slice(5, 16);
var itemid = 13;
var colorsArray = [];
var sizesArray = [];
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
} else {
event.preventDefault();
var productItemID = itemid;
var productTitleValue = document.getElementById("product-title-input").value;
var productCategoryValue = productCategoryInput.getValue(true);
var stockInputValue = document.getElementById("stocks-input").value;
var orderValue = document.getElementById("orders-input").value;
var productPriceValue = document.getElementById("product-price-input").value;
var productDiscountVal = document.getElementById("product-discount-input").value;
// clothe-colors
document.querySelectorAll(".clothe-colors li").forEach(function (item) {
if (item.querySelector("input").checked == true) {
var colorListVal = item.querySelector("input").value;
colorsArray.push(colorListVal)
}
});
// clothe-size
document.querySelectorAll(".clothe-size li").forEach(function (item) {
if (item.querySelector("input").checked == true) {
var sizeListVal = item.querySelector("input").value;
sizesArray.push(sizeListVal)
}
});
var formAction = document.getElementById("formAction").value;
if (formAction == "add" && productCategoryValue !== "" && thumbnailArray.length > 0) {
if (sessionStorage.getItem('inputValue') != null) {
var inputValueJson = JSON.parse(sessionStorage.getItem('inputValue'));
var newObj = {
"id": productItemID + 1,
"productImg": thumbnailArray[0],
"productTitle": productTitleValue,
"category": productCategoryValue,
"price": productPriceValue,
"discount": productDiscountVal,
"rating": "--",
"color": colorsArray,
"size": sizesArray,
"stock": stockInputValue,
"orders": orderValue,
"publish": date,
};
inputValueJson.push(newObj);
sessionStorage.setItem('inputValue', JSON.stringify(inputValueJson));
} else {
var inputValueJson = [];
var newObj = {
'id': productItemID,
"productImg": thumbnailArray[0],
"productTitle": productTitleValue,
"category": productCategoryValue,
"price": productPriceValue,
"discount": productDiscountVal,
"rating": "--",
"color": colorsArray,
"size": sizesArray,
"stock": stockInputValue,
"orders": orderValue,
"publish": date,
};
inputValueJson.push(newObj);
sessionStorage.setItem('inputValue', JSON.stringify(inputValueJson));
}
window.location.replace("product-list");
}else if (formAction == "edit" && productCategoryValue !== "" && thumbnailArray.length > 0) {
var editproductId = document.getElementById("product-id-input").value;
if (sessionStorage.getItem('editInputValue')) {
var editObj = {
"id": parseInt(editproductId),
"productImg": thumbnailArray[0],
"productTitle": productTitleValue,
"category": productCategoryValue,
"price": productPriceValue,
"discount": productDiscountVal,
"rating": editinputValueJson.rating,
"color": colorsArray,
"size": sizesArray,
"stock": stockInputValue,
"orders": orderValue,
"publish": editinputValueJson.publish,
};
sessionStorage.setItem('editInputValue', JSON.stringify(editObj));
}
window.location.replace("product-list");
}else {
console.log('Form Action Not Found.');
}
return false;
}
form.classList.add('was-validated');
}, false)
});
+351
View File
@@ -0,0 +1,351 @@
var perPage = 10;
var editlist = false;
var options = {
valueNames: [
"id",
"currencyName",
"usd",
"type",
"exchangeRate",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
var currencyRatesList = new List("currencyRatesList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
var idField = document.getElementById("id-field"),
exchangeRateField = document.getElementById("exchangeRate-field"),
currencyNameField = document.getElementById("currencyName-field"),
typeField = document.getElementById("type-field"),
currencyAmountField = document.getElementById("currencyAmount-field"),
addBtn = document.getElementById("add-btn")
editBtn = document.getElementById("edit-btn"),
removeBtns = document.getElementsByClassName("remove-item-btn"),
editBtns = document.getElementsByClassName("edit-item-btn");
refreshCallbacks();
var typeVal = new Choices(typeField);
document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Edit Currency";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Update Currency";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Add Currency";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Add Currency";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List Currency";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
}
});
//Add Currency
var count = 12;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
if (exchangeRateField.value == "") {
text = "Please enter a customer name";
errorMsg.innerHTML = text;
return false;
}else if (currencyNameField.value == "") {
text = "Please select a products";
errorMsg.innerHTML = text;
return false;
}else if (typeField.value == "") {
text = "Please select a type value";
errorMsg.innerHTML = text;
return false;
}else if (currencyAmountField.value == "") {
text = "Please select a delivery date";
errorMsg.innerHTML = text;
return false;
}
if (
exchangeRateField.value !== "" &&
currencyNameField.value !== "" &&
typeField.value !== "" &&
currencyAmountField.value !== "" && !editlist
) {
currencyRatesList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">${count}</a>`,
usd: exchangeRateField.value,
currencyName: currencyNameField.value,
type: isType(typeField.value),
exchangeRate: currencyAmountField.value,
});
currencyRatesList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Currency added successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
else if (
exchangeRateField.value !== "" &&
currencyNameField.value !== "" &&
typeField.value !== "" &&
currencyAmountField.value !== "" && editlist
) {
var editValues = currencyRatesList.get({
id: idField.value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + idField.value + "</a>",
usd: exchangeRateField.value,
currencyName: currencyNameField.value,
type: isType(typeField.value),
exchangeRate: currencyAmountField.value,
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Currency updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
});
function refreshCallbacks() {
// removeBtns
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = currencyRatesList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
currencyRatesList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Currency Deleted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
});
}
});
});
});
}
//editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = currencyRatesList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
editlist = true;
idField.value = selectedid;
exchangeRateField.value = x._values.usd;
currencyNameField.value = x._values.currencyName;
currencyAmountField.value = x._values.exchangeRate;
// TypeVal
if (typeVal) typeVal.destroy();
typeVal = new Choices(typeField, {
searchEnabled: false
});
val = new DOMParser().parseFromString(x._values.type, "text/html");
var typeSelec = val.body.innerHTML;
typeVal.setChoiceByValue(typeSelec);
}
});
});
});
};
};
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
currencyRatesList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">#TB${element.id}</a>`,
currencyName: element.currencyName,
usd: element.usd,
type: isType(element.type),
exchangeRate: element.exchangeRate,
});
currencyRatesList.sort('id', { order: "desc" });
refreshCallbacks();
});
currencyRatesList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TB01</a>`);
}
xhttp.open("GET", "../build/json/currency-rates.json");
xhttp.send();
function isType(val) {
switch (val) {
case "Euro (€)":
return (
val
);
case "Yuan (¥)":
return (
val
);
case "AFN (؋)":
return (
val
);
case "CAD ($)":
return (
val
);
case "DKK (Kr)":
return (
val
);
case "EGP (E£)":
return (
val
);
case "CAD ($)":
return (
val
);
case "KES (K)":
return (
val
);
case "GBP (£)":
return (
val
);
case "COP ($)":
return (
val
);
}
}
function clearFields() {
exchangeRateField.value = "";
currencyNameField.value = "";
currencyAmountField.value = "";
if (typeVal) typeVal.destroy();
typeVal = new Choices(typeField);
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
+559
View File
@@ -0,0 +1,559 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Invoice create init Js File
*/
var paymentSign = "$";
Array.from(document.getElementsByClassName("product-line-price")).forEach(function (item) {
item.value = paymentSign +"0.00"
});
function otherPayment() {
var paymentType = document.getElementById("choices-payment-currency").value;
paymentSign = paymentType;
Array.from(document.getElementsByClassName("product-line-price")).forEach(function (item) {
isUpdate = item.value.slice(1);
item.value = paymentSign + isUpdate;
});
recalculateCart();
}
var isPaymentEl = document.getElementById("choices-payment-currency");
var choices = new Choices(isPaymentEl, {
searchEnabled: false
});
// Profile Img
document
.querySelector("#profile-img-file-input")
.addEventListener("change", function () {
var preview = document.querySelector(".user-profile-image");
var file = document.querySelector(".profile-img-file-input").files[0];
var reader = new FileReader();
reader.addEventListener(
"load",
function () {
preview.src = reader.result;
//localStorage.setItem("invoiceLogo", reader.result);
},
false
);
if (file) {
reader.readAsDataURL(file);
}
});
flatpickr("#date-field", {
enableTime: true,
dateFormat: "d M, Y, h:i K",
});
isData();
function isData() {
var plus = document.getElementsByClassName("plus"),
minus = document.getElementsByClassName("minus");
if (plus) {
Array.from(plus).forEach(function (e) {
e.onclick = function (event) {
if (parseInt(e.previousElementSibling.value) < 10) {
event.target.previousElementSibling.value++;
var itemAmount = e.parentElement.parentElement.previousElementSibling.querySelector(".product-price").value;
var priceselection = e.parentElement.parentElement.nextElementSibling.querySelector(".product-line-price");
var productQty = e.parentElement.querySelector(".product-quantity").value;
updateQuantity(productQty, itemAmount, priceselection);
}
}
});
}
if (minus) {
Array.from(minus).forEach(function (e) {
e.onclick = function (event) {
if (parseInt(e.nextElementSibling.value) > 1) {
event.target.nextElementSibling.value--;
var itemAmount = e.parentElement.parentElement.previousElementSibling.querySelector(".product-price").value;
var priceselection = e.parentElement.parentElement.nextElementSibling.querySelector(".product-line-price");
// var productQty = 1;
var productQty = e.parentElement.querySelector(".product-quantity").value;
updateQuantity(productQty, itemAmount, priceselection);
}
};
});
}
}
var count = 1;
function new_link() {
count++;
var tr1 = document.createElement("tr");
tr1.id = count;
tr1.className = "product";
var delLink =
"<tr>" +
'<th scope="row" class="product-id">' +
count +
"</th>" +
'<td class="text-start">' +
'<div class="mb-2">' +
'<input class="form-control bg-light border-0" type="text" id="productName-' + count + '" placeholder="Product Name">' +
'</div>' +
'<textarea class="form-control bg-light border-0" id="productDetails-' + count + '" rows="2" placeholder="Product Details"></textarea>' +
"</div>" +
"</td>" +
"<td>" +
'<input class="form-control bg-light border-0 product-price" type="number" id="productRate-' + count + '" step="0.01" placeholder="$0.00">' +
"</td>" +
"<td>" +
'<div class="input-step">' +
'<button type="button" class="minus"></button>' +
'<input type="number" class="product-quantity" id="product-qty-' + count + '" value="0" readonly>' +
'<button type="button" class="plus">+</button>' +
"</div>" +
"</td>" +
'<td class="text-end">' +
"<div>" +
'<input type="text" class="form-control bg-light border-0 product-line-price" id="productPrice-' + count + '" value="$0.00" placeholder="$0.00" />' +
"</div>" +
"</td>" +
'<td class="product-removal">' +
'<a class="btn btn-danger">Delete</a>' +
"</td>" +
"</tr>";
tr1.innerHTML = document.getElementById("newForm").innerHTML + delLink;
document.getElementById("newlink").appendChild(tr1);
var genericExamples = document.querySelectorAll("[data-trigger]");
Array.from(genericExamples).forEach(function (genericExamp) {
var element = genericExamp;
new Choices(element, {
placeholderValue: "This is a placeholder set in the config",
searchPlaceholderValue: "This is a search placeholder",
});
});
isData();
remove();
amountKeyup();
resetRow()
}
remove();
/* Set rates + misc */
var taxRate = 0.125;
var shippingRate = 65.0;
var discountRate = 0.15;
function remove() {
Array.from(document.querySelectorAll(".product-removal a")).forEach(function (el) {
el.addEventListener("click", function (e) {
removeItem(e);
resetRow()
});
});
}
function resetRow() {
Array.from(document.getElementById("newlink").querySelectorAll("tr")).forEach(function (subItem, index) {
var incid = index + 1;
subItem.querySelector('.product-id').innerHTML = incid;
});
}
/* Recalculate cart */
function recalculateCart() {
var subtotal = 0;
Array.from(document.getElementsByClassName("product")).forEach(function (item) {
Array.from(item.getElementsByClassName("product-line-price")).forEach(function (e) {
if (e.value) {
subtotal += parseFloat(e.value.slice(1));
}
});
});
/* Calculate totals */
var tax = subtotal * taxRate;
var discount = subtotal * discountRate;
var shipping = subtotal > 0 ? shippingRate : 0;
var total = subtotal + tax + shipping - discount;
document.getElementById("cart-subtotal").value =
paymentSign + subtotal.toFixed(2);
document.getElementById("cart-tax").value = paymentSign + tax.toFixed(2);
document.getElementById("cart-shipping").value =
paymentSign + shipping.toFixed(2);
document.getElementById("cart-total").value = paymentSign + total.toFixed(2);
document.getElementById("cart-discount").value =
paymentSign + discount.toFixed(2);
document.getElementById("totalamountInput").value =
paymentSign + total.toFixed(2);
document.getElementById("amountTotalPay").value =
paymentSign + total.toFixed(2);
}
function amountKeyup() {
// var listArray = [];
// listArray.push(document.getElementsByClassName('product-price'));
Array.from(document.getElementsByClassName('product-price')).forEach(function (item) {
item.addEventListener('keyup', function (e) {
var priceselection = item.parentElement.nextElementSibling.nextElementSibling.querySelector('.product-line-price');
var amount = e.target.value;
var itemQuntity = item.parentElement.nextElementSibling.querySelector('.product-quantity').value;
updateQuantity(amount, itemQuntity, priceselection);
});
});
}
amountKeyup();
/* Update quantity */
function updateQuantity(amount, itemQuntity, priceselection) {
var linePrice = amount * itemQuntity;
/* Update line price display and recalc cart totals */
linePrice = linePrice.toFixed(2);
priceselection.value = paymentSign + linePrice;
recalculateCart();
}
/* Remove item from cart */
function removeItem(removeButton) {
removeButton.target.closest("tr").remove();
recalculateCart();
}
//Choise Js
var genericExamples = document.querySelectorAll("[data-trigger]");
Array.from(genericExamples).forEach(function (genericExamp) {
var element = genericExamp;
new Choices(element, {
placeholderValue: "This is a placeholder set in the config",
searchPlaceholderValue: "This is a search placeholder",
});
});
//Address
function billingFunction() {
if (document.getElementById("same").checked) {
document.getElementById("shippingName").value =
document.getElementById("billingName").value;
document.getElementById("shippingAddress").value =
document.getElementById("billingAddress").value;
document.getElementById("shippingPhoneno").value =
document.getElementById("billingPhoneno").value;
document.getElementById("shippingTaxno").value =
document.getElementById("billingTaxno").value;
} else {
document.getElementById("shippingName").value = "";
document.getElementById("shippingAddress").value = "";
document.getElementById("shippingPhoneno").value = "";
document.getElementById("shippingTaxno").value = "";
}
}
var cleaveBlocks = new Cleave('#cardNumber', {
blocks: [4, 4, 4, 4],
uppercase: true
});
var genericExamples = document.querySelectorAll('[data-plugin="cleave-phone"]');
Array.from(genericExamples).forEach(function (genericExamp) {
var element = genericExamp;
new Cleave(element, {
delimiters: ['(', ')', '-'],
blocks: [0, 3, 3, 4]
});
});
let viewobj;
var invoices_list = localStorage.getItem("invoices-list");
var options = localStorage.getItem("option");
var invoice_no = localStorage.getItem("invoice_no");
var invoices = JSON.parse(invoices_list);
if (localStorage.getItem("invoice_no") === null && localStorage.getItem("option") === null) {
viewobj = '';
var value = "#VL" + Math.floor(11111111 + Math.random() * 99999999);
document.getElementById("invoicenoInput").value = value;
} else {
viewobj = invoices.find(o => o.invoice_no === invoice_no);
}
// Invoice Data Load On Form
if ((viewobj != '') && (options == "edit-invoice")) {
document.getElementById("registrationNumber").value = viewobj.company_details.legal_registration_no;
document.getElementById("companyEmail").value = viewobj.company_details.email;
document.getElementById('companyWebsite').value = viewobj.company_details.website;
new Cleave("#compnayContactno", {
prefix: viewobj.company_details.contact_no,
delimiters: ['(', ')', '-'],
blocks: [0, 3, 3, 4]
});
document.getElementById("companyAddress").value = viewobj.company_details.address;
document.getElementById("companyaddpostalcode").value = viewobj.company_details.zip_code;
var preview = document.querySelectorAll(".user-profile-image");
if (viewobj.img !== ''){
preview.src = viewobj.img;
}
document.getElementById("invoicenoInput").value = "#VAL" + viewobj.invoice_no;
document.getElementById("invoicenoInput").setAttribute('readonly',true);
document.getElementById("date-field").value = viewobj.date;
document.getElementById("choices-payment-status").value = viewobj.status;
document.getElementById("totalamountInput").value = "$" + viewobj.order_summary.total_amount;
document.getElementById("billingName").value = viewobj.billing_address.full_name;
document.getElementById("billingAddress").value = viewobj.billing_address.address;
new Cleave("#billingPhoneno", {
prefix: viewobj.company_details.contact_no,
delimiters: ['(', ')', '-'],
blocks: [0, 3, 3, 4]
});
document.getElementById("billingTaxno").value = viewobj.billing_address.tax;
document.getElementById("shippingName").value = viewobj.shipping_address.full_name;
document.getElementById("shippingAddress").value = viewobj.shipping_address.address;
new Cleave("#shippingPhoneno", {
prefix: viewobj.company_details.contact_no,
delimiters: ['(', ')', '-'],
blocks: [0, 3, 3, 4]
});
document.getElementById("shippingTaxno").value = viewobj.billing_address.tax;
var paroducts_list = viewobj.prducts;
var counter = 1;
do {
counter++;
if (paroducts_list.length > 1) {
document.getElementById("add-item").click();
}
} while (paroducts_list.length - 1 >= counter);
var counter_1 = 1;
setTimeout(() => {
Array.from(paroducts_list).forEach(function (element) {
document.getElementById("productName-" + counter_1).value = element.product_name;
document.getElementById("productDetails-" + counter_1).value = element.product_details;
document.getElementById("productRate-" + counter_1).value = element.rates;
document.getElementById("product-qty-" + counter_1).value = element.quantity;
document.getElementById("productPrice-" + counter_1).value = "$" + ((element.rates) * (element.quantity));
counter_1++;
});
}, 300);
document.getElementById("cart-subtotal").value = "$" + viewobj.order_summary.sub_total;
document.getElementById("cart-tax").value = "$" + viewobj.order_summary.estimated_tex;
document.getElementById("cart-discount").value = "$" + viewobj.order_summary.discount;
document.getElementById("cart-shipping").value = "$" + viewobj.order_summary.shipping_charge;
document.getElementById("cart-total").value = "$" + viewobj.order_summary.total_amount;
document.getElementById("choices-payment-type").value = viewobj.payment_details.payment_method;
document.getElementById("cardholderName").value = viewobj.payment_details.card_holder_name;
var cleave = new Cleave('#cardNumber', {
prefix: viewobj.payment_details.card_number,
delimiter: ' ',
blocks: [4, 4, 4, 4],
uppercase: true
});
document.getElementById("amountTotalPay").value = "$" + viewobj.order_summary.total_amount;
document.getElementById("exampleFormControlTextarea1").value = viewobj.notes;
}
document.addEventListener("DOMContentLoaded", function () {
// //Form Validation
var formEvent = document.getElementById('invoice_form');
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
formEvent.addEventListener("submit", function (event) {
event.preventDefault();
// get fields value
var i_no = (document.getElementById("invoicenoInput").value).slice(4);
var email = document.getElementById("companyEmail").value;
var date = document.getElementById("date-field").value;
var invoice_amount = (document.getElementById("totalamountInput").value).slice(1);
var status = document.getElementById("choices-payment-status").value;
var billing_address_full_name = document.getElementById("billingName").value;
var billing_address_address = document.getElementById("billingAddress").value;
var billing_address_phone = (document.getElementById("billingPhoneno").value).replace(/[^0-9]/g, "");
var billing_address_tax = document.getElementById("billingTaxno").value;
var shipping_address_full_name = document.getElementById("shippingName").value;
var shipping_address_address = document.getElementById("shippingAddress").value;
var shipping_address_phone = (document.getElementById("shippingPhoneno").value).replace(/[^0-9]/g, "");
var shipping_address_tax = document.getElementById("shippingTaxno").value;
var payment_details_payment_method = document.getElementById("choices-payment-type").value;
var payment_details_card_holder_name = document.getElementById("cardholderName").value;
var payment_details_card_number = (document.getElementById("cardNumber").value).replace(/[^0-9]/g, "");
var payment_details_total_amount = (document.getElementById("amountTotalPay").value).slice(1);
var company_details_legal_registration_no = (document.getElementById("registrationNumber").value).replace(/[^0-9]/g, "");
var company_details_email = document.getElementById("companyEmail").value;
var company_details_website = document.getElementById('companyWebsite').value;
var company_details_contact_no = (document.getElementById("compnayContactno").value).replace(/[^0-9]/g, "");
var company_details_address = document.getElementById("companyAddress").value;
var company_details_zip_code = document.getElementById("companyaddpostalcode").value;
var order_summary_sub_total = (document.getElementById("cart-subtotal").value).slice(1);
var order_summary_estimated_tex = (document.getElementById("cart-tax").value).slice(1);
var order_summary_discount = (document.getElementById("cart-discount").value).slice(1);
var order_summary_shipping_charge = (document.getElementById("cart-shipping").value).slice(1);
var order_summary_total_amount = (document.getElementById("cart-total").value).slice(1);
var notes = document.getElementById("exampleFormControlTextarea1").value;
// get product value and make array
var products = document.getElementsByClassName("product");
var count = 1;
var new_product_obj = [];
Array.from(products).forEach(element => {
var product_name = element.querySelector("#productName-"+count).value;
var product_details = element.querySelector("#productDetails-"+count).value;
var product_rate = parseInt(element.querySelector("#productRate-"+count).value);
var product_qty = parseInt(element.querySelector("#product-qty-"+count).value);
var product_price = (element.querySelector("#productPrice-"+count).value).split("$");;
var product_obj = {
product_name: product_name,
product_details: product_details,
rates: product_rate,
quantity: product_qty,
amount: parseInt(product_price[1])
}
new_product_obj.push(product_obj);
count++;
});
if (formEvent.checkValidity() === false) {
formEvent.classList.add("was-validated");
} else {
if ((options == "edit-invoice") && (invoice_no == i_no)) {
objIndex = invoices.findIndex((obj => obj.invoice_no == i_no));
invoices[objIndex].invoice_no = i_no;
invoices[objIndex].customer = billing_address_full_name;
invoices[objIndex].img = '';
invoices[objIndex].email = email;
invoices[objIndex].date = date;
invoices[objIndex].invoice_amount = invoice_amount;
invoices[objIndex].status = status;
invoices[objIndex].billing_address = {
full_name: billing_address_full_name,
address: billing_address_address,
phone: billing_address_phone,
tax: billing_address_tax
};
invoices[objIndex].shipping_address = {
full_name: shipping_address_full_name,
address: shipping_address_address,
phone: shipping_address_phone,
tax: shipping_address_tax
};
invoices[objIndex].payment_details = {
payment_method: payment_details_payment_method,
card_holder_name: payment_details_card_holder_name,
card_number: payment_details_card_number,
total_amount: payment_details_total_amount
};
invoices[objIndex].company_details = {
legal_registration_no: company_details_legal_registration_no,
email: company_details_email,
website: company_details_website,
contact_no: company_details_contact_no,
address: company_details_address,
zip_code: company_details_zip_code
};
invoices[objIndex].order_summary = {
sub_total: order_summary_sub_total,
estimated_tex: order_summary_estimated_tex,
discount: order_summary_discount,
shipping_charge: order_summary_shipping_charge,
total_amount: order_summary_total_amount,
};
invoices[objIndex].prducts = new_product_obj;
invoices[objIndex].notes = notes;
localStorage.removeItem("invoices-list");
localStorage.removeItem("option");
localStorage.removeItem("invoice_no");
localStorage.setItem("invoices-list", JSON.stringify(invoices));
} else {
var new_data_object = {
invoice_no: i_no,
customer: billing_address_full_name,
img: '',
email: email,
date: date,
invoice_amount: invoice_amount,
status: status,
billing_address: {
full_name: billing_address_full_name,
address: billing_address_address,
phone: billing_address_phone,
tax: billing_address_tax
},
shipping_address: {
full_name: shipping_address_full_name,
address: shipping_address_address,
phone: shipping_address_phone,
tax: shipping_address_tax
},
payment_details: {
payment_method: payment_details_payment_method,
card_holder_name: payment_details_card_holder_name,
card_number: payment_details_card_number,
total_amount: payment_details_total_amount
},
company_details: {
legal_registration_no: company_details_legal_registration_no,
email: company_details_email,
website: company_details_website,
contact_no: company_details_contact_no,
address: company_details_address,
zip_code: company_details_zip_code
},
order_summary:{
sub_total: order_summary_sub_total,
estimated_tex: order_summary_estimated_tex,
discount: order_summary_discount,
shipping_charge: order_summary_shipping_charge,
total_amount: order_summary_total_amount
},
prducts: new_product_obj,
notes: notes
};
localStorage.setItem("new_data_object", JSON.stringify(new_data_object));
}
window.location.href = "invoices-list";
}
});
});
+139
View File
@@ -0,0 +1,139 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Invoice Details init Js File
*/
function tConvert(time) {
var d = new Date(time);
time_s = (d.getHours() + ':' + d.getMinutes());
var t = time_s.split(":");
var hours = t[0];
var minutes = t[1];
var newformat = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return (hours + ':' + minutes + ' ' + newformat);
}
var str_dt = function formatDate(date) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date(date),
month = '' + monthNames[(d.getMonth())],
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [day + " " + month, year].join(', ');
};
if ((localStorage.getItem("invoices-list") !== null) && (localStorage.getItem("option") !== null) && (localStorage.getItem("invoice_no") !== null)) {
var invoices_list = localStorage.getItem("invoices-list");
var options = localStorage.getItem("option");
var invoice_no = localStorage.getItem("invoice_no");
var invoices = JSON.parse(invoices_list);
let viewobj = invoices.find(o => o.invoice_no === invoice_no);
if ((viewobj != '') && (options == "view-invoice")) {
let badge;
switch (viewobj.status) {
case 'Paid':
badge = "success";
break;
case 'Refund':
badge = "primary";
break;
case 'Unpaid':
badge = "warning";
break;
case 'Cancel':
badge = "danger";
};
document.getElementById("legal-register-no").innerHTML = viewobj.company_details.legal_registration_no;
document.getElementById("email").innerHTML = viewobj.company_details.email;
document.getElementById('website').href = viewobj.company_details.website;
document.getElementById("website").innerHTML = viewobj.company_details.website;
document.getElementById("contact-no").innerHTML = viewobj.company_details.contact_no;
document.getElementById("address-details").innerHTML = viewobj.company_details.address;
document.getElementById("zip-code").innerHTML = viewobj.company_details.zip_code;
document.getElementById("invoice-no").innerHTML = viewobj.invoice_no;
document.getElementById("invoice-date").innerHTML = str_dt(viewobj.date);
document.getElementById("invoice-time").innerHTML = tConvert(viewobj.date);
document.getElementById("payment-status").innerHTML = viewobj.status;
document.getElementById("payment-status").classList.replace("bg-success-subtle text-success ", 'badge-soft-' + badge);
document.getElementById("total-amount").innerHTML = viewobj.invoice_amount;
document.getElementById("billing-name").innerHTML = viewobj.billing_address.full_name;
document.getElementById("billing-address-line-1").innerHTML = viewobj.billing_address.address;
document.getElementById("billing-phone-no").innerHTML = viewobj.billing_address.phone;
document.getElementById("billing-tax-no").innerHTML = viewobj.billing_address.tax;
document.getElementById("shipping-name").innerHTML = viewobj.shipping_address.full_name;
document.getElementById("shipping-address-line-1").innerHTML = viewobj.shipping_address.address;
document.getElementById("shipping-phone-no").innerHTML = viewobj.shipping_address.phone;
document.getElementById("products-list").innerHTML = "";
var paroducts_list = viewobj.prducts;
var counter = 1;
Array.from(paroducts_list).forEach(function (element) {
product_data = `
<tr>
<th scope="row">` + counter + `</th>
<td class="text-start">
<span class="fw-medium">` + element.product_name + `</span>
<p class="text-muted mb-0">` + element.product_details + `</p>
</td>
<td>` + element.rates + `</td>
<td>` + element.quantity + `</td>
<td class="text-end">$` + element.amount + `</td>
</tr>`;
document.getElementById("products-list").innerHTML += product_data;
counter++;
});
var order_summary = `
<tr class="border-top border-top-dashed mt-2">
<td colspan="3"></td>
<td colspan="2" class="fw-medium p-0">
<table class="table table-borderless text-start table-nowrap align-middle mb-0">
<tbody>
<tr>
<td>Sub Total</td>
<td class="text-end">$` + viewobj.order_summary.sub_total + `</td>
</tr>
<tr>
<td>Estimated Tax (12.5%)</td>
<td class="text-end">$` + viewobj.order_summary.estimated_tex + `</td>
</tr>
<tr>
<td>Discount <small class="text-muted">(VELZON15)</small></td>
<td class="text-end">- $` + viewobj.order_summary.discount + `</td>
</tr>
<tr>
<td>Shipping Charge</td>
<td class="text-end">$` + viewobj.order_summary.shipping_charge + `</td>
</tr>
<tr class="border-top border-top-dashed">
<th scope="row">Total Amount</th>
<td class="text-end">$` + viewobj.order_summary.total_amount + `</td>
</tr>
</tbody>
</table><!--end table-->
</td>
</tr>`;
document.getElementById("products-list").innerHTML += order_summary;
document.getElementById("payment-method").innerHTML = viewobj.payment_details.payment_method;
document.getElementById("card-holder-name").innerHTML = viewobj.payment_details.card_holder_name;
document.getElementById("card-number").innerHTML = viewobj.payment_details.card_number;
document.getElementById("card-total-amount").innerHTML = viewobj.payment_details.total_amount;
document.getElementById("note").innerHTML = viewobj.notes;
}
}
File diff suppressed because it is too large Load Diff
+476
View File
@@ -0,0 +1,476 @@
var perPage = 10;
var editlist = false;
//Table
var options = {
valueNames: [
"id",
"customer_name",
"product_name",
"amount",
"order_date",
"delivery_date",
"payment_method",
"status",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
// Init list
var orderList = new List("orderList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
orderList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TBT' + element.id + '</a>',
customer_name: element.customer_name,
product_name: element.product_name,
amount: element.amount,
order_date: element.order_date,
delivery_date: element.delivery_date,
payment_method: element.payment_method,
status: isStatus(element.status)
});
orderList.sort('id', { order: "desc" });
refreshCallbacks();
});
orderList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TBT42101</a>`);
}
xhttp.open("GET", "../build/json/orders-list.init.json");
xhttp.send();
isCount = new DOMParser().parseFromString(
orderList.items.slice(-1)[0]._values.id,
"text/html"
);
var isValue = isCount.body.firstElementChild.innerHTML;
function isStatus(val) {
switch (val) {
case "Delivered":
return (
'<span class="badge bg-success-subtle text-success text-uppercase">' +
val +
"</span>"
);
case "Cancelled":
return (
'<span class="badge bg-danger-subtle text-danger text-uppercase">' +
val +
"</span>"
);
case "Inprogress":
return (
'<span class="badge bg-secondary-subtle text-secondary text-uppercase">' +
val +
"</span>"
);
case "Pickups":
return (
'<span class="badge bg-info-subtle text-info text-uppercase">' + val + "</span>"
);
case "Returns":
return (
'<span class="badge bg-primary-subtle text-primary text-uppercase">' +
val +
"</span>"
);
case "Pending":
return (
'<span class="badge bg-warning-subtle text-warning text-uppercase">' +
val +
"</span>"
);
}
}
var idField = document.getElementById("orderId"),
customerNameField = document.getElementById("customername-field"),
productNameField = document.getElementById("productname-field"),
createDateField = document.getElementById("createdate-field"),
deliveryDateField = document.getElementById("deliverydate-field"),
amountField = document.getElementById("amount-field"),
paymentField = document.getElementById("payment-field"),
statusField = document.getElementById("delivered-status"),
addBtn = document.getElementById("add-btn")
editBtn = document.getElementById("edit-btn"),
removeBtns = document.getElementsByClassName("remove-item-btn"),
editBtns = document.getElementsByClassName("edit-item-btn");
refreshCallbacks();
var paymentVal = new Choices(paymentField,{
searchEnabled: false,
});
var statusVal = new Choices(statusField,{
searchEnabled: false,
});
var productnameVal = new Choices(productNameField,{
searchEnabled: false,
});
document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("modal-id").style.display = "block";
document.getElementById("exampleModalLabel").innerHTML = "Edit Order";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Update";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("modal-id").style.display = "none";
document.getElementById("exampleModalLabel").innerHTML = "Add Order";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Add Order";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List Order";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
}
});
function refreshCallbacks() {
// removeBtns
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = orderList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
orderList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
});
}
});
});
});
}
// editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = orderList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
editlist = true;
idField.value = selectedid;
customerNameField.value = x._values.customer_name;
productNameField.value = x._values.product_name;
amountField.value = x._values.amount;
createDateField.value = x._values.order_date;
deliveryDateField.value = x._values.delivery_date;
amountField.value = x._values.amount;
// paymentVal
if (paymentVal) paymentVal.destroy();
paymentVal = new Choices(paymentField, {
searchEnabled: false
});
var selected = x._values.payment_method;
paymentVal.setChoiceByValue(selected);
// productnameVal
if (productnameVal) productnameVal.destroy();
productnameVal = new Choices(productNameField, {
searchEnabled: false,
});
var selectedproduct = x._values.product_name;
productnameVal.setChoiceByValue(selectedproduct);
// statusVal
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField, {
searchEnabled: false
});
val = new DOMParser().parseFromString(x._values.status, "text/html");
var statusSelec = val.body.firstElementChild.innerHTML;
statusVal.setChoiceByValue(statusSelec);
flatpickr("#createdate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.order_date,
});
flatpickr("#deliverydate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.delivery_date,
});
}
});
});
});
};
};
var count = 13;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
if (customerNameField.value == "") {
text = "Please enter a customer name";
errorMsg.innerHTML = text;
return false;
}else if (productNameField.value == "") {
text = "Please select a products";
errorMsg.innerHTML = text;
return false;
}else if (createDateField.value == "") {
text = "Please select a order date";
errorMsg.innerHTML = text;
return false;
}else if (deliveryDateField.value == "") {
text = "Please select a delivery date";
errorMsg.innerHTML = text;
return false;
}else if (amountField.value == "") {
text = "Please enter a amount";
errorMsg.innerHTML = text;
return false;
}else if (paymentField.value == "") {
text = "Please select a payment method";
errorMsg.innerHTML = text;
return false;
}else if (statusField.value == "") {
text = "Please select a delivery status";
errorMsg.innerHTML = text;
return false;
}
if (
customerNameField.value !== "" &&
productNameField.value !== "" &&
createDateField.value !== "" &&
deliveryDateField.value !== "" &&
amountField.value !== "" && statusField.value !== "" &&
paymentField.value !== "" && !editlist
) {
orderList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TBT' + count + "</a>",
customer_name: customerNameField.value,
product_name: productNameField.value,
amount: "$" + amountField.value,
order_date: createDateField.value,
delivery_date: deliveryDateField.value,
payment_method: paymentField.value,
status: isStatus(statusField.value),
});
orderList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Order inserted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
} else if (
customerNameField.value !== "" &&
productNameField.value !== "" &&
createDateField.value !== "" &&
deliveryDateField.value !== "" &&
amountField.value !== "" && statusField.value !== "" &&
paymentField.value !== "" && editlist
) {
var editValues = orderList.get({
id: idField.value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + idField.value + "</a>",
customer_name: customerNameField.value,
product_name: productNameField.value,
order_date: createDateField.value,
delivery_date: deliveryDateField.value,
amount: amountField.value,
payment: paymentField.value,
status: isStatus(statusField.value),
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Order updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
});
function filterData() {
var isstatus = document.getElementById("idStatus").value;
var payment = document.getElementById("idPayment").value;
var pickerVal = document.getElementById("demo-datepicker").value;
var date1 = pickerVal.split(" to ")[0];
var date2 = pickerVal.split(" to ")[1];
orderList.filter(function (data) {
matchData = new DOMParser().parseFromString(
data.values().status,
"text/html"
);
var status = matchData.body.firstElementChild.innerHTML;
var statusFilter = false;
var paymentFilter = false;
var dateFilter = false;
if (status == "all" || isstatus == "all") {
statusFilter = true;
} else {
statusFilter = status == isstatus;
}
if (data.values().payment == "all" || payment == "all") {
paymentFilter = true;
} else {
paymentFilter = data.values().payment == payment;
}
if (
new Date(data.values().order_date) >= new Date(date1) &&
new Date(data.values().order_date) <= new Date(date2)
) {
dateFilter = true;
} else {
dateFilter = false;
}
if (statusFilter && paymentFilter && dateFilter) {
return statusFilter && paymentFilter && dateFilter;
} else if (statusFilter && paymentFilter && pickerVal == "") {
return statusFilter && paymentFilter;
} else if (paymentFilter && dateFilter && pickerVal == "") {
return paymentFilter && dateFilter;
}
});
orderList.update();
}
function clearFields() {
idField.value = "";
customerNameField.value = "";
productNameField.value = "";
createDateField.value = "";
deliveryDateField.value = "";
amountField.value = "";
paymentField.value = "";
var createDField = flatpickr("#createdate-field");
createDField.clear();
var deliveryDField = flatpickr("#deliverydate-field");
deliveryDField.clear();
if (paymentVal) paymentVal.destroy();
paymentVal = new Choices(paymentField);
if (productnameVal) productnameVal.destroy();
productnameVal = new Choices(productNameField);
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField);
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
@@ -0,0 +1,411 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: product category init File
*/
var categoryListData = [
{
'id': 1,
"categoryImg": "../build/images/ecommerce/headphone.png",
"categoryTitle": "Headphone",
"subCategory": ["Wireless", "Gaming", "Circumaural (over-ear)", "Supra-aural (on-ear)", "Over-Ear Headphones", "On-Ear Headphones", "True Wireless Earbuds"],
"description": "Headphones are a pair of small speakers used for listening to sound from a computer, music player or other such electronic device."
}, {
'id': 2,
"categoryImg": "../build/images/ecommerce/smart-watch.png",
"categoryTitle": "Watch",
"subCategory": ["Digital Watches", "Dive Watches", "Pilot's Watches", "Field Watches", "Analog Watches", "Quartz Watches"],
"description": "A watch is a symbol of time and wearing a watch implies that you respect the importance of time."
}, {
'id': 3,
"categoryImg": "../build/images/ecommerce/sofa.png",
"categoryTitle": "Furniture",
"subCategory": ["Beds", "Cabinets", "Chairs & Seating", "Desks"],
"description": "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores"
}, {
'id': 4,
"categoryImg": "../build/images/ecommerce/clothes.png",
"categoryTitle": "Clothing",
"subCategory": ["Casual Wear", "Formal Wear", "Business Attire", "Sportswear", "Jackets and coats", "Suits"],
"description": "In enim justo rhoncus ut imperdiet a venenatis vitae justo. Nullam dictum felis eu pede mollis pretium integer tincidunt aenean vulputate eleifend tellus."
}, {
'id': 5,
"categoryImg": "../build/images/ecommerce/baby-shoe.png",
"categoryTitle": "Footwear",
"subCategory": ["Athletic Shoes", "Leather Shoes", "Figure Shoes", "Crocs"],
"description": "It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend"
}, {
'id': 6,
"categoryImg": "../build/images/ecommerce/light-bulb.png",
"categoryTitle": "Lighting",
"subCategory": ["Ambient Lighting", "Task Lighting", "Accent Lighting", "Track Light"],
"description": "To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting."
}, {
'id': 7,
"categoryImg": "../build/images/ecommerce/cosmetics.png",
"categoryTitle": "Beauty & Personal Care",
"subCategory": ["Baby Care", "Deodorants", "Feminine Care", "Fragrances"],
"description": "Beauty Care is basically the science of beauty treatment that involves skin Care, hair Care, manicure, pedicure, Anti- aging treatments, facials, styling and so on."
}, {
'id': 8,
"categoryImg": "../build/images/ecommerce/book.png",
"categoryTitle": "Books",
"subCategory": ["Fantasy", "Horror", "Mystery", "Romance", "Classics", "Poetry", "Short stories"],
"description": "Books are portable and compact, and thus have an advantage over other media forms. Unlike other print media, books most often deal with a single subject."
}, {
'id': 9,
"categoryImg": "../build/images/ecommerce/smart-watch.png",
"categoryTitle": "Other Accessories",
"subCategory": ["Bags", "Eyewear", "Belts", "Hair accessories"],
"description": "For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words."
}, , {
'id': 10,
"categoryImg": "../build/images/ecommerce/cosmetics.png",
"categoryTitle": "Beauty & Personal Care",
"subCategory": ["Baby Care", "Deodorants", "Feminine Care", "Fragrances"],
"description": "Beauty Care is basically the science of beauty treatment that involves skin Care, hair Care, manicure, pedicure, Anti- aging treatments, facials, styling and so on."
}, {
'id': 11,
"categoryImg": "../build/images/ecommerce/book.png",
"categoryTitle": "Books",
"subCategory": ["Fantasy", "Horror", "Mystery", "Romance", "Classics", "Poetry", "Short stories"],
"description": "Books are portable and compact, and thus have an advantage over other media forms. Unlike other print media, books most often deal with a single subject."
}, {
'id': 12,
"categoryImg": "../build/images/ecommerce/smart-watch.png",
"categoryTitle": "Other Accessories",
"subCategory": ["Bags", "Eyewear", "Belts", "Hair accessories"],
"description": "For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words."
}
];
var prevButton = document.getElementById('page-prev');
var nextButton = document.getElementById('page-next');
var currentPage = 1;
var itemsPerPage = 9;
loadcategoryList(categoryListData, currentPage);
paginationEvents();
function loadcategoryList(datas, page) {
var pages = Math.ceil(datas.length / itemsPerPage)
if (page < 1) page = 1
if (page > pages) page = pages;
document.getElementById("categories-list").innerHTML = "";
for (var i = (page - 1) * itemsPerPage; i < (page * itemsPerPage) && i < datas.length; i++) {
if (datas[i]) {
// Array.from(datas).forEach(function (listdata) {
var showElem = 4;
var subCategoryElem = datas[i].subCategory;
var subCategoryHtml = '';
if (datas[i].subCategory) {
Array.from(subCategoryElem.slice(0, showElem)).forEach(function (elem) {
subCategoryHtml += '<li><a href="#!" class="text-muted">' + elem + '</a></li>';
});
}
document.getElementById("categories-list").innerHTML += '<div class="col-xl-4 col-md-6">\
<div class="card card-height-100 categrory-widgets overflow-hidden">\
<div class="card-body p-4">\
<div class="d-flex align-items-center mb-3">\
<h5 class="flex-grow-1 mb-0">'+ datas[i].categoryTitle + '</h5>\
<ul class="flex-shrink-0 list-unstyled hstack gap-1 mb-0">\
<li><a href="#!" class="badge bg-info-subtle text-info edit-list" data-edit-id="'+ datas[i].id + '">Edit</a></li>\
<li><a href="#delteModal" data-bs-toggle="modal" class="badge bg-danger-subtle text-danger remove-list" data-remove-id="'+ datas[i].id + '">Delete</a></li>\
</ul>\
</div>\
<ul class="list-unstyled vstack gap-2 mb-0">'+ subCategoryHtml + '</ul>\
<div class="d-none">'+ datas[i].description + '</div>\
<div class="mt-3">\
<a data-bs-toggle="offcanvas" href="#overviewOffcanvas" data-view-id="'+ datas[i].id + '" class="overview-btn fw-medium link-effect">Read More <i class="ri-arrow-right-line align-bottom ms-1"></i></a>\
</div>\
<img src="'+ datas[i].categoryImg + '" alt="" class="img-fluid category-img object-fit-cover">\
</div>\
</div>\
</div>';
};
};
selectedPage();
currentPage == 1 ? prevButton.parentNode.classList.add('disabled') : prevButton.parentNode.classList.remove('disabled');
currentPage == pages ? nextButton.parentNode.classList.add('disabled') : nextButton.parentNode.classList.remove('disabled');
editCategoryList();
removeItem();
overViewList();
};
function selectedPage() {
var pagenumLink = document.getElementById('page-num').getElementsByClassName('clickPageNumber');
for (var i = 0; i < pagenumLink.length; i++) {
if (i == currentPage - 1) {
pagenumLink[i].parentNode.classList.add("active");
} else {
pagenumLink[i].parentNode.classList.remove("active");
}
}
};
// paginationEvents
function paginationEvents() {
var numPages = function numPages() {
return Math.ceil(categoryListData.length / itemsPerPage);
};
function clickPage() {
document.addEventListener('click', function (e) {
if (e.target.nodeName == "A" && e.target.classList.contains("clickPageNumber")) {
currentPage = e.target.textContent;
loadcategoryList(categoryListData, currentPage);
}
});
};
function pageNumbers() {
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
// for each page
for (var i = 1; i < numPages() + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
prevButton.addEventListener('click', function () {
if (currentPage > 1) {
currentPage--;
loadcategoryList(categoryListData, currentPage);
}
});
nextButton.addEventListener('click', function () {
if (currentPage < numPages()) {
currentPage++;
loadcategoryList(categoryListData, currentPage);
}
});
pageNumbers();
clickPage();
selectedPage();
}
// Search product list
var searchInputList = document.getElementById("searchInputList");
searchInputList.addEventListener("keyup", function () {
var inputVal = searchInputList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.categoryTitle.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(categoryListData, inputVal);
searchResult(filterData);
loadcategoryList(filterData, currentPage);
});
var editlist = false;
// category image
document.querySelector("#category-image-input").addEventListener("change", function () {
var preview = document.querySelector("#category-img");
var file = document.querySelector("#category-image-input").files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
var createCategoryForm = document.querySelectorAll('.createCategory-form')
Array.prototype.slice.call(createCategoryForm).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
form.classList.add('was-validated');
} else {
event.preventDefault();
var inputTitle = document.getElementById('categoryTitle').value;
var categoryImg = document.getElementById("category-img").src;
var categoryDesc = document.getElementById("descriptionInput").value;
var imgArray = window.location.href.split("#");
if (inputTitle !== "" && categoryImg !== imgArray[0] && !editlist) {
var newCategoryId = findNextId();
var newCategory = {
'id': newCategoryId,
"categoryImg": categoryImg,
"categoryTitle": inputTitle,
"subCategory": null,
"description": categoryDesc,
};
categoryListData.push(newCategory);
searchResult(categoryListData);
loadcategoryList(categoryListData, currentPage);
clearVal();
form.classList.remove('was-validated');
} else if (inputTitle !== "" && categoryImg !== imgArray[0] && editlist) {
getEditid = document.getElementById("categoryid-input").value;
categoryListData = categoryListData.map(function (item) {
if (item.id == getEditid) {
var editObj = {
'id': getEditid,
"categoryImg": categoryImg,
"categoryTitle": inputTitle,
"subCategory": item.subCategory,
"description": categoryDesc,
}
return editObj;
}
return item;
});
searchResult(categoryListData);
loadcategoryList(categoryListData, currentPage);
clearVal();
form.classList.remove('was-validated');
editlist = false;
} else {
form.classList.add('was-validated');
}
sortElementsById();
}
}, false)
});
function searchResult(data) {
if (data.length == 0) {
document.getElementById("pagination-element").style.display = "none";
// document.getElementById("search-result-elem").classList.remove("d-none");
} else {
document.getElementById("pagination-element").style.display = "flex";
// document.getElementById("search-result-elem").classList.add("d-none");
}
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
var dataPageNum = Math.ceil(data.length / itemsPerPage)
// for each page
for (var i = 1; i < dataPageNum + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
function fetchIdFromObj(category) {
return parseInt(category.id);
}
function findNextId() {
if (categoryListData.length === 0) {
return 0;
}
var lastElementId = fetchIdFromObj(categoryListData[categoryListData.length - 1]),
firstElementId = fetchIdFromObj(categoryListData[0]);
return (firstElementId >= lastElementId) ? (firstElementId + 1) : (lastElementId + 1);
}
function sortElementsById() {
var manyCategory = categoryListData.sort(function (a, b) {
var x = fetchIdFromObj(a);
var y = fetchIdFromObj(b);
if (x > y) {
return -1;
}
if (x < y) {
return 1;
}
return 0;
})
loadcategoryList(manyCategory, currentPage);
}
sortElementsById();
// editCategoryList
function editCategoryList() {
var getEditid = 0;
Array.from(document.querySelectorAll(".edit-list")).forEach(function (elem) {
elem.addEventListener('click', function (event) {
getEditid = elem.getAttribute('data-edit-id');
categoryListData = categoryListData.map(function (item) {
if (item.id == getEditid) {
editlist = true;
document.getElementById("categoryid-input").value = item.id;
document.getElementById('categoryTitle').value = item.categoryTitle;
document.getElementById("category-img").src = item.categoryImg;
document.getElementById("descriptionInput").value = item.description;
}
return item;
});
});
});
}
// overViewList
function overViewList() {
var getViewid = 0;
Array.from(document.querySelectorAll(".overview-btn")).forEach(function (elem) {
elem.addEventListener('click', function (event) {
getViewid = elem.getAttribute('data-view-id');
categoryListData = categoryListData.map(function (item) {
if (item.id == getViewid) {
document.querySelector('#overviewOffcanvas .overview-id').innerHTML = item.id;
document.querySelector('#overviewOffcanvas .overview-img').src = item.categoryImg;
document.querySelector('#overviewOffcanvas .overview-title').innerHTML = item.categoryTitle;
document.querySelector('#overviewOffcanvas .overview-desc').innerHTML = item.description;
document.querySelector('#overviewOffcanvas .subCategory').innerHTML = "";
item.subCategory.map(function(subItem){
document.querySelector('#overviewOffcanvas .subCategory').innerHTML += '<li><a href="#!" class="text-reset">'+subItem+'</a></li>'
});
document.querySelector('#overviewOffcanvas .edit-list').setAttribute("data-edit-id", getViewid);
document.querySelector('#overviewOffcanvas .remove-list').setAttribute("data-remove-id", getViewid);
}
return item;
});
});
});
}
// removeItem
function removeItem() {
var getid = 0;
Array.from(document.querySelectorAll(".remove-list")).forEach(function (item) {
item.addEventListener('click', function (event) {
getid = item.getAttribute('data-remove-id');
document.getElementById("remove-category").addEventListener("click", function () {
function arrayRemove(arr, value) {
return arr.filter(function (ele) {
return ele.id != value;
});
}
var filtered = arrayRemove(categoryListData, getid);
categoryListData = filtered;
searchResult(categoryListData);
loadcategoryList(categoryListData, currentPage);
document.getElementById("close-removecategoryModal").click();
});
});
});
}
function clearVal() {
document.getElementById('categoryTitle').value = "";
document.getElementById("category-img").src = "";
document.getElementById("slugInput").value = "";
document.getElementById("descriptionInput").value = "";
document.getElementById("category-image-input").value = "";
}
@@ -0,0 +1,34 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: product Details init js
*/
var swiper = new Swiper(".productSwiper", {
spaceBetween: 10,
slidesPerView: 4,
mousewheel: true,
freeMode: true,
watchSlidesProgress: true,
breakpoints: {
992: {
slidesPerView: 4,
spaceBetween: 10,
direction: "vertical",
},
},
});
var swiper2 = new Swiper(".productSwiper2", {
loop: true,
spaceBetween: 10,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
thumbs: {
swiper: swiper,
},
});
+541
View File
@@ -0,0 +1,541 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Product-grid init File
*/
var productListData = [{
'id': 1,
"productImg": "../build/images/products/img-10.png",
"productTitle": "World's most expensive t shirt",
"category": "Fashion",
"price": "354.99",
"discount": "25%",
"rating": "4.9",
"color": ["secondary", "light", "dark"],
"size": ["s", "m", "l"],
"stock": "12",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 2,
"productImg": "../build/images/products/img-15.png",
"productTitle": "Like Style Women Black Handbag",
"category": "Fashion",
"price": "742.00",
"discount": "0%",
"rating": "4.2",
"color": ["light", "dark"],
"stock": "06",
"orders": "30",
"publish": "06 Jan, 2021",
}, {
'id': 3,
"productImg": "../build/images/products/img-1.png",
"productTitle": "Black Horn Backpack For Men Bags 30 L Backpack",
"category": "Grocery",
"price": "150.99",
"discount": "25%",
"rating": "3.8",
"color": ["primary", "danger", "secondary"],
"size": ["s", "m", "l"],
"stock": "10",
"orders": "48",
"publish": "26 Mar, 2021",
}, {
'id': 4,
"productImg": "../build/images/products/img-7.png",
"productTitle": "Innovative education book",
"category": "Kids",
"price": "96.26",
"discount": "0%",
"rating": "4.7",
"stock": "15",
"orders": "40",
"publish": "19 Apr, 2021",
}, {
'id': 5,
"productImg": "../build/images/products/img-4.png",
"productTitle": "Sangria Girls Mint Green & Off-White Solid Open Toe Flats",
"category": "Kids",
"price": "96.26",
"discount": "75%",
"rating": "4.7",
"color": ["success", "danger", "secondary"],
"size": ["40", "41", "42"],
"stock": "08",
"orders": "55",
"publish": "30 Mar, 2021",
}, {
'id': 6,
"productImg": "../build/images/products/img-5.png",
"productTitle": "Lace-Up Casual Shoes For Men",
"category": "Fashion",
"price": "229.00",
"discount": "0%",
"rating": "4.0",
"color": ["danger"],
"size": ["40", "41", "42"],
"stock": "15",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 7,
"productImg": "../build/images/products/img-6.png",
"productTitle": "Striped High Neck Casual Men Orange Sweater",
"category": "Fashion",
"price": "120.00",
"discount": "48%",
"rating": "4.8",
"size": ["s", "m", "l", "xl"],
"stock": "12",
"orders": "45",
"publish": "15 May, 2021",
}, {
'id': 8,
"productImg": "../build/images/products/img-9.png",
"productTitle": "Lace-Up Casual Shoes For Men",
"category": "Kids",
"price": "229.00",
"discount": "15%",
"rating": "2.4",
"color": ["light", "warning"],
"size": ["s", "l"],
"stock": "20",
"orders": "48",
"publish": "21 Jun, 2021",
}, {
'id': 9,
"productImg": "../build/images/products/img-10.png",
"productTitle": "Printed, Typography Men Round Neck Black T-shirt",
"category": "Fashion",
"price": "81.99",
"discount": "0%",
"rating": "4.9",
"color": ["dark", "light"],
"size": ["s", "m", "l", "xl"],
"stock": "14",
"orders": "55",
"publish": "15 Jan, 2021",
}, {
'id': 10,
"productImg": "../build/images/products/img-12.png",
"productTitle": "Carven Lounge Chair Red",
"category": "Furniture",
"price": "209.99",
"discount": "0%",
"rating": "4.1",
"color": ["secondary", "dark", "danger", "light"],
"stock": "20",
"orders": "60",
"publish": "15 Jun, 2021",
}, {
'id': 11,
"productImg": "../build/images/products/img-3.png",
"productTitle": "Ninja Pro Max Smartwatch",
"category": "Watches",
"price": "309.09",
"discount": "20%",
"rating": "3.5",
"color": ["secondary", "info"],
"stock": "12",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 12,
"productImg": "../build/images/products/img-2.png",
"productTitle": "Opinion Striped Round Neck Green T-shirt",
"category": "Fashion",
"price": "126.99",
"discount": "0%",
"rating": "4.1",
"color": ["success"],
"size": ["s", "m", "l", "xl"],
"stock": "06",
"orders": "30",
"publish": "06 Jan, 2021",
}];
var prevButton = document.getElementById('page-prev');
var nextButton = document.getElementById('page-next');
var currentPage = 1;
var itemsPerPage = 6;
loadProductList(productListData, currentPage);
paginationEvents();
function loadProductList(datas, page) {
var pages = Math.ceil(datas.length / itemsPerPage)
if (page < 1) page = 1
if (page > pages) page = pages;
document.getElementById("product-grid").innerHTML = "";
for (var i = (page - 1) * itemsPerPage; i < (page * itemsPerPage) && i < datas.length; i++) {
if (datas[i]) {
// Array.from(datas).forEach(function (listdata) {
var num = 1;
if (datas[i].color) {
var colorElem = '<ul class="clothe-colors list-unstyled hstack gap-1 d-flex mb-0 flex-wrap mb-3">';
Array.from(datas[i].color).forEach(function (elem) {
num++;
colorElem += '<li>\
<input type="radio" name="color'+ datas[i].id + '" id="product-color-' + datas[i].id + num + '">\
<label class="avatar-xxs border border-2 border-white btn btn-'+ elem + ' p-0 d-flex align-items-center justify-content-center rounded-circle" for="product-color-' + datas[i].id + num + '"></label>\
</li>';
})
colorElem += '</ul>';
} else {
var colorElem = '';
}
if (datas[i].size) {
var sizeElem = '<ul class="clothe-size list-unstyled hstack gap-2 d-flex mb-0 flex-wrap mb-3">';
Array.from(datas[i].size).forEach(function (elem) {
num++;
sizeElem += '<li>\
<input type="radio" name="sizes'+ datas[i].id + '" id="product-size-' + datas[i].id + num + '">\
<label class="avatar-xxs border border-2 border-white btn btn-soft-primary text-uppercase p-0 fs-12 d-flex align-items-center justify-content-center rounded-circle" for="product-size-'+ datas[i].id + num + '">' + elem + '</label>\
</li>';
})
sizeElem += '</ul>';
} else {
var sizeElem = '';
}
var text = datas[i].discount;
var myArray = text.split("%");
var discount = myArray[0];
var afterDiscount = datas[i].price - (datas[i].price * discount / 100);
if (discount > 0) {
var discountElem = '<div class="avatar-xs label">\
<div class="avatar-title bg-danger rounded-circle fs-11">'+ datas[i].discount + '</div>\
</div>';
var afterDiscountElem = '<h5 class="text-primary fs-17 mb-0">$' + afterDiscount.toFixed(2) + ' <span class="text-muted fs-14"><del>$' + datas[i].price + '</del></span></h5>'
} else {
var discountElem = "";
var afterDiscountElem = '<h5 class="text-primary fs-17 mb-0">$' + datas[i].price + '</h5>'
}
document.getElementById("product-grid").innerHTML += '<div class="col-lg-4 col-sm-6">\
<div class="card ecommerce-product-widgets overflow-hidden">\
<div class="card-body">\
<div class="bg-light rounded py-5 position-relative">\
<div class="dropdown action">\
<button class="btn btn-soft-secondary btn-sm btn-icon" type="button" data-bs-toggle="dropdown" aria-expanded="false">\
<i class="ph-dots-three-outline"></i>\
</button>\
<ul class="dropdown-menu">\
<li><a class="dropdown-item" href="#">Edit</a></li>\
<li><a class="dropdown-item" href="#">Remove</a></li>\
</ul>\
</div>\
<img src="'+ datas[i].productImg + '" alt="" style="max-height: 150px;max-width: 100%;" class="mx-auto d-block rounded-2">\
'+ discountElem + '\
</div>\
<div class="mt-3">\
<div class="mb-2 d-flex justify-content-between align-items-center">\
'+ afterDiscountElem + '\
<span>'+ datas[i].rating + ' <i class="ri-star-half-fill text-warning align-middle"></i></span>\
</div>\
<a href="#!">\
<h6 class="fs-16 text-capitalize lh-base text-truncate mb-0">'+ datas[i].productTitle + '</h6>\
</a>\
<p class="text-muted">'+ datas[i].category + '</p>\
<div class="row d-none">\
<div class="col-6">'+ colorElem + '</div>\
<div class="col-6">'+ sizeElem + '</div>\
</div>\
<div class="row text-center g-0">\
<div class="col-4 border-end border-end-dashed">\
<div class="mt-3">\
<h5 class="fs-15 text-truncate mb-1">'+ datas[i].stock + '</h5>\
<p class="text-muted mb-0">Stocks</p>\
</div>\
</div>\
<div class="col-4 border-end border-end-dashed">\
<div class="mt-3">\
<h5 class="fs-15 text-truncate mb-1">'+ datas[i].orders + '</h5>\
<p class="text-muted mb-0">Orders</p>\
</div>\
</div>\
<div class="col-4">\
<div class="mt-3">\
<h5 class="fs-15 text-truncate mb-1">'+ datas[i].publish + '</h5>\
<p class="text-muted mb-0">Publish</p>\
</div>\
</div>\
</div>\
</div>\
</div>\
</div>';
}
};
selectedPage();
currentPage == 1 ? prevButton.parentNode.classList.add('disabled') : prevButton.parentNode.classList.remove('disabled');
currentPage == pages ? nextButton.parentNode.classList.add('disabled') : nextButton.parentNode.classList.remove('disabled');
}
function selectedPage() {
var pagenumLink = document.getElementById('page-num').getElementsByClassName('clickPageNumber');
for (var i = 0; i < pagenumLink.length; i++) {
if (i == currentPage - 1) {
pagenumLink[i].parentNode.classList.add("active");
} else {
pagenumLink[i].parentNode.classList.remove("active");
}
}
};
// paginationEvents
function paginationEvents() {
var numPages = function numPages() {
return Math.ceil(productListData.length / itemsPerPage);
};
function clickPage() {
document.addEventListener('click', function (e) {
if (e.target.nodeName == "A" && e.target.classList.contains("clickPageNumber")) {
currentPage = e.target.textContent;
loadProductList(productListData, currentPage);
}
});
};
function pageNumbers() {
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
// for each page
for (var i = 1; i < numPages() + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
prevButton.addEventListener('click', function () {
if (currentPage > 1) {
currentPage--;
loadProductList(productListData, currentPage);
}
});
nextButton.addEventListener('click', function () {
if (currentPage < numPages()) {
currentPage++;
loadProductList(productListData, currentPage);
}
});
pageNumbers();
clickPage();
selectedPage();
}
// Search product list
var searchProductList = document.getElementById("searchProductList");
searchProductList.addEventListener("keyup", function () {
var inputVal = searchProductList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.productTitle.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(productListData, inputVal);
searchResult(filterData);
loadProductList(filterData, currentPage);
});
// category list filter
Array.from(document.querySelectorAll('.filter-list a')).forEach(function (filteritem) {
filteritem.addEventListener("click", function () {
var filterListItem = document.querySelector(".filter-list a.active");
if (filterListItem) filterListItem.classList.remove("active");
filteritem.classList.add('active');
var filterItemValue = filteritem.querySelector(".listname").innerHTML
var filterData = productListData.filter(filterlist => filterlist.category === filterItemValue);
searchResult(filterData);
loadProductList(filterData, currentPage);
});
});
// price range slider
var slider = document.getElementById('product-price-range');
if (slider) {
noUiSlider.create(slider, {
start: [0, 2000], // Handle start position
step: 10, // Slider moves in increments of '10'
margin: 20, // Handles must be more than '20' apart
connect: true, // Display a colored bar between the handles
behaviour: 'tap-drag', // Move handle on tap, bar is draggable
range: { // Slider can select '0' to '100'
'min': 0,
'max': 2000
},
format: wNumb({ decimals: 0, prefix: '$ ' })
});
var minCostInput = document.getElementById('minCost'),
maxCostInput = document.getElementById('maxCost');
var filterDataAll = '';
// When the slider value changes, update the input and span
slider.noUiSlider.on('update', function (values, handle) {
var productListupdatedAll = productListData;
if (handle) {
maxCostInput.value = values[handle];
} else {
minCostInput.value = values[handle];
}
var maxvalue = maxCostInput.value.substr(2);
var minvalue = minCostInput.value.substr(2);
filterDataAll = productListupdatedAll.filter(
product => parseFloat(product.price) >= minvalue && parseFloat(product.price) <= maxvalue
);
searchResult(filterDataAll);
loadProductList(filterDataAll, currentPage);
});
minCostInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
maxCostInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
}
// color-filter
document.querySelectorAll("#color-filter li").forEach(function (item) {
var inputVal = item.querySelector("input[type='radio']").value;
item.querySelector("input[type='radio']").addEventListener("change", function () {
var filterData = productListData.filter(function (filterlist) {
if (filterlist.color) {
return filterlist.color.some(function (g) {
return g == inputVal;
});
}
});
searchResult(filterData);
loadProductList(filterData, currentPage);
});
});
// size-filter
document.querySelectorAll("#size-filter li").forEach(function (item) {
var inputVal = item.querySelector("input[type='radio']").value;
item.querySelector("input[type='radio']").addEventListener("change", function () {
var filterData = productListData.filter(function (filterlist) {
if (filterlist.size) {
return filterlist.size.some(function (g) {
return g == inputVal;
});
}
});
searchResult(filterData);
loadProductList(filterData, currentPage);
});
});
// discount-filter
var arraylist = [];
document.querySelectorAll("#discount-filter .form-check").forEach(function (item) {
var inputVal = item.querySelector(".form-check-input").value;
item.querySelector(".form-check-input").addEventListener("change", function () {
if (item.querySelector(".form-check-input").checked) {
arraylist.push(inputVal);
} else {
arraylist.splice(arraylist.indexOf(inputVal), 1);
}
var filterproductdata = productListData;
if (item.querySelector(".form-check-input").checked && inputVal == 0) {
filterDataAll = filterproductdata.filter(function (product) {
if (product.discount) {
var listArray = product.discount.split("%");
return parseFloat(listArray[0]) < 10;
}
});
} else if (item.querySelector(".form-check-input").checked && arraylist.length > 0) {
var compareval = Math.min.apply(Math, arraylist);
filterDataAll = filterproductdata.filter(function (product) {
if (product.discount) {
var listArray = product.discount.split("%");
return parseFloat(listArray[0]) >= compareval;
}
});
} else {
filterDataAll = productListData;
}
searchResult(filterDataAll);
loadProductList(filterDataAll, currentPage);
});
});
// rating-filter
document.querySelectorAll("#rating-filter .form-check").forEach(function (item) {
var inputVal = item.querySelector(".form-check-input").value;
item.querySelector(".form-check-input").addEventListener("change", function () {
if (item.querySelector(".form-check-input").checked) {
arraylist.push(inputVal);
} else {
arraylist.splice(arraylist.indexOf(inputVal), 1);
}
var filterproductdata = productListData;
if (item.querySelector(".form-check-input").checked && inputVal == 1) {
filterDataAll = filterproductdata.filter(function (product) {
if (product.rating) {
var listArray = product.rating;
return parseFloat(listArray) == 1;
}
});
} else if (item.querySelector(".form-check-input").checked && arraylist.length > 0) {
var compareval = Math.min.apply(Math, arraylist);
filterDataAll = filterproductdata.filter(function (product) {
if (product.rating) {
var listArray = product.rating;
return parseFloat(listArray) >= compareval;
}
});
} else {
filterDataAll = productListData;
}
searchResult(filterDataAll);
loadProductList(filterDataAll, currentPage);
});
});
function searchResult(data) {
if (data.length == 0) {
document.getElementById("pagination-element").style.display = "none";
document.getElementById("search-result-elem").classList.remove("d-none");
} else {
document.getElementById("pagination-element").style.display = "flex";
document.getElementById("search-result-elem").classList.add("d-none");
}
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
var dataPageNum = Math.ceil(data.length / itemsPerPage)
// for each page
for (var i = 1; i < dataPageNum + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
+543
View File
@@ -0,0 +1,543 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: Product-list init File
*/
var productListData = [{
'id': 1,
"productImg": "../build/images/products/img-10.png",
"productTitle": "World's most expensive t shirt",
"category": "Fashion",
"price": "354.99",
"discount": "25%",
"rating": "4.9",
"color": ["secondary", "light", "dark"],
"size": ["s", "m", "l"],
"stock": "12",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 2,
"productImg": "../build/images/products/img-15.png",
"productTitle": "Like Style Women Black Handbag",
"category": "Fashion",
"price": "742.00",
"discount": "0%",
"rating": "4.2",
"color": ["light", "dark"],
"stock": "06",
"orders": "30",
"publish": "06 Jan, 2021",
}, {
'id': 3,
"productImg": "../build/images/products/img-1.png",
"productTitle": "Black Horn Backpack For Men Bags 30 L Backpack",
"category": "Grocery",
"price": "150.99",
"discount": "25%",
"rating": "3.8",
"color": ["primary", "danger", "secondary"],
"size": ["s", "m", "l"],
"stock": "10",
"orders": "48",
"publish": "26 Mar, 2021",
}, {
'id': 4,
"productImg": "../build/images/products/img-7.png",
"productTitle": "Innovative education book",
"category": "Kids",
"price": "96.26",
"discount": "0%",
"rating": "4.7",
"stock": "15",
"orders": "40",
"publish": "19 Apr, 2021",
}, {
'id': 5,
"productImg": "../build/images/products/img-4.png",
"productTitle": "Sangria Girls Mint Green & Off-White Solid Open Toe Flats",
"category": "Kids",
"price": "96.26",
"discount": "75%",
"rating": "4.7",
"color": ["success", "danger", "secondary"],
"size": ["40", "41", "42"],
"stock": "08",
"orders": "55",
"publish": "30 Mar, 2021",
}, {
'id': 6,
"productImg": "../build/images/products/img-5.png",
"productTitle": "Lace-Up Casual Shoes For Men",
"category": "Fashion",
"price": "229.00",
"discount": "0%",
"rating": "4.0",
"color": ["danger"],
"size": ["40", "41", "42"],
"stock": "15",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 7,
"productImg": "../build/images/products/img-6.png",
"productTitle": "Striped High Neck Casual Men Orange Sweater",
"category": "Fashion",
"price": "120.00",
"discount": "48%",
"rating": "4.8",
"size": ["s", "m", "l", "xl"],
"stock": "12",
"orders": "45",
"publish": "15 May, 2021",
}, {
'id': 8,
"productImg": "../build/images/products/img-9.png",
"productTitle": "Lace-Up Casual Shoes For Men",
"category": "Kids",
"price": "229.00",
"discount": "15%",
"rating": "2.4",
"color": ["light", "warning"],
"size": ["s", "l"],
"stock": "20",
"orders": "48",
"publish": "21 Jun, 2021",
}, {
'id': 9,
"productImg": "../build/images/products/img-10.png",
"productTitle": "Printed, Typography Men Round Neck Black T-shirt",
"category": "Fashion",
"price": "81.99",
"discount": "0%",
"rating": "4.9",
"color": ["dark", "light"],
"size": ["s", "m", "l", "xl"],
"stock": "14",
"orders": "55",
"publish": "15 Jan, 2021",
}, {
'id': 10,
"productImg": "../build/images/products/img-12.png",
"productTitle": "Carven Lounge Chair Red",
"category": "Furniture",
"price": "209.99",
"discount": "0%",
"rating": "4.1",
"color": ["secondary", "dark", "danger", "light"],
"stock": "20",
"orders": "60",
"publish": "15 Jun, 2021",
}, {
'id': 11,
"productImg": "../build/images/products/img-3.png",
"productTitle": "Ninja Pro Max Smartwatch",
"category": "Watches",
"price": "309.09",
"discount": "20%",
"rating": "3.5",
"color": ["secondary", "info"],
"stock": "12",
"orders": "48",
"publish": "12 Oct, 2021",
}, {
'id': 12,
"productImg": "../build/images/products/img-2.png",
"productTitle": "Opinion Striped Round Neck Green T-shirt",
"category": "Fashion",
"price": "126.99",
"discount": "0%",
"rating": "4.1",
"color": ["success"],
"size": ["s", "m", "l", "xl"],
"stock": "06",
"orders": "30",
"publish": "06 Jan, 2021",
}];
var inputValueJson = sessionStorage.getItem('inputValue');
if (inputValueJson) {
inputValueJson = JSON.parse(inputValueJson);
Array.from(inputValueJson).forEach(element => {
productListData.push(element);
});
}
var editinputValueJson = sessionStorage.getItem('editInputValue');
if (editinputValueJson) {
editinputValueJson = JSON.parse(editinputValueJson);
productListData = productListData.map(function (item) {
if (item.id == editinputValueJson.id) {
return editinputValueJson;
}
return item;
});
}
// product-list
if (document.getElementById("product-list")) {
var productList = new gridjs.Grid({
columns: [
{
name: '#',
width: '40px',
sort: {
enabled: false
},
data: (function (row) {
return gridjs.html('<div class="form-check checkbox-product-list">\
<input class="form-check-input" type="checkbox" value="'+ row.id + '" id="checkbox-' + row.id + '">\
<label class="form-check-label" for="checkbox-'+ row.id + '"></label>\
</div>');
})
},
{
name: 'Product name',
data: (function (row) {
var num = 1;
if (row.color) {
var colorElem = '<ul class="clothe-colors list-unstyled hstack gap-1 mb-0 flex-wrap d-none">';
Array.from(row.color).forEach(function (elem) {
num++;
colorElem += '<li>\
<input type="radio" name="color'+ row.id + '" id="product-color-' + row.id + num + '">\
<label class="avatar-xxs border border-2 border-white btn btn-'+ elem + ' p-0 d-flex align-items-center justify-content-center rounded-circle" for="product-color-' + row.id + num + '"></label>\
</li>';
})
colorElem += '</ul>';
} else {
var colorElem = '';
}
if (row.size) {
var sizeElem = '<ul class="clothe-size list-unstyled hstack gap-2 mb-0 flex-wrap d-none">';
Array.from(row.size).forEach(function (elem) {
num++;
sizeElem += '<li>\
<input type="radio" name="sizes'+ row.id + '" id="product-size-' + row.id + num + '">\
<label class="avatar-xxs border border-2 border-white btn btn-soft-primary text-uppercase p-0 fs-13 d-flex align-items-center justify-content-center rounded-circle" for="product-size-'+ row.id + num + '">' + elem + '</label>\
</li>';
})
sizeElem += '</ul>';
} else {
var sizeElem = '';
}
return gridjs.html('<div class="d-flex align-items-center">\
<div class="flex-shrink-0 me-2 avatar-sm">\
<div class="avatar-title bg-light rounded">\
<img src="'+ row.productImg + '" alt="" class="avatar-xs" />\
</div>\
</div>\
<div class="flex-grow-1">\
<h6 class="mb-1"><a href="product-create" class="d-block text-reset">'+ row.productTitle + '</a></h6>\
<p class="mb-0 text-muted">Category : <span class="fw-medium">'+ row.category + '</span></p>\
</div>\
</div>'+ colorElem + sizeElem);
}),
width: '400px',
},
{
name: 'Stock',
width: '94px',
},
{
name: 'Rate',
data: (function (row) {
return gridjs.html('<span class="badge bg-light text-body fs-13 fw-medium"><i class="mdi mdi-star text-warning me-1"></i>' + row.rating + '</span>');
}),
width: '80px',
},
{
name: 'Price',
data: (function (row) {
var text = row.discount;
var myArray = text.split("%");
var discount = myArray[0];
var afterDiscount = row.price - (row.price * discount / 100);
if (discount > 0) {
var afterDiscountElem = '<div>$' + afterDiscount.toFixed(2) + ' <span class="text-muted fs-14"><del>$' + row.price + '</del></span></div>'
} else {
var afterDiscountElem = '<div>$' + row.price + '</div>'
}
return gridjs.html(afterDiscountElem);
}),
width: '60px',
},
{
name: 'Orders',
width: '84px',
},
{
name: 'Publish',
width: '120px',
}, {
name: 'Action',
width: '80px',
data: (function (row) {
return gridjs.html('<div class="text-center dropdown">\
<a href="javascript:void(0);" class="btn btn-ghost-primary btn-icon btn-sm" data-bs-toggle="dropdown" aria-expanded="false" class=""><i class="mdi mdi-dots-horizontal"></i></a>\
<ul class="dropdown-menu dropdown-menu-end">\
<li>\
<a class="dropdown-item" onClick="editProductList('+ row.id + ')" href="product-create"><i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit</a>\
</li>\
<li>\
<a class="dropdown-item remove-list" onClick="removeItem('+ row.id +')" data-bs-toggle="modal" href="#removeItemModal"><i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i>Delete</a>\
</li>\
</ul>\
</div>');
})
},
],
sort: true,
pagination: {
limit: 10
},
data: productListData,
}).render(document.getElementById("product-list"));
};
function isStatus(val) {
switch (val) {
case "In stock":
return ('<span class="badge bg-success-subtle text-success align-middle ms-1">' + val + '</span>');
case "Out of stock":
return ('<span class="badge bg-danger-subtle text-danger align-middle ms-1">' + val + '</span>');
}
}
// Search product list
var searchProductList = document.getElementById("searchProductList");
searchProductList.addEventListener("keyup", function () {
var inputVal = searchProductList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.productTitle.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.category.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.stock.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.price.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(productListData, inputVal);
productList.updateConfig({
data: filterData
}).forceRender();
});
// price range slider
var slider = document.getElementById('product-price-range');
if (slider) {
noUiSlider.create(slider, {
start: [0, 2000], // Handle start position
step: 10, // Slider moves in increments of '10'
margin: 20, // Handles must be more than '20' apart
connect: true, // Display a colored bar between the handles
behaviour: 'tap-drag', // Move handle on tap, bar is draggable
range: { // Slider can select '0' to '100'
'min': 0,
'max': 2000
},
format: wNumb({ decimals: 0, prefix: '$ ' })
});
var minCostInput = document.getElementById('minCost'),
maxCostInput = document.getElementById('maxCost');
var filterDataAll = '';
// When the slider value changes, update the input and span
slider.noUiSlider.on('update', function (values, handle) {
var productListupdatedAll = productListData;
if (handle) {
maxCostInput.value = values[handle];
} else {
minCostInput.value = values[handle];
}
var maxvalue = maxCostInput.value.substr(2);
var minvalue = minCostInput.value.substr(2);
filterDataAll = productListupdatedAll.filter(
product => parseFloat(product.price) >= minvalue && parseFloat(product.price) <= maxvalue
);
productList.updateConfig({
data: filterDataAll
}).forceRender();
});
minCostInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
maxCostInput.addEventListener('change', function () {
slider.noUiSlider.set([null, this.value]);
});
}
// color-filter
document.querySelectorAll("#color-filter li").forEach(function (item) {
var inputVal = item.querySelector("input[type='radio']").value;
item.querySelector("input[type='radio']").addEventListener("change", function () {
var filterData = productListData.filter(function (filterlist) {
if (filterlist.color) {
return filterlist.color.some(function (g) {
return g == inputVal;
});
}
});
productList.updateConfig({
data: filterData
}).forceRender();
});
});
// size-filter
document.querySelectorAll("#size-filter li").forEach(function (item) {
var inputVal = item.querySelector("input[type='radio']").value;
item.querySelector("input[type='radio']").addEventListener("change", function () {
var filterData = productListData.filter(function (filterlist) {
if (filterlist.size) {
return filterlist.size.some(function (g) {
return g == inputVal;
});
}
});
productList.updateConfig({
data: filterData
}).forceRender();
});
});
// discount-filter
var arraylist = [];
document.querySelectorAll("#discount-filter .form-check").forEach(function (item) {
var inputVal = item.querySelector(".form-check-input").value;
item.querySelector(".form-check-input").addEventListener("change", function () {
if (item.querySelector(".form-check-input").checked) {
arraylist.push(inputVal);
} else {
arraylist.splice(arraylist.indexOf(inputVal), 1);
}
var filterproductdata = productListData;
if (item.querySelector(".form-check-input").checked && inputVal == 0) {
filterDataAll = filterproductdata.filter(function (product) {
if (product.discount) {
var listArray = product.discount.split("%");
return parseFloat(listArray[0]) < 10;
}
});
} else if (item.querySelector(".form-check-input").checked && arraylist.length > 0) {
var compareval = Math.min.apply(Math, arraylist);
filterDataAll = filterproductdata.filter(function (product) {
if (product.discount) {
var listArray = product.discount.split("%");
return parseFloat(listArray[0]) >= compareval;
}
});
} else {
filterDataAll = productListData;
}
productList.updateConfig({
data: filterDataAll
}).forceRender();
});
});
// rating-filter
document.querySelectorAll("#rating-filter .form-check").forEach(function (item) {
var inputVal = item.querySelector(".form-check-input").value;
item.querySelector(".form-check-input").addEventListener("change", function () {
if (item.querySelector(".form-check-input").checked) {
arraylist.push(inputVal);
} else {
arraylist.splice(arraylist.indexOf(inputVal), 1);
}
var filterproductdata = productListData;
if (item.querySelector(".form-check-input").checked && inputVal == 1) {
filterDataAll = filterproductdata.filter(function (product) {
if (product.rating) {
var listArray = product.rating;
return parseFloat(listArray) == 1;
}
});
} else if (item.querySelector(".form-check-input").checked && arraylist.length > 0) {
var compareval = Math.min.apply(Math, arraylist);
filterDataAll = filterproductdata.filter(function (product) {
if (product.rating) {
var listArray = product.rating;
return parseFloat(listArray) >= compareval;
}
});
} else {
filterDataAll = productListData;
}
productList.updateConfig({
data: filterDataAll
}).forceRender();
});
});
document.getElementById("addproduct-btn").addEventListener("click", function () {
sessionStorage.setItem('editInputValue', "")
})
function editProductList(elem) {
var getEditid = elem;
productListData = productListData.map(function (item) {
if (item.id == getEditid) {
sessionStorage.setItem('editInputValue', JSON.stringify(item));
}
return item;
});
};
// removeItem event
function removeItem(elem) {
var getid = elem;
document.getElementById("remove-product").addEventListener("click", function () {
function arrayRemove(arr, value) {
return arr.filter(function (ele) {
return ele.id != value;
});
}
var filtered = arrayRemove(productListData, getid);
productListData = filtered;
productList.updateConfig({
data: productListData
}).forceRender();
document.getElementById("close-removeproductModal").click();
});
}
// category list filter
Array.from(document.querySelectorAll('.filter-list a')).forEach(function (filteritem) {
filteritem.addEventListener("click", function () {
var filterListItem = document.querySelector(".filter-list a.active");
if (filterListItem) filterListItem.classList.remove("active");
filteritem.classList.add('active');
var filterItemValue = filteritem.querySelector(".listname").innerHTML
var filterData = productListData.filter(filterlist => filterlist.category === filterItemValue);
productList.updateConfig({
data: filterData
}).forceRender();
});
});
@@ -0,0 +1,291 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: product category init File
*/
var subCategoriesData = [
{
"id": 1,
"subcategory": "Wireless",
"category": "Headphone",
"createby": "Admin",
"description": "Headphones are a pair of small speakers used for listening to sound from a computer, music player or other such electronic device."
}, {
"id": 2,
"subcategory": "Leather Shoes",
"category": "Footwear",
"createby": "Admin",
"description": "It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend"
}, {
"id": 3,
"subcategory": "Bags",
"category": "Other Accessories",
"createby": "Admin",
"description": "For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words."
},{
"id": 4,
"subcategory": "Cabinets",
"category": "Furniture",
"createby": "Admin",
"description": "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores"
}, {
"id": 5,
"subcategory": "Digital Watches",
"category": "Watch",
"createby": "Admin",
"description": "A watch is a symbol of time and wearing a watch implies that you respect the importance of time."
}, {
"id": 6,
"subcategory": "Supra-aural (on-ear)",
"category": "Headphone",
"createby": "Admin",
},{
"id": 7,
"subcategory": "Sportswear",
"category": "Clothing",
"createby": "Admin",
"description": "Headphones are a pair of small speakers used for listening to sound from a computer, music player or other such electronic device."
}, {
"id": 8,
"subcategory": "Casual Wear",
"category": "Clothing",
"createby": "Admin",
"description": "In enim justo rhoncus ut imperdiet a venenatis vitae justo. Nullam dictum felis eu pede mollis pretium integer tincidunt aenean vulputate eleifend tellus."
}, {
"id": 9,
"subcategory": "Ambient",
"category": "Lighting",
"createby": "Admin",
},{
"id": 10,
"subcategory": "Chairs & Seating",
"category": "Furniture",
"createby": "Admin",
"description": "To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting."
}, {
"id": 11,
"subcategory": "Feminine Care",
"category": "Beauty & Personal Care",
"createby": "Admin",
"description": "Beauty Care is basically the science of beauty treatment that involves skin Care, hair Care, manicure, pedicure, Anti- aging treatments, facials, styling and so on."
}, {
"id": 12,
"subcategory": "Horror",
"category": "Books",
"createby": "Admin",
"description": "Books are portable and compact, and thus have an advantage over other media forms. Unlike other print media, books most often deal with a single subject."
}
];
var editList = false;
// product-sub-categories
if (document.getElementById("product-sub-categories")) {
var categoryList = new gridjs.Grid({
columns: [
{
name: 'Id',
width: '80px',
data: (function (row) {
return gridjs.html('<div class="fw-medium">#TBSC' + row.id + '</div>');
})
},
{
name: 'Subcategory',
width: '120px'
},
{
name: 'Category',
width: '160px'
},
{
name: 'Createby',
width: '60px'
},{
name: 'Action',
width: '80px',
data: (function (row) {
return gridjs.html('<ul class="hstack gap-2 list-unstyled mb-0">\
<li>\
<a href="#" class="badge bg-success-subtle text-success " onClick="editCategoryList('+ row.id + ')">Edit</a>\
</li>\
<li>\
<a href="#removeItemModal" data-bs-toggle="modal" class="badge bg-danger-subtle text-danger " onClick="removeItem('+ row.id + ')">Delete</a>\
</li>\
</ul>');
})
},
],
sort: true,
pagination: {
limit: 10
},
data: subCategoriesData,
}).render(document.getElementById("product-sub-categories"));
};
// Search result list
var searchResultList = document.getElementById("searchResultList");
searchResultList.addEventListener("keyup", function () {
var inputVal = searchResultList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.subcategory.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.category.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.createby.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(subCategoriesData, inputVal);
categoryList.updateConfig({
data: filterData
}).forceRender();
});
var cateField = document.getElementById("categorySelect");
var categoryInput = new Choices(cateField, {
searchEnabled: false,
});
var createCategoryForm = document.querySelectorAll('.createCategory-form')
Array.prototype.slice.call(createCategoryForm).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
form.classList.add('was-validated');
} else {
event.preventDefault();
var subcategoryTitle = document.getElementById('SubcategoryTitle').value;
var categoryInputVal = categoryInput.getValue(true);
var categoryDesc = document.getElementById("descriptionInput").value;
if (subcategoryTitle !== "" && categoryInputVal !== "" && categoryDesc !== "" && !editList) {
var newCategoryId = findNextId();
var newCategory = {
'id': newCategoryId,
"subcategory": subcategoryTitle,
"category": categoryInputVal,
"createby": "Admin",
"description": categoryDesc
};
subCategoriesData.push(newCategory);
categoryList.updateConfig({
data: subCategoriesData
}).forceRender();
clearVal();
form.classList.remove('was-validated');
}else if(subcategoryTitle !== "" && categoryInputVal !== "" && categoryDesc !== "" && editList){
var getEditid = document.getElementById("categoryid-input").value;
subCategoriesData = subCategoriesData.map(function (item) {
if (item.id == getEditid) {
var editObj = {
'id': getEditid,
"subcategory": subcategoryTitle,
"category": categoryInputVal,
"createby": item.createby,
"description": categoryDesc
}
return editObj;
}
return item;
});
categoryList.updateConfig({
data: subCategoriesData
}).forceRender();
clearVal();
form.classList.remove('was-validated');
editList = false;
} else {
form.classList.add('was-validated');
}
sortElementsById();
}
}, false)
});
function fetchIdFromObj(category) {
return parseInt(category.id);
}
function findNextId() {
if (subCategoriesData.length === 0) {
return 0;
}
var lastElementId = fetchIdFromObj(subCategoriesData[subCategoriesData.length - 1]),
firstElementId = fetchIdFromObj(subCategoriesData[0]);
return (firstElementId >= lastElementId) ? (firstElementId + 1) : (lastElementId + 1);
}
function sortElementsById() {
var categories = subCategoriesData.sort(function (a, b) {
var x = fetchIdFromObj(a);
var y = fetchIdFromObj(b);
if (x > y) {
return -1;
}
if (x < y) {
return 1;
}
return 0;
})
}
sortElementsById();
function editCategoryList(elem){
var getEditid = elem;
subCategoriesData = subCategoriesData.map(function (item) {
if (item.id == getEditid) {
editList = true;
document.getElementById("addCategoryLabel").innerHTML = "Edit Sub Categories";
document.getElementById("addNewCategory").innerHTML = "Save";
document.getElementById("categoryid-input").value = item.id;
document.getElementById("SubcategoryTitle").value = item.subcategory;
categoryInput.setChoiceByValue(item.category);
document.getElementById("descriptionInput").value = item.description;
}
return item;
});
}
// removeItem event
function removeItem(elem) {
var getid = elem;
document.getElementById("remove-category").addEventListener("click", function () {
function arrayRemove(arr, value) {
return arr.filter(function (ele) {
return ele.id != value;
});
}
var filtered = arrayRemove(subCategoriesData, getid);
subCategoriesData = filtered;
categoryList.updateConfig({
data: subCategoriesData
}).forceRender();
document.getElementById("close-removecategoryModal").click();
});
}
function clearVal() {
document.getElementById("addCategoryLabel").innerHTML = "Create Sub Categories";
document.getElementById("addNewCategory").innerHTML = "Add Sub Category";
document.getElementById('SubcategoryTitle').value = "";
document.getElementById("descriptionInput").value = "";
categoryInput.removeActiveItems();
categoryInput.setChoiceByValue("");
}
@@ -0,0 +1,389 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: sellers grid list init File
*/
var url = "../build/json/";
var sellerList = '';
var editList = false;
var prevButton = document.getElementById('page-prev');
var nextButton = document.getElementById('page-next');
// configuration variables
var currentPage = 1;
var itemsPerPage = 8;
var getJSON = function (jsonurl, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url + jsonurl, true);
xhr.responseType = "json";
xhr.onload = function () {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
// get json
getJSON("sellers-grid-list.json", function (err, data) {
if (err !== null) {
console.log("Something went wrong: " + err);
} else {
sellerList = data;
loadSellersListData(sellerList, currentPage);
paginationEvents();
sortElementsById();;
}
});
function loadSellersListData(datas, page) {
var pages = Math.ceil(datas.length / itemsPerPage);
if (page < 1) page = 1;
if (page > pages) page = pages;
document.getElementById("seller-list").innerHTML = "";
for (var i = (page - 1) * itemsPerPage; i < (page * itemsPerPage) && i < datas.length; i++) {
// Array.from(datas).forEach(function (listData){
var checkVerified = datas[i].verified ? '<i class="ph-circle-wavy-check-fill text-primary align-middle fs-15 ms-1"></i></h5>' : "";
document.getElementById("seller-list").innerHTML += '<div class="col-xxl-3 col-lg-6">\
<div class="card">\
<div class="card-body p-4">\
<div class="avatar-md mx-auto">\
<div class="avatar-title bg-light rounded">\
<img src="'+datas[i].companyLogo+'" alt="" class="avatar-xs">\
</div>\
</div>\
<div class="text-center mt-3">\
<a href="seller-overview"><h5 class="mb-1">'+datas[i].sellerName+checkVerified+'</h5></a>\
<p class="text-muted fs-16 mb-4">'+datas[i].webUrl+'</p>\
</div>\
<div class="row">\
<div class="col-6">\
<div class="text-center">\
<p class="text-muted mb-2 fs-15">Item Stock</p>\
<h5 class="mb-0">'+datas[i].stock+'</h5>\
</div>\
</div>\
<div class="col-6 border-start border-start-dashed">\
<div class="text-center">\
<p class="text-muted mb-2 fs-15">Revenue</p>\
<h5 class="mb-0">'+datas[i].revenue+'</h5>\
</div>\
</div>\
</div>\
<div class="mt-4 hstack gap-2">\
<button type="button" class="btn btn-soft-secondary w-100">View Details</button>\
<div class="dropdown flex-shrink-0">\
<button class="btn btn-soft-info btn-icon" type="button" data-bs-toggle="dropdown" aria-expanded="false">\
<i class="ph-dots-three-outline-vertical-fill"></i>\
</button>\
<ul class="dropdown-menu">\
<li><a class="dropdown-item edit-list" href="#createModal" data-bs-toggle="modal" data-edit-id="'+datas[i].id+'">Edit</a></li>\
<li><a class="dropdown-item remove-list" href="#deleteRecordModal" data-remove-id="'+datas[i].id+'" data-bs-toggle="modal">Delete</a></li>\
</ul>\
</div>\
</div>\
</div>\
</div>\
</div>';
}
selectedPage();
refreshCallbacks();
currentPage == 1 ? prevButton.parentNode.classList.add('disabled') : prevButton.parentNode.classList.remove('disabled');
currentPage == pages ? nextButton.parentNode.classList.add('disabled') : nextButton.parentNode.classList.remove('disabled');
// });
}
// companyLogo image
document.querySelector("#companyLogo-image-input").addEventListener("change", function () {
var preview = document.querySelector("#companyLogo-img");
var file = document.querySelector("#companyLogo-image-input").files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
var companyLogoImg = document.getElementById("companyLogo-img");
var sellerNameVal = document.getElementById("sellerName-input");
var webUrlVal = document.getElementById("webUrl-input");
var stockVal = document.getElementById("itemStock-input");
var revenueVal = document.getElementById("revenue-input");
// create-form
var forms = document.querySelectorAll('.create-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var imgArray = window.location.href.split("#");
var logoArray = companyLogoImg.src.split("#");
var text;
if (logoArray[0] == imgArray[0]) {
text = "Please select a company logo image";
errorMsg.innerHTML = text;
return false;
} else if (sellerNameVal.value == "") {
text = "Please enter a seller name";
errorMsg.innerHTML = text;
return false;
} else if (webUrlVal.value == "") {
text = "Please enter a web url";
errorMsg.innerHTML = text;
return false;
} else if (stockVal.value == "") {
text = "Please enter a number of stocks";
errorMsg.innerHTML = text;
return false;
} else if (revenueVal.value == "") {
text = "Please enter a revenue";
errorMsg.innerHTML = text;
return false;
}
if (imgArray[0] && sellerNameVal.value !== "" && webUrlVal.value !== "" && stockVal.value !== "" && revenueVal.value !== "" && !editList) {
var newArrayId = findNextId();
var newArray = {
'id': newArrayId,
"sellerName": sellerNameVal.value,
"companyLogo": companyLogoImg.src,
"verified": false,
"webUrl": webUrlVal.value,
"stock" : stockVal.value,
"revenue" : revenueVal.value
};
sellerList.push(newArray);
sortElementsById();
}else if (imgArray[0] && sellerNameVal.value !== "" && webUrlVal.value !== "" && stockVal.value !== "" && revenueVal.value !== "" && editList) {
var getEditid = 0;
getEditid = document.getElementById("id-field").value;
sellerList = sellerList.map(function (item) {
if (item.id == getEditid) {
var editObj = {
'id': getEditid,
"sellerName": sellerNameVal.value,
"companyLogo": companyLogoImg.src,
"verified": item.verified,
"webUrl": webUrlVal.value,
"stock" : stockVal.value,
"revenue" : revenueVal.value
}
return editObj;
}
return item;
});
editList = false;
}
pageEvent(sellerList);
loadSellersListData(sellerList, currentPage);
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("createModal-close").click();
return true;
});
});
function selectedPage() {
var pagenumLink = document.getElementById('page-num').getElementsByClassName('clickPageNumber');
for (var i = 0; i < pagenumLink.length; i++) {
if (i == currentPage - 1) {
pagenumLink[i].parentNode.classList.add("active");
} else {
pagenumLink[i].parentNode.classList.remove("active");
}
}
};
// paginationEvents
function paginationEvents() {
var numPages = function numPages() {
return Math.ceil(sellerList.length / itemsPerPage);
};
function clickPage() {
document.addEventListener('click', function (e) {
if (e.target.nodeName == "A" && e.target.classList.contains("clickPageNumber")) {
currentPage = e.target.textContent;
loadSellersListData(sellerList, currentPage);
}
});
};
function pageNumbers() {
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
// for each page
for (var i = 1; i < numPages() + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
prevButton.addEventListener('click', function () {
if (currentPage > 1) {
currentPage--;
loadSellersListData(sellerList, currentPage);
}
});
nextButton.addEventListener('click', function () {
if (currentPage < numPages()) {
currentPage++;
loadSellersListData(sellerList, currentPage);
}
});
pageNumbers();
clickPage();
selectedPage();
}
function fetchIdFromObj(member) {
return parseInt(member.id);
}
function findNextId() {
if (sellerList.length === 0) {
return 0;
}
var lastElementId = fetchIdFromObj(sellerList[sellerList.length - 1]),
firstElementId = fetchIdFromObj(sellerList[0]);
return (firstElementId >= lastElementId) ? (firstElementId + 1) : (lastElementId + 1);
}
function sortElementsById() {
var manySellerList = sellerList.sort(function (a, b) {
var x = fetchIdFromObj(a);
var y = fetchIdFromObj(b);
if (x > y) {
return -1;
}
if (x < y) {
return 1;
}
return 0;
})
loadSellersListData(manySellerList, currentPage);
}
// refreshCallbacks
function refreshCallbacks() {
// edit-list
var getEditid = 0;
Array.from(document.querySelectorAll(".edit-list")).forEach(function (elem) {
elem.addEventListener('click', function (event) {
getEditid = elem.getAttribute('data-edit-id');
sellerList = sellerList.map(function (item) {
if (item.id == getEditid) {
editList = true;
document.getElementById("createModalLabel").innerHTML = "Edit seller details";
document.getElementById("addNew").innerHTML = "Save";
document.getElementById("id-field").value = item.id;
companyLogoImg.src = item.companyLogo;
sellerNameVal.value = item.sellerName;
webUrlVal.value = item.webUrl;
stockVal.value = item.stock;
revenueVal.value = item.revenue;
}
return item;
});
});
});
// remove-list
var getid = 0;
Array.from(document.querySelectorAll(".remove-list")).forEach(function (item) {
item.addEventListener('click', function (event) {
getid = item.getAttribute('data-remove-id');
document.getElementById("remove-item").addEventListener("click", function () {
function arrayRemove(arr, value) {
return arr.filter(function (ele) {
return ele.id != value;
});
}
var filtered = arrayRemove(sellerList, getid);
sellerList = filtered;
pageEvent(sellerList);
loadSellersListData(sellerList, currentPage);
document.getElementById("close-removeModal").click();
});
});
});
}
// clearFields
function clearFields() {
document.getElementById("id-field").value = ""
companyLogoImg.src = "";
sellerNameVal.value = "";
webUrlVal.value = "";
stockVal.value = "";
revenueVal.value = "";
document.getElementById("companyLogo-image-input").value = "";
}
document.getElementById('createModal').addEventListener('hidden.bs.modal', event => {
clearFields();
});
// pageEvent
function pageEvent(data) {
if (data.length == 0) {
document.getElementById("pagination-element").style.display = "none";
document.getElementById("noresult").classList.remove("d-none");
} else {
document.getElementById("pagination-element").style.display = "flex";
document.getElementById("noresult").classList.add("d-none");
}
var pageNumber = document.getElementById('page-num');
pageNumber.innerHTML = "";
var dataPageNum = Math.ceil(data.length / itemsPerPage)
// for each page
for (var i = 1; i < dataPageNum + 1; i++) {
pageNumber.innerHTML += "<div class='page-item'><a class='page-link clickPageNumber' href='javascript:void(0);'>" + i + "</a></div>";
}
}
// Search input list
var searchInputList = document.getElementById("searchInputList");
searchInputList.addEventListener("keyup", function () {
var inputVal = searchInputList.value.toLowerCase();
function filterItems(arr, query) {
return arr.filter(function (el) {
return el.sellerName.toLowerCase().indexOf(query.toLowerCase()) !== -1 || el.webUrl.toLowerCase().indexOf(query.toLowerCase()) !== -1
})
}
var filterData = filterItems(sellerList, inputVal);
pageEvent(filterData);
loadSellersListData(filterData, currentPage);
});
+417
View File
@@ -0,0 +1,417 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: sellers list init File
*/
var perPage = 10;
var editlist = false;
var options = {
valueNames: [
"id",
"sellerName",
"itemStock",
"balance",
"email",
"phone",
"createDate",
"accountStatus",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
var sellersList = new List("sellersList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
//Sellers List
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
sellersList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">#TB${element.id}</a>`,
sellerName: element.sellerName,
itemStock: element.itemStock,
balance :element.balance,
email: element.email,
phone: element.phone,
createDate: element.createDate,
accountStatus: isStatus(element.accountStatus)
});
sellersList.sort('id', { order: "desc" });
refreshCallbacks();
});
sellersList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TB01</a>`);
}
xhttp.open("GET", "../build/json/sellers-list.json");
xhttp.send();
isCount = new DOMParser().parseFromString(
sellersList.items.slice(-1)[0]._values.id,
"text/html"
);
var isValue = isCount.body.firstElementChild.innerHTML;
function isStatus(val) {
switch (val) {
case "Active":
return (
'<span class="badge bg-success-subtle text-success text-uppercase">' +
val +
"</span>"
);
case "Inactive":
return (
'<span class="badge bg-danger-subtle text-danger text-uppercase">' +
val +
"</span>"
);
}
}
var idField = document.getElementById("id-field"),
sellerNameField = document.getElementById("seller-name-field"),
itemStockField = document.getElementById("item-stock-field"),
balanceField = document.getElementById("balance-field"),
emailField = document.getElementById("email-field"),
phoneField = document.getElementById("phone-field"),
dateField = document.getElementById("date-field"),
accountStatusField = document.getElementById("account-status-field"),
addBtn = document.getElementById("add-btn"),
editBtns = document.getElementsByClassName("edit-item-btn"),
removeBtns = document.getElementsByClassName("remove-item-btn");
refreshCallbacks();
var accountStatusVal = new Choices(accountStatusField, {
searchEnabled: false
});
document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Edit Seller";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Update";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Add Seller";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Add Seller";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List Seller";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
}
});
function refreshCallbacks() {
// removeBtns
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = sellersList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
sellersList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
Swal.fire({
position: 'center',
icon: 'success',
title: 'User Deleted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
});
}
});
});
});
}
// editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = sellersList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
editlist = true;
idField.value = selectedid;
sellerNameField.value = x._values.sellerName;
itemStockField.value = x._values.itemStock;
balanceField.value = x._values.balance;
emailField.value = x._values.email;
phoneField.value = x._values.phone;
dateField.value = x._values.createDate;
// statusVal
if (accountStatusVal) accountStatusVal.destroy();
accountStatusVal = new Choices(accountStatusField, {
searchEnabled: false
});
var val = new DOMParser().parseFromString(x._values.accountStatus, "text/html");
var statusSelec = val.body.firstElementChild.innerHTML;
accountStatusVal.setChoiceByValue(statusSelec);
flatpickr("#date-field", {
dateFormat: "d M, Y",
defaultDate: x._values.createDate,
});
}
});
});
});
};
};
// Add Seller
var count = 12;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (sellerNameField.value == "") {
text = "Please enter a seller name";
errorMsg.innerHTML = text;
return false;
}else if (itemStockField.value == "") {
text = "Please enter a item stock";
errorMsg.innerHTML = text;
return false;
}else if (balanceField.value == "") {
text = "Please enter a balance ";
errorMsg.innerHTML = text;
return false;
}else if (!emailField.value.match(validRegex)) {
text = "Please enter valid email address";
errorMsg.innerHTML = text;
return false;
}else if (phoneField.value == "") {
text = "Please enter a phone number";
errorMsg.innerHTML = text;
return false;
}else if (dateField.value == "") {
text = "Please select a date";
errorMsg.innerHTML = text;
return false;
}else if (accountStatusField.value == "") {
text = "Please select a status";
errorMsg.innerHTML = text;
return false;
}
if (
sellerNameField.value !== "" &&
itemStockField.value !== "" &&
balanceField.value !== "" &&
emailField.value.match(validRegex) &&
phoneField.value !== "" && dateField.value !== "" &&
accountStatusField.value !== "" && !editlist
) {
sellersList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TB' + count + "</a>",
sellerName: sellerNameField.value,
itemStock: itemStockField.value,
balance: "$" + balanceField.value,
email: emailField.value,
phone: phoneField.value,
createDate: dateField.value,
accountStatus: isStatus(accountStatusField.value),
});
sellersList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Seller details added successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
else if (
sellerNameField.value !== "" &&
itemStockField.value !== "" &&
balanceField.value !== "" &&
emailField.value.match(validRegex) &&
phoneField.value !== "" && dateField.value !== "" &&
accountStatusField.value !== "" && editlist
) {
var editValues = sellersList.get({
id: idField.value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + idField.value + "</a>",
sellerName: sellerNameField.value,
itemStock: itemStockField.value,
balance: balanceField.value,
email: emailField.value,
phone: phoneField.value,
createDate: dateField.value,
accountStatus: isStatus(accountStatusField.value),
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Seller details updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
});
// choices status
var statusInput = new Choices(document.getElementById('idStatus'), {
searchEnabled: false,
});
statusInput.passedElement.element.addEventListener('change', function (event) {
var statusInputValue = event.detail.value;
sellersList.filter(function (data) {
matchData = new DOMParser().parseFromString(
data.values().accountStatus,
"text/html"
);
var status = matchData.body.firstElementChild.innerHTML;
var statusFilter = false;
if (status == "All" || statusInputValue == "All") {
statusFilter = true;
} else {
statusFilter = status == statusInputValue;
}
if (statusFilter) {
return statusFilter;
}
});
sellersList.update();
}, false);
function clearFields() {
sellerNameField.value = "";
itemStockField.value = "";
balanceField.value = "";
emailField.value = "";
phoneField.value = "";
dateField.value = "";
accountStatusField.value = "";
var datePicker = flatpickr("#date-field");
datePicker.clear();
if (accountStatusVal) accountStatusVal.destroy();
accountStatusVal = new Choices(accountStatusField);
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
+467
View File
@@ -0,0 +1,467 @@
/*
Template Name: Toner - Admin & Dashboard Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: shipments list init File
*/
var perPage = 10;
var editlist = false;
//Table
var options = {
valueNames: [
"id",
"shipment_no",
"customer_name",
"supplier",
"location",
"order_date",
"arrival_date",
"status",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
// Init list
var shipmentsList = new List("shipmentsList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
shipmentsList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TBT' + element.id + '</a>',
shipment_no: '<a href="javascript:void(0);" class="text-reset">#' + element.shipment_no + '</a>',
customer_name: element.customer_name,
supplier: element.supplier,
location: element.location,
order_date: element.order_date,
arrival_date: element.arrival_date,
status: isStatus(element.status)
});
shipmentsList.sort('id', { order: "desc" });
refreshCallbacks();
});
shipmentsList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TBSC2830</a>`);
}
xhttp.open("GET", "../build/json/shipments.json");
xhttp.send();
function isStatus(val) {
switch (val) {
case "Pending":
return (
'<span class="badge bg-warning-subtle text-warning ">' +
val +
"</span>"
);
case "Delivered":
return (
'<span class="badge bg-success-subtle text-success ">' +
val +
"</span>"
);
case "Shipping":
return (
'<span class="badge bg-info-subtle text-info ">' +
val +
"</span>"
);
case "Pickups":
return (
'<span class="badge bg-secondary-subtle text-secondary ">' + val + "</span>"
);
case "Returns":
return (
'<span class="badge bg-primary-subtle text-primary ">' +
val +
"</span>"
);
case "Pending":
return (
'<span class="badge bg-warning-subtle text-warning ">' +
val +
"</span>"
);
case "Out Of Delivery":
return (
'<span class="badge bg-danger-subtle text-danger ">' +
val +
"</span>"
);
}
}
var idField = document.getElementById("orderId"),
shipmentNoField = document.getElementById("shipmentNo"),
customerNameField = document.getElementById("customerName-field"),
supplierNameField = document.getElementById("supplierName-field"),
orderDateField = document.getElementById("orderDate-field"),
arrivalDateField = document.getElementById("arrivalDate-field"),
locationField = document.getElementById("locationSelect"),
statusField = document.getElementById("statusSelect"),
addBtn = document.getElementById("add-btn")
editBtn = document.getElementById("edit-btn"),
removeBtns = document.getElementsByClassName("remove-item-btn"),
editBtns = document.getElementsByClassName("edit-item-btn");
refreshCallbacks();
var locationVal = new Choices(locationField,{
searchEnabled: false,
});
var statusVal = new Choices(statusField,{
searchEnabled: false,
});
var count = 13;
document.getElementById("createModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("modal-id").style.display = "block";
document.getElementById("exampleModalLabel").innerHTML = "Edit Shipping Info";
document.getElementById("add-btn").innerHTML = "Update";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("modal-id").style.display = "none";
document.getElementById("exampleModalLabel").innerHTML = "Create Shipping";
document.getElementById("add-btn").innerHTML = "Add Shipping";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List Shipping ";
}
});
function refreshCallbacks() {
// removeBtns
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = shipmentsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
var deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
shipmentsList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Shipping record Deleted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
});
}
});
});
});
}
// editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = shipmentsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
var isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
var ship_no = new DOMParser().parseFromString(x._values.shipment_no, "text/html");
if (selectedid == itemId) {
editlist = true;
document.getElementById("orderID").value = selectedid;
shipmentNoField.value = ship_no.body.firstElementChild.innerHTML;
customerNameField.value = x._values.customer_name;
supplierNameField.value = x._values.supplier;
orderDateField.value = x._values.order_date;
arrivalDateField.value = x._values.arrival_date;
// locationVal
if(locationVal) locationVal.destroy();
var locationValue = new Choices(locationField,{
searchEnabled: false,
});
locationValue.setChoiceByValue(x._values.location);
// statusVal
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField, {
searchEnabled: false
});
val = new DOMParser().parseFromString(x._values.status, "text/html");
var statusSelec = val.body.firstElementChild.innerHTML;
statusVal.setChoiceByValue(statusSelec);
flatpickr("#orderDate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.order_date,
});
flatpickr("#arrivalDate-field", {
dateFormat: "d M, Y",
defaultDate: x._values.arrival_date,
});
}
});
});
});
};
};
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
if (customerNameField.value == "") {
text = "Please enter a customer name";
errorMsg.innerHTML = text;
return false;
} else if (supplierNameField.value == "") {
text = "Please enter a supplier name";
errorMsg.innerHTML = text;
return false;
} else if (orderDateField.value == "") {
text = "Please select a order date";
errorMsg.innerHTML = text;
return false;
} else if (arrivalDateField.value == "") {
text = "Please select a arrival date";
errorMsg.innerHTML = text;
return false;
} else if (locationField.value == "") {
text = "Please select a location";
errorMsg.innerHTML = text;
return false;
} else if (statusField.value == "") {
text = "Please select a status";
errorMsg.innerHTML = text;
return false;
}
if (
customerNameField.value !== "" &&
supplierNameField.value !== "" &&
orderDateField.value !== "" &&
arrivalDateField.value !== "" &&
locationField.value !== "" &&
statusField.value !== "" && !editlist
) {
shipmentsList.add({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">#TBT' + count + "</a>",
shipment_no: '<a href="javascript:void(0);" class="text-reset">#TBSN15414524986</a>',
customer_name: customerNameField.value,
supplier: supplierNameField.value,
location: locationField.value,
order_date: orderDateField.value,
arrival_date: arrivalDateField.value,
status: isStatus(statusField.value),
});
shipmentsList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-createmodal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Shipping record inserted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}else if (
customerNameField.value !== "" &&
supplierNameField.value !== "" &&
orderDateField.value !== "" &&
arrivalDateField.value !== "" &&
locationField.value !== "" &&
statusField.value !== "" && editlist
){
var editValues = shipmentsList.get({
id: document.getElementById("orderID").value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + document.getElementById("orderID").value + "</a>",
shipment_no: '<a href="javascript:void(0);" class="text-reset">' + shipmentNoField.value + "</a>",
customer_name: customerNameField.value,
supplier: supplierNameField.value,
location: locationField.value,
order_date: orderDateField.value,
arrival_date: arrivalDateField.value,
status: isStatus(statusField.value),
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-createmodal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'Shipping record updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
});
function filterData() {
var isstatus = document.getElementById("idStatus").value;
var pickerVal = document.getElementById("demo-datepicker").value;
var date1 = pickerVal.split(" to ")[0];
var date2 = pickerVal.split(" to ")[1];
shipmentsList.filter(function (data) {
matchData = new DOMParser().parseFromString(
data.values().status,
"text/html"
);
var status = matchData.body.firstElementChild.innerHTML;
var statusFilter = false;
var dateFilter = false;
if (status == "all" || isstatus == "all") {
statusFilter = true;
} else {
statusFilter = status == isstatus;
}
if (
new Date(data.values().order_date) >= new Date(date1) &&
new Date(data.values().order_date) <= new Date(date2)
) {
dateFilter = true;
} else {
dateFilter = false;
}
if (statusFilter && dateFilter) {
return statusFilter && dateFilter;
} else if (statusFilter && pickerVal == "") {
return statusFilter;
} else if (dateFilter) {
return dateFilter;
}
});
shipmentsList.update();
}
function clearFields() {
// idField.value = "";
shipmentNoField.value = "";
customerNameField.value = "";
supplierNameField.value = "";
var orderDField = flatpickr("#orderDate-field");
orderDField.clear();
var arrivalDField = flatpickr("#arrivalDate-field");
arrivalDField.clear();
if (locationVal) locationVal.destroy();
locationVal = new Choices(locationField,{
searchEnabled: false,
});
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField,{
searchEnabled: false,
});
}
document.getElementById("createModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
@@ -0,0 +1,80 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Version: 1.2.0
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: shipping-list init File
*/
function getChartColorsArray(chartId) {
if (document.getElementById(chartId) !== null) {
var colors = document.getElementById(chartId).getAttribute("data-colors");
if (colors) {
colors = JSON.parse(colors);
return colors.map(function (value) {
var newValue = value.replace(" ", "");
if (newValue.indexOf(",") === -1) {
var color = getComputedStyle(document.documentElement).getPropertyValue(newValue);
if (color) return color;
else return newValue;;
} else {
var val = value.split(',');
if (val.length == 2) {
var rgbaColor = getComputedStyle(document.documentElement).getPropertyValue(val[0]);
rgbaColor = "rgba(" + rgbaColor + "," + val[1] + ")";
return rgbaColor;
} else {
return newValue;
}
}
});
} else {
console.warn('data-colors atributes not found on', chartId);
}
}
}
// world map with line & markers
var vectorMapWorldLineColors = getChartColorsArray("users-by-country");
if (vectorMapWorldLineColors) {
var worldlinemap = new jsVectorMap({
map: "world_merc",
selector: "#users-by-country",
zoomOnScroll: false,
zoomButtons: false,
markers: [
{
name: "Egypt",
coords: [26.8206, 30.8025]
},
{
name: "United States",
coords: [37.0902, -95.7129]
},
],
lines: [{
from: "United States",
to: "Egypt"
},
],
regionStyle: {
initial: {
stroke: "#9599ad",
strokeWidth: 0.25,
fill: vectorMapWorldLineColors,
fillOpacity: 1,
},
},
labels: {
markers: {
render(marker, index) {
return marker.name || marker.labelName || 'Not available'
}
}
},
lineStyle: {
animation: true,
strokeDasharray: "6 3 6",
},
})
}
+272
View File
@@ -0,0 +1,272 @@
/*
Template Name: Toner eCommerce + Admin HTML Template
Author: Themesbrand
Website: https://Themesbrand.com/
Contact: Themesbrand@gmail.com
File: statistics init js
*/
// get colors array from the string
function getChartColorsArray(chartId) {
if (document.getElementById(chartId) !== null) {
var colors = document.getElementById(chartId).getAttribute("data-colors");
if (colors) {
colors = JSON.parse(colors);
return colors.map(function (value) {
var newValue = value.replace(" ", "");
if (newValue.indexOf(",") === -1) {
var color = getComputedStyle(document.documentElement).getPropertyValue(newValue);
if (color) return color;
else return newValue;;
} else {
var val = value.split(',');
if (val.length == 2) {
var rgbaColor = getComputedStyle(document.documentElement).getPropertyValue(val[0]);
rgbaColor = "rgba(" + rgbaColor + "," + val[1] + ")";
return rgbaColor;
} else {
return newValue;
}
}
});
}
}
}
// Line chart datalabel
var linechartDatalabelColors = getChartColorsArray("line_chart_datalabel");
if (linechartDatalabelColors) {
var options = {
chart: {
height: 380,
type: 'line',
zoom: {
enabled: false
},
toolbar: {
show: false
}
},
colors: linechartDatalabelColors,
dataLabels: {
enabled: false,
},
stroke: {
width: [3, 3],
curve: 'straight'
},
series: [{
name: "Sales",
data: [15, 24, 32, 36, 33, 31, 33]
},
{
name: "Purchase",
data: [18, 30, 19, 25, 17, 22, 18]
}
],
grid: {
row: {
colors: ['transparent', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.2
},
borderColor: '#f1f1f1'
},
markers: {
style: 'inverted',
size: 6
},
xaxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
},
responsive: [{
breakpoint: 600,
options: {
chart: {
toolbar: {
show: false
}
},
legend: {
show: false
},
}
}]
}
var chart = new ApexCharts(
document.querySelector("#line_chart_datalabel"),
options
);
chart.render();
}
// Basic Column Chart
var chartColumnColors = getChartColorsArray("income_statistics");
if (chartColumnColors) {
var options = {
chart: {
height: 380,
type: 'bar',
toolbar: {
show: false,
}
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '45%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: 2,
colors: ['transparent']
},
series: [{
name: 'Net Profit',
data: [296, 285, 365, 410, 321, 357, 436, 397, 510]
}],
colors: chartColumnColors,
xaxis: {
categories: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'],
},
yaxis: {
title: {
text: '$ (Thousands)'
}
},
grid: {
borderColor: '#f1f1f1',
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function (val) {
return "$ " + val + " thousands"
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#income_statistics"),
options
);
chart.render();
}
// top selling product
var chartColumnStackedColors = getChartColorsArray("selling_product");
if (chartColumnStackedColors) {
var options = {
series: [{
name: 'Phone',
data: [44, 55, 41, 67, 22, 43, 24, 41, 25, 10, 32]
}, {
name: 'Clothes',
data: [13, 23, 20, 8, 13, 27, 19, 20, 14, 36, 18]
}, {
name: 'Smartwatch',
data: [11, 17, 15, 15, 21, 14, 8, 11, 12, 17, 20]
}, {
name: 'Footwear',
data: [21, 7, 25, 13, 22, 8, 32, 16, 30, 22, 13]
}, {
name: 'Other',
data: [47, 15, 10, 9, 18, 10, 41, 31, 45, 20, 64]
}],
yaxis: {
title: {
text: 'Products Order'
}
},
legend: {
show: false,
},
chart: {
type: 'bar',
height: 400,
stacked: true,
toolbar: {
show: false
},
zoom: {
enabled: false
},
toolbar: {
show: false,
}
},
responsive: [{
breakpoint: 480,
}],
xaxis: {
categories: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
},
fill: {
opacity: 1
},
colors: chartColumnStackedColors,
};
var chart = new ApexCharts(document.querySelector("#selling_product"), options);
chart.render();
}
// Countries charts
var barchartCountriesColors = getChartColorsArray("countries_charts");
if (barchartCountriesColors) {
var options = {
series: [{
data: [1245, 1640, 490, 1255, 1050, 689, 800, 1879, 1014],
name: 'Orders',
}],
chart: {
type: 'bar',
height: 400,
toolbar: {
show: false,
}
},
plotOptions: {
bar: {
borderRadius: 4,
horizontal: true,
distributed: true,
dataLabels: {
position: 'top',
},
}
},
colors: barchartCountriesColors,
dataLabels: {
enabled: true,
offsetX: 32,
style: {
fontSize: '12px',
fontWeight: 500,
colors: ['#adb5bd']
}
},
legend: {
show: false,
},
grid: {
show: false,
},
xaxis: {
categories: ['India', 'US', 'China', 'Indonesia', 'Russia', 'Canada', 'Brazil', 'USA', 'UK'],
},
};
var chart = new ApexCharts(document.querySelector("#countries_charts"), options);
chart.render();
}
+524
View File
@@ -0,0 +1,524 @@
var perPage = 10;
var editlist = false;
var options = {
valueNames: [
"id",
"vatId",
"clientName",
"cleintEmail",
"type",
"transactionID",
"amount",
"paymentMethod",
"transactionDate",
"status"
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
var transactionsList = new List("transactionsList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
var idField = document.getElementById("id-field"),
clientNameField = document.getElementById("clientName-field"),
clientEmailField = document.getElementById("cleintEmail-field"),
typeField = document.getElementById("type-field"),
transactionIDField = document.getElementById("transactionID-field"),
vatField = document.getElementById("vatID-field"),
amountField = document.getElementById("amount-field"),
paymentMethodField = document.getElementById("paymentMethod-field"),
transactionDateField = document.getElementById("transactionDate-field"),
statusField = document.getElementById("statusSelect"),
addBtn = document.getElementById("add-btn"),
viewBtns = document.getElementsByClassName("view-item-btn"),
editBtn = document.getElementById("edit-btn");
refreshCallbacks();
var typeVal = new Choices(typeField,{
searchEnabled: false,
});
var statusVal = new Choices(statusField,{
searchEnabled: false,
});
const values = [
{
value: 'American Express',
label: '<img src="../build/images/ecommerce/payment/american-express.png" class="avatar-xxs me-1"/> American Express',
id: 1
},
{
value: 'PayPal',
label: '<img src="../build/images/ecommerce/payment/paypal.png" class="avatar-xxs me-1"/> American PayPal',
id: 2
},
{
value: 'Discover',
label: '<img src="../build/images/ecommerce/payment/discover.png" class="avatar-xxs me-1"/> Discover',
id: 3
},
{
value: 'Visa Credit/Debit',
label: '<img src="../build/images/ecommerce/payment/visa.png" class="avatar-xxs me-1"/> Visa Credit/Debit',
id: 4
}
]
var paymentElement = document.querySelector('#paymentMethod-field');
var paymentMethodVal = new Choices(paymentElement, {
choices: values,
searchEnabled: false,
});
//Add Transaction
var count = 11;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (clientNameField.value == "") {
text = "Please enter Client name";
errorMsg.innerHTML = text;
return false;
}else if (!clientEmailField.value.match(validRegex)) {
text = "Please enter valid email address";
errorMsg.innerHTML = text;
return false;
}else if (typeField.value == "") {
text = "Please select a type";
errorMsg.innerHTML = text;
return false;
}else if (transactionIDField.value == "") {
text = "Please enter a transaction ID";
errorMsg.innerHTML = text;
return false;
}else if (vatField.value == "") {
text = "Please enter Vat ID";
errorMsg.innerHTML = text;
return false;
}else if (amountField.value == "") {
text = "Please select a type";
errorMsg.innerHTML = text;
return false;
}else if (paymentMethodField.value == "") {
text = "Please Select Payment Method";
errorMsg.innerHTML = text;
return false;
}else if (transactionDateField.value == "") {
text = "Please select transaction date";
errorMsg.innerHTML = text;
return false;
}else if (statusField.value == "") {
text = "Please select transaction";
errorMsg.innerHTML = text;
return false;
}
if (
clientNameField.value !== "" &&
clientEmailField.value !== "" &&
typeField.value !== "" &&
transactionIDField.value !== "" &&
vatField.value !== "" &&
amountField.value !== "" &&
paymentMethodField.value !== "" &&
transactionDateField.value !== "" &&
statusField.value !== "" && !editlist
)
{
transactionsList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">${count}</a>`,
clientName : clientNameField.value,
cleintEmail: clientEmailField.value,
type:isTypeIcon(typeField.value),
transactionID:`<a href="#!" class="fw-medium">${transactionIDField.value}</a>`,
vatId : vatField.value,
amount : amountField.value,
paymentMethod: isPaymentMethod(paymentMethodField.value) ,
transactionDate: transactionDateField.value,
status: isStatus(statusField.value)
});
transactionsList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'Transaction added successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
}
);
//load json records
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
transactionsList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">#TB${element.id}</a>`,
vatId: element.vatId,
clientName: element.clientName,
cleintEmail: element.cleintEmail,
type:isTypeIcon(element.type),
transactionID : `<a href="#!" class="fw-medium">${element.transactionID}</a>`,
amount : element.amount,
paymentMethod: '<div class="d-flex align-items-center gap-2">\
<div class="flex-shrink-0">\
<img src="'+element.paymentMethod[0]+'" alt="" class="avatar-xs object-fit-cover paycard-image">\
</div>\
<div class="flex-grow-1">\
<h6 class="mb-0 paycard">'+element.paymentMethod[1] +'</h6>\
</div>\
</div>',
transactionDate: element.transactionDate,
status: isStatus(element.status)
});
transactionsList.sort('id', { order: "desc" });
refreshCallbacks();
});
transactionsList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#TB01</a>`);
}
xhttp.open("GET", "../build/json/transactions-list.json");
xhttp.send();
function refreshCallbacks() {
//View button
if(viewBtns){
Array.from(viewBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[0].innerText;
itemId = e.target.closest("tr").children[0].innerText;
var itemValues = transactionsList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
var isTransID = new DOMParser().parseFromString(x._values.transactionID, "text/html");
var isTransIDVal = isTransID.body.firstElementChild.innerHTML;
var isPaymethod = new DOMParser().parseFromString(x._values.paymentMethod, "text/html");
var payCardimg = isPaymethod.body.querySelector(".paycard-image").src;
var payCard = isPaymethod.body.querySelector(".paycard").innerHTML;
if (selectedid == itemId) {
var codeBlock = `<div class="table-responsive table-card">
<table class="table table-borderless align-middle">
<tr>
<td style="width: 150px;">
<span class="text-muted text-uppercase">Transaction ID</span>
</td>
<td>
<span class="fw-semibold">${isTransIDVal}</span>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Date</span>
</td>
<td>
<span class="fw-semibold">${x._values.transactionDate}</span>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">VAT ID:</span>
</td>
<td>
<span class="fw-semibold">${x._values.vatId}</span>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Client Name</span>
</td>
<td>
<span class="fw-semibold">${x._values.clientName}</span>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Email ID</span>
</td>
<td>
<div class="fw-semibold">${x._values.cleintEmail}</div>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Amount</span>
</td>
<td>
<span class="fw-semibold">${x._values.amount}</span>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Payment Method</span>
</td>
<td>
<div class="d-flex align-items-center gap-2">
<div class="flex-shrink-0">
<img src="${payCardimg}" alt="" class="avatar-xs object-fit-cover">
</div>
<div class="flex-grow-1">
<h6 class="mb-0">${payCard}</h6>
</div>
</div>
</td>
</tr>
<tr>
<td>
<span class="text-muted text-uppercase">Status</span>
</td>
<td>
${x._values.status}
</td>
</tr>
</table>
</div>
<div class="mt-3 hstack gap-2">
<button type="button" class="btn btn-soft-danger w-100">Download Receipt</button>
<button type="button" class="btn btn-soft-secondary w-100">All Statement</button>
</div>`;
document.getElementById('transactionDetails').innerHTML = codeBlock;
}
});
});
});
}
};
function isTypeIcon(val) {
switch (val) {
case "up":
return (
'<i class="bx bx-trending-' + val + ' align-middle text-success"></i>'
);
case "down":
return (
'<i class="bx bx-trending-' + val + ' align-middle text-danger"></i>'
);
}
}
function isStatus(val) {
switch (val) {
case "Successful":
return (
'<span class="badge bg-success-subtle text-success ">' +
val +
"</span>"
);
case "Pending":
return (
'<span class="badge bg-warning-subtle text-warning ">' +
val +
"</span>"
);
case "Denied":
return (
'<span class="badge bg-danger-subtle text-danger ">' +
val +
"</span>"
);
}
}
function isPaymentMethod(value){
switch(value){
case "American Express":
return(
`<div class="d-flex align-items-center gap-2">
<div class="flex-shrink-0">
<img src="../build/images/ecommerce/payment/american-express.png" alt="" class="avatar-xs object-fit-cover paycard-image">
</div>
<div class="flex-grow-1">
<h6 class="mb-0 paycard">${value}</h6>
</div>
</div>`
)
case "PayPal":
return(
`<div class="d-flex align-items-center gap-2">
<div class="flex-shrink-0">
<img src="../build/images/ecommerce/payment/paypal.png" alt="" class="avatar-xs object-fit-cover paycard-image">
</div>
<div class="flex-grow-1">
<h6 class="mb-0 paycard">${value}</h6>
</div>
</div>`
)
case "Discover":
return(
`<div class="d-flex align-items-center gap-2">
<div class="flex-shrink-0">
<img src="../build/images/ecommerce/payment/discover.png" alt="" class="avatar-xs object-fit-cover paycard-image">
</div>
<div class="flex-grow-1">
<h6 class="mb-0 paycard">${value}</h6>
</div>
</div>`
)
case "Visa Credit/Debit":
return(
`<div class="d-flex align-items-center gap-2">
<div class="flex-shrink-0">
<img src="../build/images/ecommerce/payment/visa.png" alt="" class="avatar-xs object-fit-cover paycard-image">
</div>
<div class="flex-grow-1">
<h6 class="mb-0 paycard">${value}</h6>
</div>
</div>`
)
}
}
function clearFields() {
clientNameField.value = "";
clientEmailField.value = "";
transactionIDField.value = "";
vatField.value = "";
amountField.value = "";
transactionDateField.value = "";
if (typeVal) typeVal.destroy();
typeVal = new Choices(typeField);
if (statusVal) statusVal.destroy();
statusVal = new Choices(statusField);
if (paymentMethodVal) paymentMethodVal.destroy();
paymentMethodVal = new Choices(paymentElement, {
choices: values,
searchEnabled: false,
});
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
function filterData() {
var isstatus = document.getElementById("idStatus").value;
var pickerVal = document.getElementById("demo-datepicker").value;
var date1 = pickerVal.split(" to ")[0];
var date2 = pickerVal.split(" to ")[1];
transactionsList.filter(function (data) {
matchData = new DOMParser().parseFromString(
data.values().status,
"text/html"
);
var status = matchData.body.firstElementChild.innerHTML;
var statusFilter = false;
var dateFilter = false;
if (status == "all" || isstatus == "all") {
statusFilter = true;
} else {
statusFilter = status == isstatus;
}
if (
new Date(data.values().transactionDate) >= new Date(date1) &&
new Date(data.values().transactionDate) <= new Date(date2)
) {
dateFilter = true;
} else {
dateFilter = false;
}
if (statusFilter && dateFilter) {
return statusFilter && dateFilter;
} else if (statusFilter && pickerVal == "") {
return statusFilter;
} else if (dateFilter && pickerVal !== "") {
return dateFilter;
}
});
transactionsList.update();
}
+381
View File
@@ -0,0 +1,381 @@
var perPage = 10;
var editlist = false;
var options = {
valueNames: [
"id",
"user_name",
"email_id",
"date",
"status",
],
page: perPage,
pagination: true,
plugins: [
ListPagination({
left: 2,
right: 2,
}),
],
};
var usersList = new List("usersList", options).on("updated", function (list) {
list.matchingItems.length == 0 ?
(document.getElementsByClassName("noresult")[0].style.display = "block") :
(document.getElementsByClassName("noresult")[0].style.display = "none");
var isFirst = list.i == 1;
var isLast = list.i > list.matchingItems.length - list.page;
// make the Prev and Nex buttons disabled on first and last pages accordingly
document.querySelector(".pagination-prev.disabled") ?
document.querySelector(".pagination-prev.disabled").classList.remove("disabled") : "";
document.querySelector(".pagination-next.disabled") ?
document.querySelector(".pagination-next.disabled").classList.remove("disabled") : "";
if (isFirst) {
document.querySelector(".pagination-prev").classList.add("disabled");
}
if (isLast) {
document.querySelector(".pagination-next").classList.add("disabled");
}
if (list.matchingItems.length <= perPage) {
document.querySelector(".pagination-wrap").style.display = "none";
} else {
document.querySelector(".pagination-wrap").style.display = "flex";
}
if (list.matchingItems.length == perPage) {
document.querySelector(".pagination.listjs-pagination").firstElementChild.children[0].click()
}
if (list.matchingItems.length > 0) {
document.getElementsByClassName("noresult")[0].style.display = "none";
} else {
document.getElementsByClassName("noresult")[0].style.display = "block";
}
});
var idField = document.getElementById("id-field"),
usersImg = document.getElementById("users-img-field"),
userNameField = document.getElementById("user-name-field"),
emailField = document.getElementById("email-field"),
dateField = document.getElementById("date-field"),
accountStatusField = document.getElementById("account-status-field"),
addBtn = document.getElementById("add-btn")
editBtn = document.getElementById("edit-btn")
editBtns = document.getElementsByClassName("edit-item-btn");
removeBtns = document.getElementsByClassName("remove-item-btn")
refreshCallbacks();
var accountStatusVal = new Choices(accountStatusField, {
searchEnabled: false
});
document.getElementById("showModal").addEventListener("show.bs.modal", function (e) {
if (e.relatedTarget.classList.contains("edit-item-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Edit User";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Update";
} else if (e.relatedTarget.classList.contains("add-btn")) {
document.getElementById("exampleModalLabel").innerHTML = "Add User";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "block";
document.getElementById("add-btn").innerHTML = "Add User";
} else {
document.getElementById("exampleModalLabel").innerHTML = "List User";
document.getElementById("showModal").querySelector(".modal-footer").style.display = "none";
}
});
function refreshCallbacks() {
// removeBtns
if (removeBtns){
Array.from(removeBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = usersList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
deleteid = new DOMParser().parseFromString(x._values.id, "text/html");
var isElem = deleteid.body.firstElementChild;
var isdeleteid = deleteid.body.firstElementChild.innerHTML;
if (isdeleteid == itemId) {
document.getElementById("delete-record").addEventListener("click", function () {
usersList.remove("id", isElem.outerHTML);
document.getElementById("deleteRecord-close").click();
Swal.fire({
position: 'center',
icon: 'success',
title: 'User Deleted successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
});
}
});
});
});
}
// editBtns
if (editBtns){
Array.from(editBtns).forEach(function (btn) {
btn.addEventListener("click", function (e) {
e.target.closest("tr").children[1].innerText;
itemId = e.target.closest("tr").children[1].innerText;
var itemValues = usersList.get({
id: itemId,
});
Array.from(itemValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
editlist = true;
idField.value = selectedid;
var userName = new DOMParser().parseFromString(x._values.user_name, "text/html");
var userImgVal = userName.body.querySelector(".user-profile-img").src;
usersImg.src = userImgVal;
var userNameVal = userName.body.querySelector(".user_name").innerHTML;
userNameField.value = userNameVal;
emailField.value = x._values.email_id;
dateField.value = x._values.date;
// statusVal
if (accountStatusVal) accountStatusVal.destroy();
accountStatusVal = new Choices(accountStatusField, {
searchEnabled: false
});
val = new DOMParser().parseFromString(x._values.status, "text/html");
var statusSelec = val.body.firstElementChild.innerHTML;
accountStatusVal.setChoiceByValue(statusSelec);
flatpickr("#date-field", {
dateFormat: "d M, Y",
defaultDate: x._values.date,
});
}
});
});
});
};
};
//Add User
var count = 11;
var forms = document.querySelectorAll('.tablelist-form')
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault();
var errorMsg = document.getElementById("alert-error-msg");
errorMsg.classList.remove("d-none");
setTimeout(() => errorMsg.classList.add("d-none"), 2000);
var text;
if (userNameField.value == "") {
text = "Please enter User name";
errorMsg.innerHTML = text;
return false;
}else if (emailField.value == "") {
text = "Please enter User email";
errorMsg.innerHTML = text;
return false;
}else if (dateField.value == "") {
text = "Please select a date";
errorMsg.innerHTML = text;
return false;
}else if (accountStatusField.value == "") {
text = "Please select a account status";
errorMsg.innerHTML = text;
return false;
}
if (
userNameField.value !== "" &&
emailField.value !== "" &&
dateField.value !== "" &&
accountStatusField.value !== "" && !editlist
)
{
usersList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">${count}</a>`,
user_name: '<div class="d-flex align-items-center gap-2">\
<div class="flex-shrink-0"><img src="'+usersImg.src+'" alt="" class="avatar-xs rounded-circle user-profile-img"></div>\
<div class="flex-grow-1 ms-2 user_name">'+userNameField.value+'</div>\
</div>',
email_id: emailField.value,
date: dateField.value,
status: isStatus(accountStatusField.value)
});
usersList.sort('id', { order: "desc" });
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
refreshCallbacks();
count++;
Swal.fire({
position: 'center',
icon: 'success',
title: 'User added successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
else if (
userNameField.value !== "" &&
emailField.value !== "" &&
dateField.value !== "" &&
accountStatusField.value !== "" && editlist
) {
var editValues = usersList.get({
id: idField.value,
});
Array.from(editValues).forEach(function (x) {
isid = new DOMParser().parseFromString(x._values.id, "text/html");
var selectedid = isid.body.firstElementChild.innerHTML;
if (selectedid == itemId) {
x.values({
id: '<a href="javascript:void(0);" class="fw-medium link-primary">' + idField.value + "</a>",
user_name: '<div class="d-flex align-items-center gap-2">\
<div class="flex-shrink-0"><img src="'+usersImg.src+'" alt="" class="avatar-xs rounded-circle user-profile-img"></div>\
<div class="flex-grow-1 ms-2 user_name">'+userNameField.value+'</div>\
</div>',
email_id: emailField.value,
date: dateField.value,
status: isStatus(accountStatusField.value),
});
}
});
document.getElementById("alert-error-msg").classList.add("d-none");
document.getElementById("close-modal").click();
clearFields();
Swal.fire({
position: 'center',
icon: 'success',
title: 'User updated Successfully!',
showConfirmButton: false,
timer: 2000,
showCloseButton: true
});
}
return true;
})
}
);
const xhttp = new XMLHttpRequest();
xhttp.onload = function () {
var json_records = JSON.parse(this.responseText);
Array.from(json_records).forEach(function (element) {
usersList.add({
id: `<a href="javascript:void(0);" class="fw-medium link-primary">#VZ${element.id}</a>`,
user_name: '<div class="d-flex align-items-center gap-2">\
<div class="flex-shrink-0"><img src="'+element.user_name[0]+'" alt="" class="avatar-xs rounded-circle user-profile-img"></div>\
<div class="flex-grow-1 ms-2 user_name">'+element.user_name[1]+'</div>\
</div>',
// user_name: element.user_name,
email_id: element.email_id,
date: element.date,
status: isStatus(element.status)
});
usersList.sort('id', { order: "desc" });
refreshCallbacks();
});
usersList.remove("id", `<a href="javascript:void(0);" class="fw-medium link-primary">#VZ001</a>`);
}
xhttp.open("GET", "../build/json/users-list.json");
xhttp.send();
isCount = new DOMParser().parseFromString(
usersList.items.slice(-1)[0]._values.id,
"text/html"
);
var isValue = isCount.body.firstElementChild.innerHTML;
function isStatus(val) {
switch (val) {
case "Active":
return (
'<span class="badge bg-success-subtle text-success ">' +
val +
"</span>"
);
case "Inactive":
return (
'<span class="badge bg-danger-subtle text-danger ">' +
val +
"</span>"
);
}
}
function clearFields() {
userNameField.value = "";
emailField.value = "";
dateField.value = "";
accountStatusField.value = "";
if (accountStatusVal) accountStatusVal.destroy();
accountStatusVal = new Choices(accountStatusField);
document.getElementById("users-img-field").src = "../build/images/users/user-dummy-img.jpg";
document.getElementById("users-image-input").value = "";
}
document.getElementById("showModal").addEventListener("hidden.bs.modal", function () {
clearFields();
});
document.querySelector(".pagination-next").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").nextElementSibling.children[0].click() : "" : "";
});
document.querySelector(".pagination-prev").addEventListener("click", function () {
document.querySelector(".pagination.listjs-pagination") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active") ?
document.querySelector(".pagination.listjs-pagination").querySelector(".active").previousSibling.children[0].click() : "" : "";
});
// brandLogo image
document.querySelector("#users-image-input").addEventListener("change", function () {
var preview = document.querySelector("#users-img-field");
var file = document.querySelector("#users-image-input").files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
});