| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202 |
- /**
- * 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('<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 + '%');
- }
- /**
- * Initialize clear media categories form
- */
- function initClearMediaForm() {
- console.log('STUDIOU WC: Initializing clear media form handlers');
- // Check all button handler
- $('#studiou-wcpcm-clear-media-check-all').on('click', function(e) {
- e.preventDefault();
- console.log('STUDIOU WC: Clear media check all button clicked');
- $('#clear_media_categories_list input[type="checkbox"]').prop('checked', true);
- });
- // Uncheck all button handler
- $('#studiou-wcpcm-clear-media-uncheck-all').on('click', function(e) {
- e.preventDefault();
- console.log('STUDIOU WC: Clear media uncheck all button clicked');
- $('#clear_media_categories_list input[type="checkbox"]').prop('checked', false);
- });
- // Form submit handler
- $('#studiou-wcpcm-clear-media-form').on('submit', function(e) {
- e.preventDefault();
- console.log('STUDIOU WC: Clear media form submitted');
- // Get selected categories
- var selectedCategories = [];
- $('#clear_media_categories_list input[type="checkbox"]:checked').each(function() {
- selectedCategories.push($(this).val());
- });
- console.log('STUDIOU WC: Selected media categories:', selectedCategories);
- // Validate input
- if (selectedCategories.length === 0) {
- console.log('STUDIOU WC: No media categories selected');
- showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category');
- return;
- }
- // Confirm deletion
- if (!confirm(studiouWcpcm.i18n.confirmClearMedia || 'Are you sure you want to permanently delete ALL media files in the selected media categories? This action cannot be undone!')) {
- console.log('STUDIOU WC: User cancelled clear media');
- return;
- }
- // Show spinner
- var $submitBtn = $(this).find('#studiou-wcpcm-clear-media-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-clear-media-results').hide();
- $('.studiou-wcpcm-clear-media-progress').show();
- $('#studiou-wcpcm-clear-media-progress-text').text('Initializing...');
- updateClearMediaProgressBar(0);
- // Send AJAX request to get media IDs
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_clear_media',
- media_categories: selectedCategories,
- nonce: studiouWcpcm.nonce
- },
- success: function(response) {
- console.log('STUDIOU WC: Clear media AJAX response:', response);
- if (response.success) {
- var mediaIds = response.data.media_ids;
- var totalCount = response.data.total_count;
- console.log('STUDIOU WC: Total media files to delete:', totalCount);
- if (totalCount === 0) {
- showNotice('success', studiouWcpcm.i18n.noMediaFound || 'No media files found in selected categories');
- $('.studiou-wcpcm-clear-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- return;
- }
- // Process media in batches
- processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner);
- } else {
- showNotice('error', response.data.message);
- $('.studiou-wcpcm-clear-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC: Clear media AJAX error:', status, error);
- console.error('STUDIOU WC: Response text:', xhr.responseText);
- showNotice('error', (studiouWcpcm.i18n.clearMediaError || 'Clear media operation error') + ': ' + error);
- $('.studiou-wcpcm-clear-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- });
- });
- }
- /**
- * Process media deletion in batches
- */
- function processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner) {
- var batchSize = 10;
- var batches = [];
- var totalDeleted = 0;
- var totalFailed = 0;
- var failedMedia = [];
- // Split media into batches
- for (var i = 0; i < mediaIds.length; i += batchSize) {
- batches.push(mediaIds.slice(i, i + batchSize));
- }
- console.log('STUDIOU WC: Processing ' + batches.length + ' batches of media files');
- var currentBatch = 0;
- function processBatch() {
- if (currentBatch >= batches.length) {
- console.log('STUDIOU WC: All media batches completed');
- onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner);
- return;
- }
- var batch = batches[currentBatch];
- var progress = Math.round((currentBatch / batches.length) * 100);
- $('#studiou-wcpcm-clear-media-progress-text').text(
- 'Deleting media files... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
- );
- updateClearMediaProgressBar(progress);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_clear_media_batch',
- media_ids: batch,
- nonce: studiouWcpcm.nonce
- },
- success: function(response) {
- if (response.success) {
- totalDeleted += response.data.deleted_count;
- totalFailed += response.data.failed_count;
- failedMedia = failedMedia.concat(response.data.failed_media);
- console.log('STUDIOU WC: Media batch ' + currentBatch + ' completed - Deleted: ' +
- response.data.deleted_count + ', Failed: ' + response.data.failed_count);
- currentBatch++;
- processBatch();
- } else {
- showNotice('error', response.data.message);
- $('.studiou-wcpcm-clear-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC: Media batch delete AJAX error:', status, error);
- showNotice('error', 'Error deleting media batch: ' + error);
- $('.studiou-wcpcm-clear-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- });
- }
- processBatch();
- }
- /**
- * Handle media deletion completion
- */
- function onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner) {
- updateClearMediaProgressBar(100);
- $('#studiou-wcpcm-clear-media-progress-text').text('Deletion complete!');
- var message = '<p><strong>Deletion Summary:</strong></p>';
- message += '<ul>';
- message += '<li>Total media files deleted: ' + totalDeleted + '</li>';
- if (totalFailed > 0) {
- message += '<li>Failed to delete: ' + totalFailed + '</li>';
- if (failedMedia.length > 0) {
- message += '<li>Failed media IDs: ' + failedMedia.join(', ') + '</li>';
- }
- }
- message += '</ul>';
- $('#studiou-wcpcm-clear-media-message').html(message);
- $('.studiou-wcpcm-clear-media-results').show();
- setTimeout(function() {
- $('.studiou-wcpcm-clear-media-progress').fadeOut();
- }, 2000);
- if (totalDeleted > 0) {
- showNotice('success', (studiouWcpcm.i18n.clearMediaSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' media files');
- setTimeout(function() {
- location.reload();
- }, 3000);
- } else {
- showNotice('error', studiouWcpcm.i18n.clearMediaError || 'Failed to delete any media files');
- }
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- /**
- * Update clear media progress bar
- */
- function updateClearMediaProgressBar(percentage) {
- $('#studiou-wcpcm-clear-media-progress-bar').css('width', percentage + '%');
- $('#studiou-wcpcm-clear-media-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);
- console.log('STUDIOU WC: Clear media form exists:', $('#studiou-wcpcm-clear-media-form').length > 0);
- });
- })(jQuery);
|