frontend.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. (function ($) {
  2. 'use strict';
  3. $(document).ready(function () {
  4. var $uploadWrap = $('.studiou-fpp-upload-wrap');
  5. if (!$uploadWrap.length) {
  6. return;
  7. }
  8. var productId = $uploadWrap.data('product-id');
  9. var maxFileSize = parseInt($uploadWrap.data('max-file-size'), 10) || 50;
  10. var chunkSize = parseInt(studiouWcfppFront.chunkSize, 10) || 1048576;
  11. var uploadedAttachmentId = null;
  12. var uploadedFileRecordId = null;
  13. var isUploading = false;
  14. var originalGalleryImages = {};
  15. // Upload area elements
  16. var $dropzone = $uploadWrap.find('#studiou-fpp-dropzone');
  17. var $fileInput = $uploadWrap.find('#studiou-fpp-file-input');
  18. var $progress = $uploadWrap.find('.studiou-fpp-progress');
  19. var $progressFill = $uploadWrap.find('.studiou-fpp-progress-fill');
  20. var $progressText = $uploadWrap.find('.studiou-fpp-progress-text');
  21. var $preview = $uploadWrap.find('.studiou-fpp-preview');
  22. var $previewImg = $preview.find('img');
  23. var $previewName = $uploadWrap.find('.studiou-fpp-preview-name');
  24. var $removeBtn = $uploadWrap.find('.studiou-fpp-remove-file');
  25. var $messages = $uploadWrap.find('.studiou-fpp-messages');
  26. // ==========================================
  27. // Restore session state on page load
  28. // ==========================================
  29. if (typeof studiouWcfppSession !== 'undefined' && studiouWcfppSession.attachment_id) {
  30. uploadedAttachmentId = studiouWcfppSession.attachment_id;
  31. uploadedFileRecordId = studiouWcfppSession.file_record_id;
  32. showPreview(studiouWcfppSession.thumbnail_url, studiouWcfppSession.file_name);
  33. updateProductGallery(studiouWcfppSession.preview_url || studiouWcfppSession.thumbnail_url);
  34. }
  35. // ==========================================
  36. // Drag and drop
  37. // ==========================================
  38. $dropzone.on('dragover dragenter', function (e) {
  39. e.preventDefault();
  40. e.stopPropagation();
  41. $(this).addClass('studiou-fpp-dragover');
  42. });
  43. $dropzone.on('dragleave drop', function (e) {
  44. e.preventDefault();
  45. e.stopPropagation();
  46. $(this).removeClass('studiou-fpp-dragover');
  47. });
  48. $dropzone.on('drop', function (e) {
  49. var files = e.originalEvent.dataTransfer.files;
  50. if (files.length > 0) {
  51. handleFile(files[0]);
  52. }
  53. });
  54. $dropzone.on('click', function () {
  55. if (!isUploading) {
  56. $fileInput.trigger('click');
  57. }
  58. });
  59. $fileInput.on('change', function () {
  60. if (this.files.length > 0) {
  61. handleFile(this.files[0]);
  62. }
  63. });
  64. // Remove file
  65. $removeBtn.on('click', function () {
  66. removeUploadedFile();
  67. });
  68. // ==========================================
  69. // Upload logic
  70. // ==========================================
  71. function handleFile(file) {
  72. if (isUploading) return;
  73. var maxBytes = maxFileSize * 1024 * 1024;
  74. if (file.size > maxBytes) {
  75. showMessage(studiouWcfppFront.i18n.fileTooLarge.replace('%s', maxFileSize), 'error');
  76. return;
  77. }
  78. clearMessages();
  79. startChunkedUpload(file);
  80. }
  81. function startChunkedUpload(file) {
  82. isUploading = true;
  83. var totalChunks = Math.ceil(file.size / chunkSize);
  84. var uploadId = 'upload_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  85. var currentChunk = 0;
  86. $dropzone.hide();
  87. $progress.show();
  88. function uploadNextChunk() {
  89. var start = currentChunk * chunkSize;
  90. var end = Math.min(start + chunkSize, file.size);
  91. var blob = file.slice(start, end);
  92. var formData = new FormData();
  93. formData.append('action', 'studiou_wcfpp_upload_chunk');
  94. formData.append('nonce', studiouWcfppFront.nonce);
  95. formData.append('product_id', productId);
  96. formData.append('upload_id', uploadId);
  97. formData.append('chunk_index', currentChunk);
  98. formData.append('total_chunks', totalChunks);
  99. formData.append('file_name', file.name);
  100. formData.append('file_size', file.size);
  101. formData.append('chunk', blob, 'chunk');
  102. var isLastChunk = (currentChunk === totalChunks - 1);
  103. if (isLastChunk) {
  104. $progressFill.css('width', '100%');
  105. $progressText.text(studiouWcfppFront.i18n.processing || 'Processing...');
  106. }
  107. $.ajax({
  108. url: studiouWcfppFront.ajaxUrl,
  109. type: 'POST',
  110. data: formData,
  111. processData: false,
  112. contentType: false,
  113. timeout: isLastChunk ? 120000 : 30000,
  114. success: function (response) {
  115. if (response.success) {
  116. if (!isLastChunk) {
  117. currentChunk++;
  118. var percent = Math.round((currentChunk / totalChunks) * 100);
  119. $progressFill.css('width', percent + '%');
  120. $progressText.text(percent + '%');
  121. }
  122. if (response.data.complete) {
  123. uploadedAttachmentId = response.data.attachment_id;
  124. uploadedFileRecordId = response.data.file_record_id;
  125. storeInSession(
  126. response.data.attachment_id,
  127. response.data.file_record_id,
  128. response.data.file_name
  129. );
  130. showPreview(response.data.thumbnail_url, response.data.file_name);
  131. updateProductGallery(response.data.preview_url || response.data.thumbnail_url);
  132. $progress.hide();
  133. isUploading = false;
  134. } else {
  135. uploadNextChunk();
  136. }
  137. } else {
  138. uploadFailed(response.data ? response.data.message : studiouWcfppFront.i18n.uploadError);
  139. }
  140. },
  141. error: function () {
  142. uploadFailed(studiouWcfppFront.i18n.uploadError);
  143. }
  144. });
  145. }
  146. uploadNextChunk();
  147. }
  148. // ==========================================
  149. // Session management
  150. // ==========================================
  151. function storeInSession(attachmentId, fileRecordId, fileName) {
  152. $.ajax({
  153. url: studiouWcfppFront.ajaxUrl,
  154. type: 'POST',
  155. data: {
  156. action: 'studiou_wcfpp_set_upload_session',
  157. nonce: studiouWcfppFront.nonce,
  158. attachment_id: attachmentId,
  159. file_record_id: fileRecordId,
  160. file_name: fileName
  161. }
  162. });
  163. }
  164. function clearSession() {
  165. $.ajax({
  166. url: studiouWcfppFront.ajaxUrl,
  167. type: 'POST',
  168. data: {
  169. action: 'studiou_wcfpp_clear_upload_session',
  170. nonce: studiouWcfppFront.nonce
  171. }
  172. });
  173. }
  174. // ==========================================
  175. // Product gallery image replacement
  176. // ==========================================
  177. function updateProductGallery(imageUrl) {
  178. if (!imageUrl) return;
  179. var selectors = [
  180. '.woocommerce-product-gallery__image img',
  181. '.product .wp-post-image',
  182. '.product-image img',
  183. '.product-thumbnail img',
  184. '.entry-summary img.attachment-woocommerce_thumbnail',
  185. '.product-gallery img:first'
  186. ];
  187. var $img = null;
  188. for (var i = 0; i < selectors.length; i++) {
  189. $img = $(selectors[i]).first();
  190. if ($img.length) break;
  191. }
  192. if (!$img || !$img.length) return;
  193. if (!originalGalleryImages.src) {
  194. originalGalleryImages.src = $img.attr('src');
  195. originalGalleryImages.srcset = $img.attr('srcset') || '';
  196. originalGalleryImages.sizes = $img.attr('sizes') || '';
  197. var $link = $img.closest('a');
  198. if ($link.length) originalGalleryImages.href = $link.attr('href');
  199. }
  200. $img.attr('src', imageUrl).removeAttr('srcset').removeAttr('sizes');
  201. var $link = $img.closest('a');
  202. if ($link.length) $link.attr('href', imageUrl);
  203. }
  204. function restoreProductGallery() {
  205. if (!originalGalleryImages.src) return;
  206. var selectors = [
  207. '.woocommerce-product-gallery__image img',
  208. '.product .wp-post-image',
  209. '.product-image img',
  210. '.product-thumbnail img',
  211. '.entry-summary img.attachment-woocommerce_thumbnail',
  212. '.product-gallery img:first'
  213. ];
  214. var $img = null;
  215. for (var i = 0; i < selectors.length; i++) {
  216. $img = $(selectors[i]).first();
  217. if ($img.length) break;
  218. }
  219. if (!$img || !$img.length) return;
  220. $img.attr('src', originalGalleryImages.src);
  221. if (originalGalleryImages.srcset) $img.attr('srcset', originalGalleryImages.srcset);
  222. if (originalGalleryImages.sizes) $img.attr('sizes', originalGalleryImages.sizes);
  223. if (originalGalleryImages.href) $img.closest('a').attr('href', originalGalleryImages.href);
  224. originalGalleryImages = {};
  225. }
  226. // ==========================================
  227. // UI helpers
  228. // ==========================================
  229. function uploadFailed(message) {
  230. isUploading = false;
  231. $progress.hide();
  232. $dropzone.show();
  233. showMessage(message, 'error');
  234. $fileInput.val('');
  235. }
  236. function showPreview(thumbnailUrl, fileName) {
  237. if (thumbnailUrl) {
  238. $previewImg.attr('src', thumbnailUrl).show();
  239. } else {
  240. $previewImg.hide();
  241. }
  242. $previewName.text(fileName);
  243. $preview.show();
  244. $dropzone.hide();
  245. }
  246. function removeUploadedFile() {
  247. if (!uploadedFileRecordId) return;
  248. $.ajax({
  249. url: studiouWcfppFront.ajaxUrl,
  250. type: 'POST',
  251. data: {
  252. action: 'studiou_wcfpp_remove_upload',
  253. nonce: studiouWcfppFront.nonce,
  254. file_record_id: uploadedFileRecordId
  255. },
  256. success: function () {
  257. resetUpload();
  258. }
  259. });
  260. }
  261. function resetUpload() {
  262. uploadedAttachmentId = null;
  263. uploadedFileRecordId = null;
  264. clearSession();
  265. restoreProductGallery();
  266. $preview.hide();
  267. $previewImg.attr('src', '');
  268. $previewName.text('');
  269. $dropzone.show();
  270. $fileInput.val('');
  271. clearMessages();
  272. }
  273. function showMessage(text, type) {
  274. var cls = type === 'error' ? 'studiou-fpp-msg-error' : 'studiou-fpp-msg-success';
  275. $messages.html('<div class="studiou-fpp-msg ' + cls + '">' + escHtml(text) + '</div>');
  276. }
  277. function clearMessages() {
  278. $messages.empty();
  279. }
  280. function escHtml(str) {
  281. var div = document.createElement('div');
  282. div.appendChild(document.createTextNode(str));
  283. return div.innerHTML;
  284. }
  285. // ==========================================
  286. // Quantity discount tier display + live price update
  287. // ==========================================
  288. initQtyTiers();
  289. initVariantTableTiers();
  290. function initVariantTableTiers() {
  291. // Handles custom variant-table plugins (e.g. pvtfw / product-variant-table-for-woocommerce)
  292. // where each variation is rendered as a <tr> with its own qty input and price.
  293. var tierData = (typeof window.studiouFppTierData === 'object' && window.studiouFppTierData) ? window.studiouFppTierData : null;
  294. if (!tierData) {
  295. return;
  296. }
  297. var $table = $('table.variant').first();
  298. if (!$table.length) {
  299. return;
  300. }
  301. var i18n = studiouWcfppFront.i18n;
  302. $table.find('tbody > tr').each(function () {
  303. var $row = $(this);
  304. var $cartBtn = $row.find('.pvtfw_variant_table_cart_btn').first();
  305. var variantId = $cartBtn.length ? String($cartBtn.data('variant')) : '';
  306. if (!variantId) {
  307. var $qtyInput = $row.find('input.qty').first();
  308. variantId = $qtyInput.attr('id') || '';
  309. }
  310. if (!variantId || !tierData[variantId]) {
  311. return;
  312. }
  313. var cfg = tierData[variantId];
  314. var tiers = cfg.tiers || [];
  315. var basePrice = parseFloat(cfg.base_price) || 0;
  316. if (tiers.length === 0 || basePrice <= 0) {
  317. return;
  318. }
  319. var $priceCell = $row.find('td[data-title="Price"]').first();
  320. if (!$priceCell.length) $priceCell = $row.find('.woocommerce-Price-amount').first().closest('td');
  321. var $priceEl = $priceCell.find('.woocommerce-Price-amount').first();
  322. var $qty = $row.find('input.qty').first();
  323. if (!$priceEl.length || !$qty.length) {
  324. return;
  325. }
  326. // Append a compact tier summary beneath the price
  327. var tierListHtml = '<div class="studiou-fpp-row-tiers" title="' + escHtml(i18n.qtyTiersTitle) + '">';
  328. tierListHtml += '<span class="dashicons dashicons-tag"></span>';
  329. tierListHtml += '<span class="studiou-fpp-row-tiers-list">';
  330. for (var i = 0; i < tiers.length; i++) {
  331. var t = tiers[i];
  332. tierListHtml += '<span class="studiou-fpp-row-tier">' + t.from_qty + '+: −' + formatPercent(t.percent) + '</span>';
  333. }
  334. tierListHtml += '</span></div>';
  335. $priceCell.append(tierListHtml);
  336. // Store the original price HTML so we can revert when qty falls below the first tier
  337. if (!$priceEl.data('studiou-fpp-base-html')) {
  338. $priceEl.data('studiou-fpp-base-html', $priceEl.html());
  339. }
  340. // Bind qty change handlers to update this row's price display
  341. var handler = function () {
  342. updateRowPrice($row, tiers, basePrice, $priceEl, $qty);
  343. };
  344. $qty.on('input change keyup', handler);
  345. // pvtfw ± buttons sit next to the input; they dispatch change events on the input,
  346. // but some themes intercept them — bind click too
  347. $row.find('.qty-count').on('click', function () {
  348. setTimeout(handler, 0);
  349. });
  350. // Initial update (qty=1 usually, just to install the "Save X%" indicator if applicable)
  351. updateRowPrice($row, tiers, basePrice, $priceEl, $qty);
  352. });
  353. }
  354. function updateRowPrice($row, tiers, basePrice, $priceEl, $qty) {
  355. var qty = parseInt($qty.val(), 10) || 1;
  356. var tier = resolveTierSimple(tiers, qty);
  357. $row.find('.studiou-fpp-row-save-badge').remove();
  358. if (!tier || tier.percent <= 0) {
  359. // Revert to original HTML
  360. var base = $priceEl.data('studiou-fpp-base-html');
  361. if (base) {
  362. $priceEl.html(base);
  363. }
  364. return;
  365. }
  366. var unit = basePrice * (1 - tier.percent / 100);
  367. $priceEl.html(formatPriceInner(unit));
  368. var badge = '<span class="studiou-fpp-row-save-badge">−' + formatPercent(tier.percent) + '</span>';
  369. $priceEl.after(badge);
  370. }
  371. function resolveTierSimple(tiers, qty) {
  372. var match = null;
  373. for (var i = 0; i < tiers.length; i++) {
  374. if (tiers[i].from_qty <= qty) match = tiers[i];
  375. else break;
  376. }
  377. return match;
  378. }
  379. function formatPercent(percent) {
  380. var p = parseFloat(percent) || 0;
  381. var str = p.toFixed(2).replace(/\.?0+$/, '');
  382. return str + ' %';
  383. }
  384. function formatPriceInner(amount) {
  385. var curr = studiouWcfppFront.currency || {};
  386. var decimals = parseInt(curr.decimals, 10);
  387. if (isNaN(decimals)) decimals = 2;
  388. var decSep = curr.decimalSeparator || '.';
  389. var thouSep = curr.thousandSeparator || ',';
  390. var fmt = curr.priceFormat || '%1$s%2$s';
  391. var symbol = curr.symbol || '';
  392. var fixed = parseFloat(amount).toFixed(decimals);
  393. var parts = fixed.split('.');
  394. var intPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
  395. var decPart = parts.length > 1 ? parts[1] : '';
  396. var numStr = decPart ? intPart + decSep + decPart : intPart;
  397. var symbolHtml = '<span class="woocommerce-Price-currencySymbol">' + symbol + '</span>';
  398. return fmt.replace('%1$s', symbolHtml).replace('%2$s', numStr);
  399. }
  400. function initQtyTiers() {
  401. var $container = $('.studiou-fpp-qty-tiers-display');
  402. var $form = $('form.variations_form').first();
  403. if (!$container.length || !$form.length) {
  404. return;
  405. }
  406. var currentTiers = [];
  407. var currentBasePrice = 0;
  408. $form.on('found_variation', function (event, variation) {
  409. currentTiers = (variation && variation.studiou_fpp_qty_tiers) ? variation.studiou_fpp_qty_tiers : [];
  410. currentBasePrice = (variation && variation.studiou_fpp_base_price) ? parseFloat(variation.studiou_fpp_base_price) : 0;
  411. // WC re-renders .single_variation on every selection, so defer a tick to run after it
  412. setTimeout(function () {
  413. renderTierTable();
  414. updateDisplayedPrice();
  415. }, 0);
  416. });
  417. $form.on('reset_data', function () {
  418. currentTiers = [];
  419. currentBasePrice = 0;
  420. $container.hide().empty();
  421. });
  422. // Live price update on quantity change — broad listener so themes with non-standard
  423. // qty input placement still trigger the update.
  424. $(document).on('input change keyup', 'input.qty, input[name="quantity"]', function () {
  425. updateDisplayedPrice();
  426. });
  427. function renderTierTable() {
  428. if (!currentTiers || currentTiers.length === 0) {
  429. $container.hide().empty();
  430. return;
  431. }
  432. var i18n = studiouWcfppFront.i18n;
  433. var html = '<div class="studiou-fpp-qty-tiers-box">';
  434. html += '<h4><span class="dashicons dashicons-tag"></span> ' + escHtml(i18n.qtyTiersTitle || 'Quantity Discount') + '</h4>';
  435. html += '<table class="studiou-fpp-qty-tiers-table-display"><thead><tr>';
  436. html += '<th>' + escHtml(i18n.qtyTiersFromQty || 'From Qty') + '</th>';
  437. html += '<th>' + escHtml(i18n.qtyTiersDiscount || 'Discount') + '</th>';
  438. html += '<th>' + escHtml(i18n.qtyTiersUnitPrice || 'Unit Price') + '</th>';
  439. html += '</tr></thead><tbody>';
  440. for (var i = 0; i < currentTiers.length; i++) {
  441. var t = currentTiers[i];
  442. var unit = computeDiscounted(currentBasePrice, t.percent);
  443. html += '<tr data-from-qty="' + t.from_qty + '">';
  444. html += '<td>' + t.from_qty + '+</td>';
  445. html += '<td>' + formatPercent(t.percent) + '</td>';
  446. html += '<td>' + formatPrice(unit) + '</td>';
  447. html += '</tr>';
  448. }
  449. html += '</tbody></table></div>';
  450. $container.html(html).show();
  451. }
  452. function findPriceElement() {
  453. var selectors = [
  454. '.single_variation .woocommerce-variation-price .woocommerce-Price-amount',
  455. 'form.variations_form .woocommerce-variation-price .woocommerce-Price-amount',
  456. '.single_variation_wrap .woocommerce-Price-amount',
  457. 'form.variations_form .price .woocommerce-Price-amount'
  458. ];
  459. for (var i = 0; i < selectors.length; i++) {
  460. var $el = $(selectors[i]).first();
  461. if ($el.length) return $el;
  462. }
  463. return $();
  464. }
  465. function findQtyInput() {
  466. var $qty = $form.find('input.qty').first();
  467. if (!$qty.length) $qty = $('input.qty').first();
  468. if (!$qty.length) $qty = $('input[name="quantity"]').first();
  469. return $qty;
  470. }
  471. function updateDisplayedPrice() {
  472. if (!currentBasePrice || !currentTiers || currentTiers.length === 0) {
  473. highlightActiveTierRow(0);
  474. return;
  475. }
  476. var $qty = findQtyInput();
  477. var qty = $qty.length ? (parseInt($qty.val(), 10) || 1) : 1;
  478. var tier = resolveTier(currentTiers, qty);
  479. var unit = tier ? computeDiscounted(currentBasePrice, tier.percent) : currentBasePrice;
  480. var $wcPrice = findPriceElement();
  481. if ($wcPrice.length) {
  482. $wcPrice.html(formatPriceInner(unit));
  483. }
  484. highlightActiveTierRow(tier ? tier.from_qty : 0);
  485. }
  486. function highlightActiveTierRow(fromQty) {
  487. $container.find('tr').removeClass('studiou-fpp-qty-tier-active');
  488. if (fromQty > 0) {
  489. $container.find('tr[data-from-qty="' + fromQty + '"]').addClass('studiou-fpp-qty-tier-active');
  490. }
  491. }
  492. function resolveTier(tiers, qty) {
  493. var match = null;
  494. for (var i = 0; i < tiers.length; i++) {
  495. if (tiers[i].from_qty <= qty) {
  496. match = tiers[i];
  497. } else {
  498. break;
  499. }
  500. }
  501. return match;
  502. }
  503. function computeDiscounted(basePrice, percent) {
  504. var p = parseFloat(percent) || 0;
  505. if (p <= 0) return basePrice;
  506. return basePrice * (1 - p / 100);
  507. }
  508. function formatPercent(percent) {
  509. var p = parseFloat(percent) || 0;
  510. // Strip trailing zeros
  511. var str = p.toFixed(2).replace(/\.?0+$/, '');
  512. return str + ' %';
  513. }
  514. function formatPrice(amount) {
  515. return '<span class="woocommerce-Price-amount amount">' + formatPriceInner(amount) + '</span>';
  516. }
  517. function formatPriceInner(amount) {
  518. var curr = studiouWcfppFront.currency || {};
  519. var decimals = parseInt(curr.decimals, 10);
  520. if (isNaN(decimals)) decimals = 2;
  521. var decSep = curr.decimalSeparator || '.';
  522. var thouSep = curr.thousandSeparator || ',';
  523. var fmt = curr.priceFormat || '%1$s%2$s';
  524. var symbol = curr.symbol || '';
  525. var fixed = parseFloat(amount).toFixed(decimals);
  526. var parts = fixed.split('.');
  527. var intPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
  528. var decPart = parts.length > 1 ? parts[1] : '';
  529. var numStr = decPart ? intPart + decSep + decPart : intPart;
  530. var symbolHtml = '<span class="woocommerce-Price-currencySymbol">' + symbol + '</span>';
  531. return fmt.replace('%1$s', symbolHtml).replace('%2$s', numStr);
  532. }
  533. }
  534. });
  535. })(jQuery);