| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698 |
- /**
- * Admin JavaScript for Studiou WC Product Category Manager
- */
- (function($) {
- 'use strict';
-
- // Safe init wrapper - prevents one form's error from breaking others
- function safeInit(name, selector, initFn) {
- try {
- if ($(selector).length) {
- console.log('STUDIOU WC: ' + name + ' found, initializing');
- initFn();
- }
- } catch (e) {
- console.error('STUDIOU WC: Error initializing ' + name + ':', e);
- }
- }
- // Initialize admin scripts
- $(document).ready(function() {
- // Debug: Log that script is loaded
- console.log('STUDIOU WC: Admin script loaded v1.5.3');
- if (typeof studiouWcpcm === 'undefined') {
- console.error('STUDIOU WC: studiouWcpcm object is NOT defined - AJAX will not work');
- return;
- }
- console.log('STUDIOU WC: studiouWcpcm object:', studiouWcpcm);
- safeInit('Import form', '#studiou-wcpcm-import-form', initImportForm);
- safeInit('Export form', '#studiou-wcpcm-export-form', initExportForm);
- safeInit('Move form', '#studiou-wcpcm-move-form', initMoveForm);
- safeInit('Batch description form', '#studiou-wcpcm-batch-description-form', initBatchDescriptionForm);
- safeInit('Delete products form', '#studiou-wcpcm-delete-products-form', initDeleteProductsForm);
- safeInit('Clear media form', '#studiou-wcpcm-clear-media-form', initClearMediaForm);
- safeInit('Remove unassigned media form', '#studiou-wcpcm-remove-unassigned-media-form', initRemoveUnassignedMediaForm);
- safeInit('Sample download', '#studiou-wcpcm-download-sample', initSampleDownload);
- safeInit('Product import form', '#studiou-wcpcm-product-import-form', initProductImportForm);
- safeInit('Product export form', '#studiou-wcpcm-product-export-form', initProductExportForm);
- safeInit('Update variant prices form', '#studiou-wcpcm-upvp-form', initUpdateVariantPricesForm);
- });
-
- /**
- * 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 + '%');
- }
- /**
- * Initialize remove unassigned media form
- */
- function initRemoveUnassignedMediaForm() {
- console.log('STUDIOU WC: Initializing remove unassigned media form handlers');
- $('#studiou-wcpcm-remove-unassigned-media-form').on('submit', function(e) {
- e.preventDefault();
- console.log('STUDIOU WC: Remove unassigned media form submitted');
- if (!confirm(studiouWcpcm.i18n.confirmRemoveUnassigned || 'Are you sure you want to permanently delete ALL unused uncategorized media files? This action cannot be undone!')) {
- return;
- }
- var $submitBtn = $(this).find('#studiou-wcpcm-remove-unassigned-media-button');
- var $spinner = $(this).find('.spinner');
- $submitBtn.prop('disabled', true);
- $spinner.css('visibility', 'visible');
- $('.studiou-wcpcm-notice-area').empty();
- $('.studiou-wcpcm-remove-unassigned-media-results').hide();
- $('.studiou-wcpcm-remove-unassigned-media-progress').show();
- $('#studiou-wcpcm-remove-unassigned-media-progress-text').text('Initializing...');
- updateRemoveUnassignedProgressBar(0);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_remove_unassigned_media',
- nonce: studiouWcpcm.nonce
- },
- success: function(response) {
- console.log('STUDIOU WC: Remove unassigned media response:', response);
- if (response.success) {
- var mediaIds = response.data.media_ids;
- var totalCount = response.data.total_count;
- if (totalCount === 0) {
- showNotice('success', studiouWcpcm.i18n.noUnassignedMedia || 'No unused uncategorized media files found');
- $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- return;
- }
- processUnassignedMediaBatches(mediaIds, totalCount, $submitBtn, $spinner);
- } else {
- showNotice('error', response.data.message);
- $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC: Remove unassigned media error:', status, error);
- showNotice('error', (studiouWcpcm.i18n.removeUnassignedError || 'Error') + ': ' + error);
- $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- });
- });
- }
- /**
- * Process unassigned media deletion in batches
- */
- function processUnassignedMediaBatches(mediaIds, totalCount, $submitBtn, $spinner) {
- var batchSize = 10;
- var batches = [];
- var totalDeleted = 0;
- var totalFailed = 0;
- var failedMedia = [];
- for (var i = 0; i < mediaIds.length; i += batchSize) {
- batches.push(mediaIds.slice(i, i + batchSize));
- }
- var currentBatch = 0;
- function processBatch() {
- if (currentBatch >= batches.length) {
- onUnassignedMediaComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner);
- return;
- }
- var batch = batches[currentBatch];
- var progress = Math.round((currentBatch / batches.length) * 100);
- $('#studiou-wcpcm-remove-unassigned-media-progress-text').text(
- 'Deleting media files... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
- );
- updateRemoveUnassignedProgressBar(progress);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_remove_unassigned_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);
- currentBatch++;
- processBatch();
- } else {
- showNotice('error', response.data.message);
- $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC: Unassigned media batch error:', status, error);
- showNotice('error', 'Error deleting batch: ' + error);
- $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- });
- }
- processBatch();
- }
- /**
- * Handle unassigned media deletion completion
- */
- function onUnassignedMediaComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner) {
- updateRemoveUnassignedProgressBar(100);
- $('#studiou-wcpcm-remove-unassigned-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-remove-unassigned-media-message').html(message);
- $('.studiou-wcpcm-remove-unassigned-media-results').show();
- setTimeout(function() {
- $('.studiou-wcpcm-remove-unassigned-media-progress').fadeOut();
- }, 2000);
- if (totalDeleted > 0) {
- showNotice('success', (studiouWcpcm.i18n.removeUnassignedSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' media files');
- setTimeout(function() {
- location.reload();
- }, 3000);
- } else {
- showNotice('error', studiouWcpcm.i18n.removeUnassignedError || 'Failed to delete any media files');
- }
- $submitBtn.prop('disabled', false);
- $spinner.css('visibility', 'hidden');
- }
- /**
- * Update remove unassigned media progress bar
- */
- function updateRemoveUnassignedProgressBar(percentage) {
- $('#studiou-wcpcm-remove-unassigned-media-progress-bar').css('width', percentage + '%');
- $('#studiou-wcpcm-remove-unassigned-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);
- console.log('STUDIOU WC: UPVP form exists:', $('#studiou-wcpcm-upvp-form').length > 0);
- });
- /**
- * Initialize Update Product Variant Prices form (UPVP) — v1.5.3
- */
- function initUpdateVariantPricesForm() {
- var $form = $('#studiou-wcpcm-upvp-form');
- var $catList = $('#upvp_categories_list');
- var $attrSelect = $('#upvp_attribute');
- var $valueSelect = $('#upvp_attribute_value');
- var $newPrice = $('#upvp_new_price');
- var $countLabel = $('#studiou-wcpcm-upvp-affected-count');
- var $dryRunBtn = $('#studiou-wcpcm-upvp-dry-run-button');
- var $applyBtn = $('#studiou-wcpcm-upvp-apply-button');
- var $spinner = $form.find('.spinner');
- var $resultsBox = $('.studiou-wcpcm-upvp-results');
- var $resultsMsg = $('#studiou-wcpcm-upvp-message');
- var i18n = (studiouWcpcm && studiouWcpcm.i18n) ? studiouWcpcm.i18n : {};
- var countDebounceHandle = null;
- var countInFlight = false;
- function getSelectedCategoryIds() {
- var ids = [];
- $catList.find('input[type="checkbox"]:checked').each(function() {
- ids.push($(this).val());
- });
- return ids;
- }
- function setApplyEnabled(count) {
- var enabled = (count > 0) && !countInFlight;
- $dryRunBtn.prop('disabled', !enabled);
- $applyBtn.prop('disabled', !enabled);
- }
- function loadAttributes() {
- $attrSelect.prop('disabled', true).html(
- '<option value="">' + (i18n.upvpLoadingAttributes || 'Loading attributes...') + '</option>'
- );
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_upvp_get_attributes',
- nonce: studiouWcpcm.nonce
- },
- success: function(response) {
- $attrSelect.empty();
- $attrSelect.append('<option value="">' + (i18n.upvpSelectAttribute || '-- Select attribute --') + '</option>');
- if (response.success && response.data && response.data.attributes) {
- $.each(response.data.attributes, function(_, a) {
- $attrSelect.append(
- $('<option/>')
- .val(a.key)
- .attr('data-istax', a.is_taxonomy ? '1' : '0')
- .text(a.label)
- );
- });
- }
- $attrSelect.prop('disabled', false);
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC UPVP: get_attributes failed', status, error);
- $attrSelect.prop('disabled', false);
- }
- });
- }
- function loadValues() {
- var key = $attrSelect.val();
- $valueSelect.prop('disabled', true).empty();
- $valueSelect.append('<option value="">' + (i18n.upvpLoadingValues || 'Loading values...') + '</option>');
- if (!key) {
- $valueSelect.empty();
- $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
- $valueSelect.prop('disabled', true);
- refreshCount();
- return;
- }
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_upvp_get_attribute_values',
- nonce: studiouWcpcm.nonce,
- attribute_key: key,
- category_ids: getSelectedCategoryIds()
- },
- success: function(response) {
- $valueSelect.empty();
- $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
- if (response.success && response.data && response.data.values) {
- $.each(response.data.values, function(_, v) {
- $valueSelect.append($('<option/>').val(v.value).text(v.label));
- });
- }
- $valueSelect.prop('disabled', false);
- refreshCount();
- },
- error: function(xhr, status, error) {
- console.error('STUDIOU WC UPVP: get_attribute_values failed', status, error);
- $valueSelect.empty();
- $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
- $valueSelect.prop('disabled', false);
- }
- });
- }
- function refreshCount() {
- if (countDebounceHandle) {
- clearTimeout(countDebounceHandle);
- }
- countDebounceHandle = setTimeout(doRefreshCount, 300);
- }
- function doRefreshCount() {
- var cats = getSelectedCategoryIds();
- var key = $attrSelect.val();
- var val = $valueSelect.val();
- if (!cats.length || !key || !val) {
- $countLabel.text('0');
- setApplyEnabled(0);
- return;
- }
- countInFlight = true;
- setApplyEnabled(0);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_upvp_count',
- nonce: studiouWcpcm.nonce,
- category_ids: cats,
- attribute_key: key,
- attribute_value: val
- },
- success: function(response) {
- countInFlight = false;
- if (response.success && response.data) {
- var c = parseInt(response.data.count, 10) || 0;
- $countLabel.text(c);
- setApplyEnabled(c);
- } else {
- $countLabel.text('0');
- setApplyEnabled(0);
- }
- },
- error: function() {
- countInFlight = false;
- $countLabel.text('0');
- setApplyEnabled(0);
- }
- });
- }
- function renderSampleTable(sample, newPriceLabel) {
- if (!sample || !sample.length) return '';
- var html = '<table class="studiou-wcpcm-upvp-preview-table">';
- html += '<thead><tr>';
- html += '<th>ID</th><th>SKU</th><th>Name</th><th>Parent</th><th>Current</th>';
- if (newPriceLabel !== undefined) html += '<th>New</th>';
- html += '</tr></thead><tbody>';
- $.each(sample, function(_, r) {
- html += '<tr>';
- html += '<td>' + r.id + '</td>';
- html += '<td>' + (r.sku || '') + '</td>';
- html += '<td>' + (r.name || '') + '</td>';
- html += '<td>' + (r.parent_name || '') + '</td>';
- html += '<td>' + (r.current_price || '') + '</td>';
- if (newPriceLabel !== undefined) html += '<td>' + newPriceLabel + '</td>';
- html += '</tr>';
- });
- html += '</tbody></table>';
- return html;
- }
- // Wire up Check All / Uncheck All
- $('#studiou-wcpcm-upvp-check-all').on('click', function(e) {
- e.preventDefault();
- $catList.find('input[type="checkbox"]').prop('checked', true);
- refreshCount();
- });
- $('#studiou-wcpcm-upvp-uncheck-all').on('click', function(e) {
- e.preventDefault();
- $catList.find('input[type="checkbox"]').prop('checked', false);
- refreshCount();
- });
- $catList.on('change', 'input[type="checkbox"]', refreshCount);
- $attrSelect.on('change', loadValues);
- $valueSelect.on('change', refreshCount);
- // Dry Run
- $dryRunBtn.on('click', function(e) {
- e.preventDefault();
- var cats = getSelectedCategoryIds();
- var key = $attrSelect.val();
- var val = $valueSelect.val();
- if (!cats.length) {
- showNotice('error', i18n.selectAtLeastOneCategory || 'Please select at least one category');
- return;
- }
- if (!key) {
- showNotice('error', i18n.upvpSelectAttribute || 'Please select an attribute');
- return;
- }
- if (!val) {
- showNotice('error', i18n.upvpSelectValue || 'Please select an attribute value');
- return;
- }
- $('.studiou-wcpcm-notice-area').empty();
- $resultsBox.hide();
- $spinner.css('visibility', 'visible');
- $dryRunBtn.prop('disabled', true);
- $applyBtn.prop('disabled', true);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_upvp_count',
- nonce: studiouWcpcm.nonce,
- category_ids: cats,
- attribute_key: key,
- attribute_value: val
- },
- success: function(response) {
- if (response.success && response.data) {
- var c = parseInt(response.data.count, 10) || 0;
- var sample = response.data.sample || [];
- var price = $newPrice.val();
- var msg = '';
- if (c === 0) {
- msg = '<p>' + (i18n.upvpNoMatches || 'No variations match the current filter.') + '</p>';
- } else {
- var tpl = i18n.upvpDryRunComplete || 'Dry run complete: %d variations would be updated to %s.';
- msg = '<p>' + tpl.replace('%d', c).replace('%s', price !== '' ? price : '—') + '</p>';
- msg += renderSampleTable(sample, price !== '' ? price : undefined);
- }
- $resultsMsg.html(msg);
- $resultsBox.show();
- $countLabel.text(c);
- setApplyEnabled(c);
- } else {
- showNotice('error', (response.data && response.data.message) || 'Dry run failed');
- }
- },
- error: function(xhr, status, error) {
- showNotice('error', 'Dry run error: ' + error);
- },
- complete: function() {
- $spinner.css('visibility', 'hidden');
- }
- });
- });
- // Apply
- $applyBtn.on('click', function(e) {
- e.preventDefault();
- var cats = getSelectedCategoryIds();
- var key = $attrSelect.val();
- var val = $valueSelect.val();
- var price = $newPrice.val();
- var count = parseInt($countLabel.text(), 10) || 0;
- if (!cats.length) {
- showNotice('error', i18n.selectAtLeastOneCategory || 'Please select at least one category');
- return;
- }
- if (!key) {
- showNotice('error', i18n.upvpSelectAttribute || 'Please select an attribute');
- return;
- }
- if (!val) {
- showNotice('error', i18n.upvpSelectValue || 'Please select an attribute value');
- return;
- }
- if (price === '' || isNaN(parseFloat(price)) || parseFloat(price) < 0) {
- showNotice('error', i18n.upvpInvalidPrice || 'Please enter a valid new price');
- return;
- }
- var confirmTpl = i18n.upvpConfirmApply || 'Are you sure you want to update %d variations?';
- if (!confirm(confirmTpl.replace('%d', count))) {
- return;
- }
- $('.studiou-wcpcm-notice-area').empty();
- $resultsBox.hide();
- $spinner.css('visibility', 'visible');
- $dryRunBtn.prop('disabled', true);
- $applyBtn.prop('disabled', true);
- $.ajax({
- url: studiouWcpcm.ajaxUrl,
- type: 'POST',
- data: {
- action: 'studiou_wcpcm_upvp_apply',
- nonce: studiouWcpcm.nonce,
- category_ids: cats,
- attribute_key: key,
- attribute_value: val,
- new_price: price
- },
- success: function(response) {
- if (response.success && response.data) {
- showNotice('success', i18n.upvpApplySuccess || 'Variant prices updated successfully');
- var html = '<p><strong>' + (response.data.message || '') + '</strong></p>';
- if (response.data.failed_ids && response.data.failed_ids.length) {
- html += '<p>Failed IDs: ' + response.data.failed_ids.join(', ') + '</p>';
- }
- $resultsMsg.html(html);
- $resultsBox.show();
- refreshCount();
- } else {
- showNotice('error', (response.data && response.data.message) || (i18n.upvpApplyError || 'Variant prices update error'));
- }
- },
- error: function(xhr, status, error) {
- showNotice('error', (i18n.upvpApplyError || 'Variant prices update error') + ': ' + error);
- },
- complete: function() {
- $spinner.css('visibility', 'hidden');
- $dryRunBtn.prop('disabled', false);
- $applyBtn.prop('disabled', false);
- }
- });
- });
- // Initial load
- loadAttributes();
- setApplyEnabled(0);
- }
- })(jQuery);
|