Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- jQuery(document).ready(function ($) {
- //Date sort plugin
- $.fn.dataTable.moment('x');
- // Main function to run when table exists on the page
- if ($('#idemailwiz_campaign_table').length) {
- idemailwiz_do_ajax('idwiz_get_campaign_table_view', idAjax_data_tables.nonce, {}, campaign_table_success_response, campaign_table_error_response);
- }
- let table;
- // Success and Error Callbacks
- function campaign_table_success_response(data) {
- // Initialize DataTables with the parsed data
- table = $('#idemailwiz_campaign_table').DataTable({
- data: data,
- order: [[3, 'asc'], [2, 'desc']],
- autoWidth: false,
- fixedColumns: { left: 2 },
- columns: wizcampaigns_columns,
- buttons: wizcampaigns_buttons,
- language: wizcampaign_language,
- dom: '<"#wiztable_top_wrapper"><"wiztable_toolbar" <"#wiztable_top_search" f><"#wiztable_top_dates"> B>t',
- fixedHeader: { header: true, footer: false },
- colReorder: { realtime: false },
- scroller: true,
- scrollX: true,
- scrollY: '700px',
- paging: true,
- scrollResize: true,
- scrollCollapse: true,
- processing: true,
- select: { selector: "td:not(:first-child)" },
- stateRestore: {
- create: true,
- remove: true,
- rename: true,
- save: true
- },
- drawCallback: idwiz_dt_draw_callback,
- initComplete: idwiz_dt_init_callback,
- });
- // Event listeners to enable/disable "Actions" button
- setupRowSelectionEvents(table);
- // Handle state save and restore
- setupStateHandling(table);
- }
- function campaign_table_error_response(errorThrown) {
- console.log(errorThrown);
- }
- // Handle state save and restore
- function setupStateHandling(table) {
- table.on('stateSaveParams', function(e, settings, data) {
- // Save the current values of the date pickers
- data.startDate = $('#wiztable_startDate').val();
- data.endDate = $('#wiztable_endDate').val();
- });
- table.on('stateLoadParams', function(e, settings, data) {
- // Delay the restoration of the date picker values
- setTimeout(function() {
- $('#wiztable_startDate').val(data.startDate);
- $('#wiztable_endDate').val(data.endDate);
- }, 500);
- });
- }
- // Event listeners to enable/disable "Actions" button
- function setupRowSelectionEvents(table) {
- table.on('select', function (e, dt, type, indexes) {
- if (type === 'row') {
- table.button('Actions:name').enable();
- }
- });
- table.on('deselect', function (e, dt, type, indexes) {
- if (type === 'row') {
- if (!table.rows({ selected: true }).any()) {
- table.button('Actions:name').disable();
- }
- }
- });
- }
- // Main Init callback function
- function idwiz_dt_init_callback(settings, json) {
- appendDateSelector();
- addDateFilter();
- addDateChangeListener();
- addCampaignNavigation();
- }
- // Main draw callback function
- function idwiz_dt_draw_callback(settings, json) {
- var api = this.api();
- // Hide the loader and title
- $('#idemailwiz_tableLoader').hide();
- $('#saved_state_title').text('');
- // Move some buttons
- moveButtons();
- // Create the counter column
- updateCounterColumn(api);
- // Readjust the column widths
- api.columns.adjust();
- // Get current record count and calculate totals and rates
- var metrics = calculateMetrics(api);
- // Update the HTML element with the calculated total and rates
- updateMetricsHTML(metrics);
- }
- // Sync Button
- $(document).on('click', '.sync-db', function() {
- handle_idwiz_sync_buttons("idemailwiz_ajax_sync", idAjax_data_tables.nonce);
- });
- let lastCallTime = 0;
- const debounceTime = 500; // 500 milliseconds
- // Custom function to handle Ajax for state saving and loading
- function idwiz_handle_states(data, callback) {
- const currentTime = Date.now();
- if (currentTime - lastCallTime < debounceTime) {
- console.log("Function call debounced");
- return;
- }
- lastCallTime = currentTime;
- console.log("idwiz_handle_states called with data:", data);
- // Include the action type in the data to be sent to the server
- var ajaxData = {
- dataTableAction: data.action, // This is the DataTables action like "load" or "save"
- stateRestore: data.stateRestore
- };
- idemailwiz_do_ajax(
- 'idwiz_handle_dt_states',
- idAjax_data_tables.nonce,
- ajaxData,
- function(response) {
- console.log(response);
- if (data.action == 'load' && response.success) {
- callback(response.data); // Pass the state data back to DataTables
- } else {
- console.log('State action successful:', response);
- table.draw();
- }
- },
- function(error) {
- console.log('Error:', error);
- console.log('Status:', error.status);
- console.log('Status Text:', error.statusText);
- console.log('Response Text:', error.responseText);
- }
- );
- }
- // Append date range into DataTables DOM
- function appendDateSelector() {
- var dateSelector = '<div id="idemailwiz_date_range"><label><input type="date" id="wiztable_startDate"></label> thru <label><input type="date" id="wiztable_endDate"></label></div>';
- $('#wiztable_top_dates').append(dateSelector);
- }
- // Add date filter search logic
- function addDateFilter() {
- $.fn.dataTable.ext.search.push(
- function(settings, data, dataIndex, rowData) {
- var startDateInput = $('#wiztable_startDate').val();
- var endDateInput = $('#wiztable_endDate').val();
- // Check if the date filter is being used
- if (startDateInput || endDateInput) {
- // Exclude records with "N/A" date
- if (!rowData.campaign_start) return false;
- var campaignDate = new Date(parseInt(rowData.campaign_start)).toISOString().split('T')[0]; // UTC date string
- if (startDateInput && campaignDate < startDateInput) return false;
- if (endDateInput && campaignDate > endDateInput) return false;
- }
- return true;
- }
- );
- }
- // Refresh the table when the dates are changed
- function addDateChangeListener() {
- $('#wiztable_startDate, #wiztable_endDate').change(function() {
- $('.idemailwiz_table').DataTable().draw();
- });
- }
- // Add click event to navigate to single campaign page
- function addCampaignNavigation() {
- $('.idemailwiz_table').on('click', 'td.details-control', function() {
- var table = $('.idemailwiz_table').DataTable();
- var tr = $(this).closest('tr');
- var row = table.row(tr);
- // Access the campaign_id from the row's data
- var campaignId = row.data().campaign_id;
- // Construct the URL
- var url = "https://localhost/metrics/campaign/?id=" + campaignId;
- // Open the URL in a new tab
- window.open(url, '_blank');
- });
- }
- // Function to move buttons to their respective locations
- function moveButtons() {
- var advSearch = $('.btn-advanced-search').closest('.dt-button');
- advSearch.insertAfter('#wiztable_top_search');
- var FYbutton = $('.dt-button.fiscal-year')
- var prevMonthButton = $('.dt-button.prev-month');
- var thisMonthButton = $('.dt-button.current-month');
- var nextMonthButton = $('.dt-button.next-month');
- thisMonthButton.insertAfter('#wiztable_top_dates');
- prevMonthButton.insertBefore(thisMonthButton);
- nextMonthButton.insertAfter(thisMonthButton);
- FYbutton.insertAfter(nextMonthButton);
- }
- // Function to update the counter column
- function updateCounterColumn(api) {
- var info = api.page.info();
- var start = info.start;
- api.column(0, { page: 'current' }).nodes().each(function (cell, i) {
- cell.innerHTML = i + 1 + start;
- });
- }
- // Function to calculate metrics based on the DataTable API
- function calculateMetrics(api) {
- var metrics = [];
- // Define a function to calculate the sum of a column
- var sumColumn = function(columnName) {
- var data = api.column(columnName + ':name', {search:'applied'}).data();
- if (data.toArray) {
- data = data.toArray();
- }
- return data.reduce(function(a, b) {
- return a + Number(b) || 0;
- }, 0);
- };
- // Define a function to calculate the ratio
- var calculateRatio = function(numerator, denominator) {
- return denominator ? (numerator / denominator) * 100 : 0;
- };
- // Calculate the totals
- var totalSends = sumColumn('unique_email_sends');
- var totalDelivered = sumColumn('unique_delivered');
- var totalOpens = sumColumn('unique_email_opens');
- var totalClicks = sumColumn('unique_email_clicks');
- var totalUnsubs = sumColumn('unique_unsubscribes');
- var totalPurchases = sumColumn('unique_purchases');
- var totalRevenue = sumColumn('revenue');
- // Calculate the rates
- var openRate = calculateRatio(totalOpens, totalSends);
- var delivRate = calculateRatio(totalDelivered, totalSends);
- var clickRate = calculateRatio(totalClicks, totalSends);
- var unsubRate = calculateRatio(totalUnsubs, totalSends);
- var cto = calculateRatio(totalClicks, totalOpens);
- var cvr = calculateRatio(totalPurchases, totalOpens);
- // Push metrics into the array
- metrics.push({ label: 'Campaigns', value: api.rows({search:'applied'}).count().toLocaleString() });
- metrics.push({ label: 'Sends', value: totalSends.toLocaleString() });
- metrics.push({ label: 'Delivered', value: totalDelivered.toLocaleString() });
- metrics.push({ label: 'Deliv. Rate', value: delivRate.toFixed(2) + '%' });
- metrics.push({ label: 'Opens', value: totalOpens.toLocaleString() });
- metrics.push({ label: 'Open Rate', value: openRate.toFixed(2) + '%' });
- metrics.push({ label: 'Clicks', value: totalClicks.toLocaleString() });
- metrics.push({ label: 'CTR', value: clickRate.toFixed(2) + '%' });
- metrics.push({ label: 'CTO', value: cto.toFixed(2) + '%' });
- metrics.push({ label: 'Unsubs', value: totalUnsubs.toLocaleString() });
- metrics.push({ label: 'Unsub. Rate', value: unsubRate.toFixed(2) + '%' });
- metrics.push({ label: 'Purchases', value: totalPurchases.toLocaleString() });
- metrics.push({ label: 'Revenue', value: '$' + totalRevenue.toLocaleString() });
- metrics.push({ label: 'CVR', value: cvr.toFixed(2) + '%' });
- return metrics;
- }
- // Function to update metrics HTML
- function updateMetricsHTML(metrics) {
- var html = '<table class="wiztable_view_metrics_table"><tr>';
- metrics.forEach(function(metric) {
- html += `<td><span class="metric_view_label">${metric.label}</span><span class="metric_view_value"> ${metric.value}</span></td>`;
- });
- html += '</tr></table>';
- $('#wiztable_view_metrics').html(html);
- }
- var wizcampaigns_columns = [
- {
- "className": 'row-counter',
- "title": '#',
- "name": 'row-counter',
- "orderable": false,
- "data": null,
- "width": "20px",
- },
- {
- "className": 'details-control customColName',
- "title": '<i class="fa-solid fa-arrow-up-right-from-square"></i>',
- "name": 'details-control',
- "orderable": false,
- "data": null,
- "defaultContent": '<i class="fa-solid fa-circle-info"></i>',
- "colvisName": 'Details'
- },
- {
- "data": "campaign_start",
- "name": "campaign_start",
- "title": "Sent At",
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "date",
- "render": function(data) {
- return new Date(parseInt(data))
- .toLocaleString('en-US', {
- month: 'numeric',
- day: 'numeric',
- year: 'numeric',
- hour: 'numeric',
- minute: 'numeric',
- hour12: true
- });
- },
- "type": "date",
- },
- {
- "data": "campaign_type",
- "name": "campaign_type",
- "title": "Type",
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "message_medium",
- "name": "message_medium",
- "title": "Medium",
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "campaign_name",
- "name": "campaign_name",
- "title": "Campaign Name",
- "render": $.fn.dataTable.render.ellipsis(50, true),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "campaign_labels",
- "name": "campaign_labels",
- "title": "Labels",
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "experiment_ids",
- "name": "experiment_ids",
- "title": '<i class="fa fa-flask"></i>',
- "searchBuilderTitle": 'Has Experiment',
- "searchBuilderType": "string",
- "searchBuilder.defaultConditions": "==",
- "className": "idwiz_searchBuilder_enabled customColName",
- "type": "bool",
- "render": function(data, type) {
- if (type === 'display') {
- return data ? '<i class="fa fa-flask"></i>' : '';
- }
- if (type === 'filter') {
- return !data ? 'True' : 'False';
- }
- return data;
- },
- "searchBuilder": {
- "orthogonal": {
- "search": "filter",
- "display": "filter",
- }
- },
- "colvisName": 'Has Experiment'
- },
- {
- "data": "unique_email_sends",
- "name": "unique_email_sends",
- "title": "Sends",
- "type": "num",
- "render": $.fn.dataTable.render.number(',', ''),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "unique_delivered",
- "name": "unique_delivered",
- "title": "Delivered",
- "type": "num",
- "render": $.fn.dataTable.render.number(',', ''),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_delivery_rate",
- "name": "wiz_delivery_rate",
- "title": "Deliv. Rate",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "unique_email_opens",
- "name": "unique_email_opens",
- "title": "Opens",
- "render": $.fn.dataTable.render.number(',', ''),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_open_rate",
- "name": "wiz_open_rate",
- "title": "Open Rate",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "unique_email_clicks",
- "name": "unique_email_clicks",
- "title": "Clicks",
- "render": $.fn.dataTable.render.number(',', ''),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_ctr",
- "name": "wiz_ctr",
- "title": "CTR",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_cto",
- "name": "wiz_cto",
- "title": "CTO",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "unique_unsubscribes",
- "name": "unique_unsubscribes",
- "title": "Unsubs.",
- "render": function(data, type, row) {
- return $.fn.dataTable.render.number(',', '').display(data);
- },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_unsub_rate",
- "name": "wiz_unsub_rate",
- "title": "Unsub. Rate",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "unique_purchases",
- "name": "unique_purchases",
- "title": "Purchases",
- "render": function(data, type, row) {
- return $.fn.dataTable.render.number(',', '').display(data);
- },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "wiz_cvr",
- "name": "wiz_cvr",
- "title": "CVR",
- "render": function (data) { return parseFloat(data).toFixed(2) + '%'; },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "revenue",
- "name": "revenue",
- "title": "Revenue",
- "render": function (data) { return '$' + parseFloat(data).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); },
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num-fmt",
- },
- {
- "data": "template_subject",
- "name": "template_subject",
- "title": "Subject Line",
- "render": $.fn.dataTable.render.ellipsis(40, true),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "template_preheader",
- "name": "template_preheader",
- "title": "Pre Header",
- "render": $.fn.dataTable.render.ellipsis(40, true),
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "string",
- },
- {
- "data": "campaign_id",
- "name": "campaign_id",
- "title": "ID",
- "className": "idwiz_searchBuilder_enabled",
- "searchBuilderType": "num",
- "searchBuilder.defaultConditions": "==",
- },
- ];
- var wizcampaigns_buttons = [
- {
- extend: 'searchBuilder',
- background: false,
- text: '<i class="fa-solid fa-sliders"></i>',
- className: 'btn-advanced-search wiz-dt-button',
- attr: {
- 'title': 'Advanced search and filter',
- },
- config: {
- columns: '.idwiz_searchBuilder_enabled',
- },
- // Add a class to the popover for SearchBuilder so we can resize it with CSS
- action: function (e, dt, node, config) {
- this.popover(config._searchBuilder.getNode(), {
- collectionLayout: 'wiz_sbpopover'
- });
- // Need to redraw the contents to calculate the correct positions for the elements
- if (config._searchBuilder.s.topGroup !== undefined) {
- config._searchBuilder.s.topGroup.dom.container.trigger('dtsb-redrawContents');
- }
- if (config._searchBuilder.s.topGroup.s.criteria.length === 0) {
- $('.' + $.fn.dataTable.Group.classes.add).click();
- }
- },
- },
- {
- text: '<i class="fa-solid fa-angle-left"></i>',
- className: 'wiz-dt-button skinny prev-month',
- action: function ( e, dt, node, config ) {
- var table = $('.idemailwiz_table').DataTable();
- table.button('.next-month').enable(); // Enable the "Next" button
- var startDateStr = $('#wiztable_startDate').val();
- var startDate = startDateStr ? new Date(startDateStr) : new Date();
- startDate.setUTCHours(0, 0, 0, 0);
- var today = new Date();
- today.setUTCHours(0, 0, 0, 0);
- if (isNaN(startDate.getTime()) || !startDateStr) {
- startDate = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
- }
- startDate.setUTCMonth(startDate.getUTCMonth() - 1);
- var endDate = new Date(Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth() + 1, 0));
- $('#wiztable_startDate').val(startDate.toISOString().split('T')[0]);
- $('#wiztable_endDate').val(endDate.toISOString().split('T')[0]);
- $('#saved_state_title').text(`Custom View: ${startDate.toLocaleString('default', { month: 'long', timeZone: 'UTC' })}, ${startDate.getUTCFullYear()}`);
- table.draw();
- }
- },
- {
- text: function() {
- var today = new Date();
- var monthAbbr = today.toLocaleString('default', { month: 'short' }); // Get the three-letter abbreviation
- var yearTwoDigit = today.getFullYear() % 100; // Get the last two digits of the year
- return `<i class="fa-regular fa-calendar"></i> ${monthAbbr} '${yearTwoDigit}`;
- },
- action: function ( e, dt, node, config ) {
- var today = new Date();
- var firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
- var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
- $('#wiztable_startDate').val(firstDayOfMonth.toISOString().split('T')[0]);
- $('#wiztable_endDate').val(lastDayOfMonth.toISOString().split('T')[0]);
- $('#saved_state_title').text(`Custom View: ${today.toLocaleString('default', { month: 'long' })}, ${today.getFullYear()}`);
- $('.idemailwiz_table').DataTable().draw();
- },
- className: 'wiz-dt-button current-month',
- },
- {
- text: '<i class="fa-solid fa-angle-right"></i>',
- className: 'wiz-dt-button skinny next-month',
- action: function ( e, dt, node, config ) {
- var table = $('.idemailwiz_table').DataTable();
- var startDateStr = $('#wiztable_startDate').val();
- var startDate = startDateStr ? new Date(startDateStr) : new Date();
- startDate.setUTCHours(0, 0, 0, 0);
- var today = new Date();
- today.setUTCHours(0, 0, 0, 0);
- if (isNaN(startDate.getTime()) || !startDateStr) {
- startDate = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), 1));
- table.button('.next-month').disable(); // Disable the "Next" button when fields are empty or unorthodox
- return;
- }
- if (startDate.getUTCFullYear() < today.getUTCFullYear() || (startDate.getUTCFullYear() === today.getUTCFullYear() && startDate.getUTCMonth() < today.getUTCMonth())) {
- startDate.setUTCMonth(startDate.getUTCMonth() + 1);
- var endDate = new Date(Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth() + 1, 0));
- $('#wiztable_startDate').val(startDate.toISOString().split('T')[0]);
- $('#wiztable_endDate').val(endDate.toISOString().split('T')[0]);
- $('#saved_state_title').text(`Custom View: ${startDate.toLocaleString('default', { month: 'long', timeZone: 'UTC' })}, ${startDate.getUTCFullYear()}`);
- table.draw();
- }
- if (startDate.getUTCFullYear() === today.getUTCFullYear() && startDate.getUTCMonth() >= today.getUTCMonth()) {
- table.button('.next-month').disable(); // Disable the "Next" button
- } else {
- table.button('.next-month').enable(); // Enable the "Next" button
- }
- }
- },
- {
- text: function() {
- var today = new Date();
- var year = today.getFullYear();
- // Fiscal year starts on November 1st of the previous year
- if (today.getMonth() >= 10) { // January is 0, November is 10
- year += 1;
- }
- var yearTwoDigit = year % 100;
- return `<i class="fa-regular fa-calendar"></i> FY '${yearTwoDigit}`;
- },
- action: function ( e, dt, node, config ) {
- var today = new Date();
- var fiscalYearStart = new Date(today.getFullYear(), 10, 1); // Nov 1
- var fiscalYearEnd = new Date(today.getFullYear() + 1, 9, 31); // Oct 31
- if (today < fiscalYearStart) {
- fiscalYearStart.setFullYear(fiscalYearStart.getFullYear() - 1);
- fiscalYearEnd.setFullYear(fiscalYearEnd.getFullYear() - 1);
- }
- $('#wiztable_startDate').val(fiscalYearStart.toISOString().split('T')[0]);
- $('#wiztable_endDate').val(fiscalYearEnd.toISOString().split('T')[0]);
- $('#saved_state_title').text(`Custom View: ${fiscalYearStart.getFullYear()} Fiscal Year`);
- $('.idemailwiz_table').DataTable().draw();
- },
- className: 'wiz-dt-button fiscal-year',
- },
- {
- extend: 'selected',
- text: '<i class="fa-regular fa-plus"></i>',
- name: 'Actions',
- className: 'wiz-dt-button',
- attr: {
- 'title': 'Actions',
- },
- action: function(e, dt, node, config) {
- // Retrieve selected row indices
- let selectedRowIndices = dt.rows({ selected: true }).indexes().toArray();
- // Extract campaign IDs from selected rows
- let selectedCampaignIds = selectedRowIndices.map(index => {
- return dt.cell(index, 'campaign_id:name').data();
- });
- Swal.fire({
- title: 'Add to Initiative',
- html: '<select id="initiative-select"></select>',
- showCancelButton: true,
- cancelButtonText: 'Cancel',
- confirmButtonText: 'Add campaigns',
- preConfirm: () => {
- let selectedInitiative = $('#initiative-select').val();
- // Perform AJAX call to add campaigns to the selected initiative
- idemailwiz_do_ajax(
- 'idemailwiz_add_remove_campaign_from_initiative',
- idAjax_data_tables.nonce,
- {
- initiative_id: selectedInitiative,
- campaign_ids: selectedCampaignIds,
- campaignAction: 'add',
- },
- function(successData) {
- console.log(successData);
- alert('Campaigns have been added to initiative!');
- },
- function(errorData) {
- // Handle error
- console.error("Failed to add campaigns to initiative", errorData);
- }
- );
- },
- didOpen: () => {
- $('#initiative-select').select2({
- minimumInputLength: 0,
- placeholder: "Search initiatives...",
- allowClear: true,
- ajax: {
- delay: 250,
- transport: function(params, success, failure) {
- idemailwiz_do_ajax(
- 'idemailwiz_get_initiatives_for_select',
- idAjax_data_tables.nonce,
- {
- q: params.data.term,
- },
- function(data) {
- success({results: data});
- },
- function(error) {
- console.error("Failed to fetch initiatives", error);
- failure();
- }
- );
- }
- }
- });
- }
- });
- }
- },
- {
- text: '<i class="fa-solid fa-rotate"></i>',
- className: 'wiz-dt-button sync-db sync-everything',
- attr: {
- "data-sync-db": "everything",
- "title": "Sync Databases"
- },
- autoClose: true,
- background: false,
- },
- {
- extend: 'spacer',
- style: 'bar'
- },
- {
- extend: 'collection',
- text: '<i class="fa-solid fa-table-columns"></i>',
- className: 'wiz-dt-button',
- attr: {
- 'title': 'Show/hide columns',
- },
- align: 'button-right',
- buttons: [
- {
- extend: 'colvis',
- columnText: function ( dt, idx, title ) {
- if ( idx == dt.colReorder.transpose( 1 ) ) {
- return 'Info';
- }
- if ( idx == dt.colReorder.transpose( 7 ) ) {
- return 'Has Experiment';
- } else {
- return title;
- }
- }
- },
- {
- extend: 'colvisRestore',
- text: 'Restore Defaults',
- className: 'wizcols_restore',
- align: 'button-right',
- }
- ],
- background: false,
- },
- {
- extend: 'collection',
- text: '<i class="fa-regular fa-hand-pointer"></i>',
- className: 'wiz-dt-button',
- attr: {
- 'title': 'Selection mode',
- },
- align: 'button-right',
- autoClose: true,
- buttons: [
- 'selectNone',
- 'selectRows',
- 'selectColumns',
- 'selectCells',
- ],
- background: false,
- },
- {
- extend: 'spacer',
- style: 'bar'
- },
- {
- extend: 'collection',
- text: '<i class="fa-solid fa-floppy-disk"></i>',
- className: 'wiz-dt-button saved-views',
- attr: {
- 'title': 'View options',
- },
- align: 'button-right',
- background: false,
- buttons: [
- {
- extend: 'createState',
- text: 'Create View',
- attr: {
- 'title': 'Create View',
- },
- config: {
- creationModal: true,
- }
- },
- {
- extend: 'savedStates',
- text: 'Saved Views',
- className: 'saved-views',
- background: false,
- attr: {
- 'title': 'Saved Views',
- },
- config: {
- ajax: idwiz_handle_states
- }
- }
- ]
- },
- {
- extend: 'collection',
- text: '<i class="fa-solid fa-file-arrow-down"></i>',
- className: 'wiz-dt-button',
- attr: {
- 'title': 'Export current view',
- },
- align: 'button-right',
- autoClose: true,
- buttons: [
- 'copy',
- 'csv',
- 'excel' ],
- background: false,
- },
- ];
- var wizcampaign_language = {
- buttons: {
- createState: 'Create View',
- removeState: 'Delete View',
- renameState: 'Rename View',
- savedStates: 'Saved Views',
- },
- stateRestore: {
- creationModal:{
- title: 'Create new View',
- button: 'Create View'
- },
- emptyError: 'Please enter a valid name!',
- removeError: 'Error removing View.',
- removeTitle: 'Delete View'
- },
- searchBuilder: {
- data: 'Select column...',
- title: 'Advanced Campaign Filter',
- button: {
- 0: '<i class="fa-solid fa-sliders"></i> Filters',
- _: '<i class="fa-solid fa-sliders"></i> Filters (%d)'
- },
- },
- search: '',
- searchPlaceholder: 'Quick search',
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement