/** * Admin JavaScript for Studiou WC Product Category Manager */ (function($) { 'use strict'; // Initialize admin scripts $(document).ready(function() { // Debug: Log that script is loaded console.log('STUDIOU WC: Admin script loaded'); console.log('STUDIOU WC: studiouWcpcm object:', studiouWcpcm); // Import form handling if ($('#studiou-wcpcm-import-form').length) { console.log('STUDIOU WC: Import form found'); initImportForm(); } // Export form handling if ($('#studiou-wcpcm-export-form').length) { console.log('STUDIOU WC: Export form found'); initExportForm(); } // Move products form handling if ($('#studiou-wcpcm-move-form').length) { console.log('STUDIOU WC: Move form found'); initMoveForm(); } else { console.log('STUDIOU WC: Move form NOT found'); } // Batch description form handling if ($('#studiou-wcpcm-batch-description-form').length) { console.log('STUDIOU WC: Batch description form found'); initBatchDescriptionForm(); } // Delete products form handling if ($('#studiou-wcpcm-delete-products-form').length) { console.log('STUDIOU WC: Delete products form found'); initDeleteProductsForm(); } // Clear media categories form handling if ($('#studiou-wcpcm-clear-media-form').length) { console.log('STUDIOU WC: Clear media form found'); initClearMediaForm(); } // Sample CSV download handler if ($('#studiou-wcpcm-download-sample').length) { initSampleDownload(); } // Product import form handling if ($('#studiou-wcpcm-product-import-form').length) { console.log('STUDIOU WC: Product import form found'); initProductImportForm(); } // Product export form handling if ($('#studiou-wcpcm-product-export-form').length) { console.log('STUDIOU WC: Product export form found'); initProductExportForm(); } }); /** * Initialize import form */ function initImportForm() { $('#studiou-wcpcm-import-form').on('submit', function(e) { e.preventDefault(); // Show spinner var $submitBtn = $(this).find('#studiou-wcpcm-import-button'); var $spinner = $(this).find('.spinner'); $submitBtn.prop('disabled', true); $spinner.css('visibility', 'visible'); // Clear previous notices $('.studiou-wcpcm-notice-area').empty(); // Create form data var formData = new FormData(this); formData.append('action', 'studiou_wcpcm_import'); formData.append('nonce', studiouWcpcm.nonce); // Send AJAX request $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: formData, processData: false, contentType: false, success: function(response) { if (response.success) { showNotice('success', studiouWcpcm.i18n.importSuccess); // Show results $('#studiou-wcpcm-import-results').text(response.data.message); $('.studiou-wcpcm-import-results').show(); } else { showNotice('error', response.data.message); } }, error: function() { showNotice('error', studiouWcpcm.i18n.importError); }, complete: function() { // Hide spinner $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Initialize export form */ function initExportForm() { $('#studiou-wcpcm-export-form').on('submit', function(e) { e.preventDefault(); // Show spinner var $submitBtn = $(this).find('#studiou-wcpcm-export-button'); var $spinner = $(this).find('.spinner'); $submitBtn.prop('disabled', true); $spinner.css('visibility', 'visible'); // Clear previous notices $('.studiou-wcpcm-notice-area').empty(); // Send AJAX request $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: { action: 'studiou_wcpcm_export', nonce: studiouWcpcm.nonce }, success: function(response) { if (response.success) { showNotice('success', studiouWcpcm.i18n.exportSuccess); // Show download link $('#studiou-wcpcm-export-message').text(response.data.message); $('#studiou-wcpcm-download-export').attr('href', response.data.download_url); $('.studiou-wcpcm-export-results').show(); } else { showNotice('error', response.data.message); } }, error: function() { showNotice('error', studiouWcpcm.i18n.exportError); }, complete: function() { // Hide spinner $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Initialize move products form */ function initMoveForm() { console.log('STUDIOU WC: Initializing move form handlers'); // Add debug button click handler first $('#studiou-wcpcm-move-button').on('click', function(e) { console.log('STUDIOU WC: Move button clicked directly'); }); $('#studiou-wcpcm-move-form').on('submit', function(e) { e.preventDefault(); // Debug: Log form submission console.log('STUDIOU WC: Move form submitted'); // Validate that different categories are selected var sourceCategory = $('#source_category').val(); var targetCategory = $('#target_category').val(); console.log('STUDIOU WC: Source category:', sourceCategory, 'Target category:', targetCategory); if (!sourceCategory || !targetCategory) { console.log('STUDIOU WC: Missing category selection'); showNotice('error', 'Please select both source and target categories'); return; } if (sourceCategory === targetCategory) { console.log('STUDIOU WC: Same category selected'); showNotice('error', studiouWcpcm.i18n.selectDifferentCategories); return; } // Show spinner var $submitBtn = $(this).find('#studiou-wcpcm-move-button'); var $spinner = $(this).find('.spinner'); $submitBtn.prop('disabled', true); $spinner.css('visibility', 'visible'); // Clear previous notices $('.studiou-wcpcm-notice-area').empty(); // Debug: Log AJAX request details console.log('STUDIOU WC: Sending AJAX request to:', studiouWcpcm.ajaxUrl); console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce); // Send AJAX request $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: { action: 'studiou_wcpcm_move_products', source_category: sourceCategory, target_category: targetCategory, nonce: studiouWcpcm.nonce }, success: function(response) { console.log('STUDIOU WC: AJAX response:', response); if (response.success) { showNotice('success', studiouWcpcm.i18n.moveSuccess); // Show results $('#studiou-wcpcm-move-message').html('
' + response.data.message + '
'); $('.studiou-wcpcm-move-results').show(); // Refresh the page to update category counts setTimeout(function() { location.reload(); }, 3000); } else { showNotice('error', response.data.message); } }, error: function(xhr, status, error) { console.error('STUDIOU WC: AJAX error:', status, error); console.error('STUDIOU WC: Response text:', xhr.responseText); showNotice('error', studiouWcpcm.i18n.moveError + ': ' + error); }, complete: function() { // Hide spinner $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Initialize batch description form */ function initBatchDescriptionForm() { console.log('STUDIOU WC: Initializing batch description form handlers'); // Check all button handler $('#studiou-wcpcm-check-all').on('click', function(e) { e.preventDefault(); console.log('STUDIOU WC: Check all button clicked'); $('#categories_list input[type="checkbox"]').prop('checked', true); }); // Uncheck all button handler $('#studiou-wcpcm-uncheck-all').on('click', function(e) { e.preventDefault(); console.log('STUDIOU WC: Uncheck all button clicked'); $('#categories_list input[type="checkbox"]').prop('checked', false); }); // Form submit handler $('#studiou-wcpcm-batch-description-form').on('submit', function(e) { e.preventDefault(); console.log('STUDIOU WC: Batch description form submitted'); // Get selected categories var selectedCategories = []; $('#categories_list input[type="checkbox"]:checked').each(function() { selectedCategories.push($(this).val()); }); var description = $('#category_description').val(); console.log('STUDIOU WC: Selected categories:', selectedCategories); console.log('STUDIOU WC: Description:', description); // Validate input if (selectedCategories.length === 0) { console.log('STUDIOU WC: No categories selected'); showNotice('error', 'Please select at least one category'); return; } // Show spinner var $submitBtn = $(this).find('#studiou-wcpcm-batch-description-button'); var $spinner = $(this).find('.spinner'); $submitBtn.prop('disabled', true); $spinner.css('visibility', 'visible'); // Clear previous notices $('.studiou-wcpcm-notice-area').empty(); // Debug: Log AJAX request details console.log('STUDIOU WC: Sending batch description AJAX request to:', studiouWcpcm.ajaxUrl); console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce); // Send AJAX request $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: { action: 'studiou_wcpcm_batch_description', selected_categories: selectedCategories, description: description, nonce: studiouWcpcm.nonce }, success: function(response) { console.log('STUDIOU WC: Batch description AJAX response:', response); if (response.success) { showNotice('success', studiouWcpcm.i18n.batchDescriptionSuccess || 'Batch description operation successful'); // Show results $('#studiou-wcpcm-batch-description-message').html('' + response.data.message + '
'); $('.studiou-wcpcm-batch-description-results').show(); } else { showNotice('error', response.data.message); } }, error: function(xhr, status, error) { console.error('STUDIOU WC: Batch description AJAX error:', status, error); console.error('STUDIOU WC: Response text:', xhr.responseText); showNotice('error', (studiouWcpcm.i18n.batchDescriptionError || 'Batch description operation error') + ': ' + error); }, complete: function() { // Hide spinner $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Initialize sample CSV download */ function initSampleDownload() { $('#studiou-wcpcm-download-sample').on('click', function(e) { e.preventDefault(); // Sample CSV content var csvContent = 'name,url-name,parent-name,description,display-type,visibility,protected-passwords,operation\n' + '"Clothing","clothing","","Top quality clothing","default","public","","A"\n' + '"Men","men","Clothing","Men\'s clothing","products","public","","A"\n' + '"Women","women","Clothing","Women\'s clothing","products","protected","password123","A"\n' + '"Kids","kids","Clothing","Kids clothing","products","public","","U"\n' + '"Accessories","accessories","","All accessories","default","public","","D"'; // Create download link var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); var url = URL.createObjectURL(blob); var link = document.createElement('a'); link.setAttribute('href', url); link.setAttribute('download', 'sample-product-categories.csv'); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } /** * Initialize delete products form */ function initDeleteProductsForm() { console.log('STUDIOU WC: Initializing delete products form handlers'); console.log('STUDIOU WC: Form element:', $('#studiou-wcpcm-delete-products-form')); console.log('STUDIOU WC: Check all button:', $('#studiou-wcpcm-delete-check-all')); console.log('STUDIOU WC: Delete button:', $('#studiou-wcpcm-delete-products-button')); // Check all button handler $('#studiou-wcpcm-delete-check-all').on('click', function(e) { e.preventDefault(); console.log('STUDIOU WC: Delete check all button clicked'); $('#delete_categories_list input[type="checkbox"]').prop('checked', true); }); // Uncheck all button handler $('#studiou-wcpcm-delete-uncheck-all').on('click', function(e) { e.preventDefault(); console.log('STUDIOU WC: Delete uncheck all button clicked'); $('#delete_categories_list input[type="checkbox"]').prop('checked', false); }); // Form submit handler $('#studiou-wcpcm-delete-products-form').on('submit', function(e) { e.preventDefault(); console.log('STUDIOU WC: Delete products form submitted'); // Get selected categories var selectedCategories = []; $('#delete_categories_list input[type="checkbox"]:checked').each(function() { selectedCategories.push($(this).val()); }); console.log('STUDIOU WC: Selected categories:', selectedCategories); // Validate input if (selectedCategories.length === 0) { console.log('STUDIOU WC: No categories selected'); showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category'); return; } // Confirm deletion if (!confirm(studiouWcpcm.i18n.confirmDelete || 'Are you sure you want to permanently delete ALL products in the selected categories? This action cannot be undone!')) { console.log('STUDIOU WC: User cancelled deletion'); return; } // Show spinner var $submitBtn = $(this).find('#studiou-wcpcm-delete-products-button'); var $spinner = $(this).find('.spinner'); $submitBtn.prop('disabled', true); $spinner.css('visibility', 'visible'); // Clear previous notices $('.studiou-wcpcm-notice-area').empty(); // Hide results, show progress $('.studiou-wcpcm-delete-results').hide(); $('.studiou-wcpcm-delete-progress').show(); $('#studiou-wcpcm-delete-progress-text').text('Initializing...'); updateProgressBar(0); // Debug: Log AJAX request details console.log('STUDIOU WC: Sending delete products AJAX request to:', studiouWcpcm.ajaxUrl); console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce); // Send AJAX request to get product IDs $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: { action: 'studiou_wcpcm_delete_products', delete_categories: selectedCategories, nonce: studiouWcpcm.nonce }, success: function(response) { console.log('STUDIOU WC: Delete products AJAX response:', response); if (response.success) { var productIds = response.data.product_ids; var totalCount = response.data.total_count; console.log('STUDIOU WC: Total products to delete:', totalCount); if (totalCount === 0) { showNotice('success', studiouWcpcm.i18n.noProductsFound || 'No products found in selected categories'); $('.studiou-wcpcm-delete-progress').hide(); $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); return; } // Process products in batches processDeletionBatches(productIds, totalCount, $submitBtn, $spinner); } else { showNotice('error', response.data.message); $('.studiou-wcpcm-delete-progress').hide(); $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }, error: function(xhr, status, error) { console.error('STUDIOU WC: Delete products AJAX error:', status, error); console.error('STUDIOU WC: Response text:', xhr.responseText); showNotice('error', (studiouWcpcm.i18n.deleteError || 'Delete products operation error') + ': ' + error); $('.studiou-wcpcm-delete-progress').hide(); $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Process deletion in batches */ function processDeletionBatches(productIds, totalCount, $submitBtn, $spinner) { var batchSize = 10; // Process 10 products at a time var batches = []; var totalDeleted = 0; var totalFailed = 0; var failedProducts = []; // Split products into batches for (var i = 0; i < productIds.length; i += batchSize) { batches.push(productIds.slice(i, i + batchSize)); } console.log('STUDIOU WC: Processing ' + batches.length + ' batches of products'); var currentBatch = 0; function processBatch() { if (currentBatch >= batches.length) { // All batches completed console.log('STUDIOU WC: All batches completed'); onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner); return; } var batch = batches[currentBatch]; var progress = Math.round((currentBatch / batches.length) * 100); $('#studiou-wcpcm-delete-progress-text').text( 'Deleting products... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed' ); updateProgressBar(progress); // Send batch delete request $.ajax({ url: studiouWcpcm.ajaxUrl, type: 'POST', data: { action: 'studiou_wcpcm_delete_products_batch', product_ids: batch, nonce: studiouWcpcm.nonce }, success: function(response) { if (response.success) { totalDeleted += response.data.deleted_count; totalFailed += response.data.failed_count; failedProducts = failedProducts.concat(response.data.failed_products); console.log('STUDIOU WC: Batch ' + currentBatch + ' completed - Deleted: ' + response.data.deleted_count + ', Failed: ' + response.data.failed_count); // Process next batch currentBatch++; processBatch(); } else { showNotice('error', response.data.message); $('.studiou-wcpcm-delete-progress').hide(); $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }, error: function(xhr, status, error) { console.error('STUDIOU WC: Batch delete AJAX error:', status, error); showNotice('error', 'Error deleting batch: ' + error); $('.studiou-wcpcm-delete-progress').hide(); $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); } // Start processing batches processBatch(); } /** * Handle deletion completion */ function onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner) { // Update progress bar to 100% updateProgressBar(100); $('#studiou-wcpcm-delete-progress-text').text('Deletion complete!'); // Show results var message = 'Deletion Summary:
'; message += 'Deletion Summary:
'; message += 'Import Summary:
'; message += '' + importMessages.join('\n') + '';
$('#studiou-wcpcm-product-import-details-content').html(details);
}
$('.studiou-wcpcm-product-import-results').show();
// Show save failed button if there are failed items
if (importFailed > 0 && importFailedCsv) {
window.studiouWcpcmFailedCsv = importFailedCsv;
$('.studiou-wcpcm-product-import-failed').show();
}
// Hide progress after delay
setTimeout(function() {
$('.studiou-wcpcm-product-import-progress').fadeOut();
}, 2000);
$submitBtn.prop('disabled', false);
$spinner.css('visibility', 'hidden');
} else {
// Process next batch
processBatch(importProcessed, $submitBtn, $spinner);
}
} else {
showNotice('error', response.data.message || 'Batch processing failed');
$('.studiou-wcpcm-product-import-progress').hide();
$submitBtn.prop('disabled', false);
$spinner.css('visibility', 'hidden');
}
},
error: function(xhr, status, error) {
console.error('STUDIOU WC: Batch processing error:', status, error);
showNotice('error', 'Batch processing error: ' + error);
$('.studiou-wcpcm-product-import-progress').hide();
$submitBtn.prop('disabled', false);
$spinner.css('visibility', 'hidden');
}
});
}
// Save failed products button handler
$('#studiou-wcpcm-save-failed-products').on('click', function(e) {
e.preventDefault();
if (window.studiouWcpcmFailedCsv) {
var blob = new Blob([window.studiouWcpcmFailedCsv], { type: 'text/csv;charset=utf-8;' });
var url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'failed-products-' + Date.now() + '.csv');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
/**
* Initialize product export form
*/
function initProductExportForm() {
console.log('STUDIOU WC: Initializing product export form handlers');
// Select all button handler
$('#studiou-wcpcm-export-select-all').on('click', function(e) {
e.preventDefault();
console.log('STUDIOU WC: Export select all button clicked');
$('#export_categories_list input[type="checkbox"]').prop('checked', true);
});
// Deselect all button handler
$('#studiou-wcpcm-export-deselect-all').on('click', function(e) {
e.preventDefault();
console.log('STUDIOU WC: Export deselect all button clicked');
$('#export_categories_list input[type="checkbox"]').prop('checked', false);
});
// Form submit handler
$('#studiou-wcpcm-product-export-form').on('submit', function(e) {
e.preventDefault();
console.log('STUDIOU WC: Product export form submitted');
// Get selected categories
var selectedCategories = [];
$('#export_categories_list input[type="checkbox"]:checked').each(function() {
selectedCategories.push($(this).val());
});
console.log('STUDIOU WC: Selected categories:', selectedCategories);
// Validate input
if (selectedCategories.length === 0) {
console.log('STUDIOU WC: No categories selected');
showNotice('error', 'Please select at least one category');
return;
}
// Show spinner
var $submitBtn = $(this).find('#studiou-wcpcm-product-export-button');
var $spinner = $(this).find('.spinner');
$submitBtn.prop('disabled', true);
$spinner.css('visibility', 'visible');
// Clear previous notices
$('.studiou-wcpcm-notice-area').empty();
$('.studiou-wcpcm-product-export-results').hide();
// Debug: Log AJAX request details
console.log('STUDIOU WC: Sending product export AJAX request to:', studiouWcpcm.ajaxUrl);
console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
// Send AJAX request
$.ajax({
url: studiouWcpcm.ajaxUrl,
type: 'POST',
data: {
action: 'studiou_wcpcm_product_export',
export_categories: selectedCategories,
nonce: studiouWcpcm.nonce
},
success: function(response) {
console.log('STUDIOU WC: Product export AJAX response:', response);
if (response.success) {
showNotice('success', 'Export successful!');
// Show results
$('#studiou-wcpcm-product-export-message').html('' + response.data.message + '
'); $('#studiou-wcpcm-download-product-export').attr('href', response.data.download_url); $('.studiou-wcpcm-product-export-results').show(); } else { showNotice('error', response.data.message || 'Export failed'); } }, error: function(xhr, status, error) { console.error('STUDIOU WC: Product export AJAX error:', status, error); console.error('STUDIOU WC: Response text:', xhr.responseText); showNotice('error', 'Product export error: ' + error); }, complete: function() { // Hide spinner $submitBtn.prop('disabled', false); $spinner.css('visibility', 'hidden'); } }); }); } /** * Update product import progress bar */ function updateProductImportProgressBar(percentage) { $('#studiou-wcpcm-product-import-progress-bar').css('width', percentage + '%'); $('#studiou-wcpcm-product-import-progress-bar').attr('data-progress', Math.round(percentage) + '%'); } // Additional debug: Check if elements exist after DOM load $(window).on('load', function() { console.log('STUDIOU WC: Window loaded'); console.log('STUDIOU WC: Move form exists:', $('#studiou-wcpcm-move-form').length > 0); console.log('STUDIOU WC: Move button exists:', $('#studiou-wcpcm-move-button').length > 0); console.log('STUDIOU WC: Source select exists:', $('#source_category').length > 0); console.log('STUDIOU WC: Target select exists:', $('#target_category').length > 0); console.log('STUDIOU WC: Batch description form exists:', $('#studiou-wcpcm-batch-description-form').length > 0); console.log('STUDIOU WC: Batch description button exists:', $('#studiou-wcpcm-batch-description-button').length > 0); console.log('STUDIOU WC: Delete products form exists:', $('#studiou-wcpcm-delete-products-form').length > 0); console.log('STUDIOU WC: Product import form exists:', $('#studiou-wcpcm-product-import-form').length > 0); console.log('STUDIOU WC: Product export form exists:', $('#studiou-wcpcm-product-export-form').length > 0); console.log('STUDIOU WC: Clear media form exists:', $('#studiou-wcpcm-clear-media-form').length > 0); }); })(jQuery);