first upload all files

This commit is contained in:
NW
2023-06-11 13:14:03 +01:00
parent f14dbc52b5
commit c08b36d1b6
1705 changed files with 106852 additions and 0 deletions

View File

@@ -0,0 +1,176 @@
import NProgress from 'nprogress';
export default class {
constructor() {
this.selectize();
this.dateTimePicker();
this.changeAccordionTabState();
this.preventChangingCurrentTab();
this.buttonLoading();
this.confirmationModal();
this.tooltip();
this.shortcuts();
this.nprogress();
}
selectize() {
let selects = $('select.selectize').removeClass('form-control custom-select-black');
let options = _.merge({
valueField: 'id',
labelField: 'name',
searchField: 'name',
delimiter: ',',
persist: true,
selectOnTab: true,
hideSelected: false,
allowEmptyOption: true,
onItemAdd(value) {
this.getItem(value)[0].innerHTML = this.getItem(value)[0].innerHTML.replace(/¦––\s/g, '');
},
onInitialize() {
for (let index in this.options) {
let label = this.options[index].name;
let value = this.options[index].id;
this.$control.find(`.item[data-value="${value}"]`).html(
label.replace(/¦––\s/g, '') +
'<a href="javascript:void(0)" class="remove" tabindex="-1">×</a>'
);
}
},
}, ...FleetCart.selectize);
for (let select of selects) {
select = $(select);
let create = true;
let plugins = ['remove_button', 'restore_on_backspace'];
if (select.hasClass('prevent-creation')) {
create = false;
plugins.remove('restore_on_backspace');
}
select.selectize(_.merge(options, { create, plugins }));
}
}
dateTimePicker(elements) {
elements = elements || $('.datetime-picker');
elements = elements instanceof jQuery ? elements : $(elements);
for (let el of elements) {
$(el).flatpickr({
mode: el.hasAttribute('data-range') ? 'range' : 'single',
enableTime: el.hasAttribute('data-time'),
noCalender: el.hasAttribute('data-no-calender'),
altInput: true,
});
}
}
changeAccordionTabState() {
$('.accordion-box [data-toggle="tab"]').on('click', (e) => {
if (! $(e.currentTarget).parent().hasClass('active')) {
$('.accordion-tab li.active').removeClass('active');
}
});
}
preventChangingCurrentTab() {
$('[data-toggle="tab"]').on('click', (e) => {
let targetElement = $(e.currentTarget);
if (targetElement.parent().hasClass('active')) {
return false;
}
});
}
removeSubmitButtonOffsetOn(tabs, tabsSelector = null) {
tabs = Array.isArray(tabs) ? tabs : [tabs];
$(tabsSelector || '.accordion-tab li > a').on('click', (e) => {
if (tabs.includes(e.currentTarget.getAttribute('href'))) {
setTimeout(() => {
$('button[type=submit]').parent().removeClass('col-md-offset-2');
}, 150);
} else {
setTimeout(() => {
$('button[type=submit]').parent().addClass('col-md-offset-2');
}, 150);
}
});
}
buttonLoading() {
$(document).on('click', '[data-loading]', (e) => {
let button = $(e.currentTarget);
button.data('loading-text', button.html())
.addClass('btn-loading')
.button('loading');
});
}
stopButtonLoading(button) {
button = button instanceof jQuery ? button : $(button);
button.data('loading-text', button.html())
.removeClass('btn-loading')
.button('reset');
}
confirmationModal() {
let confirmationModal = $('#confirmation-modal');
$('[data-confirm]').on('click', () => {
confirmationModal.modal('show');
});
confirmationModal.find('form').on('submit', () => {
confirmationModal.find('button.delete').prop('disabled', true);
});
confirmationModal.on('hidden.bs.modal', () => {
confirmationModal.find('button.delete').prop('disabled', false);
});
confirmationModal.on('shown.bs.modal', () => {
confirmationModal.find('button.delete').focus();
});
}
tooltip() {
$('[data-toggle="tooltip"]').tooltip({ trigger : 'hover' })
.on('click', (e) => {
$(e.currentTarget).tooltip('hide');
});
}
shortcuts() {
Mousetrap.bind('f1', () => {
window.open(`http://envaysoft.com/fleetcart/docs/${FleetCart.version}`, '_blank');
});
Mousetrap.bind('?', () => {
$('#keyboard-shortcuts-modal').modal();
});
}
nprogress() {
let inMobile = /iphone|ipod|android|ie|blackberry|fennec/i.test(window.navigator.userAgent);
if (inMobile) {
return;
}
NProgress.configure({ showSpinner: false });
$(document).ajaxStart(() => NProgress.start());
$(document).ajaxComplete(() => NProgress.done());
}
}

View File

@@ -0,0 +1,281 @@
// Initialize state holders.
FleetCart.dataTable = { routes: {}, selected: {} };
export default class {
constructor(selector, options, callback) {
this.selector = selector;
this.element = $(selector);
if (FleetCart.dataTable.selected[selector] === undefined) {
FleetCart.dataTable.selected[selector] = [];
}
this.initiateDataTable(options, callback);
this.addErrorHandler();
this.registerTableProcessingPlugin();
}
initiateDataTable(options, callback) {
let sortColumn = this.element.find("th[data-sort]");
this.element.dataTable(
_.merge(
{
serverSide: true,
processing: true,
ajax: this.route("index", { table: true }),
stateSave: true,
sort: true,
info: true,
filter: true,
lengthChange: true,
paginate: true,
autoWidth: false,
pageLength: 20,
lengthMenu: [10, 20, 50, 100, 200],
language: {
processing: '<i class="fa fa-refresh fa-spin"></i>',
},
order: [
sortColumn.index() !== -1 ? sortColumn.index() : 1,
sortColumn.data("sort") || "desc",
],
initComplete: () => {
if (this.hasRoute("destroy")) {
let deleteButton = this.addTableActions();
deleteButton.on("click", () => this.deleteRows());
this.selectAllRowsEventListener();
}
if (this.hasRoute("show") || this.hasRoute("edit")) {
this.onRowClick(this.redirectToRowPage);
}
if (callback !== undefined) {
callback.call(this);
}
},
rowCallback: (row, data) => {
if (this.hasRoute("show") || this.hasRoute("edit")) {
this.makeRowClickable(row, data.id);
}
},
drawCallback: () => {
this.element.find(".select-all").prop("checked", false);
setTimeout(() => {
this.selectRowEventListener();
this.checkSelectedCheckboxes(
this.constructor.getSelectedIds(this.selector)
);
});
},
stateSaveParams(settings, data) {
delete data.start;
delete data.search;
},
},
options
)
);
}
addTableActions() {
let button = `
<button type="button" class="btn btn-default btn-delete">
${trans("admin::admin.buttons.delete")}
</button>
`;
return $(button).appendTo(
this.element
.closest(".dataTables_wrapper")
.find(".dataTables_length")
);
}
deleteRows() {
let checked = this.element.find(".select-row:checked");
if (checked.length === 0) {
return;
}
let confirmationModal = $("#confirmation-modal");
let deleted = [];
confirmationModal
.modal("show")
.find("form")
.on("submit", (e) => {
e.preventDefault();
confirmationModal.modal("hide");
let table = this.element.DataTable();
table.processing(true);
let ids = this.constructor.getRowIds(checked);
// Don't make ajax request if an id was previously deleted.
if (
deleted.length !== 0 &&
_.difference(deleted, ids).length === 0
) {
return;
}
$.ajax({
type: "DELETE",
url: this.route("destroy", { ids: ids.join() }),
success: () => {
deleted = _.flatten(deleted.concat(ids));
this.constructor.setSelectedIds(this.selector, []);
this.constructor.reload(this.element);
},
error: (xhr) => {
error(xhr.responseJSON.message);
deleted = _.flatten(deleted.concat(ids));
this.constructor.setSelectedIds(this.selector, []);
this.constructor.reload(this.element);
},
});
});
}
makeRowClickable(row, id) {
let key = this.hasRoute("show") ? "show" : "edit";
let url = this.route(key, { id });
$(row).addClass("clickable-row").data("href", url);
setTimeout(() => {
$(".clickable-row td:not(:first-child)").css("cursor", "pointer");
});
}
onRowClick(handler) {
let row = "tbody tr.clickable-row td";
if (this.element.find(".select-all").length !== 0) {
row += ":not(:first-child)";
}
this.element.on("click", row, handler);
}
redirectToRowPage(e) {
window.open(
$(e.currentTarget).parent().data("href"),
e.ctrlKey ? "_blank" : "_self"
);
}
selectAllRowsEventListener() {
this.element.find(".select-all").on("change", (e) => {
this.element
.find(".select-row")
.prop("checked", e.currentTarget.checked);
});
}
selectRowEventListener() {
this.element.find(".select-row").on("change", (e) => {
if (e.currentTarget.checked) {
this.appendToSelected(e.currentTarget.value);
} else {
this.removeFromSelected(e.currentTarget.value);
}
});
}
appendToSelected(id) {
id = parseInt(id);
if (!FleetCart.dataTable.selected[this.selector].includes(id)) {
FleetCart.dataTable.selected[this.selector].push(id);
}
}
removeFromSelected(id) {
id = parseInt(id);
FleetCart.dataTable.selected[this.selector].remove(id);
}
checkSelectedCheckboxes(selectedIds) {
let rows = this.element.find(".select-row");
let checkableRows = rows.toArray().filter((row) => {
return selectedIds.includes(parseInt(row.value));
});
$(checkableRows).prop("checked", true);
}
route(name, params) {
let router = FleetCart.dataTable.routes[this.selector][name];
if (typeof router === "string") {
router = { name: router, params };
}
router.params = _.merge(params, router.params);
return window.route(router.name, router.params);
}
hasRoute(name) {
return FleetCart.dataTable.routes[this.selector][name] !== undefined;
}
static setRoutes(selector, routes) {
FleetCart.dataTable.routes[selector] = routes;
}
static setSelectedIds(selector, selected) {
FleetCart.dataTable.selected[selector] = selected;
}
static getSelectedIds(selector) {
return FleetCart.dataTable.selected[selector];
}
static reload(selector, callback, resetPaging = false) {
$(selector).DataTable().ajax.reload(callback, resetPaging);
}
static getRowIds(rows) {
return rows.toArray().reduce((ids, row) => {
return ids.concat(row.value);
}, []);
}
static removeLengthFields() {
$(".dataTables_length select").remove();
}
addErrorHandler() {
$.fn.dataTable.ext.errMode = (settings, helpPage, message) => {
this.element.html(message);
};
}
// https://datatables.net/plug-ins/api/processing()
registerTableProcessingPlugin() {
$.fn.dataTable.Api.register("processing()", function (show) {
return this.iterator("table", function (ctx) {
ctx.oApi._fnProcessingDisplay(ctx, show);
});
});
}
}

View File

@@ -0,0 +1,20 @@
export default class {
appendHiddenInput(form, name, value) {
$('<input>').attr({
type: 'hidden',
name: name ,
value: value,
}).appendTo(form);
}
appendHiddenInputs(form, name, values) {
for (let value of values) {
this.appendHiddenInput(form, name + '[]', value);
}
}
removeErrors() {
$('.has-error > .help-block').remove();
$('.has-error').removeClass('has-error');
}
}

View File

@@ -0,0 +1,215 @@
$.FleetCart = {};
/* ----------------------------------
- FleetCart Options -
---------------------------------- */
$.FleetCart.options = {
animationSpeed: 300,
// Sidebar push menu toggle button selector
sidebarToggleSelector: '[data-toggle=\'offcanvas\']',
// Activate sidebar push menu
sidebarPushMenu: true,
// BoxRefresh Plugin
enableBoxRefresh: true,
// Bootstrap.js tooltip
enableBSToppltip: true,
BSTooltipSelector: '[data-toggle=\'tooltip\']',
// Control Sidebar Tree views
enableControlTreeView: true,
// The standard screen sizes that bootstrap uses.
screenSizes: {
xs: 480,
sm: 768,
md: 992,
lg: 1200,
},
};
/* ----------------------------------
- Implementation -
---------------------------------- */
$(function () {
// Easy access to options
var o = $.FleetCart.options;
// Set up the object
_init();
// Activate layout
$.FleetCart.layout.activate();
// Enable sidebar tree view controls
if (o.enableControlTreeView) {
$.FleetCart.tree('.sidebar');
}
// Activate sidebar push menu
if (o.sidebarPushMenu) {
$.FleetCart.pushMenu.activate(o.sidebarToggleSelector);
}
// Activate Bootstrap tooltip
if (o.enableBSToppltip) {
$('body').tooltip({
selector: o.BSTooltipSelector,
container: 'body',
});
}
});
/* ----------------------------------
- Initialize the FleetCart Object -
---------------------------------- */
function _init() {
// Layout
$.FleetCart.layout = {
activate: function () {
var _this = this;
_this.fix();
$(window, '.wrapper').resize(function () {
_this.fix();
});
},
fix: function () {
var window_height = $(window).height();
$('.wrapper').css('min-height', window_height + 'px');
}
};
// PushMenu
$.FleetCart.pushMenu = {
activate: function (toggleBtn) {
var screenSizes = $.FleetCart.options.screenSizes;
$(document).on('click', toggleBtn, function (e) {
e.preventDefault();
if ($(window).outerWidth() > (screenSizes.md - 1)) {
if ($('body').hasClass('sidebar-collapse')) {
$('body').removeClass('sidebar-collapse').trigger('expanded.pushMenu');
return;
}
$('body').addClass('sidebar-collapse').trigger('collapsed.pushMenu');
return;
}
if ($('body').hasClass('sidebar-open')) {
$('body').removeClass('sidebar-open').removeClass('sidebar-collapse').trigger('collapsed.pushMenu');
return;
}
$('body').addClass('sidebar-open').trigger('expanded.pushMenu');
});
$(window).on('resize', function () {
if ($(window).outerWidth() > (screenSizes.md - 1)) {
return;
} else {
$('body').removeClass('sidebar-collapse');
}
});
$('.content-wrapper').click(function () {
if ($(window).width() <= (screenSizes.md - 1) && $('body').hasClass('sidebar-open')) {
$('body').removeClass('sidebar-open');
}
});
}
};
// Tree
$.FleetCart.tree = function (menu) {
var animationSpeed = $.FleetCart.options.animationSpeed;
$(document).off('click', menu + ' li a')
.on('click', menu + ' li a', function (e) {
var self = $(this);
var checkElement = self.next();
var activeElement = self.closest('.sidebar-menu').find('.active');
if (checkElement.is('.treeview-menu')) {
self.closest('.sidebar-menu').find('.selected').removeClass('selected');
e.preventDefault();
}
if (self.parent().is('.active')) {
activeElement.toggleClass('closed');
} else {
activeElement.addClass('closed');
}
if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible')) && (!$('body').hasClass('sidebar-collapse'))) {
self.parent().removeClass('selected');
checkElement.slideUp(animationSpeed);
}
else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {
var ul = self.parents('ul').first().find('ul:visible').slideUp(animationSpeed);
self.parent().addClass('selected');
checkElement.slideDown(animationSpeed);
}
});
};
}
/* ----------------------------------
- Box Refresh Button -
---------------------------------- */
(function ($) {
$.fn.boxRefresh = function (options) {
var settings = $.extend({
trigger: '.refresh-btn',
source: '',
onLoadStart: function (box) {
return box;
},
onLoadDone: function (box) {
return box;
},
}, options);
var overlay = $('<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>');
return this.each(function () {
if (settings.source === '') {
if (window.console) {
window.console.log('Please specify a source first - boxRefresh()');
}
return;
}
var box = $(this);
var rBtn = box.find(settings.trigger).first();
rBtn.on('click', function (e) {
e.preventDefault();
start(box);
box.find('.box-body').load(settings.source, function () {
done(box);
});
});
});
function start(box) {
box.append(overlay);
settings.onLoadStart.call(box);
}
function done(box) {
box.find(overlay).remove();
settings.onLoadDone.call(box);
}
};
})(jQuery);

View File

@@ -0,0 +1,64 @@
import Chart from 'chart.js';
$(function () {
$.ajax({
type: 'GET',
url: route('admin.sales_analytics.index'),
success(response) {
let data = { labels: response.labels, sales: [], formatted: [], totalOrders: [] };
for (let item of response.data) {
data.sales.push(item.total.amount);
data.formatted.push(item.total.formatted);
data.totalOrders.push(item.total_orders);
}
initSalesAnalyticsChart(data);
},
});
});
function initSalesAnalyticsChart(data) {
new Chart($('.sales-analytics .chart'), {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
data: data.sales,
backgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(75, 192, 192, 0.5)',
'rgba(153, 102, 255, 0.5)',
'rgba(255, 159, 64, 0.5)',
],
}],
},
barThickness: 1,
options: {
maintainAspectRatio: false,
legend: {
display: false,
},
tooltips: {
displayColors: false,
callbacks: {
label(item) {
let orders = `${trans('admin::dashboard.sales_analytics.orders')}: ${data.totalOrders[item.index]}`;
let sales = `${trans('admin::dashboard.sales_analytics.sales')}: ${data.formatted[item.index]}`;
return [orders, sales];
},
},
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
},
});
}

View File

@@ -0,0 +1,77 @@
import { ohSnap } from './ohsnap';
export function trans(langKey, replace = {}) {
let line = window.FleetCart.langs[langKey];
for (let key in replace) {
line = line.replace(`:${key}`, replace[key]);
}
return line;
}
export function keypressAction(actions) {
$(document).keypressAction({ actions });
}
export function notify(type, message, { duration = 5000, context = document }) {
let types = {
'info': 'blue',
'success': 'green',
'warning': 'yellow',
'error': 'red',
};
ohSnap(message, {
'container-id': 'notification-toast',
context,
color: types[type],
duration,
});
}
export function info(message, duration) {
notify('info', message, { duration });
}
export function success(message, duration) {
notify('success', message, { duration });
}
export function warning(message, duration) {
notify('warning', message, { duration });
}
export function error(message, duration) {
notify('error', message, { duration });
}
/**
* @see https://stackoverflow.com/a/3955096
*/
if (! Array.prototype.remove) {
Array.prototype.remove = function () {
let what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
}
/**
* @see https://stackoverflow.com/a/4673436
*/
if (! String.prototype.format) {
String.prototype.format = function () {
return this.replace(/%(\d+)%/g, (match, number) => {
return typeof arguments[number] !== 'undefined' ? arguments[number] : match;
});
};
}

View File

@@ -0,0 +1,38 @@
(function ($, window, document, undefined) {
let pluginName = 'keypressAction', defaults = {};
// The actual plugin constructor
function keypressAction(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(keypressAction.prototype, {
bindKeyToRoute(key, route) {
Mousetrap.bind([key], (e) => {
window.location = route;
return false;
});
},
init() {
$.each(this.settings.actions, (index, object) => {
this.bindKeyToRoute(object.key, object.route);
});
},
});
$.fn[pluginName] = function (options) {
this.each(function () {
if (! $.data(this, `plugin_${pluginName}`)) {
$.data(this, `plugin_${pluginName}`, new keypressAction(this, options));
}
});
// chain jQuery functions
return this;
};
})(jQuery, window, document);

View File

@@ -0,0 +1,43 @@
window._ = require('lodash');
window.Sortable = require('sortablejs');
window.$ = window.jQuery = require('jquery');
require('bootstrap');
require('selectize');
require('flatpickr');
require('jquery-slimscroll');
require('mousetrap');
require('datatables.net');
require('datatables.net-bs');
require('./app');
require('./wysiwyg');
require('./jquery.keypressAction');
import Admin from './Admin';
import Form from './Form';
import DataTable from './DataTable';
import { trans, keypressAction, notify, info, success, warning, error } from './functions';
window.admin = new Admin();
window.form = new Form();
window.DataTable = DataTable;
window.trans = trans;
window.keypressAction = keypressAction;
window.notify = notify;
window.info = info;
window.success = success;
window.warning = warning;
window.error = error;
$.ajaxSetup({
headers: {
'Authorization': FleetCart.apiToken,
'X-CSRF-TOKEN': FleetCart.csrfToken,
},
});
$(document).on('preInit.dt', () => {
$('.dataTables_length select').addClass('custom-select-black');
});

View File

@@ -0,0 +1,85 @@
/**
* == OhSnap!.js ==
* A simple jQuery/Zepto notification library designed to be used in mobile apps
*
* author: Justin Domingue
* date: september 18, 2015
* version: 1.0.0
* copyright - nice copyright over here
*/
/* Shows a toast on the page
* Params:
* text: text to show
* options: object that can override the following options
* color: alert will have class 'ohsnap-alert-color'. Default null
* icon: class of the icon to show before the alert. Default null
* duration: duration of the notification in ms. Default 5000ms
* container-id: id of the alert container. Default 'ohsnap'
* fade-duration: duration of the fade in/out of the alerts. Default 'fast'
*/
export function ohSnap(text, options) {
let defaultOptions = {
'color' : null, // color is CSS class `ohsnap-alert-color`
'icon' : null, // class of the icon to show before the alert text
'duration' : 5000, // duration of the notification in ms
'container-id': 'ohsnap', // id of the alert container
'context': document,
'fade-duration': 'fast', // duration of the fade in/out of the alerts. fast, slow or integer in ms
};
options = (typeof options === 'object') ? $.extend(defaultOptions, options) : defaultOptions;
let container = $('#' + options['container-id'], options.context),
icon_markup = '',
color_markup = '';
if (options.icon) {
icon_markup = '<span class=\'' + options.icon + '\'></span> ';
}
if (options.color) {
color_markup = 'ohsnap-alert-' + options.color;
}
// Generate the HTML
let html = $('<div class="ohsnap-alert ' + color_markup + '">' + icon_markup + text + '</div>').fadeIn(options['fade-duration']);
// Append the label to the container
container.append(html);
// Remove the notification on click
html.on('click', function () {
ohSnapX($(this));
});
// After 'duration' seconds, the animation fades out
setTimeout(function () {
ohSnapX(html);
}, options.duration);
}
/* Removes a toast from the page
* params:
* Called without arguments, the function removes all alerts
* element: a jQuery object to remove
* options:
* duration: duration of the alert fade out - 'fast', 'slow' or time in ms. Default 'fast'
*/
export function ohSnapX(element, options) {
let defaultOptions = {
'duration': 'fast',
};
options = (typeof options === 'object') ? $.extend(defaultOptions, options) : defaultOptions;
if (typeof element !== 'undefined') {
element.fadeOut(options.duration, function () {
$(this).remove();
});
} else {
$('.ohsnap-alert').fadeOut(options.duration, function () {
$(this).remove();
});
}
}

View File

@@ -0,0 +1,38 @@
import tinyMCE from 'tinymce';
tinyMCE.baseURL = `${FleetCart.baseUrl}/modules/admin/js/wysiwyg`;
tinyMCE.init({
selector: '.wysiwyg',
theme: 'silver',
mobile: { theme: 'mobile' },
height: 350,
menubar: false,
branding: false,
image_advtab: true,
automatic_uploads: true,
media_alt_source: false,
media_poster: false,
relative_urls: false,
directionality: FleetCart.rtl ? 'rtl' : 'ltr',
cache_suffix: `?v=${FleetCart.version}`,
plugins: 'lists, link, table, image, media, paste, autosave, autolink, wordcount, code, fullscreen',
toolbar: 'styleselect bold italic underline | bullist numlist | alignleft aligncenter alignright | outdent indent | image media link table | code fullscreen',
images_upload_handler(blobInfo, success, failure) {
let formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
$.ajax({
method: 'POST',
url: route('admin.media.store'),
data: formData,
processData: false,
contentType: false,
}).then((file) => {
success(file.path);
}).catch((xhr) => {
failure(xhr.responseJSON.message);
});
},
});