wc-product-import.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*global ajaxurl, wc_product_import_params */
  2. ;(function ( $, window ) {
  3. /**
  4. * productImportForm handles the import process.
  5. */
  6. var productImportForm = function( $form ) {
  7. this.$form = $form;
  8. this.xhr = false;
  9. this.mapping = wc_product_import_params.mapping;
  10. this.position = 0;
  11. this.file = wc_product_import_params.file;
  12. this.update_existing = wc_product_import_params.update_existing;
  13. this.delimiter = wc_product_import_params.delimiter;
  14. this.security = wc_product_import_params.import_nonce;
  15. // Number of import successes/failures.
  16. this.imported = 0;
  17. this.failed = 0;
  18. this.updated = 0;
  19. this.skipped = 0;
  20. // Initial state.
  21. this.$form.find('.woocommerce-importer-progress').val( 0 );
  22. this.run_import = this.run_import.bind( this );
  23. // Start importing.
  24. this.run_import();
  25. };
  26. /**
  27. * Run the import in batches until finished.
  28. */
  29. productImportForm.prototype.run_import = function() {
  30. var $this = this;
  31. $.ajax( {
  32. type: 'POST',
  33. url: ajaxurl,
  34. data: {
  35. action : 'woocommerce_do_ajax_product_import',
  36. position : $this.position,
  37. mapping : $this.mapping,
  38. file : $this.file,
  39. update_existing : $this.update_existing,
  40. delimiter : $this.delimiter,
  41. security : $this.security
  42. },
  43. dataType: 'json',
  44. success: function( response ) {
  45. if ( response.success ) {
  46. $this.position = response.data.position;
  47. $this.imported += response.data.imported;
  48. $this.failed += response.data.failed;
  49. $this.updated += response.data.updated;
  50. $this.skipped += response.data.skipped;
  51. $this.$form.find('.woocommerce-importer-progress').val( response.data.percentage );
  52. if ( 'done' === response.data.position ) {
  53. window.location = response.data.url + '&products-imported=' + parseInt( $this.imported, 10 ) + '&products-failed=' + parseInt( $this.failed, 10 ) + '&products-updated=' + parseInt( $this.updated, 10 ) + '&products-skipped=' + parseInt( $this.skipped, 10 );
  54. } else {
  55. $this.run_import();
  56. }
  57. }
  58. }
  59. } ).fail( function( response ) {
  60. window.console.log( response );
  61. } );
  62. };
  63. /**
  64. * Function to call productImportForm on jQuery selector.
  65. */
  66. $.fn.wc_product_importer = function() {
  67. new productImportForm( this );
  68. return this;
  69. };
  70. $( '.woocommerce-importer' ).wc_product_importer();
  71. })( jQuery, window );