| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964 |
- /**
- * 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();
- }
- // 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('<p>' + response.data.message + '</p>');
- $('.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('<p>' + response.data.message + '</p>');
- $('.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 = '<p><strong>Deletion Summary:</strong></p>';
- message += '<ul>';
- message += '<li>Total products deleted: ' + totalDeleted + '</li>';
- if (totalFailed > 0) {
- message += '<li>Failed to delete: ' + totalFailed + '</li>';
- if (failedProducts.length > 0) {
- message += '<li>Failed product IDs: ' + failedProducts.join(', ') + '</li>';
- }
- }
- message += '</ul>';
- $('#studiou-wcpcm-delete-message').html(message);
- $('.studiou-wcpcm-delete-results').show();
- // Hide progress after a delay
- setTimeout(function() {
- $('.studiou-wcpcm-delete-progress').fadeOut();
- }, 2000);
- if (totalDeleted > 0) {
- showNotice('success', (studiouWcpcm.i18n.deleteSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' products');
- // Reload page after 3 seconds
- setTimeout(function() {
- location.reload();
- }, 3000);
- } else {
- showNotice('error', studiouWcpcm.i18n.deleteError || 'Failed to delete any products');
- }
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- /**
- * Update progress bar
- */
- function updateProgressBar(percentage) {
- $('#studiou-wcpcm-delete-progress-bar').css('width', percentage + '%');
- $('#studiou-wcpcm-delete-progress-bar').attr('data-progress', percentage + '%');
- }
- /**
- * Show notice message
- *
- * @param {string} type Notice type (success, error)
- * @param {string} message Notice message
- */
- function showNotice(type, message) {
- var $notice = $('<div class="studiou-wcpcm-notice studiou-wcpcm-notice-' + type + '"></div>').text(message);
- $('.studiou-wcpcm-notice-area').append($notice);
- // Scroll to notice
- $('html, body').animate({
- scrollTop: $('.studiou-wcpcm-notice-area').offset().top - 50
- }, 500);
- }
- /**
- * Initialize product import form
- */
- function initProductImportForm() {
- console.log('STUDIOU WC: Initializing product import form handlers');
- // Global variables for batch processing
- var importTransientKey = null;
- var importTotal = 0;
- var importProcessed = 0;
- var importSuccess = 0;
- var importFailed = 0;
- var importSkipped = 0;
- var importMessages = [];
- var importFailedCsv = '';
- $('#studiou-wcpcm-product-import-form').on('submit', function(e) {
- e.preventDefault();
- console.log('STUDIOU WC: Product import form submitted');
- // Validate file is selected
- var fileInput = $('#import_file')[0];
- if (!fileInput.files || !fileInput.files[0]) {
- showNotice('error', 'Please select a CSV file to import');
- return;
- }
- // Show spinner and progress
- var $submitBtn = $(this).find('#studiou-wcpcm-product-import-button');
- var $spinner = $(this).find('.spinner');
- $submitBtn.prop('disabled', true);
- $spinner.css('visibility', 'visible');
- // Clear previous results
- $('.studiou-wcpcm-notice-area').empty();
- $('.studiou-wcpcm-product-import-results').hide();
- $('.studiou-wcpcm-product-import-failed').hide();
- // Reset counters
- importTransientKey = null;
- importTotal = 0;
- importProcessed = 0;
- importSuccess = 0;
- importFailed = 0;
- importSkipped = 0;
- importMessages = [];
- importFailedCsv = '';
- // Show progress bar
- $('.studiou-wcpcm-product-import-progress').show();
- $('#studiou-wcpcm-product-import-progress-text').text('Parsing CSV file...');
- updateProductImportProgressBar(0);
- // Step 1: Parse CSV file
- var formData = new FormData(this);
- formData.append('action', 'studiou_wcpcm_product_import_parse');
- formData.append('nonce', studiouWcpcm.nonce);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: formData,
- processData: false,
- contentType: false,
- success: function(response) {
- console.log('STUDIOU WC: Product import parse response:', response);
- if (response.success) {
- importTransientKey = response.data.transient_key;
- importTotal = response.data.total;
- // Start batch processing
- processBatch(0, $submitBtn, $spinner);
- } else {
- showNotice('error', response.data.message || 'Parse failed');
- $('.studiou-wcpcm-product-import-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC: Product import parse error:', status, error);
- console.error('STUDIOU WC: Response text:', xhr.responseText);
- showNotice('error', 'Product import error: ' + error);
- $('.studiou-wcpcm-product-import-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- });
- });
- // Process batch of products
- function processBatch(offset, $submitBtn, $spinner) {
- console.log('STUDIOU WC: Processing batch at offset', offset);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_product_import_batch',
- nonce: studiouWcpcm.nonce,
- transient_key: importTransientKey,
- offset: offset
- },
- success: function(response) {
- console.log('STUDIOU WC: Batch response:', response);
- if (response.success) {
- // Accumulate results
- importSuccess += response.data.success;
- importFailed += response.data.failed;
- importSkipped += response.data.skipped;
- importProcessed = response.data.processed;
- importTotal = response.data.total;
- importMessages = importMessages.concat(response.data.messages);
- if (response.data.failed_csv) {
- importFailedCsv = response.data.failed_csv;
- }
- // Update progress
- var percent = (importProcessed / importTotal) * 100;
- updateProductImportProgressBar(percent);
- $('#studiou-wcpcm-product-import-progress-text').text(
- 'Processing: ' + importProcessed + ' / ' + importTotal + ' products'
- );
- // Check if complete
- if (importProcessed >= importTotal) {
- // Import complete
- $('#studiou-wcpcm-product-import-progress-text').text('Complete!');
- showNotice('success', 'Product import completed!');
- // Show results
- var message = '<p><strong>Import Summary:</strong></p>';
- message += '<ul>';
- message += '<li>Successful: ' + importSuccess + '</li>';
- message += '<li>Failed: ' + importFailed + '</li>';
- message += '<li>Skipped: ' + importSkipped + '</li>';
- message += '</ul>';
- $('#studiou-wcpcm-product-import-message').html(message);
- // Show detailed messages
- if (importMessages.length > 0) {
- var details = '<pre>' + importMessages.join('\n') + '</pre>';
- $('#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('<p>' + response.data.message + '</p>');
- $('#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);
- });
- })(jQuery);
|