admin.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. /**
  2. * Admin JavaScript for Studiou WC Product Category Manager
  3. */
  4. (function($) {
  5. 'use strict';
  6. // Safe init wrapper - prevents one form's error from breaking others
  7. function safeInit(name, selector, initFn) {
  8. try {
  9. if ($(selector).length) {
  10. console.log('STUDIOU WC: ' + name + ' found, initializing');
  11. initFn();
  12. }
  13. } catch (e) {
  14. console.error('STUDIOU WC: Error initializing ' + name + ':', e);
  15. }
  16. }
  17. // Initialize admin scripts
  18. $(document).ready(function() {
  19. // Debug: Log that script is loaded
  20. console.log('STUDIOU WC: Admin script loaded v1.5.1');
  21. if (typeof studiouWcpcm === 'undefined') {
  22. console.error('STUDIOU WC: studiouWcpcm object is NOT defined - AJAX will not work');
  23. return;
  24. }
  25. console.log('STUDIOU WC: studiouWcpcm object:', studiouWcpcm);
  26. safeInit('Import form', '#studiou-wcpcm-import-form', initImportForm);
  27. safeInit('Export form', '#studiou-wcpcm-export-form', initExportForm);
  28. safeInit('Move form', '#studiou-wcpcm-move-form', initMoveForm);
  29. safeInit('Batch description form', '#studiou-wcpcm-batch-description-form', initBatchDescriptionForm);
  30. safeInit('Delete products form', '#studiou-wcpcm-delete-products-form', initDeleteProductsForm);
  31. safeInit('Clear media form', '#studiou-wcpcm-clear-media-form', initClearMediaForm);
  32. safeInit('Sample download', '#studiou-wcpcm-download-sample', initSampleDownload);
  33. safeInit('Product import form', '#studiou-wcpcm-product-import-form', initProductImportForm);
  34. safeInit('Product export form', '#studiou-wcpcm-product-export-form', initProductExportForm);
  35. });
  36. /**
  37. * Initialize import form
  38. */
  39. function initImportForm() {
  40. $('#studiou-wcpcm-import-form').on('submit', function(e) {
  41. e.preventDefault();
  42. // Show spinner
  43. var $submitBtn = $(this).find('#studiou-wcpcm-import-button');
  44. var $spinner = $(this).find('.spinner');
  45. $submitBtn.prop('disabled', true);
  46. $spinner.css('visibility', 'visible');
  47. // Clear previous notices
  48. $('.studiou-wcpcm-notice-area').empty();
  49. // Create form data
  50. var formData = new FormData(this);
  51. formData.append('action', 'studiou_wcpcm_import');
  52. formData.append('nonce', studiouWcpcm.nonce);
  53. // Send AJAX request
  54. $.ajax({
  55. url: studiouWcpcm.ajaxUrl,
  56. type: 'POST',
  57. data: formData,
  58. processData: false,
  59. contentType: false,
  60. success: function(response) {
  61. if (response.success) {
  62. showNotice('success', studiouWcpcm.i18n.importSuccess);
  63. // Show results
  64. $('#studiou-wcpcm-import-results').text(response.data.message);
  65. $('.studiou-wcpcm-import-results').show();
  66. } else {
  67. showNotice('error', response.data.message);
  68. }
  69. },
  70. error: function() {
  71. showNotice('error', studiouWcpcm.i18n.importError);
  72. },
  73. complete: function() {
  74. // Hide spinner
  75. $submitBtn.prop('disabled', false);
  76. $spinner.css('visibility', 'hidden');
  77. }
  78. });
  79. });
  80. }
  81. /**
  82. * Initialize export form
  83. */
  84. function initExportForm() {
  85. $('#studiou-wcpcm-export-form').on('submit', function(e) {
  86. e.preventDefault();
  87. // Show spinner
  88. var $submitBtn = $(this).find('#studiou-wcpcm-export-button');
  89. var $spinner = $(this).find('.spinner');
  90. $submitBtn.prop('disabled', true);
  91. $spinner.css('visibility', 'visible');
  92. // Clear previous notices
  93. $('.studiou-wcpcm-notice-area').empty();
  94. // Send AJAX request
  95. $.ajax({
  96. url: studiouWcpcm.ajaxUrl,
  97. type: 'POST',
  98. data: {
  99. action: 'studiou_wcpcm_export',
  100. nonce: studiouWcpcm.nonce
  101. },
  102. success: function(response) {
  103. if (response.success) {
  104. showNotice('success', studiouWcpcm.i18n.exportSuccess);
  105. // Show download link
  106. $('#studiou-wcpcm-export-message').text(response.data.message);
  107. $('#studiou-wcpcm-download-export').attr('href', response.data.download_url);
  108. $('.studiou-wcpcm-export-results').show();
  109. } else {
  110. showNotice('error', response.data.message);
  111. }
  112. },
  113. error: function() {
  114. showNotice('error', studiouWcpcm.i18n.exportError);
  115. },
  116. complete: function() {
  117. // Hide spinner
  118. $submitBtn.prop('disabled', false);
  119. $spinner.css('visibility', 'hidden');
  120. }
  121. });
  122. });
  123. }
  124. /**
  125. * Initialize move products form
  126. */
  127. function initMoveForm() {
  128. console.log('STUDIOU WC: Initializing move form handlers');
  129. // Add debug button click handler first
  130. $('#studiou-wcpcm-move-button').on('click', function(e) {
  131. console.log('STUDIOU WC: Move button clicked directly');
  132. });
  133. $('#studiou-wcpcm-move-form').on('submit', function(e) {
  134. e.preventDefault();
  135. // Debug: Log form submission
  136. console.log('STUDIOU WC: Move form submitted');
  137. // Validate that different categories are selected
  138. var sourceCategory = $('#source_category').val();
  139. var targetCategory = $('#target_category').val();
  140. console.log('STUDIOU WC: Source category:', sourceCategory, 'Target category:', targetCategory);
  141. if (!sourceCategory || !targetCategory) {
  142. console.log('STUDIOU WC: Missing category selection');
  143. showNotice('error', 'Please select both source and target categories');
  144. return;
  145. }
  146. if (sourceCategory === targetCategory) {
  147. console.log('STUDIOU WC: Same category selected');
  148. showNotice('error', studiouWcpcm.i18n.selectDifferentCategories);
  149. return;
  150. }
  151. // Show spinner
  152. var $submitBtn = $(this).find('#studiou-wcpcm-move-button');
  153. var $spinner = $(this).find('.spinner');
  154. $submitBtn.prop('disabled', true);
  155. $spinner.css('visibility', 'visible');
  156. // Clear previous notices
  157. $('.studiou-wcpcm-notice-area').empty();
  158. // Debug: Log AJAX request details
  159. console.log('STUDIOU WC: Sending AJAX request to:', studiouWcpcm.ajaxUrl);
  160. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  161. // Send AJAX request
  162. $.ajax({
  163. url: studiouWcpcm.ajaxUrl,
  164. type: 'POST',
  165. data: {
  166. action: 'studiou_wcpcm_move_products',
  167. source_category: sourceCategory,
  168. target_category: targetCategory,
  169. nonce: studiouWcpcm.nonce
  170. },
  171. success: function(response) {
  172. console.log('STUDIOU WC: AJAX response:', response);
  173. if (response.success) {
  174. showNotice('success', studiouWcpcm.i18n.moveSuccess);
  175. // Show results
  176. $('#studiou-wcpcm-move-message').html('<p>' + response.data.message + '</p>');
  177. $('.studiou-wcpcm-move-results').show();
  178. // Refresh the page to update category counts
  179. setTimeout(function() {
  180. location.reload();
  181. }, 3000);
  182. } else {
  183. showNotice('error', response.data.message);
  184. }
  185. },
  186. error: function(xhr, status, error) {
  187. console.error('STUDIOU WC: AJAX error:', status, error);
  188. console.error('STUDIOU WC: Response text:', xhr.responseText);
  189. showNotice('error', studiouWcpcm.i18n.moveError + ': ' + error);
  190. },
  191. complete: function() {
  192. // Hide spinner
  193. $submitBtn.prop('disabled', false);
  194. $spinner.css('visibility', 'hidden');
  195. }
  196. });
  197. });
  198. }
  199. /**
  200. * Initialize batch description form
  201. */
  202. function initBatchDescriptionForm() {
  203. console.log('STUDIOU WC: Initializing batch description form handlers');
  204. // Check all button handler
  205. $('#studiou-wcpcm-check-all').on('click', function(e) {
  206. e.preventDefault();
  207. console.log('STUDIOU WC: Check all button clicked');
  208. $('#categories_list input[type="checkbox"]').prop('checked', true);
  209. });
  210. // Uncheck all button handler
  211. $('#studiou-wcpcm-uncheck-all').on('click', function(e) {
  212. e.preventDefault();
  213. console.log('STUDIOU WC: Uncheck all button clicked');
  214. $('#categories_list input[type="checkbox"]').prop('checked', false);
  215. });
  216. // Form submit handler
  217. $('#studiou-wcpcm-batch-description-form').on('submit', function(e) {
  218. e.preventDefault();
  219. console.log('STUDIOU WC: Batch description form submitted');
  220. // Get selected categories
  221. var selectedCategories = [];
  222. $('#categories_list input[type="checkbox"]:checked').each(function() {
  223. selectedCategories.push($(this).val());
  224. });
  225. var description = $('#category_description').val();
  226. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  227. console.log('STUDIOU WC: Description:', description);
  228. // Validate input
  229. if (selectedCategories.length === 0) {
  230. console.log('STUDIOU WC: No categories selected');
  231. showNotice('error', 'Please select at least one category');
  232. return;
  233. }
  234. // Show spinner
  235. var $submitBtn = $(this).find('#studiou-wcpcm-batch-description-button');
  236. var $spinner = $(this).find('.spinner');
  237. $submitBtn.prop('disabled', true);
  238. $spinner.css('visibility', 'visible');
  239. // Clear previous notices
  240. $('.studiou-wcpcm-notice-area').empty();
  241. // Debug: Log AJAX request details
  242. console.log('STUDIOU WC: Sending batch description AJAX request to:', studiouWcpcm.ajaxUrl);
  243. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  244. // Send AJAX request
  245. $.ajax({
  246. url: studiouWcpcm.ajaxUrl,
  247. type: 'POST',
  248. data: {
  249. action: 'studiou_wcpcm_batch_description',
  250. selected_categories: selectedCategories,
  251. description: description,
  252. nonce: studiouWcpcm.nonce
  253. },
  254. success: function(response) {
  255. console.log('STUDIOU WC: Batch description AJAX response:', response);
  256. if (response.success) {
  257. showNotice('success', studiouWcpcm.i18n.batchDescriptionSuccess || 'Batch description operation successful');
  258. // Show results
  259. $('#studiou-wcpcm-batch-description-message').html('<p>' + response.data.message + '</p>');
  260. $('.studiou-wcpcm-batch-description-results').show();
  261. } else {
  262. showNotice('error', response.data.message);
  263. }
  264. },
  265. error: function(xhr, status, error) {
  266. console.error('STUDIOU WC: Batch description AJAX error:', status, error);
  267. console.error('STUDIOU WC: Response text:', xhr.responseText);
  268. showNotice('error', (studiouWcpcm.i18n.batchDescriptionError || 'Batch description operation error') + ': ' + error);
  269. },
  270. complete: function() {
  271. // Hide spinner
  272. $submitBtn.prop('disabled', false);
  273. $spinner.css('visibility', 'hidden');
  274. }
  275. });
  276. });
  277. }
  278. /**
  279. * Initialize sample CSV download
  280. */
  281. function initSampleDownload() {
  282. $('#studiou-wcpcm-download-sample').on('click', function(e) {
  283. e.preventDefault();
  284. // Sample CSV content
  285. var csvContent = 'name,url-name,parent-name,description,display-type,visibility,protected-passwords,operation\n' +
  286. '"Clothing","clothing","","Top quality clothing","default","public","","A"\n' +
  287. '"Men","men","Clothing","Men\'s clothing","products","public","","A"\n' +
  288. '"Women","women","Clothing","Women\'s clothing","products","protected","password123","A"\n' +
  289. '"Kids","kids","Clothing","Kids clothing","products","public","","U"\n' +
  290. '"Accessories","accessories","","All accessories","default","public","","D"';
  291. // Create download link
  292. var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  293. var url = URL.createObjectURL(blob);
  294. var link = document.createElement('a');
  295. link.setAttribute('href', url);
  296. link.setAttribute('download', 'sample-product-categories.csv');
  297. link.style.visibility = 'hidden';
  298. document.body.appendChild(link);
  299. link.click();
  300. document.body.removeChild(link);
  301. });
  302. }
  303. /**
  304. * Initialize delete products form
  305. */
  306. function initDeleteProductsForm() {
  307. console.log('STUDIOU WC: Initializing delete products form handlers');
  308. console.log('STUDIOU WC: Form element:', $('#studiou-wcpcm-delete-products-form'));
  309. console.log('STUDIOU WC: Check all button:', $('#studiou-wcpcm-delete-check-all'));
  310. console.log('STUDIOU WC: Delete button:', $('#studiou-wcpcm-delete-products-button'));
  311. // Check all button handler
  312. $('#studiou-wcpcm-delete-check-all').on('click', function(e) {
  313. e.preventDefault();
  314. console.log('STUDIOU WC: Delete check all button clicked');
  315. $('#delete_categories_list input[type="checkbox"]').prop('checked', true);
  316. });
  317. // Uncheck all button handler
  318. $('#studiou-wcpcm-delete-uncheck-all').on('click', function(e) {
  319. e.preventDefault();
  320. console.log('STUDIOU WC: Delete uncheck all button clicked');
  321. $('#delete_categories_list input[type="checkbox"]').prop('checked', false);
  322. });
  323. // Form submit handler
  324. $('#studiou-wcpcm-delete-products-form').on('submit', function(e) {
  325. e.preventDefault();
  326. console.log('STUDIOU WC: Delete products form submitted');
  327. // Get selected categories
  328. var selectedCategories = [];
  329. $('#delete_categories_list input[type="checkbox"]:checked').each(function() {
  330. selectedCategories.push($(this).val());
  331. });
  332. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  333. // Validate input
  334. if (selectedCategories.length === 0) {
  335. console.log('STUDIOU WC: No categories selected');
  336. showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category');
  337. return;
  338. }
  339. // Confirm deletion
  340. if (!confirm(studiouWcpcm.i18n.confirmDelete || 'Are you sure you want to permanently delete ALL products in the selected categories? This action cannot be undone!')) {
  341. console.log('STUDIOU WC: User cancelled deletion');
  342. return;
  343. }
  344. // Show spinner
  345. var $submitBtn = $(this).find('#studiou-wcpcm-delete-products-button');
  346. var $spinner = $(this).find('.spinner');
  347. $submitBtn.prop('disabled', true);
  348. $spinner.css('visibility', 'visible');
  349. // Clear previous notices
  350. $('.studiou-wcpcm-notice-area').empty();
  351. // Hide results, show progress
  352. $('.studiou-wcpcm-delete-results').hide();
  353. $('.studiou-wcpcm-delete-progress').show();
  354. $('#studiou-wcpcm-delete-progress-text').text('Initializing...');
  355. updateProgressBar(0);
  356. // Debug: Log AJAX request details
  357. console.log('STUDIOU WC: Sending delete products AJAX request to:', studiouWcpcm.ajaxUrl);
  358. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  359. // Send AJAX request to get product IDs
  360. $.ajax({
  361. url: studiouWcpcm.ajaxUrl,
  362. type: 'POST',
  363. data: {
  364. action: 'studiou_wcpcm_delete_products',
  365. delete_categories: selectedCategories,
  366. nonce: studiouWcpcm.nonce
  367. },
  368. success: function(response) {
  369. console.log('STUDIOU WC: Delete products AJAX response:', response);
  370. if (response.success) {
  371. var productIds = response.data.product_ids;
  372. var totalCount = response.data.total_count;
  373. console.log('STUDIOU WC: Total products to delete:', totalCount);
  374. if (totalCount === 0) {
  375. showNotice('success', studiouWcpcm.i18n.noProductsFound || 'No products found in selected categories');
  376. $('.studiou-wcpcm-delete-progress').hide();
  377. $submitBtn.prop('disabled', false);
  378. $spinner.css('visibility', 'hidden');
  379. return;
  380. }
  381. // Process products in batches
  382. processDeletionBatches(productIds, totalCount, $submitBtn, $spinner);
  383. } else {
  384. showNotice('error', response.data.message);
  385. $('.studiou-wcpcm-delete-progress').hide();
  386. $submitBtn.prop('disabled', false);
  387. $spinner.css('visibility', 'hidden');
  388. }
  389. },
  390. error: function(xhr, status, error) {
  391. console.error('STUDIOU WC: Delete products AJAX error:', status, error);
  392. console.error('STUDIOU WC: Response text:', xhr.responseText);
  393. showNotice('error', (studiouWcpcm.i18n.deleteError || 'Delete products operation error') + ': ' + error);
  394. $('.studiou-wcpcm-delete-progress').hide();
  395. $submitBtn.prop('disabled', false);
  396. $spinner.css('visibility', 'hidden');
  397. }
  398. });
  399. });
  400. }
  401. /**
  402. * Process deletion in batches
  403. */
  404. function processDeletionBatches(productIds, totalCount, $submitBtn, $spinner) {
  405. var batchSize = 10; // Process 10 products at a time
  406. var batches = [];
  407. var totalDeleted = 0;
  408. var totalFailed = 0;
  409. var failedProducts = [];
  410. // Split products into batches
  411. for (var i = 0; i < productIds.length; i += batchSize) {
  412. batches.push(productIds.slice(i, i + batchSize));
  413. }
  414. console.log('STUDIOU WC: Processing ' + batches.length + ' batches of products');
  415. var currentBatch = 0;
  416. function processBatch() {
  417. if (currentBatch >= batches.length) {
  418. // All batches completed
  419. console.log('STUDIOU WC: All batches completed');
  420. onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner);
  421. return;
  422. }
  423. var batch = batches[currentBatch];
  424. var progress = Math.round((currentBatch / batches.length) * 100);
  425. $('#studiou-wcpcm-delete-progress-text').text(
  426. 'Deleting products... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
  427. );
  428. updateProgressBar(progress);
  429. // Send batch delete request
  430. $.ajax({
  431. url: studiouWcpcm.ajaxUrl,
  432. type: 'POST',
  433. data: {
  434. action: 'studiou_wcpcm_delete_products_batch',
  435. product_ids: batch,
  436. nonce: studiouWcpcm.nonce
  437. },
  438. success: function(response) {
  439. if (response.success) {
  440. totalDeleted += response.data.deleted_count;
  441. totalFailed += response.data.failed_count;
  442. failedProducts = failedProducts.concat(response.data.failed_products);
  443. console.log('STUDIOU WC: Batch ' + currentBatch + ' completed - Deleted: ' +
  444. response.data.deleted_count + ', Failed: ' + response.data.failed_count);
  445. // Process next batch
  446. currentBatch++;
  447. processBatch();
  448. } else {
  449. showNotice('error', response.data.message);
  450. $('.studiou-wcpcm-delete-progress').hide();
  451. $submitBtn.prop('disabled', false);
  452. $spinner.css('visibility', 'hidden');
  453. }
  454. },
  455. error: function(xhr, status, error) {
  456. console.error('STUDIOU WC: Batch delete AJAX error:', status, error);
  457. showNotice('error', 'Error deleting batch: ' + error);
  458. $('.studiou-wcpcm-delete-progress').hide();
  459. $submitBtn.prop('disabled', false);
  460. $spinner.css('visibility', 'hidden');
  461. }
  462. });
  463. }
  464. // Start processing batches
  465. processBatch();
  466. }
  467. /**
  468. * Handle deletion completion
  469. */
  470. function onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner) {
  471. // Update progress bar to 100%
  472. updateProgressBar(100);
  473. $('#studiou-wcpcm-delete-progress-text').text('Deletion complete!');
  474. // Show results
  475. var message = '<p><strong>Deletion Summary:</strong></p>';
  476. message += '<ul>';
  477. message += '<li>Total products deleted: ' + totalDeleted + '</li>';
  478. if (totalFailed > 0) {
  479. message += '<li>Failed to delete: ' + totalFailed + '</li>';
  480. if (failedProducts.length > 0) {
  481. message += '<li>Failed product IDs: ' + failedProducts.join(', ') + '</li>';
  482. }
  483. }
  484. message += '</ul>';
  485. $('#studiou-wcpcm-delete-message').html(message);
  486. $('.studiou-wcpcm-delete-results').show();
  487. // Hide progress after a delay
  488. setTimeout(function() {
  489. $('.studiou-wcpcm-delete-progress').fadeOut();
  490. }, 2000);
  491. if (totalDeleted > 0) {
  492. showNotice('success', (studiouWcpcm.i18n.deleteSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' products');
  493. // Reload page after 3 seconds
  494. setTimeout(function() {
  495. location.reload();
  496. }, 3000);
  497. } else {
  498. showNotice('error', studiouWcpcm.i18n.deleteError || 'Failed to delete any products');
  499. }
  500. $submitBtn.prop('disabled', false);
  501. $spinner.css('visibility', 'hidden');
  502. }
  503. /**
  504. * Update progress bar
  505. */
  506. function updateProgressBar(percentage) {
  507. $('#studiou-wcpcm-delete-progress-bar').css('width', percentage + '%');
  508. $('#studiou-wcpcm-delete-progress-bar').attr('data-progress', percentage + '%');
  509. }
  510. /**
  511. * Initialize clear media categories form
  512. */
  513. function initClearMediaForm() {
  514. console.log('STUDIOU WC: Initializing clear media form handlers');
  515. // Check all button handler
  516. $('#studiou-wcpcm-clear-media-check-all').on('click', function(e) {
  517. e.preventDefault();
  518. console.log('STUDIOU WC: Clear media check all button clicked');
  519. $('#clear_media_categories_list input[type="checkbox"]').prop('checked', true);
  520. });
  521. // Uncheck all button handler
  522. $('#studiou-wcpcm-clear-media-uncheck-all').on('click', function(e) {
  523. e.preventDefault();
  524. console.log('STUDIOU WC: Clear media uncheck all button clicked');
  525. $('#clear_media_categories_list input[type="checkbox"]').prop('checked', false);
  526. });
  527. // Form submit handler
  528. $('#studiou-wcpcm-clear-media-form').on('submit', function(e) {
  529. e.preventDefault();
  530. console.log('STUDIOU WC: Clear media form submitted');
  531. // Get selected categories
  532. var selectedCategories = [];
  533. $('#clear_media_categories_list input[type="checkbox"]:checked').each(function() {
  534. selectedCategories.push($(this).val());
  535. });
  536. console.log('STUDIOU WC: Selected media categories:', selectedCategories);
  537. // Validate input
  538. if (selectedCategories.length === 0) {
  539. console.log('STUDIOU WC: No media categories selected');
  540. showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category');
  541. return;
  542. }
  543. // Confirm deletion
  544. 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!')) {
  545. console.log('STUDIOU WC: User cancelled clear media');
  546. return;
  547. }
  548. // Show spinner
  549. var $submitBtn = $(this).find('#studiou-wcpcm-clear-media-button');
  550. var $spinner = $(this).find('.spinner');
  551. $submitBtn.prop('disabled', true);
  552. $spinner.css('visibility', 'visible');
  553. // Clear previous notices
  554. $('.studiou-wcpcm-notice-area').empty();
  555. // Hide results, show progress
  556. $('.studiou-wcpcm-clear-media-results').hide();
  557. $('.studiou-wcpcm-clear-media-progress').show();
  558. $('#studiou-wcpcm-clear-media-progress-text').text('Initializing...');
  559. updateClearMediaProgressBar(0);
  560. // Send AJAX request to get media IDs
  561. $.ajax({
  562. url: studiouWcpcm.ajaxUrl,
  563. type: 'POST',
  564. data: {
  565. action: 'studiou_wcpcm_clear_media',
  566. media_categories: selectedCategories,
  567. nonce: studiouWcpcm.nonce
  568. },
  569. success: function(response) {
  570. console.log('STUDIOU WC: Clear media AJAX response:', response);
  571. if (response.success) {
  572. var mediaIds = response.data.media_ids;
  573. var totalCount = response.data.total_count;
  574. console.log('STUDIOU WC: Total media files to delete:', totalCount);
  575. if (totalCount === 0) {
  576. showNotice('success', studiouWcpcm.i18n.noMediaFound || 'No media files found in selected categories');
  577. $('.studiou-wcpcm-clear-media-progress').hide();
  578. $submitBtn.prop('disabled', false);
  579. $spinner.css('visibility', 'hidden');
  580. return;
  581. }
  582. // Process media in batches
  583. processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner);
  584. } else {
  585. showNotice('error', response.data.message);
  586. $('.studiou-wcpcm-clear-media-progress').hide();
  587. $submitBtn.prop('disabled', false);
  588. $spinner.css('visibility', 'hidden');
  589. }
  590. },
  591. error: function(xhr, status, error) {
  592. console.error('STUDIOU WC: Clear media AJAX error:', status, error);
  593. console.error('STUDIOU WC: Response text:', xhr.responseText);
  594. showNotice('error', (studiouWcpcm.i18n.clearMediaError || 'Clear media operation error') + ': ' + error);
  595. $('.studiou-wcpcm-clear-media-progress').hide();
  596. $submitBtn.prop('disabled', false);
  597. $spinner.css('visibility', 'hidden');
  598. }
  599. });
  600. });
  601. }
  602. /**
  603. * Process media deletion in batches
  604. */
  605. function processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner) {
  606. var batchSize = 10;
  607. var batches = [];
  608. var totalDeleted = 0;
  609. var totalFailed = 0;
  610. var failedMedia = [];
  611. // Split media into batches
  612. for (var i = 0; i < mediaIds.length; i += batchSize) {
  613. batches.push(mediaIds.slice(i, i + batchSize));
  614. }
  615. console.log('STUDIOU WC: Processing ' + batches.length + ' batches of media files');
  616. var currentBatch = 0;
  617. function processBatch() {
  618. if (currentBatch >= batches.length) {
  619. console.log('STUDIOU WC: All media batches completed');
  620. onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner);
  621. return;
  622. }
  623. var batch = batches[currentBatch];
  624. var progress = Math.round((currentBatch / batches.length) * 100);
  625. $('#studiou-wcpcm-clear-media-progress-text').text(
  626. 'Deleting media files... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
  627. );
  628. updateClearMediaProgressBar(progress);
  629. $.ajax({
  630. url: studiouWcpcm.ajaxUrl,
  631. type: 'POST',
  632. data: {
  633. action: 'studiou_wcpcm_clear_media_batch',
  634. media_ids: batch,
  635. nonce: studiouWcpcm.nonce
  636. },
  637. success: function(response) {
  638. if (response.success) {
  639. totalDeleted += response.data.deleted_count;
  640. totalFailed += response.data.failed_count;
  641. failedMedia = failedMedia.concat(response.data.failed_media);
  642. console.log('STUDIOU WC: Media batch ' + currentBatch + ' completed - Deleted: ' +
  643. response.data.deleted_count + ', Failed: ' + response.data.failed_count);
  644. currentBatch++;
  645. processBatch();
  646. } else {
  647. showNotice('error', response.data.message);
  648. $('.studiou-wcpcm-clear-media-progress').hide();
  649. $submitBtn.prop('disabled', false);
  650. $spinner.css('visibility', 'hidden');
  651. }
  652. },
  653. error: function(xhr, status, error) {
  654. console.error('STUDIOU WC: Media batch delete AJAX error:', status, error);
  655. showNotice('error', 'Error deleting media batch: ' + error);
  656. $('.studiou-wcpcm-clear-media-progress').hide();
  657. $submitBtn.prop('disabled', false);
  658. $spinner.css('visibility', 'hidden');
  659. }
  660. });
  661. }
  662. processBatch();
  663. }
  664. /**
  665. * Handle media deletion completion
  666. */
  667. function onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner) {
  668. updateClearMediaProgressBar(100);
  669. $('#studiou-wcpcm-clear-media-progress-text').text('Deletion complete!');
  670. var message = '<p><strong>Deletion Summary:</strong></p>';
  671. message += '<ul>';
  672. message += '<li>Total media files deleted: ' + totalDeleted + '</li>';
  673. if (totalFailed > 0) {
  674. message += '<li>Failed to delete: ' + totalFailed + '</li>';
  675. if (failedMedia.length > 0) {
  676. message += '<li>Failed media IDs: ' + failedMedia.join(', ') + '</li>';
  677. }
  678. }
  679. message += '</ul>';
  680. $('#studiou-wcpcm-clear-media-message').html(message);
  681. $('.studiou-wcpcm-clear-media-results').show();
  682. setTimeout(function() {
  683. $('.studiou-wcpcm-clear-media-progress').fadeOut();
  684. }, 2000);
  685. if (totalDeleted > 0) {
  686. showNotice('success', (studiouWcpcm.i18n.clearMediaSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' media files');
  687. setTimeout(function() {
  688. location.reload();
  689. }, 3000);
  690. } else {
  691. showNotice('error', studiouWcpcm.i18n.clearMediaError || 'Failed to delete any media files');
  692. }
  693. $submitBtn.prop('disabled', false);
  694. $spinner.css('visibility', 'hidden');
  695. }
  696. /**
  697. * Update clear media progress bar
  698. */
  699. function updateClearMediaProgressBar(percentage) {
  700. $('#studiou-wcpcm-clear-media-progress-bar').css('width', percentage + '%');
  701. $('#studiou-wcpcm-clear-media-progress-bar').attr('data-progress', percentage + '%');
  702. }
  703. /**
  704. * Show notice message
  705. *
  706. * @param {string} type Notice type (success, error)
  707. * @param {string} message Notice message
  708. */
  709. function showNotice(type, message) {
  710. var $notice = $('<div class="studiou-wcpcm-notice studiou-wcpcm-notice-' + type + '"></div>').text(message);
  711. $('.studiou-wcpcm-notice-area').append($notice);
  712. // Scroll to notice
  713. $('html, body').animate({
  714. scrollTop: $('.studiou-wcpcm-notice-area').offset().top - 50
  715. }, 500);
  716. }
  717. /**
  718. * Initialize product import form
  719. */
  720. function initProductImportForm() {
  721. console.log('STUDIOU WC: Initializing product import form handlers');
  722. // Global variables for batch processing
  723. var importTransientKey = null;
  724. var importTotal = 0;
  725. var importProcessed = 0;
  726. var importSuccess = 0;
  727. var importFailed = 0;
  728. var importSkipped = 0;
  729. var importMessages = [];
  730. var importFailedCsv = '';
  731. $('#studiou-wcpcm-product-import-form').on('submit', function(e) {
  732. e.preventDefault();
  733. console.log('STUDIOU WC: Product import form submitted');
  734. // Validate file is selected
  735. var fileInput = $('#import_file')[0];
  736. if (!fileInput.files || !fileInput.files[0]) {
  737. showNotice('error', 'Please select a CSV file to import');
  738. return;
  739. }
  740. // Show spinner and progress
  741. var $submitBtn = $(this).find('#studiou-wcpcm-product-import-button');
  742. var $spinner = $(this).find('.spinner');
  743. $submitBtn.prop('disabled', true);
  744. $spinner.css('visibility', 'visible');
  745. // Clear previous results
  746. $('.studiou-wcpcm-notice-area').empty();
  747. $('.studiou-wcpcm-product-import-results').hide();
  748. $('.studiou-wcpcm-product-import-failed').hide();
  749. // Reset counters
  750. importTransientKey = null;
  751. importTotal = 0;
  752. importProcessed = 0;
  753. importSuccess = 0;
  754. importFailed = 0;
  755. importSkipped = 0;
  756. importMessages = [];
  757. importFailedCsv = '';
  758. // Show progress bar
  759. $('.studiou-wcpcm-product-import-progress').show();
  760. $('#studiou-wcpcm-product-import-progress-text').text('Parsing CSV file...');
  761. updateProductImportProgressBar(0);
  762. // Step 1: Parse CSV file
  763. var formData = new FormData(this);
  764. formData.append('action', 'studiou_wcpcm_product_import_parse');
  765. formData.append('nonce', studiouWcpcm.nonce);
  766. $.ajax({
  767. url: studiouWcpcm.ajaxUrl,
  768. type: 'POST',
  769. data: formData,
  770. processData: false,
  771. contentType: false,
  772. success: function(response) {
  773. console.log('STUDIOU WC: Product import parse response:', response);
  774. if (response.success) {
  775. importTransientKey = response.data.transient_key;
  776. importTotal = response.data.total;
  777. // Start batch processing
  778. processBatch(0, $submitBtn, $spinner);
  779. } else {
  780. showNotice('error', response.data.message || 'Parse failed');
  781. $('.studiou-wcpcm-product-import-progress').hide();
  782. $submitBtn.prop('disabled', false);
  783. $spinner.css('visibility', 'hidden');
  784. }
  785. },
  786. error: function(xhr, status, error) {
  787. console.error('STUDIOU WC: Product import parse error:', status, error);
  788. console.error('STUDIOU WC: Response text:', xhr.responseText);
  789. showNotice('error', 'Product import error: ' + error);
  790. $('.studiou-wcpcm-product-import-progress').hide();
  791. $submitBtn.prop('disabled', false);
  792. $spinner.css('visibility', 'hidden');
  793. }
  794. });
  795. });
  796. // Process batch of products
  797. function processBatch(offset, $submitBtn, $spinner) {
  798. console.log('STUDIOU WC: Processing batch at offset', offset);
  799. $.ajax({
  800. url: studiouWcpcm.ajaxUrl,
  801. type: 'POST',
  802. data: {
  803. action: 'studiou_wcpcm_product_import_batch',
  804. nonce: studiouWcpcm.nonce,
  805. transient_key: importTransientKey,
  806. offset: offset
  807. },
  808. success: function(response) {
  809. console.log('STUDIOU WC: Batch response:', response);
  810. if (response.success) {
  811. // Accumulate results
  812. importSuccess += response.data.success;
  813. importFailed += response.data.failed;
  814. importSkipped += response.data.skipped;
  815. importProcessed = response.data.processed;
  816. importTotal = response.data.total;
  817. importMessages = importMessages.concat(response.data.messages);
  818. if (response.data.failed_csv) {
  819. importFailedCsv = response.data.failed_csv;
  820. }
  821. // Update progress
  822. var percent = (importProcessed / importTotal) * 100;
  823. updateProductImportProgressBar(percent);
  824. $('#studiou-wcpcm-product-import-progress-text').text(
  825. 'Processing: ' + importProcessed + ' / ' + importTotal + ' products'
  826. );
  827. // Check if complete
  828. if (importProcessed >= importTotal) {
  829. // Import complete
  830. $('#studiou-wcpcm-product-import-progress-text').text('Complete!');
  831. showNotice('success', 'Product import completed!');
  832. // Show results
  833. var message = '<p><strong>Import Summary:</strong></p>';
  834. message += '<ul>';
  835. message += '<li>Successful: ' + importSuccess + '</li>';
  836. message += '<li>Failed: ' + importFailed + '</li>';
  837. message += '<li>Skipped: ' + importSkipped + '</li>';
  838. message += '</ul>';
  839. $('#studiou-wcpcm-product-import-message').html(message);
  840. // Show detailed messages
  841. if (importMessages.length > 0) {
  842. var details = '<pre>' + importMessages.join('\n') + '</pre>';
  843. $('#studiou-wcpcm-product-import-details-content').html(details);
  844. }
  845. $('.studiou-wcpcm-product-import-results').show();
  846. // Show save failed button if there are failed items
  847. if (importFailed > 0 && importFailedCsv) {
  848. window.studiouWcpcmFailedCsv = importFailedCsv;
  849. $('.studiou-wcpcm-product-import-failed').show();
  850. }
  851. // Hide progress after delay
  852. setTimeout(function() {
  853. $('.studiou-wcpcm-product-import-progress').fadeOut();
  854. }, 2000);
  855. $submitBtn.prop('disabled', false);
  856. $spinner.css('visibility', 'hidden');
  857. } else {
  858. // Process next batch
  859. processBatch(importProcessed, $submitBtn, $spinner);
  860. }
  861. } else {
  862. showNotice('error', response.data.message || 'Batch processing failed');
  863. $('.studiou-wcpcm-product-import-progress').hide();
  864. $submitBtn.prop('disabled', false);
  865. $spinner.css('visibility', 'hidden');
  866. }
  867. },
  868. error: function(xhr, status, error) {
  869. console.error('STUDIOU WC: Batch processing error:', status, error);
  870. showNotice('error', 'Batch processing error: ' + error);
  871. $('.studiou-wcpcm-product-import-progress').hide();
  872. $submitBtn.prop('disabled', false);
  873. $spinner.css('visibility', 'hidden');
  874. }
  875. });
  876. }
  877. // Save failed products button handler
  878. $('#studiou-wcpcm-save-failed-products').on('click', function(e) {
  879. e.preventDefault();
  880. if (window.studiouWcpcmFailedCsv) {
  881. var blob = new Blob([window.studiouWcpcmFailedCsv], { type: 'text/csv;charset=utf-8;' });
  882. var url = URL.createObjectURL(blob);
  883. var link = document.createElement('a');
  884. link.setAttribute('href', url);
  885. link.setAttribute('download', 'failed-products-' + Date.now() + '.csv');
  886. link.style.visibility = 'hidden';
  887. document.body.appendChild(link);
  888. link.click();
  889. document.body.removeChild(link);
  890. }
  891. });
  892. }
  893. /**
  894. * Initialize product export form
  895. */
  896. function initProductExportForm() {
  897. console.log('STUDIOU WC: Initializing product export form handlers');
  898. // Select all button handler
  899. $('#studiou-wcpcm-export-select-all').on('click', function(e) {
  900. e.preventDefault();
  901. console.log('STUDIOU WC: Export select all button clicked');
  902. $('#export_categories_list input[type="checkbox"]').prop('checked', true);
  903. });
  904. // Deselect all button handler
  905. $('#studiou-wcpcm-export-deselect-all').on('click', function(e) {
  906. e.preventDefault();
  907. console.log('STUDIOU WC: Export deselect all button clicked');
  908. $('#export_categories_list input[type="checkbox"]').prop('checked', false);
  909. });
  910. // Form submit handler
  911. $('#studiou-wcpcm-product-export-form').on('submit', function(e) {
  912. e.preventDefault();
  913. console.log('STUDIOU WC: Product export form submitted');
  914. // Get selected categories
  915. var selectedCategories = [];
  916. $('#export_categories_list input[type="checkbox"]:checked').each(function() {
  917. selectedCategories.push($(this).val());
  918. });
  919. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  920. // Validate input
  921. if (selectedCategories.length === 0) {
  922. console.log('STUDIOU WC: No categories selected');
  923. showNotice('error', 'Please select at least one category');
  924. return;
  925. }
  926. // Show spinner
  927. var $submitBtn = $(this).find('#studiou-wcpcm-product-export-button');
  928. var $spinner = $(this).find('.spinner');
  929. $submitBtn.prop('disabled', true);
  930. $spinner.css('visibility', 'visible');
  931. // Clear previous notices
  932. $('.studiou-wcpcm-notice-area').empty();
  933. $('.studiou-wcpcm-product-export-results').hide();
  934. // Debug: Log AJAX request details
  935. console.log('STUDIOU WC: Sending product export AJAX request to:', studiouWcpcm.ajaxUrl);
  936. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  937. // Send AJAX request
  938. $.ajax({
  939. url: studiouWcpcm.ajaxUrl,
  940. type: 'POST',
  941. data: {
  942. action: 'studiou_wcpcm_product_export',
  943. export_categories: selectedCategories,
  944. nonce: studiouWcpcm.nonce
  945. },
  946. success: function(response) {
  947. console.log('STUDIOU WC: Product export AJAX response:', response);
  948. if (response.success) {
  949. showNotice('success', 'Export successful!');
  950. // Show results
  951. $('#studiou-wcpcm-product-export-message').html('<p>' + response.data.message + '</p>');
  952. $('#studiou-wcpcm-download-product-export').attr('href', response.data.download_url);
  953. $('.studiou-wcpcm-product-export-results').show();
  954. } else {
  955. showNotice('error', response.data.message || 'Export failed');
  956. }
  957. },
  958. error: function(xhr, status, error) {
  959. console.error('STUDIOU WC: Product export AJAX error:', status, error);
  960. console.error('STUDIOU WC: Response text:', xhr.responseText);
  961. showNotice('error', 'Product export error: ' + error);
  962. },
  963. complete: function() {
  964. // Hide spinner
  965. $submitBtn.prop('disabled', false);
  966. $spinner.css('visibility', 'hidden');
  967. }
  968. });
  969. });
  970. }
  971. /**
  972. * Update product import progress bar
  973. */
  974. function updateProductImportProgressBar(percentage) {
  975. $('#studiou-wcpcm-product-import-progress-bar').css('width', percentage + '%');
  976. $('#studiou-wcpcm-product-import-progress-bar').attr('data-progress', Math.round(percentage) + '%');
  977. }
  978. // Additional debug: Check if elements exist after DOM load
  979. $(window).on('load', function() {
  980. console.log('STUDIOU WC: Window loaded');
  981. console.log('STUDIOU WC: Move form exists:', $('#studiou-wcpcm-move-form').length > 0);
  982. console.log('STUDIOU WC: Move button exists:', $('#studiou-wcpcm-move-button').length > 0);
  983. console.log('STUDIOU WC: Source select exists:', $('#source_category').length > 0);
  984. console.log('STUDIOU WC: Target select exists:', $('#target_category').length > 0);
  985. console.log('STUDIOU WC: Batch description form exists:', $('#studiou-wcpcm-batch-description-form').length > 0);
  986. console.log('STUDIOU WC: Batch description button exists:', $('#studiou-wcpcm-batch-description-button').length > 0);
  987. console.log('STUDIOU WC: Delete products form exists:', $('#studiou-wcpcm-delete-products-form').length > 0);
  988. console.log('STUDIOU WC: Product import form exists:', $('#studiou-wcpcm-product-import-form').length > 0);
  989. console.log('STUDIOU WC: Product export form exists:', $('#studiou-wcpcm-product-export-form').length > 0);
  990. console.log('STUDIOU WC: Clear media form exists:', $('#studiou-wcpcm-clear-media-form').length > 0);
  991. });
  992. })(jQuery);