admin.js 75 KB

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