| Server IP : 85.158.181.41 / Your IP : 216.73.217.12 Web Server : Apache System : Linux cloud9-vm129 6.1.178+1-ph #ph SMP PREEMPT_DYNAMIC Wed Jul 29 09:00:54 UTC 2026 x86_64 User : moncbefd ( 1024) PHP Version : 7.3.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : OFF | Pkexec : OFF Directory : /home/moncbefd/www.moneta.at/admin/javascript/engine/controllers/invoices/overview/ |
Upload File : |
/* --------------------------------------------------------------
events.js 2019-02-26
Gambio GmbH
http://www.gambio.de
Copyright (c) 2018 Gambio GmbH
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
*/
/**
* Main Table Events
*
* Handles the events of the main invoices table.
*/
gx.controllers.module('events', ['loading_spinner'], function (data) {
'use strict';
// ------------------------------------------------------------------------
// VARIABLES
// ------------------------------------------------------------------------
/**
* Module Selector
*
* @type {jQuery}
*/
const $this = $(this);
/**
* Module Instance
*
* @type {Object}
*/
const module = {};
/**
* Loading spinner instance.
*
* @type {jQuery|null}
*/
let $spinner = null;
// ------------------------------------------------------------------------
// FUNCTIONS
// ------------------------------------------------------------------------
/**
* On Bulk Selection Change
*
* @param {jQuery.Event} event jQuery event object.
* @param {Boolean} propagate Whether to affect the body elements. We do not need this on "draw.dt" event.
*/
function _onBulkSelectionChange(event, propagate = true) {
if (propagate === false) {
return; // Do not propagate on draw event because the body checkboxes are unchecked by default.
}
$this.find('tbody input:checkbox').single_checkbox('checked', $(this).prop('checked')).trigger('change');
}
/**
* On Table Row Click
*
* When a row is clicked then the row-checkbox must be toggled.
*
* @param {jQuery.Event} event
*/
function _onTableRowClick(event) {
if (!$(event.target).is('td')) {
return;
}
$(this).find('input:checkbox')
.prop('checked', !$(this).find('input:checkbox').prop('checked'))
.trigger('change');
}
/**
* On Table Row Checkbox Change
*
* Adjust the bulk actions state whenever there are changes in the table checkboxes.
*/
function _onTableRowCheckboxChange() {
if ($this.find('input:checkbox:checked').length > 0) {
$this.parents('.invoices').find('.bulk-action > button').removeClass('disabled');
} else {
$this.parents('.invoices').find('.bulk-action > button').addClass('disabled');
}
}
/**
* Collects the required data of the selected invoices in an array.
*
* @param {jQuery} $target Target element which triggered the data collection.
*
* @return {*[]} Returns an array of the requested invoice data.
*/
function _getSelectedInvoicesData($target, dataKey) {
const selectedInvoices = [];
if ($target.parents('.bulk-action').length > 0) {
// Fetch the selected order IDs.
$this.find('tbody input:checkbox:checked').each((index, checkbox) =>
selectedInvoices.push($(checkbox).parents('tr').data(dataKey)));
} else {
const rowId = $target.parents('tr').data(dataKey);
if (!rowId) {
return; // No invoice ID was found.
}
selectedInvoices.push(rowId);
}
return selectedInvoices;
}
/**
* On Change Order Status Click
*
* Display the change order status modal.
*
* @param {jQuery.Event} event
*/
function _onChangeOrderStatusClick(event) {
if ($(event.target).hasClass('order-status')) {
event.stopPropagation();
}
const $modal = $('.status.modal');
const rowData = $(this).parents('tr').data();
const selectedOrders = _getSelectedInvoicesData($(this), 'orderId').filter(orderId => orderId !== 0);
if (!selectedOrders.length) {
const title = jse.core.lang.translate('HEADING_GM_STATUS', 'orders');
const message = jse.core.lang.translate('NO_RECORDS_ERROR', 'orders');
jse.libs.modal.showMessage(title, message);
return;
}
$modal.find('#status-dropdown').val((rowData) ? rowData.statusId : '');
$modal.find('#comment').val('');
$modal.find('#notify-customer, #send-parcel-tracking-code, #send-comment')
.attr('checked', false)
.parents('.single-checkbox')
.removeClass('checked');
// Show the order change status modal (remove duplicate entries from selectedOrders).
$modal.find('.selected-orders').text(Array.from(new Set(selectedOrders)).join(', '));
$modal.modal('show');
}
/**
* Opens the URL which provide the bulk PDF's as download.
*
* @param {Number[]} invoiceIds The invoices to be concatenated.
*/
function _openBulkPdfUrl(invoiceIds) {
const parameters = {
do: 'InvoicesModalsAjax/BulkPdfInvoices',
pageToken: jse.core.config.get('pageToken'),
i: invoiceIds
};
const url = jse.core.config.get('appUrl') + '/admin/admin.php?' + $.param(parameters);
window.open(url, '_parent');
jse.libs.loading_spinner.hide($spinner);
}
/**
* Creates a bulk PDF with invoices.
*
* @param {Number[]} invoiceIds The invoices to be concatenated.
*/
function _createBulkPdf(invoiceIds) {
const zIndex = $('.table-fixed-header thead.fixed').css('z-index'); // Could be "undefined" as well.
$spinner = jse.libs.loading_spinner.show($this, zIndex);
_openBulkPdfUrl(invoiceIds);
}
/**
* Opens the gm_pdf_order.php in a new tab with invoices as type $_GET argument.
*
* The order ids are passed as a serialized array to the oID $_GET argument.
*/
function _onBulkDownloadInvoiceClick() {
const invoiceIds = _getSelectedInvoicesData($(this), 'invoiceId');
if (invoiceIds.length > data.maxAmountInvoicesBulkPdf) {
const $modal = $('.bulk-error.modal');
$modal.modal('show');
const $invoiceMessageContainer = $modal.find('.invoices-message');
$invoiceMessageContainer.removeClass('hidden');
$modal.on('hide.bs.modal', () => $invoiceMessageContainer.addClass('hidden'));
return;
}
_createBulkPdf(invoiceIds);
}
/**
* On Single Checkbox Ready
*
* This callback will use the event.data.invoiceIds to set the checked checkboxes after a table re-render.
*
* @param {jQuery.Event} event
*/
function _onSingleCheckboxReady(event) {
event.data.invoiceIds.forEach(id => {
$this.find(`tr#${id} input:checkbox`).single_checkbox('checked', true).trigger('change');
});
// Bulk action button should't be disabled after a datatable reload.
if ($('tr input:checkbox:checked').length) {
$('.bulk-action').find('button').removeClass('disabled')
}
}
/**
* Cancellation Invoice Generation
*
* This method will create a new cancellation invoice for the selected invoices.
*/
function _onCancellationInvoiceClick() {
const invoices = [];
const {invoiceId, invoiceNumber, orderId, isCancellationInvoice} = $(this).parents('tr').data();
if (isCancellationInvoice || orderId === 0) {
return;
}
invoices.push({
invoiceId,
invoiceNumber,
orderId
});
const title = jse.core.lang.translate('HEADING_MODAL_CANCELLATION_INVOICE', 'orders');
const message = jse.core.lang.translate('TEXT_MODAL_CANCELLATION_INVOICE', 'orders')
.replace('%s', invoices.map(invoice => invoice.invoiceNumber).join(', '));
const buttons = [
{
title: jse.core.lang.translate('no', 'lightbox_buttons'),
callback: event => $(event.currentTarget).parents('.modal').modal('hide')
},
{
title: jse.core.lang.translate('yes', 'lightbox_buttons'),
callback() {
const invoice = invoices.pop();
const url = `gm_pdf_order.php?oID=${invoice.orderId}&type=invoice`
+ `&cancel_invoice_id=${invoice.invoiceId}`;
window.open(url, '_blank');
const invoiceIds = invoices.map(invoice => invoice.invoiceId);
$this.DataTable().ajax.reload(() => {
$this
.off('single_checkbox:ready', _onSingleCheckboxReady)
.on('single_checkbox:ready', {invoiceIds}, _onSingleCheckboxReady);
});
$(this).parents('.modal').modal('hide');
}
}
];
jse.libs.modal.showMessage(title, message, buttons);
}
/**
* Bulk Cancellation Invoice Generation
*
* This method will create cancellation invoices for the selected invoices.
*/
function _onBulkCancellationInvoiceClick() {
const invoices = [];
$this.find('tbody input:checkbox:checked').each(function () {
const {invoiceId, invoiceNumber, orderId, isCancellationInvoice} = $(this).parents('tr').data();
if (!isCancellationInvoice && orderId > 0) {
invoices.push({
invoiceId,
invoiceNumber,
orderId
});
}
});
if (!invoices.length) {
const title = jse.core.lang.translate('HEADING_MODAL_CANCELLATION_INVOICE', 'orders');
const message = jse.core.lang.translate('NO_RECORDS_ERROR', 'orders');
jse.libs.modal.showMessage(title, message);
return;
}
const title = jse.core.lang.translate('HEADING_MODAL_CANCELLATION_INVOICE', 'orders');
const message = jse.core.lang.translate('TEXT_MODAL_CANCELLATION_INVOICE', 'orders')
.replace('%s', invoices.map(invoice => invoice.invoiceNumber).join(', '));
const buttons = [
{
title: jse.core.lang.translate('no', 'lightbox_buttons'),
callback: event => $(event.currentTarget).parents('.modal').modal('hide')
},
{
title: jse.core.lang.translate('yes', 'lightbox_buttons'),
callback() {
// Create new cancellation invoices and refresh the table.
const requests = [];
invoices.forEach(invoice => {
const url = `gm_pdf_order.php?oID=${invoice.orderId}&type=invoice`
+ `&cancel_invoice_id=${invoice.invoiceId}&ajax=1`;
requests.push($.get(url));
});
$.when(...requests).done((...responses) => {
const cancellationInvoiceIds = [];
if (requests.length === 1) {
responses = [responses]; // Always treat the responses as an array.
}
responses.forEach(response => {
const {invoiceId} = JSON.parse(response[0]);
cancellationInvoiceIds.push(invoiceId);
});
_createBulkPdf(cancellationInvoiceIds);
const invoiceIds = invoices.map(invoice => invoice.invoiceId);
$this.DataTable().ajax.reload(() => {
$this
.off('single_checkbox:ready', _onSingleCheckboxReady)
.on('single_checkbox:ready', {invoiceIds}, _onSingleCheckboxReady);
});
$(this).parents('.modal').modal('hide');
});
}
}
];
jse.libs.modal.showMessage(title, message, buttons);
}
/**
* On Email Invoice Click
*
* Display the email-invoice modal.
*/
function _onEmailInvoiceClick() {
const $modal = $('.email-invoice.modal');
const rowData = $(this).parents('tr').data();
const url = jse.core.config.get('appUrl') + '/admin/admin.php';
const data = {
do: 'InvoicesModalsAjax/GetEmailInvoiceInformation',
pageToken: jse.core.config.get('pageToken'),
o: [rowData.orderId]
};
$modal
.data('invoiceId', rowData.invoiceId)
.data('orderId', rowData.orderId)
.modal('show');
$.ajax({url, data, dataType: 'json'}).done(response => {
const dateFormat = jse.core.config.get('languageCode') === 'de' ? 'DD.MM.YY' : 'MM.DD.YY';
const subject = response.subject
.replace('{INVOICE_ID}', rowData.invoiceNumber)
.replace('{DATE}', moment(rowData.invoiceDate.date).format(dateFormat))
.replace('{ORDER_ID}', rowData.orderId);
$modal.find('.subject').val(subject);
let customerInfo = `"${rowData.customerName}"`;
if (response.emails[rowData.orderId]) {
customerInfo += ` "${response.emails[rowData.orderId]}"`;
}
$modal.find('.customer-info').text(customerInfo);
$modal.find('.email-address').val(response.emails[rowData.orderId] || '');
});
}
/**
* Generate email row markup.
*
* This method is used by the bulk email modal for dynamic email-row generation.
*
* @param {Object} invoice Contains the required row data.
* @param {Object} emailInformation Contains the subject and email addresses for the invoices.
*
* @return {jQuery} Returns the row selector.
*/
function _generateMailRowMarkup(invoice, emailInformation) {
const $row = $('<div/>', {class: 'form-group email-list-item'});
const $idColumn = $('<div/>', {class: 'col-sm-3'});
const $dateColumn = $('<div/>', {class: 'col-sm-3'});
const $emailColumn = $('<div/>', {class: 'col-sm-6'});
const $idLabel = $('<label/>', {
class: 'control-label id-label force-text-color-black force-text-normal-weight',
html: `<a href="request_port.php?module=OrderAdmin&action=showPdf&type=invoice`
+ `&invoice_number=${invoice.invoiceNumber}&order_id=${invoice.orderId}" target="_blank">`
+ `${invoice.invoiceNumber}</a>`
});
const dateFormat = jse.core.config.get('languageCode') === 'de' ? 'DD.MM.YYYY' : 'MM.DD.YYYY';
const $dateLabel = $('<label/>', {
class: 'control-label date-label force-text-color-black force-text-normal-weight',
text: moment(invoice.invoiceDate.date).format(dateFormat)
});
const $emailInput = $('<input/>', {
class: 'form-control email-input',
type: 'text',
value: emailInformation.emails[invoice.orderId]
});
$idLabel.appendTo($idColumn);
$dateLabel.appendTo($dateColumn);
$emailInput.appendTo($emailColumn);
$row.append([$idColumn, $dateColumn, $emailColumn]);
$row.data('invoice', invoice);
return $row;
}
/**
* Bulk Email Invoice Click.
*
* Sends emails with the selected invoices.
*
* @param {jQuery.Event} event
*/
function _onBulkEmailInvoiceClick(event) {
event.preventDefault();
const $modal = $('.bulk-email-invoice.modal');
const $mailList = $modal.find('.email-list');
const selectedInvoices = [];
$this.find('tbody input:checkbox:checked').each((index, checkbox) => {
const rowData = $(checkbox).parents('tr').data();
selectedInvoices.push(rowData);
});
// Sort selected invoices by date (descending).
selectedInvoices.sort((invoice1, invoice2) => invoice1.invoiceDate - invoice2.invoiceDate).reverse();
if (selectedInvoices.length) {
$mailList.empty();
const url = jse.core.config.get('appUrl') + '/admin/admin.php';
const data = {
do: 'InvoicesModalsAjax/GetEmailInvoiceInformation',
pageToken: jse.core.config.get('pageToken'),
o: [...new Set(selectedInvoices.map(invoice => invoice.orderId))] // Unique orders number array.
};
$.ajax({
url,
data,
dataType: 'json'
})
.done(response => {
selectedInvoices.forEach(invoice => $mailList.append(_generateMailRowMarkup(invoice, response)))
});
$modal.modal('show');
}
}
// ------------------------------------------------------------------------
// INITIALIZATION
// ------------------------------------------------------------------------
module.init = function (done) {
// Bind table row actions.
$this
.on('click', 'tbody tr', _onTableRowClick)
.on('change', '.bulk-selection', _onBulkSelectionChange)
.on('change', 'input:checkbox', _onTableRowCheckboxChange)
.on('click', '.email-invoice', _onEmailInvoiceClick)
.on('click', '.cancellation-invoice', _onCancellationInvoiceClick);
// Bind table row and bulk actions.
$this.parents('.invoices')
.on('click', '.order-status, .btn-group .change-status', _onChangeOrderStatusClick)
.on('click', '.btn-group .bulk-download-invoice', _onBulkDownloadInvoiceClick)
.on('click', '.btn-group .bulk-cancellation-invoice', _onBulkCancellationInvoiceClick)
.on('click', '.btn-group .bulk-email-invoice', _onBulkEmailInvoiceClick);
done();
};
return module;
});