admin.js 80 KB

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