admin.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  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.3');
  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('Remove unassigned media form', '#studiou-wcpcm-remove-unassigned-media-form', initRemoveUnassignedMediaForm);
  33. safeInit('Sample download', '#studiou-wcpcm-download-sample', initSampleDownload);
  34. safeInit('Product import form', '#studiou-wcpcm-product-import-form', initProductImportForm);
  35. safeInit('Product export form', '#studiou-wcpcm-product-export-form', initProductExportForm);
  36. safeInit('Update variant prices form', '#studiou-wcpcm-upvp-form', initUpdateVariantPricesForm);
  37. });
  38. /**
  39. * Initialize import form
  40. */
  41. function initImportForm() {
  42. $('#studiou-wcpcm-import-form').on('submit', function(e) {
  43. e.preventDefault();
  44. // Show spinner
  45. var $submitBtn = $(this).find('#studiou-wcpcm-import-button');
  46. var $spinner = $(this).find('.spinner');
  47. $submitBtn.prop('disabled', true);
  48. $spinner.css('visibility', 'visible');
  49. // Clear previous notices
  50. $('.studiou-wcpcm-notice-area').empty();
  51. // Create form data
  52. var formData = new FormData(this);
  53. formData.append('action', 'studiou_wcpcm_import');
  54. formData.append('nonce', studiouWcpcm.nonce);
  55. // Send AJAX request
  56. $.ajax({
  57. url: studiouWcpcm.ajaxUrl,
  58. type: 'POST',
  59. data: formData,
  60. processData: false,
  61. contentType: false,
  62. success: function(response) {
  63. if (response.success) {
  64. showNotice('success', studiouWcpcm.i18n.importSuccess);
  65. // Show results
  66. $('#studiou-wcpcm-import-results').text(response.data.message);
  67. $('.studiou-wcpcm-import-results').show();
  68. } else {
  69. showNotice('error', response.data.message);
  70. }
  71. },
  72. error: function() {
  73. showNotice('error', studiouWcpcm.i18n.importError);
  74. },
  75. complete: function() {
  76. // Hide spinner
  77. $submitBtn.prop('disabled', false);
  78. $spinner.css('visibility', 'hidden');
  79. }
  80. });
  81. });
  82. }
  83. /**
  84. * Initialize export form
  85. */
  86. function initExportForm() {
  87. $('#studiou-wcpcm-export-form').on('submit', function(e) {
  88. e.preventDefault();
  89. // Show spinner
  90. var $submitBtn = $(this).find('#studiou-wcpcm-export-button');
  91. var $spinner = $(this).find('.spinner');
  92. $submitBtn.prop('disabled', true);
  93. $spinner.css('visibility', 'visible');
  94. // Clear previous notices
  95. $('.studiou-wcpcm-notice-area').empty();
  96. // Send AJAX request
  97. $.ajax({
  98. url: studiouWcpcm.ajaxUrl,
  99. type: 'POST',
  100. data: {
  101. action: 'studiou_wcpcm_export',
  102. nonce: studiouWcpcm.nonce
  103. },
  104. success: function(response) {
  105. if (response.success) {
  106. showNotice('success', studiouWcpcm.i18n.exportSuccess);
  107. // Show download link
  108. $('#studiou-wcpcm-export-message').text(response.data.message);
  109. $('#studiou-wcpcm-download-export').attr('href', response.data.download_url);
  110. $('.studiou-wcpcm-export-results').show();
  111. } else {
  112. showNotice('error', response.data.message);
  113. }
  114. },
  115. error: function() {
  116. showNotice('error', studiouWcpcm.i18n.exportError);
  117. },
  118. complete: function() {
  119. // Hide spinner
  120. $submitBtn.prop('disabled', false);
  121. $spinner.css('visibility', 'hidden');
  122. }
  123. });
  124. });
  125. }
  126. /**
  127. * Initialize move products form
  128. */
  129. function initMoveForm() {
  130. console.log('STUDIOU WC: Initializing move form handlers');
  131. // Add debug button click handler first
  132. $('#studiou-wcpcm-move-button').on('click', function(e) {
  133. console.log('STUDIOU WC: Move button clicked directly');
  134. });
  135. $('#studiou-wcpcm-move-form').on('submit', function(e) {
  136. e.preventDefault();
  137. // Debug: Log form submission
  138. console.log('STUDIOU WC: Move form submitted');
  139. // Validate that different categories are selected
  140. var sourceCategory = $('#source_category').val();
  141. var targetCategory = $('#target_category').val();
  142. console.log('STUDIOU WC: Source category:', sourceCategory, 'Target category:', targetCategory);
  143. if (!sourceCategory || !targetCategory) {
  144. console.log('STUDIOU WC: Missing category selection');
  145. showNotice('error', 'Please select both source and target categories');
  146. return;
  147. }
  148. if (sourceCategory === targetCategory) {
  149. console.log('STUDIOU WC: Same category selected');
  150. showNotice('error', studiouWcpcm.i18n.selectDifferentCategories);
  151. return;
  152. }
  153. // Show spinner
  154. var $submitBtn = $(this).find('#studiou-wcpcm-move-button');
  155. var $spinner = $(this).find('.spinner');
  156. $submitBtn.prop('disabled', true);
  157. $spinner.css('visibility', 'visible');
  158. // Clear previous notices
  159. $('.studiou-wcpcm-notice-area').empty();
  160. // Debug: Log AJAX request details
  161. console.log('STUDIOU WC: Sending AJAX request to:', studiouWcpcm.ajaxUrl);
  162. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  163. // Send AJAX request
  164. $.ajax({
  165. url: studiouWcpcm.ajaxUrl,
  166. type: 'POST',
  167. data: {
  168. action: 'studiou_wcpcm_move_products',
  169. source_category: sourceCategory,
  170. target_category: targetCategory,
  171. nonce: studiouWcpcm.nonce
  172. },
  173. success: function(response) {
  174. console.log('STUDIOU WC: AJAX response:', response);
  175. if (response.success) {
  176. showNotice('success', studiouWcpcm.i18n.moveSuccess);
  177. // Show results
  178. $('#studiou-wcpcm-move-message').html('<p>' + response.data.message + '</p>');
  179. $('.studiou-wcpcm-move-results').show();
  180. // Refresh the page to update category counts
  181. setTimeout(function() {
  182. location.reload();
  183. }, 3000);
  184. } else {
  185. showNotice('error', response.data.message);
  186. }
  187. },
  188. error: function(xhr, status, error) {
  189. console.error('STUDIOU WC: AJAX error:', status, error);
  190. console.error('STUDIOU WC: Response text:', xhr.responseText);
  191. showNotice('error', studiouWcpcm.i18n.moveError + ': ' + error);
  192. },
  193. complete: function() {
  194. // Hide spinner
  195. $submitBtn.prop('disabled', false);
  196. $spinner.css('visibility', 'hidden');
  197. }
  198. });
  199. });
  200. }
  201. /**
  202. * Initialize batch description form
  203. */
  204. function initBatchDescriptionForm() {
  205. console.log('STUDIOU WC: Initializing batch description form handlers');
  206. // Check all button handler
  207. $('#studiou-wcpcm-check-all').on('click', function(e) {
  208. e.preventDefault();
  209. console.log('STUDIOU WC: Check all button clicked');
  210. $('#categories_list input[type="checkbox"]').prop('checked', true);
  211. });
  212. // Uncheck all button handler
  213. $('#studiou-wcpcm-uncheck-all').on('click', function(e) {
  214. e.preventDefault();
  215. console.log('STUDIOU WC: Uncheck all button clicked');
  216. $('#categories_list input[type="checkbox"]').prop('checked', false);
  217. });
  218. // Form submit handler
  219. $('#studiou-wcpcm-batch-description-form').on('submit', function(e) {
  220. e.preventDefault();
  221. console.log('STUDIOU WC: Batch description form submitted');
  222. // Get selected categories
  223. var selectedCategories = [];
  224. $('#categories_list input[type="checkbox"]:checked').each(function() {
  225. selectedCategories.push($(this).val());
  226. });
  227. var description = $('#category_description').val();
  228. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  229. console.log('STUDIOU WC: Description:', description);
  230. // Validate input
  231. if (selectedCategories.length === 0) {
  232. console.log('STUDIOU WC: No categories selected');
  233. showNotice('error', 'Please select at least one category');
  234. return;
  235. }
  236. // Show spinner
  237. var $submitBtn = $(this).find('#studiou-wcpcm-batch-description-button');
  238. var $spinner = $(this).find('.spinner');
  239. $submitBtn.prop('disabled', true);
  240. $spinner.css('visibility', 'visible');
  241. // Clear previous notices
  242. $('.studiou-wcpcm-notice-area').empty();
  243. // Debug: Log AJAX request details
  244. console.log('STUDIOU WC: Sending batch description AJAX request to:', studiouWcpcm.ajaxUrl);
  245. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  246. // Send AJAX request
  247. $.ajax({
  248. url: studiouWcpcm.ajaxUrl,
  249. type: 'POST',
  250. data: {
  251. action: 'studiou_wcpcm_batch_description',
  252. selected_categories: selectedCategories,
  253. description: description,
  254. nonce: studiouWcpcm.nonce
  255. },
  256. success: function(response) {
  257. console.log('STUDIOU WC: Batch description AJAX response:', response);
  258. if (response.success) {
  259. showNotice('success', studiouWcpcm.i18n.batchDescriptionSuccess || 'Batch description operation successful');
  260. // Show results
  261. $('#studiou-wcpcm-batch-description-message').html('<p>' + response.data.message + '</p>');
  262. $('.studiou-wcpcm-batch-description-results').show();
  263. } else {
  264. showNotice('error', response.data.message);
  265. }
  266. },
  267. error: function(xhr, status, error) {
  268. console.error('STUDIOU WC: Batch description AJAX error:', status, error);
  269. console.error('STUDIOU WC: Response text:', xhr.responseText);
  270. showNotice('error', (studiouWcpcm.i18n.batchDescriptionError || 'Batch description operation error') + ': ' + error);
  271. },
  272. complete: function() {
  273. // Hide spinner
  274. $submitBtn.prop('disabled', false);
  275. $spinner.css('visibility', 'hidden');
  276. }
  277. });
  278. });
  279. }
  280. /**
  281. * Initialize sample CSV download
  282. */
  283. function initSampleDownload() {
  284. $('#studiou-wcpcm-download-sample').on('click', function(e) {
  285. e.preventDefault();
  286. // Sample CSV content
  287. var csvContent = 'name,url-name,parent-name,description,display-type,visibility,protected-passwords,operation\n' +
  288. '"Clothing","clothing","","Top quality clothing","default","public","","A"\n' +
  289. '"Men","men","Clothing","Men\'s clothing","products","public","","A"\n' +
  290. '"Women","women","Clothing","Women\'s clothing","products","protected","password123","A"\n' +
  291. '"Kids","kids","Clothing","Kids clothing","products","public","","U"\n' +
  292. '"Accessories","accessories","","All accessories","default","public","","D"';
  293. // Create download link
  294. var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  295. var url = URL.createObjectURL(blob);
  296. var link = document.createElement('a');
  297. link.setAttribute('href', url);
  298. link.setAttribute('download', 'sample-product-categories.csv');
  299. link.style.visibility = 'hidden';
  300. document.body.appendChild(link);
  301. link.click();
  302. document.body.removeChild(link);
  303. });
  304. }
  305. /**
  306. * Initialize delete products form
  307. */
  308. function initDeleteProductsForm() {
  309. console.log('STUDIOU WC: Initializing delete products form handlers');
  310. console.log('STUDIOU WC: Form element:', $('#studiou-wcpcm-delete-products-form'));
  311. console.log('STUDIOU WC: Check all button:', $('#studiou-wcpcm-delete-check-all'));
  312. console.log('STUDIOU WC: Delete button:', $('#studiou-wcpcm-delete-products-button'));
  313. // Check all button handler
  314. $('#studiou-wcpcm-delete-check-all').on('click', function(e) {
  315. e.preventDefault();
  316. console.log('STUDIOU WC: Delete check all button clicked');
  317. $('#delete_categories_list input[type="checkbox"]').prop('checked', true);
  318. });
  319. // Uncheck all button handler
  320. $('#studiou-wcpcm-delete-uncheck-all').on('click', function(e) {
  321. e.preventDefault();
  322. console.log('STUDIOU WC: Delete uncheck all button clicked');
  323. $('#delete_categories_list input[type="checkbox"]').prop('checked', false);
  324. });
  325. // Form submit handler
  326. $('#studiou-wcpcm-delete-products-form').on('submit', function(e) {
  327. e.preventDefault();
  328. console.log('STUDIOU WC: Delete products form submitted');
  329. // Get selected categories
  330. var selectedCategories = [];
  331. $('#delete_categories_list input[type="checkbox"]:checked').each(function() {
  332. selectedCategories.push($(this).val());
  333. });
  334. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  335. // Validate input
  336. if (selectedCategories.length === 0) {
  337. console.log('STUDIOU WC: No categories selected');
  338. showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category');
  339. return;
  340. }
  341. // Confirm deletion
  342. if (!confirm(studiouWcpcm.i18n.confirmDelete || 'Are you sure you want to permanently delete ALL products in the selected categories? This action cannot be undone!')) {
  343. console.log('STUDIOU WC: User cancelled deletion');
  344. return;
  345. }
  346. // Show spinner
  347. var $submitBtn = $(this).find('#studiou-wcpcm-delete-products-button');
  348. var $spinner = $(this).find('.spinner');
  349. $submitBtn.prop('disabled', true);
  350. $spinner.css('visibility', 'visible');
  351. // Clear previous notices
  352. $('.studiou-wcpcm-notice-area').empty();
  353. // Hide results, show progress
  354. $('.studiou-wcpcm-delete-results').hide();
  355. $('.studiou-wcpcm-delete-progress').show();
  356. $('#studiou-wcpcm-delete-progress-text').text('Initializing...');
  357. updateProgressBar(0);
  358. // Debug: Log AJAX request details
  359. console.log('STUDIOU WC: Sending delete products AJAX request to:', studiouWcpcm.ajaxUrl);
  360. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  361. // Send AJAX request to get product IDs
  362. $.ajax({
  363. url: studiouWcpcm.ajaxUrl,
  364. type: 'POST',
  365. data: {
  366. action: 'studiou_wcpcm_delete_products',
  367. delete_categories: selectedCategories,
  368. nonce: studiouWcpcm.nonce
  369. },
  370. success: function(response) {
  371. console.log('STUDIOU WC: Delete products AJAX response:', response);
  372. if (response.success) {
  373. var productIds = response.data.product_ids;
  374. var totalCount = response.data.total_count;
  375. console.log('STUDIOU WC: Total products to delete:', totalCount);
  376. if (totalCount === 0) {
  377. showNotice('success', studiouWcpcm.i18n.noProductsFound || 'No products found in selected categories');
  378. $('.studiou-wcpcm-delete-progress').hide();
  379. $submitBtn.prop('disabled', false);
  380. $spinner.css('visibility', 'hidden');
  381. return;
  382. }
  383. // Process products in batches
  384. processDeletionBatches(productIds, totalCount, $submitBtn, $spinner);
  385. } else {
  386. showNotice('error', response.data.message);
  387. $('.studiou-wcpcm-delete-progress').hide();
  388. $submitBtn.prop('disabled', false);
  389. $spinner.css('visibility', 'hidden');
  390. }
  391. },
  392. error: function(xhr, status, error) {
  393. console.error('STUDIOU WC: Delete products AJAX error:', status, error);
  394. console.error('STUDIOU WC: Response text:', xhr.responseText);
  395. showNotice('error', (studiouWcpcm.i18n.deleteError || 'Delete products operation error') + ': ' + error);
  396. $('.studiou-wcpcm-delete-progress').hide();
  397. $submitBtn.prop('disabled', false);
  398. $spinner.css('visibility', 'hidden');
  399. }
  400. });
  401. });
  402. }
  403. /**
  404. * Process deletion in batches
  405. */
  406. function processDeletionBatches(productIds, totalCount, $submitBtn, $spinner) {
  407. var batchSize = 10; // Process 10 products at a time
  408. var batches = [];
  409. var totalDeleted = 0;
  410. var totalFailed = 0;
  411. var failedProducts = [];
  412. // Split products into batches
  413. for (var i = 0; i < productIds.length; i += batchSize) {
  414. batches.push(productIds.slice(i, i + batchSize));
  415. }
  416. console.log('STUDIOU WC: Processing ' + batches.length + ' batches of products');
  417. var currentBatch = 0;
  418. function processBatch() {
  419. if (currentBatch >= batches.length) {
  420. // All batches completed
  421. console.log('STUDIOU WC: All batches completed');
  422. onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner);
  423. return;
  424. }
  425. var batch = batches[currentBatch];
  426. var progress = Math.round((currentBatch / batches.length) * 100);
  427. $('#studiou-wcpcm-delete-progress-text').text(
  428. 'Deleting products... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
  429. );
  430. updateProgressBar(progress);
  431. // Send batch delete request
  432. $.ajax({
  433. url: studiouWcpcm.ajaxUrl,
  434. type: 'POST',
  435. data: {
  436. action: 'studiou_wcpcm_delete_products_batch',
  437. product_ids: batch,
  438. nonce: studiouWcpcm.nonce
  439. },
  440. success: function(response) {
  441. if (response.success) {
  442. totalDeleted += response.data.deleted_count;
  443. totalFailed += response.data.failed_count;
  444. failedProducts = failedProducts.concat(response.data.failed_products);
  445. console.log('STUDIOU WC: Batch ' + currentBatch + ' completed - Deleted: ' +
  446. response.data.deleted_count + ', Failed: ' + response.data.failed_count);
  447. // Process next batch
  448. currentBatch++;
  449. processBatch();
  450. } else {
  451. showNotice('error', response.data.message);
  452. $('.studiou-wcpcm-delete-progress').hide();
  453. $submitBtn.prop('disabled', false);
  454. $spinner.css('visibility', 'hidden');
  455. }
  456. },
  457. error: function(xhr, status, error) {
  458. console.error('STUDIOU WC: Batch delete AJAX error:', status, error);
  459. showNotice('error', 'Error deleting batch: ' + error);
  460. $('.studiou-wcpcm-delete-progress').hide();
  461. $submitBtn.prop('disabled', false);
  462. $spinner.css('visibility', 'hidden');
  463. }
  464. });
  465. }
  466. // Start processing batches
  467. processBatch();
  468. }
  469. /**
  470. * Handle deletion completion
  471. */
  472. function onDeletionComplete(totalDeleted, totalFailed, failedProducts, $submitBtn, $spinner) {
  473. // Update progress bar to 100%
  474. updateProgressBar(100);
  475. $('#studiou-wcpcm-delete-progress-text').text('Deletion complete!');
  476. // Show results
  477. var message = '<p><strong>Deletion Summary:</strong></p>';
  478. message += '<ul>';
  479. message += '<li>Total products deleted: ' + totalDeleted + '</li>';
  480. if (totalFailed > 0) {
  481. message += '<li>Failed to delete: ' + totalFailed + '</li>';
  482. if (failedProducts.length > 0) {
  483. message += '<li>Failed product IDs: ' + failedProducts.join(', ') + '</li>';
  484. }
  485. }
  486. message += '</ul>';
  487. $('#studiou-wcpcm-delete-message').html(message);
  488. $('.studiou-wcpcm-delete-results').show();
  489. // Hide progress after a delay
  490. setTimeout(function() {
  491. $('.studiou-wcpcm-delete-progress').fadeOut();
  492. }, 2000);
  493. if (totalDeleted > 0) {
  494. showNotice('success', (studiouWcpcm.i18n.deleteSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' products');
  495. // Reload page after 3 seconds
  496. setTimeout(function() {
  497. location.reload();
  498. }, 3000);
  499. } else {
  500. showNotice('error', studiouWcpcm.i18n.deleteError || 'Failed to delete any products');
  501. }
  502. $submitBtn.prop('disabled', false);
  503. $spinner.css('visibility', 'hidden');
  504. }
  505. /**
  506. * Update progress bar
  507. */
  508. function updateProgressBar(percentage) {
  509. $('#studiou-wcpcm-delete-progress-bar').css('width', percentage + '%');
  510. $('#studiou-wcpcm-delete-progress-bar').attr('data-progress', percentage + '%');
  511. }
  512. /**
  513. * Initialize clear media categories form
  514. */
  515. function initClearMediaForm() {
  516. console.log('STUDIOU WC: Initializing clear media form handlers');
  517. // Check all button handler
  518. $('#studiou-wcpcm-clear-media-check-all').on('click', function(e) {
  519. e.preventDefault();
  520. console.log('STUDIOU WC: Clear media check all button clicked');
  521. $('#clear_media_categories_list input[type="checkbox"]').prop('checked', true);
  522. });
  523. // Uncheck all button handler
  524. $('#studiou-wcpcm-clear-media-uncheck-all').on('click', function(e) {
  525. e.preventDefault();
  526. console.log('STUDIOU WC: Clear media uncheck all button clicked');
  527. $('#clear_media_categories_list input[type="checkbox"]').prop('checked', false);
  528. });
  529. // Form submit handler
  530. $('#studiou-wcpcm-clear-media-form').on('submit', function(e) {
  531. e.preventDefault();
  532. console.log('STUDIOU WC: Clear media form submitted');
  533. // Get selected categories
  534. var selectedCategories = [];
  535. $('#clear_media_categories_list input[type="checkbox"]:checked').each(function() {
  536. selectedCategories.push($(this).val());
  537. });
  538. console.log('STUDIOU WC: Selected media categories:', selectedCategories);
  539. // Validate input
  540. if (selectedCategories.length === 0) {
  541. console.log('STUDIOU WC: No media categories selected');
  542. showNotice('error', studiouWcpcm.i18n.selectAtLeastOneCategory || 'Please select at least one category');
  543. return;
  544. }
  545. // Confirm deletion
  546. 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!')) {
  547. console.log('STUDIOU WC: User cancelled clear media');
  548. return;
  549. }
  550. // Show spinner
  551. var $submitBtn = $(this).find('#studiou-wcpcm-clear-media-button');
  552. var $spinner = $(this).find('.spinner');
  553. $submitBtn.prop('disabled', true);
  554. $spinner.css('visibility', 'visible');
  555. // Clear previous notices
  556. $('.studiou-wcpcm-notice-area').empty();
  557. // Hide results, show progress
  558. $('.studiou-wcpcm-clear-media-results').hide();
  559. $('.studiou-wcpcm-clear-media-progress').show();
  560. $('#studiou-wcpcm-clear-media-progress-text').text('Initializing...');
  561. updateClearMediaProgressBar(0);
  562. // Send AJAX request to get media IDs
  563. $.ajax({
  564. url: studiouWcpcm.ajaxUrl,
  565. type: 'POST',
  566. data: {
  567. action: 'studiou_wcpcm_clear_media',
  568. media_categories: selectedCategories,
  569. nonce: studiouWcpcm.nonce
  570. },
  571. success: function(response) {
  572. console.log('STUDIOU WC: Clear media AJAX response:', response);
  573. if (response.success) {
  574. var mediaIds = response.data.media_ids;
  575. var totalCount = response.data.total_count;
  576. console.log('STUDIOU WC: Total media files to delete:', totalCount);
  577. if (totalCount === 0) {
  578. showNotice('success', studiouWcpcm.i18n.noMediaFound || 'No media files found in selected categories');
  579. $('.studiou-wcpcm-clear-media-progress').hide();
  580. $submitBtn.prop('disabled', false);
  581. $spinner.css('visibility', 'hidden');
  582. return;
  583. }
  584. // Process media in batches
  585. processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner);
  586. } else {
  587. showNotice('error', response.data.message);
  588. $('.studiou-wcpcm-clear-media-progress').hide();
  589. $submitBtn.prop('disabled', false);
  590. $spinner.css('visibility', 'hidden');
  591. }
  592. },
  593. error: function(xhr, status, error) {
  594. console.error('STUDIOU WC: Clear media AJAX error:', status, error);
  595. console.error('STUDIOU WC: Response text:', xhr.responseText);
  596. showNotice('error', (studiouWcpcm.i18n.clearMediaError || 'Clear media operation error') + ': ' + error);
  597. $('.studiou-wcpcm-clear-media-progress').hide();
  598. $submitBtn.prop('disabled', false);
  599. $spinner.css('visibility', 'hidden');
  600. }
  601. });
  602. });
  603. }
  604. /**
  605. * Process media deletion in batches
  606. */
  607. function processMediaDeletionBatches(mediaIds, totalCount, $submitBtn, $spinner) {
  608. var batchSize = 10;
  609. var batches = [];
  610. var totalDeleted = 0;
  611. var totalFailed = 0;
  612. var failedMedia = [];
  613. // Split media into batches
  614. for (var i = 0; i < mediaIds.length; i += batchSize) {
  615. batches.push(mediaIds.slice(i, i + batchSize));
  616. }
  617. console.log('STUDIOU WC: Processing ' + batches.length + ' batches of media files');
  618. var currentBatch = 0;
  619. function processBatch() {
  620. if (currentBatch >= batches.length) {
  621. console.log('STUDIOU WC: All media batches completed');
  622. onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner);
  623. return;
  624. }
  625. var batch = batches[currentBatch];
  626. var progress = Math.round((currentBatch / batches.length) * 100);
  627. $('#studiou-wcpcm-clear-media-progress-text').text(
  628. 'Deleting media files... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
  629. );
  630. updateClearMediaProgressBar(progress);
  631. $.ajax({
  632. url: studiouWcpcm.ajaxUrl,
  633. type: 'POST',
  634. data: {
  635. action: 'studiou_wcpcm_clear_media_batch',
  636. media_ids: batch,
  637. nonce: studiouWcpcm.nonce
  638. },
  639. success: function(response) {
  640. if (response.success) {
  641. totalDeleted += response.data.deleted_count;
  642. totalFailed += response.data.failed_count;
  643. failedMedia = failedMedia.concat(response.data.failed_media);
  644. console.log('STUDIOU WC: Media batch ' + currentBatch + ' completed - Deleted: ' +
  645. response.data.deleted_count + ', Failed: ' + response.data.failed_count);
  646. currentBatch++;
  647. processBatch();
  648. } else {
  649. showNotice('error', response.data.message);
  650. $('.studiou-wcpcm-clear-media-progress').hide();
  651. $submitBtn.prop('disabled', false);
  652. $spinner.css('visibility', 'hidden');
  653. }
  654. },
  655. error: function(xhr, status, error) {
  656. console.error('STUDIOU WC: Media batch delete AJAX error:', status, error);
  657. showNotice('error', 'Error deleting media batch: ' + error);
  658. $('.studiou-wcpcm-clear-media-progress').hide();
  659. $submitBtn.prop('disabled', false);
  660. $spinner.css('visibility', 'hidden');
  661. }
  662. });
  663. }
  664. processBatch();
  665. }
  666. /**
  667. * Handle media deletion completion
  668. */
  669. function onMediaDeletionComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner) {
  670. updateClearMediaProgressBar(100);
  671. $('#studiou-wcpcm-clear-media-progress-text').text('Deletion complete!');
  672. var message = '<p><strong>Deletion Summary:</strong></p>';
  673. message += '<ul>';
  674. message += '<li>Total media files deleted: ' + totalDeleted + '</li>';
  675. if (totalFailed > 0) {
  676. message += '<li>Failed to delete: ' + totalFailed + '</li>';
  677. if (failedMedia.length > 0) {
  678. message += '<li>Failed media IDs: ' + failedMedia.join(', ') + '</li>';
  679. }
  680. }
  681. message += '</ul>';
  682. $('#studiou-wcpcm-clear-media-message').html(message);
  683. $('.studiou-wcpcm-clear-media-results').show();
  684. setTimeout(function() {
  685. $('.studiou-wcpcm-clear-media-progress').fadeOut();
  686. }, 2000);
  687. if (totalDeleted > 0) {
  688. showNotice('success', (studiouWcpcm.i18n.clearMediaSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' media files');
  689. setTimeout(function() {
  690. location.reload();
  691. }, 3000);
  692. } else {
  693. showNotice('error', studiouWcpcm.i18n.clearMediaError || 'Failed to delete any media files');
  694. }
  695. $submitBtn.prop('disabled', false);
  696. $spinner.css('visibility', 'hidden');
  697. }
  698. /**
  699. * Update clear media progress bar
  700. */
  701. function updateClearMediaProgressBar(percentage) {
  702. $('#studiou-wcpcm-clear-media-progress-bar').css('width', percentage + '%');
  703. $('#studiou-wcpcm-clear-media-progress-bar').attr('data-progress', percentage + '%');
  704. }
  705. /**
  706. * Initialize remove unassigned media form
  707. */
  708. function initRemoveUnassignedMediaForm() {
  709. console.log('STUDIOU WC: Initializing remove unassigned media form handlers');
  710. $('#studiou-wcpcm-remove-unassigned-media-form').on('submit', function(e) {
  711. e.preventDefault();
  712. console.log('STUDIOU WC: Remove unassigned media form submitted');
  713. if (!confirm(studiouWcpcm.i18n.confirmRemoveUnassigned || 'Are you sure you want to permanently delete ALL unused uncategorized media files? This action cannot be undone!')) {
  714. return;
  715. }
  716. var $submitBtn = $(this).find('#studiou-wcpcm-remove-unassigned-media-button');
  717. var $spinner = $(this).find('.spinner');
  718. $submitBtn.prop('disabled', true);
  719. $spinner.css('visibility', 'visible');
  720. $('.studiou-wcpcm-notice-area').empty();
  721. $('.studiou-wcpcm-remove-unassigned-media-results').hide();
  722. $('.studiou-wcpcm-remove-unassigned-media-progress').show();
  723. $('#studiou-wcpcm-remove-unassigned-media-progress-text').text('Initializing...');
  724. updateRemoveUnassignedProgressBar(0);
  725. $.ajax({
  726. url: studiouWcpcm.ajaxUrl,
  727. type: 'POST',
  728. data: {
  729. action: 'studiou_wcpcm_remove_unassigned_media',
  730. nonce: studiouWcpcm.nonce
  731. },
  732. success: function(response) {
  733. console.log('STUDIOU WC: Remove unassigned media response:', response);
  734. if (response.success) {
  735. var mediaIds = response.data.media_ids;
  736. var totalCount = response.data.total_count;
  737. if (totalCount === 0) {
  738. showNotice('success', studiouWcpcm.i18n.noUnassignedMedia || 'No unused uncategorized media files found');
  739. $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
  740. $submitBtn.prop('disabled', false);
  741. $spinner.css('visibility', 'hidden');
  742. return;
  743. }
  744. processUnassignedMediaBatches(mediaIds, totalCount, $submitBtn, $spinner);
  745. } else {
  746. showNotice('error', response.data.message);
  747. $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
  748. $submitBtn.prop('disabled', false);
  749. $spinner.css('visibility', 'hidden');
  750. }
  751. },
  752. error: function(xhr, status, error) {
  753. console.error('STUDIOU WC: Remove unassigned media error:', status, error);
  754. showNotice('error', (studiouWcpcm.i18n.removeUnassignedError || 'Error') + ': ' + error);
  755. $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
  756. $submitBtn.prop('disabled', false);
  757. $spinner.css('visibility', 'hidden');
  758. }
  759. });
  760. });
  761. }
  762. /**
  763. * Process unassigned media deletion in batches
  764. */
  765. function processUnassignedMediaBatches(mediaIds, totalCount, $submitBtn, $spinner) {
  766. var batchSize = 10;
  767. var batches = [];
  768. var totalDeleted = 0;
  769. var totalFailed = 0;
  770. var failedMedia = [];
  771. for (var i = 0; i < mediaIds.length; i += batchSize) {
  772. batches.push(mediaIds.slice(i, i + batchSize));
  773. }
  774. var currentBatch = 0;
  775. function processBatch() {
  776. if (currentBatch >= batches.length) {
  777. onUnassignedMediaComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner);
  778. return;
  779. }
  780. var batch = batches[currentBatch];
  781. var progress = Math.round((currentBatch / batches.length) * 100);
  782. $('#studiou-wcpcm-remove-unassigned-media-progress-text').text(
  783. 'Deleting media files... ' + (currentBatch * batchSize) + ' of ' + totalCount + ' processed'
  784. );
  785. updateRemoveUnassignedProgressBar(progress);
  786. $.ajax({
  787. url: studiouWcpcm.ajaxUrl,
  788. type: 'POST',
  789. data: {
  790. action: 'studiou_wcpcm_remove_unassigned_media_batch',
  791. media_ids: batch,
  792. nonce: studiouWcpcm.nonce
  793. },
  794. success: function(response) {
  795. if (response.success) {
  796. totalDeleted += response.data.deleted_count;
  797. totalFailed += response.data.failed_count;
  798. failedMedia = failedMedia.concat(response.data.failed_media);
  799. currentBatch++;
  800. processBatch();
  801. } else {
  802. showNotice('error', response.data.message);
  803. $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
  804. $submitBtn.prop('disabled', false);
  805. $spinner.css('visibility', 'hidden');
  806. }
  807. },
  808. error: function(xhr, status, error) {
  809. console.error('STUDIOU WC: Unassigned media batch error:', status, error);
  810. showNotice('error', 'Error deleting batch: ' + error);
  811. $('.studiou-wcpcm-remove-unassigned-media-progress').hide();
  812. $submitBtn.prop('disabled', false);
  813. $spinner.css('visibility', 'hidden');
  814. }
  815. });
  816. }
  817. processBatch();
  818. }
  819. /**
  820. * Handle unassigned media deletion completion
  821. */
  822. function onUnassignedMediaComplete(totalDeleted, totalFailed, failedMedia, $submitBtn, $spinner) {
  823. updateRemoveUnassignedProgressBar(100);
  824. $('#studiou-wcpcm-remove-unassigned-media-progress-text').text('Deletion complete!');
  825. var message = '<p><strong>Deletion Summary:</strong></p>';
  826. message += '<ul>';
  827. message += '<li>Total media files deleted: ' + totalDeleted + '</li>';
  828. if (totalFailed > 0) {
  829. message += '<li>Failed to delete: ' + totalFailed + '</li>';
  830. if (failedMedia.length > 0) {
  831. message += '<li>Failed media IDs: ' + failedMedia.join(', ') + '</li>';
  832. }
  833. }
  834. message += '</ul>';
  835. $('#studiou-wcpcm-remove-unassigned-media-message').html(message);
  836. $('.studiou-wcpcm-remove-unassigned-media-results').show();
  837. setTimeout(function() {
  838. $('.studiou-wcpcm-remove-unassigned-media-progress').fadeOut();
  839. }, 2000);
  840. if (totalDeleted > 0) {
  841. showNotice('success', (studiouWcpcm.i18n.removeUnassignedSuccess || 'Successfully deleted') + ' ' + totalDeleted + ' media files');
  842. setTimeout(function() {
  843. location.reload();
  844. }, 3000);
  845. } else {
  846. showNotice('error', studiouWcpcm.i18n.removeUnassignedError || 'Failed to delete any media files');
  847. }
  848. $submitBtn.prop('disabled', false);
  849. $spinner.css('visibility', 'hidden');
  850. }
  851. /**
  852. * Update remove unassigned media progress bar
  853. */
  854. function updateRemoveUnassignedProgressBar(percentage) {
  855. $('#studiou-wcpcm-remove-unassigned-media-progress-bar').css('width', percentage + '%');
  856. $('#studiou-wcpcm-remove-unassigned-media-progress-bar').attr('data-progress', percentage + '%');
  857. }
  858. /**
  859. * Show notice message
  860. *
  861. * @param {string} type Notice type (success, error)
  862. * @param {string} message Notice message
  863. */
  864. function showNotice(type, message) {
  865. var $notice = $('<div class="studiou-wcpcm-notice studiou-wcpcm-notice-' + type + '"></div>').text(message);
  866. $('.studiou-wcpcm-notice-area').append($notice);
  867. // Scroll to notice
  868. $('html, body').animate({
  869. scrollTop: $('.studiou-wcpcm-notice-area').offset().top - 50
  870. }, 500);
  871. }
  872. /**
  873. * Initialize product import form
  874. */
  875. function initProductImportForm() {
  876. console.log('STUDIOU WC: Initializing product import form handlers');
  877. // Global variables for batch processing
  878. var importTransientKey = null;
  879. var importTotal = 0;
  880. var importProcessed = 0;
  881. var importSuccess = 0;
  882. var importFailed = 0;
  883. var importSkipped = 0;
  884. var importMessages = [];
  885. var importFailedCsv = '';
  886. $('#studiou-wcpcm-product-import-form').on('submit', function(e) {
  887. e.preventDefault();
  888. console.log('STUDIOU WC: Product import form submitted');
  889. // Validate file is selected
  890. var fileInput = $('#import_file')[0];
  891. if (!fileInput.files || !fileInput.files[0]) {
  892. showNotice('error', 'Please select a CSV file to import');
  893. return;
  894. }
  895. // Show spinner and progress
  896. var $submitBtn = $(this).find('#studiou-wcpcm-product-import-button');
  897. var $spinner = $(this).find('.spinner');
  898. $submitBtn.prop('disabled', true);
  899. $spinner.css('visibility', 'visible');
  900. // Clear previous results
  901. $('.studiou-wcpcm-notice-area').empty();
  902. $('.studiou-wcpcm-product-import-results').hide();
  903. $('.studiou-wcpcm-product-import-failed').hide();
  904. // Reset counters
  905. importTransientKey = null;
  906. importTotal = 0;
  907. importProcessed = 0;
  908. importSuccess = 0;
  909. importFailed = 0;
  910. importSkipped = 0;
  911. importMessages = [];
  912. importFailedCsv = '';
  913. // Show progress bar
  914. $('.studiou-wcpcm-product-import-progress').show();
  915. $('#studiou-wcpcm-product-import-progress-text').text('Parsing CSV file...');
  916. updateProductImportProgressBar(0);
  917. // Step 1: Parse CSV file
  918. var formData = new FormData(this);
  919. formData.append('action', 'studiou_wcpcm_product_import_parse');
  920. formData.append('nonce', studiouWcpcm.nonce);
  921. $.ajax({
  922. url: studiouWcpcm.ajaxUrl,
  923. type: 'POST',
  924. data: formData,
  925. processData: false,
  926. contentType: false,
  927. success: function(response) {
  928. console.log('STUDIOU WC: Product import parse response:', response);
  929. if (response.success) {
  930. importTransientKey = response.data.transient_key;
  931. importTotal = response.data.total;
  932. // Start batch processing
  933. processBatch(0, $submitBtn, $spinner);
  934. } else {
  935. showNotice('error', response.data.message || 'Parse failed');
  936. $('.studiou-wcpcm-product-import-progress').hide();
  937. $submitBtn.prop('disabled', false);
  938. $spinner.css('visibility', 'hidden');
  939. }
  940. },
  941. error: function(xhr, status, error) {
  942. console.error('STUDIOU WC: Product import parse error:', status, error);
  943. console.error('STUDIOU WC: Response text:', xhr.responseText);
  944. showNotice('error', 'Product import error: ' + error);
  945. $('.studiou-wcpcm-product-import-progress').hide();
  946. $submitBtn.prop('disabled', false);
  947. $spinner.css('visibility', 'hidden');
  948. }
  949. });
  950. });
  951. // Process batch of products
  952. function processBatch(offset, $submitBtn, $spinner) {
  953. console.log('STUDIOU WC: Processing batch at offset', offset);
  954. $.ajax({
  955. url: studiouWcpcm.ajaxUrl,
  956. type: 'POST',
  957. data: {
  958. action: 'studiou_wcpcm_product_import_batch',
  959. nonce: studiouWcpcm.nonce,
  960. transient_key: importTransientKey,
  961. offset: offset
  962. },
  963. success: function(response) {
  964. console.log('STUDIOU WC: Batch response:', response);
  965. if (response.success) {
  966. // Accumulate results
  967. importSuccess += response.data.success;
  968. importFailed += response.data.failed;
  969. importSkipped += response.data.skipped;
  970. importProcessed = response.data.processed;
  971. importTotal = response.data.total;
  972. importMessages = importMessages.concat(response.data.messages);
  973. if (response.data.failed_csv) {
  974. importFailedCsv = response.data.failed_csv;
  975. }
  976. // Update progress
  977. var percent = (importProcessed / importTotal) * 100;
  978. updateProductImportProgressBar(percent);
  979. $('#studiou-wcpcm-product-import-progress-text').text(
  980. 'Processing: ' + importProcessed + ' / ' + importTotal + ' products'
  981. );
  982. // Check if complete
  983. if (importProcessed >= importTotal) {
  984. // Import complete
  985. $('#studiou-wcpcm-product-import-progress-text').text('Complete!');
  986. showNotice('success', 'Product import completed!');
  987. // Show results
  988. var message = '<p><strong>Import Summary:</strong></p>';
  989. message += '<ul>';
  990. message += '<li>Successful: ' + importSuccess + '</li>';
  991. message += '<li>Failed: ' + importFailed + '</li>';
  992. message += '<li>Skipped: ' + importSkipped + '</li>';
  993. message += '</ul>';
  994. $('#studiou-wcpcm-product-import-message').html(message);
  995. // Show detailed messages
  996. if (importMessages.length > 0) {
  997. var details = '<pre>' + importMessages.join('\n') + '</pre>';
  998. $('#studiou-wcpcm-product-import-details-content').html(details);
  999. }
  1000. $('.studiou-wcpcm-product-import-results').show();
  1001. // Show save failed button if there are failed items
  1002. if (importFailed > 0 && importFailedCsv) {
  1003. window.studiouWcpcmFailedCsv = importFailedCsv;
  1004. $('.studiou-wcpcm-product-import-failed').show();
  1005. }
  1006. // Hide progress after delay
  1007. setTimeout(function() {
  1008. $('.studiou-wcpcm-product-import-progress').fadeOut();
  1009. }, 2000);
  1010. $submitBtn.prop('disabled', false);
  1011. $spinner.css('visibility', 'hidden');
  1012. } else {
  1013. // Process next batch
  1014. processBatch(importProcessed, $submitBtn, $spinner);
  1015. }
  1016. } else {
  1017. showNotice('error', response.data.message || 'Batch processing failed');
  1018. $('.studiou-wcpcm-product-import-progress').hide();
  1019. $submitBtn.prop('disabled', false);
  1020. $spinner.css('visibility', 'hidden');
  1021. }
  1022. },
  1023. error: function(xhr, status, error) {
  1024. console.error('STUDIOU WC: Batch processing error:', status, error);
  1025. showNotice('error', 'Batch processing error: ' + error);
  1026. $('.studiou-wcpcm-product-import-progress').hide();
  1027. $submitBtn.prop('disabled', false);
  1028. $spinner.css('visibility', 'hidden');
  1029. }
  1030. });
  1031. }
  1032. // Save failed products button handler
  1033. $('#studiou-wcpcm-save-failed-products').on('click', function(e) {
  1034. e.preventDefault();
  1035. if (window.studiouWcpcmFailedCsv) {
  1036. var blob = new Blob([window.studiouWcpcmFailedCsv], { type: 'text/csv;charset=utf-8;' });
  1037. var url = URL.createObjectURL(blob);
  1038. var link = document.createElement('a');
  1039. link.setAttribute('href', url);
  1040. link.setAttribute('download', 'failed-products-' + Date.now() + '.csv');
  1041. link.style.visibility = 'hidden';
  1042. document.body.appendChild(link);
  1043. link.click();
  1044. document.body.removeChild(link);
  1045. }
  1046. });
  1047. }
  1048. /**
  1049. * Initialize product export form
  1050. */
  1051. function initProductExportForm() {
  1052. console.log('STUDIOU WC: Initializing product export form handlers');
  1053. // Select all button handler
  1054. $('#studiou-wcpcm-export-select-all').on('click', function(e) {
  1055. e.preventDefault();
  1056. console.log('STUDIOU WC: Export select all button clicked');
  1057. $('#export_categories_list input[type="checkbox"]').prop('checked', true);
  1058. });
  1059. // Deselect all button handler
  1060. $('#studiou-wcpcm-export-deselect-all').on('click', function(e) {
  1061. e.preventDefault();
  1062. console.log('STUDIOU WC: Export deselect all button clicked');
  1063. $('#export_categories_list input[type="checkbox"]').prop('checked', false);
  1064. });
  1065. // Form submit handler
  1066. $('#studiou-wcpcm-product-export-form').on('submit', function(e) {
  1067. e.preventDefault();
  1068. console.log('STUDIOU WC: Product export form submitted');
  1069. // Get selected categories
  1070. var selectedCategories = [];
  1071. $('#export_categories_list input[type="checkbox"]:checked').each(function() {
  1072. selectedCategories.push($(this).val());
  1073. });
  1074. console.log('STUDIOU WC: Selected categories:', selectedCategories);
  1075. // Validate input
  1076. if (selectedCategories.length === 0) {
  1077. console.log('STUDIOU WC: No categories selected');
  1078. showNotice('error', 'Please select at least one category');
  1079. return;
  1080. }
  1081. // Show spinner
  1082. var $submitBtn = $(this).find('#studiou-wcpcm-product-export-button');
  1083. var $spinner = $(this).find('.spinner');
  1084. $submitBtn.prop('disabled', true);
  1085. $spinner.css('visibility', 'visible');
  1086. // Clear previous notices
  1087. $('.studiou-wcpcm-notice-area').empty();
  1088. $('.studiou-wcpcm-product-export-results').hide();
  1089. // Debug: Log AJAX request details
  1090. console.log('STUDIOU WC: Sending product export AJAX request to:', studiouWcpcm.ajaxUrl);
  1091. console.log('STUDIOU WC: Nonce:', studiouWcpcm.nonce);
  1092. // Send AJAX request
  1093. $.ajax({
  1094. url: studiouWcpcm.ajaxUrl,
  1095. type: 'POST',
  1096. data: {
  1097. action: 'studiou_wcpcm_product_export',
  1098. export_categories: selectedCategories,
  1099. nonce: studiouWcpcm.nonce
  1100. },
  1101. success: function(response) {
  1102. console.log('STUDIOU WC: Product export AJAX response:', response);
  1103. if (response.success) {
  1104. showNotice('success', 'Export successful!');
  1105. // Show results
  1106. $('#studiou-wcpcm-product-export-message').html('<p>' + response.data.message + '</p>');
  1107. $('#studiou-wcpcm-download-product-export').attr('href', response.data.download_url);
  1108. $('.studiou-wcpcm-product-export-results').show();
  1109. } else {
  1110. showNotice('error', response.data.message || 'Export failed');
  1111. }
  1112. },
  1113. error: function(xhr, status, error) {
  1114. console.error('STUDIOU WC: Product export AJAX error:', status, error);
  1115. console.error('STUDIOU WC: Response text:', xhr.responseText);
  1116. showNotice('error', 'Product export error: ' + error);
  1117. },
  1118. complete: function() {
  1119. // Hide spinner
  1120. $submitBtn.prop('disabled', false);
  1121. $spinner.css('visibility', 'hidden');
  1122. }
  1123. });
  1124. });
  1125. }
  1126. /**
  1127. * Update product import progress bar
  1128. */
  1129. function updateProductImportProgressBar(percentage) {
  1130. $('#studiou-wcpcm-product-import-progress-bar').css('width', percentage + '%');
  1131. $('#studiou-wcpcm-product-import-progress-bar').attr('data-progress', Math.round(percentage) + '%');
  1132. }
  1133. // Additional debug: Check if elements exist after DOM load
  1134. $(window).on('load', function() {
  1135. console.log('STUDIOU WC: Window loaded');
  1136. console.log('STUDIOU WC: Move form exists:', $('#studiou-wcpcm-move-form').length > 0);
  1137. console.log('STUDIOU WC: Move button exists:', $('#studiou-wcpcm-move-button').length > 0);
  1138. console.log('STUDIOU WC: Source select exists:', $('#source_category').length > 0);
  1139. console.log('STUDIOU WC: Target select exists:', $('#target_category').length > 0);
  1140. console.log('STUDIOU WC: Batch description form exists:', $('#studiou-wcpcm-batch-description-form').length > 0);
  1141. console.log('STUDIOU WC: Batch description button exists:', $('#studiou-wcpcm-batch-description-button').length > 0);
  1142. console.log('STUDIOU WC: Delete products form exists:', $('#studiou-wcpcm-delete-products-form').length > 0);
  1143. console.log('STUDIOU WC: Product import form exists:', $('#studiou-wcpcm-product-import-form').length > 0);
  1144. console.log('STUDIOU WC: Product export form exists:', $('#studiou-wcpcm-product-export-form').length > 0);
  1145. console.log('STUDIOU WC: Clear media form exists:', $('#studiou-wcpcm-clear-media-form').length > 0);
  1146. console.log('STUDIOU WC: UPVP form exists:', $('#studiou-wcpcm-upvp-form').length > 0);
  1147. });
  1148. /**
  1149. * Initialize Update Product Variant Prices form (UPVP) — v1.5.3
  1150. */
  1151. function initUpdateVariantPricesForm() {
  1152. var $form = $('#studiou-wcpcm-upvp-form');
  1153. var $catList = $('#upvp_categories_list');
  1154. var $attrSelect = $('#upvp_attribute');
  1155. var $valueSelect = $('#upvp_attribute_value');
  1156. var $newPrice = $('#upvp_new_price');
  1157. var $countLabel = $('#studiou-wcpcm-upvp-affected-count');
  1158. var $dryRunBtn = $('#studiou-wcpcm-upvp-dry-run-button');
  1159. var $applyBtn = $('#studiou-wcpcm-upvp-apply-button');
  1160. var $spinner = $form.find('.spinner');
  1161. var $resultsBox = $('.studiou-wcpcm-upvp-results');
  1162. var $resultsMsg = $('#studiou-wcpcm-upvp-message');
  1163. var i18n = (studiouWcpcm && studiouWcpcm.i18n) ? studiouWcpcm.i18n : {};
  1164. var countDebounceHandle = null;
  1165. var countInFlight = false;
  1166. function getSelectedCategoryIds() {
  1167. var ids = [];
  1168. $catList.find('input[type="checkbox"]:checked').each(function() {
  1169. ids.push($(this).val());
  1170. });
  1171. return ids;
  1172. }
  1173. function setApplyEnabled(count) {
  1174. var enabled = (count > 0) && !countInFlight;
  1175. $dryRunBtn.prop('disabled', !enabled);
  1176. $applyBtn.prop('disabled', !enabled);
  1177. }
  1178. function loadAttributes() {
  1179. $attrSelect.prop('disabled', true).html(
  1180. '<option value="">' + (i18n.upvpLoadingAttributes || 'Loading attributes...') + '</option>'
  1181. );
  1182. $.ajax({
  1183. url: studiouWcpcm.ajaxUrl,
  1184. type: 'POST',
  1185. data: {
  1186. action: 'studiou_wcpcm_upvp_get_attributes',
  1187. nonce: studiouWcpcm.nonce
  1188. },
  1189. success: function(response) {
  1190. $attrSelect.empty();
  1191. $attrSelect.append('<option value="">' + (i18n.upvpSelectAttribute || '-- Select attribute --') + '</option>');
  1192. if (response.success && response.data && response.data.attributes) {
  1193. $.each(response.data.attributes, function(_, a) {
  1194. $attrSelect.append(
  1195. $('<option/>')
  1196. .val(a.key)
  1197. .attr('data-istax', a.is_taxonomy ? '1' : '0')
  1198. .text(a.label)
  1199. );
  1200. });
  1201. }
  1202. $attrSelect.prop('disabled', false);
  1203. },
  1204. error: function(xhr, status, error) {
  1205. console.error('STUDIOU WC UPVP: get_attributes failed', status, error);
  1206. $attrSelect.prop('disabled', false);
  1207. }
  1208. });
  1209. }
  1210. function loadValues() {
  1211. var key = $attrSelect.val();
  1212. $valueSelect.prop('disabled', true).empty();
  1213. $valueSelect.append('<option value="">' + (i18n.upvpLoadingValues || 'Loading values...') + '</option>');
  1214. if (!key) {
  1215. $valueSelect.empty();
  1216. $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
  1217. $valueSelect.prop('disabled', true);
  1218. refreshCount();
  1219. return;
  1220. }
  1221. $.ajax({
  1222. url: studiouWcpcm.ajaxUrl,
  1223. type: 'POST',
  1224. data: {
  1225. action: 'studiou_wcpcm_upvp_get_attribute_values',
  1226. nonce: studiouWcpcm.nonce,
  1227. attribute_key: key,
  1228. category_ids: getSelectedCategoryIds()
  1229. },
  1230. success: function(response) {
  1231. $valueSelect.empty();
  1232. $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
  1233. if (response.success && response.data && response.data.values) {
  1234. $.each(response.data.values, function(_, v) {
  1235. $valueSelect.append($('<option/>').val(v.value).text(v.label));
  1236. });
  1237. }
  1238. $valueSelect.prop('disabled', false);
  1239. refreshCount();
  1240. },
  1241. error: function(xhr, status, error) {
  1242. console.error('STUDIOU WC UPVP: get_attribute_values failed', status, error);
  1243. $valueSelect.empty();
  1244. $valueSelect.append('<option value="">' + (i18n.upvpSelectValue || '-- Select value --') + '</option>');
  1245. $valueSelect.prop('disabled', false);
  1246. }
  1247. });
  1248. }
  1249. function refreshCount() {
  1250. if (countDebounceHandle) {
  1251. clearTimeout(countDebounceHandle);
  1252. }
  1253. countDebounceHandle = setTimeout(doRefreshCount, 300);
  1254. }
  1255. function doRefreshCount() {
  1256. var cats = getSelectedCategoryIds();
  1257. var key = $attrSelect.val();
  1258. var val = $valueSelect.val();
  1259. if (!cats.length || !key || !val) {
  1260. $countLabel.text('0');
  1261. setApplyEnabled(0);
  1262. return;
  1263. }
  1264. countInFlight = true;
  1265. setApplyEnabled(0);
  1266. $.ajax({
  1267. url: studiouWcpcm.ajaxUrl,
  1268. type: 'POST',
  1269. data: {
  1270. action: 'studiou_wcpcm_upvp_count',
  1271. nonce: studiouWcpcm.nonce,
  1272. category_ids: cats,
  1273. attribute_key: key,
  1274. attribute_value: val
  1275. },
  1276. success: function(response) {
  1277. countInFlight = false;
  1278. if (response.success && response.data) {
  1279. var c = parseInt(response.data.count, 10) || 0;
  1280. $countLabel.text(c);
  1281. setApplyEnabled(c);
  1282. } else {
  1283. $countLabel.text('0');
  1284. setApplyEnabled(0);
  1285. }
  1286. },
  1287. error: function() {
  1288. countInFlight = false;
  1289. $countLabel.text('0');
  1290. setApplyEnabled(0);
  1291. }
  1292. });
  1293. }
  1294. function renderSampleTable(sample, newPriceLabel) {
  1295. if (!sample || !sample.length) return '';
  1296. var html = '<table class="studiou-wcpcm-upvp-preview-table">';
  1297. html += '<thead><tr>';
  1298. html += '<th>ID</th><th>SKU</th><th>Name</th><th>Parent</th><th>Current</th>';
  1299. if (newPriceLabel !== undefined) html += '<th>New</th>';
  1300. html += '</tr></thead><tbody>';
  1301. $.each(sample, function(_, r) {
  1302. html += '<tr>';
  1303. html += '<td>' + r.id + '</td>';
  1304. html += '<td>' + (r.sku || '') + '</td>';
  1305. html += '<td>' + (r.name || '') + '</td>';
  1306. html += '<td>' + (r.parent_name || '') + '</td>';
  1307. html += '<td>' + (r.current_price || '') + '</td>';
  1308. if (newPriceLabel !== undefined) html += '<td>' + newPriceLabel + '</td>';
  1309. html += '</tr>';
  1310. });
  1311. html += '</tbody></table>';
  1312. return html;
  1313. }
  1314. // Wire up Check All / Uncheck All
  1315. $('#studiou-wcpcm-upvp-check-all').on('click', function(e) {
  1316. e.preventDefault();
  1317. $catList.find('input[type="checkbox"]').prop('checked', true);
  1318. refreshCount();
  1319. });
  1320. $('#studiou-wcpcm-upvp-uncheck-all').on('click', function(e) {
  1321. e.preventDefault();
  1322. $catList.find('input[type="checkbox"]').prop('checked', false);
  1323. refreshCount();
  1324. });
  1325. $catList.on('change', 'input[type="checkbox"]', refreshCount);
  1326. $attrSelect.on('change', loadValues);
  1327. $valueSelect.on('change', refreshCount);
  1328. // Dry Run
  1329. $dryRunBtn.on('click', function(e) {
  1330. e.preventDefault();
  1331. var cats = getSelectedCategoryIds();
  1332. var key = $attrSelect.val();
  1333. var val = $valueSelect.val();
  1334. if (!cats.length) {
  1335. showNotice('error', i18n.selectAtLeastOneCategory || 'Please select at least one category');
  1336. return;
  1337. }
  1338. if (!key) {
  1339. showNotice('error', i18n.upvpSelectAttribute || 'Please select an attribute');
  1340. return;
  1341. }
  1342. if (!val) {
  1343. showNotice('error', i18n.upvpSelectValue || 'Please select an attribute value');
  1344. return;
  1345. }
  1346. $('.studiou-wcpcm-notice-area').empty();
  1347. $resultsBox.hide();
  1348. $spinner.css('visibility', 'visible');
  1349. $dryRunBtn.prop('disabled', true);
  1350. $applyBtn.prop('disabled', true);
  1351. $.ajax({
  1352. url: studiouWcpcm.ajaxUrl,
  1353. type: 'POST',
  1354. data: {
  1355. action: 'studiou_wcpcm_upvp_count',
  1356. nonce: studiouWcpcm.nonce,
  1357. category_ids: cats,
  1358. attribute_key: key,
  1359. attribute_value: val
  1360. },
  1361. success: function(response) {
  1362. if (response.success && response.data) {
  1363. var c = parseInt(response.data.count, 10) || 0;
  1364. var sample = response.data.sample || [];
  1365. var price = $newPrice.val();
  1366. var msg = '';
  1367. if (c === 0) {
  1368. msg = '<p>' + (i18n.upvpNoMatches || 'No variations match the current filter.') + '</p>';
  1369. } else {
  1370. var tpl = i18n.upvpDryRunComplete || 'Dry run complete: %d variations would be updated to %s.';
  1371. msg = '<p>' + tpl.replace('%d', c).replace('%s', price !== '' ? price : '—') + '</p>';
  1372. msg += renderSampleTable(sample, price !== '' ? price : undefined);
  1373. }
  1374. $resultsMsg.html(msg);
  1375. $resultsBox.show();
  1376. $countLabel.text(c);
  1377. setApplyEnabled(c);
  1378. } else {
  1379. showNotice('error', (response.data && response.data.message) || 'Dry run failed');
  1380. }
  1381. },
  1382. error: function(xhr, status, error) {
  1383. showNotice('error', 'Dry run error: ' + error);
  1384. },
  1385. complete: function() {
  1386. $spinner.css('visibility', 'hidden');
  1387. }
  1388. });
  1389. });
  1390. // Apply
  1391. $applyBtn.on('click', function(e) {
  1392. e.preventDefault();
  1393. var cats = getSelectedCategoryIds();
  1394. var key = $attrSelect.val();
  1395. var val = $valueSelect.val();
  1396. var price = $newPrice.val();
  1397. var count = parseInt($countLabel.text(), 10) || 0;
  1398. if (!cats.length) {
  1399. showNotice('error', i18n.selectAtLeastOneCategory || 'Please select at least one category');
  1400. return;
  1401. }
  1402. if (!key) {
  1403. showNotice('error', i18n.upvpSelectAttribute || 'Please select an attribute');
  1404. return;
  1405. }
  1406. if (!val) {
  1407. showNotice('error', i18n.upvpSelectValue || 'Please select an attribute value');
  1408. return;
  1409. }
  1410. if (price === '' || isNaN(parseFloat(price)) || parseFloat(price) < 0) {
  1411. showNotice('error', i18n.upvpInvalidPrice || 'Please enter a valid new price');
  1412. return;
  1413. }
  1414. var confirmTpl = i18n.upvpConfirmApply || 'Are you sure you want to update %d variations?';
  1415. if (!confirm(confirmTpl.replace('%d', count))) {
  1416. return;
  1417. }
  1418. $('.studiou-wcpcm-notice-area').empty();
  1419. $resultsBox.hide();
  1420. $spinner.css('visibility', 'visible');
  1421. $dryRunBtn.prop('disabled', true);
  1422. $applyBtn.prop('disabled', true);
  1423. $.ajax({
  1424. url: studiouWcpcm.ajaxUrl,
  1425. type: 'POST',
  1426. data: {
  1427. action: 'studiou_wcpcm_upvp_apply',
  1428. nonce: studiouWcpcm.nonce,
  1429. category_ids: cats,
  1430. attribute_key: key,
  1431. attribute_value: val,
  1432. new_price: price
  1433. },
  1434. success: function(response) {
  1435. if (response.success && response.data) {
  1436. showNotice('success', i18n.upvpApplySuccess || 'Variant prices updated successfully');
  1437. var html = '<p><strong>' + (response.data.message || '') + '</strong></p>';
  1438. if (response.data.failed_ids && response.data.failed_ids.length) {
  1439. html += '<p>Failed IDs: ' + response.data.failed_ids.join(', ') + '</p>';
  1440. }
  1441. $resultsMsg.html(html);
  1442. $resultsBox.show();
  1443. refreshCount();
  1444. } else {
  1445. showNotice('error', (response.data && response.data.message) || (i18n.upvpApplyError || 'Variant prices update error'));
  1446. }
  1447. },
  1448. error: function(xhr, status, error) {
  1449. showNotice('error', (i18n.upvpApplyError || 'Variant prices update error') + ': ' + error);
  1450. },
  1451. complete: function() {
  1452. $spinner.css('visibility', 'hidden');
  1453. $dryRunBtn.prop('disabled', false);
  1454. $applyBtn.prop('disabled', false);
  1455. }
  1456. });
  1457. });
  1458. // Initial load
  1459. loadAttributes();
  1460. setApplyEnabled(0);
  1461. }
  1462. })(jQuery);