This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
+560
View File
@@ -0,0 +1,560 @@
define([
'jquery',
'ko',
'underscore',
'uiComponent',
'Magezon_QuickOrder/js/model/item',
'Magento_Catalog/js/price-utils',
'mage/translate',
'Magento_Ui/js/modal/confirm',
'Magento_Ui/js/modal/alert',
'mage/url',
'Magento_Catalog/product/view/validation',
'Magezon_QuickOrder/js/knockout.files',
'Magezon_Core/js/jquery.magnific-popup.min'
], function ($, ko, _, Component, Item, priceUtils, $t, confirm, malert, url) {
'use strict';
return Component.extend({
defaults: {
items: [],
mode: 'quickorder',
template: 'Magezon_QuickOrder/editor',
popupSelector: '#quickorder-popup',
popupMainClass: 'quickorder-popup',
enableMultiskus: true,
enableUpload: true,
showImage: true,
showPrice: true,
showQty: true,
showSubTotal: true,
showAction: true,
showGrandTotal: true,
showSku: true,
searchPlaceholder: $t('Enter SKU or Product Name'),
addBtnLabel: $t('Add Line'),
submitBtnLabel: $t('Add to Cart'),
grandTotalLabel: $t('Total value:'),
emptyBtnLabel: $t('Empty List'),
showEmptyBtn: true,
confirmMessage: $t('Are you sure you would like to empty this list?'),
multiSkusLabel: $t('Enter Multiple SKUs'),
multiSkusDescription: $t('Use commas or paragraph to seperate SKUs.'),
addToListBtnLabel: $t('Add to List'),
fileRule: $t('File must be in .csv format and include \"SKU\" and \"QTY\" columns'),
fileSuccessMessage: $t('File was imported sucessfully'),
fileLoading: false,
submitLoading: false,
loadingproduct: false,
storageKey: 'quickorderItems',
instantSearch: true,
qty: 1,
listens: {
loadingproduct: 'loadingProductSpinner'
}
},
cache: [],
initialize: function () {
this._super();
_.bindAll(this,
'removeItem',
'duplicateItem',
'openPopup',
'onLoadedFile',
'onProgressFile',
'onErrorFile'
);
var self = this;
if (this.instantSearch) {
self.loadProducts();
}
$(self.popupSelector).on('click', '.action-cancel', function(e) {
e.preventDefault();
$.magnificPopup.close();
});
$(self.popupSelector).on('click', '.action-select', function(e) {
e.preventDefault();
if (self.currentItem) {
var form = $('#product_addtocart_form');
if(form.valid()) {
var data = form.serialize();
var startDate = $(self.popupSelector).find('#zonrentals-from').val();
var endDate = $(self.popupSelector).find('#zonrentals-to').val();
if (startDate && endDate) {
data += '&rental=1';
}
self.currentItem.options(data);
self.loadItemInfo(self.currentItem);
$.magnificPopup.close();
return;
}
}
});
self.grandTotal = ko.pureComputed(function() {
var total = 0;
$.each(self.items(), function() {
total += this.subtotal();
});
self.saveItemsToLocalStorage();
return total;
});
_.each(this.getItemsFromLocalStorage(), function(item) {
this.addItem(item);
}, this);
return this;
},
initObservable: function () {
this._super()
.observe('grandTotal skus qty fileLoading submitLoading fileMessage loadingproduct')
.observe({
items: [],
products: []
});
return this;
},
submitItems: function (elem, event) {
this.submitLoading(true);
var items = [];
_.each(this.items(), function(item) {
if (item.isValid()) {
var row = {
product: item.product().value,
options: item.options(),
qty: item.qty(),
others: item.others(),
quote_type: item.quoteType(),
name: item.product().name
}
items.push(row);
}
});
if (items.length) {
var self = this;
$.ajax({
url: self.actionUrl,
data: {items: items, mode: self.mode},
type: 'post',
dataType: 'json',
success: function (res) {
if (res.message) {
alert(res.message);
}
if (res.status) {
self.clearLocalStorage();
}
if (res.redirectUrl) {
window.location.href = res.redirectUrl;
}
self.submitLoading(false);
}
});
} else {
this.submitLoading(false);
}
},
loadChildrenIds: function(product) {
var self = this;
self.spinnerloading(true);
$.ajax({
url: self.loadChildrensUrl,
data: { id: product.value, type: product.type },
type: 'post',
dataType: 'json',
success: function (res) {
if (res.status) {
_.each(res.childrens, function(product) {
var item = _.findWhere(self.products(), {id: product.id});
if (!item) {
self.products().push(product);
}
self.addItem({
price: product.price,
qty: 1,
product: product
});
});
self.spinnerloading(false);
}
}
});
},
addChildrens: function(product, item) {
item.spinnerloading(true);
var self = this;
if (!product.hasOwnProperty('childrens')) {
$.ajax({
url: self.loadChildrensUrl,
data: { id: product.value, type: product.type },
type: 'post',
dataType: 'json',
success: function (res) {
if (res.status) {
_.each(res.childrens, function(product) {
var item = _.findWhere(self.products(), {id: product.id});
if (!item) {
self.products().push(product);
}
self.addItem({
price: product.price,
qty: 1,
product: product
});
});
product.childrens = res.childrens;
self.removeItem(item);
}
}
});
} else {
_.each(product.childrens, function(product) {
var item = _.findWhere(self.products(), {id: product.id});
if (!item) {
self.products().push(product);
}
self.addItem({
price: product.price,
qty: 1,
product: product
});
});
self.removeItem(item);
}
},
addItem: function (data) {
if (data.qty==0) {
return;
}
if (!data) {
data = {};
}
data = ko.toJS(data);
data['parent'] = this;
var item = new Item(data);
this.items.push(item);
},
removeItem: function (item) {
this.items.remove(item);
},
duplicateItem: function (item) {
var data = item.getData();
data['parent'] = this;
this.items.push(new Item(data));
},
loadProducts: function() {
if (!this.productLoaded) {
var self = this;
self.loadingproduct(true);
$.ajax({
url: self.ajaxUrl,
data: {mode: self.mode},
type: 'post',
dataType: 'json',
success: function (res) {
if (res.message) alert(res.message);
self.products(res.products);
self.loadingproduct(false);
}
});
self.productLoaded = true;
}
},
/**
* FormatPrice
*/
getFormattedPrice: function (price) {
return priceUtils.formatPrice(price, this.priceFormat);
},
openPopup: function(item) {
var self = this;
if (!this.cache[item.product().value]) {
$.ajax({
url: item.product().url + '?options=cart',
data: {product: item.product().value, mgz_qo: 1,mode: self.mode},
type: 'post',
dataType: 'json',
beforeSend: function () {
$(self.popupSelector + ' .quickorder-popup-content').html('');
$(self.popupSelector).addClass('quickorder-loading');
},
success: function (res) {
if (res.message) alert(res.message);
if (res.html) {
$(self.popupSelector + ' .quickorder-popup-content').html(res.html);
$(self.popupSelector + ' .quickorder-popup-content').trigger('contentUpdated');
$(self.popupSelector + ' #product_addtocart_form').validation();
$(self.popupSelector).removeClass('quickorder-loading');
setTimeout(function() {
self.editOptions(item.options());
}, 200);
self.cache[item.product().value] = res.html;
}
}
});
} else {
var html = self.cache[item.product().value];
$(self.popupSelector).addClass('quickorder-loading');
$(self.popupSelector + ' .quickorder-popup-content').html(html);
$(self.popupSelector + ' .quickorder-popup-content').trigger('contentUpdated');
$(self.popupSelector + ' #product_addtocart_form').validation();
setTimeout(function() {
self.editOptions(item.options());
setTimeout(function() {
$(self.popupSelector).removeClass('quickorder-loading');
}, 300);
}, 200);
}
$.magnificPopup.open({
items: {
src: self.popupSelector
},
type: 'inline',
removalDelay: 300,
mainClass: self.popupMainClass,
fixedContentPos: true,
fixedBgPos: true,
overflowY: 'auto',
showCloseBtn: false,
callbacks: {
beforeOpen: function() {
$('body').addClass('quickorder-popup');
this.st.mainClass = $(self.popupSelector).attr('data-effect');
},
beforeClose: function() {
this.st.mainClass = '';
$(self.popupSelector).css('transition', '');
$('body').removeClass('quickorder-popup');
self.currentItem.checkValid();
}
},
}, 0);
this.currentItem = item;
},
loadItemInfo: function(item) {
var self = this;
$.ajax({
url: this.loadItemInfoUrl,
data: {product: item.product().value, type: item.product().type, options: item.options(),mode: self.mode},
type: 'post',
dataType: 'json',
success: function (res) {
if (res.message) alert(res.message);
if (res.status) {
item.optionsHtml(res.options);
item.price(res.price);
} else {
self.removeItem(item);
}
}
});
},
parseParams: function(str) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g;
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
var params = {}, e;
while ( e = re.exec(str) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
},
editOptions: function(options) {
var self = this;
var newOptions = self.parseParams(options);
$(self.popupSelector).find('input, select, textarea').each(function(index, el) {
var name = $(this).attr('name');
if (newOptions[name]) {
$(this).val(newOptions[name]);
$(this).trigger('change');
if ($(this).hasClass('swatch-input')) {
var parent = $(this).parents('.swatch-attribute');
parent.find('.swatch-option[option-id=' + newOptions[name] + ']').eq(0).trigger('click');
}
}
});
},
getItemsFromLocalStorage: function() {
return JSON.parse(localStorage.getItem(this.storageKey));
},
saveItemsToLocalStorage: function() {
$(".ui-helper-hidden-accessible").remove();
var items = [];
_.each(this.items(), function(item) {
items.push(item.getData());
});
return localStorage.setItem(this.storageKey, JSON.stringify(items));
},
clearLocalStorage: function() {
return localStorage.removeItem(this.storageKey);
},
emptyItems: function() {
var self = this;
confirm({
content: self.confirmMessage,
actions: {
confirm: function () {
self.items.removeAll();
},
always: function (e) {
e.stopImmediatePropagation();
}
}
});
},
addToList: function() {
if (this.skus()) {
var self = this;
var result = [];
var skus = self.skus().split("\n");
for (var i = 0; i < skus.length; i++) {
var row = skus[i];
var skus2 = row.split(",");
for (var x = 0; x < skus2.length; x++) {
var sku = skus2[x].trim();
if ($.inArray( sku, result )==-1) {
result.push(sku);
}
}
}
var products =_.filter(self.products(), function(product) {
return ($.inArray( product.sku, result )!=-1)
});
if (self.instantSearch) {
self._processAddToList(products);
} else {
$.ajax({
url: self.ajaxUrl,
data: { skus: result,mode: self.mode },
type: 'post',
dataType: 'json',
success: function (res) {
if (res.message) alert(res.message);
self._processAddToList(res.products, skus);
}
});
}
window.scrollTo({
top: 0,
behavior: 'smooth' // 平滑滚动效果
});
}
},
_processAddToList: function(products) {
var qty = parseInt(this.qty()) ? parseInt(this.qty()) : 1;
_.each(products, function(product) {
this.addItem({
price: product.price,
qty: qty,
product: product
});
}, this);
this.skus('');
this.qty('');
},
onLoadedFile: function(file, data) {
var self = this;
if (!file) {
malert({"message": "请选择你要导入的excel文件"})
return;
}
let formData = new FormData();
formData.append('file', file);
formData.append('form_key', self.formKey);
$.ajax({
url: self.excelUploadUrl,
type: 'POST',
data: formData,
contentType: false,
processData: false,
showLoader: true,
success: function (response) {
let targetUrl = '/quick-order/';
if (response.result) {
targetUrl = '/checkout/cart/'
}
window.location.href = targetUrl;
},
error: function (xhr) {
console.error(xhr.responseText);
}
});
},
_processOnLoadedFile: function(products, skus, others) {
_.each(products, function(product) {
this.addItem({
price: product.price,
others: others[product.realSku],
options: product.options==''? null : product.options,
qty: skus[product.realSku]==undefined? 0:skus[product.realSku]['qty'],
product: product
});
}, this);
this.fileLoading(false);
this.fileMessage('<span class="quickquote-message-success">' + this.fileSuccessMessage + '</span>');
},
onErrorFile: function(file, error) {
this.fileLoading(false);
this.fileMessage('<span class="quickquote-message-error">' + error + '</span>');
},
onProgressFile: function(file) {
this.fileLoading(true);
this.fileMessage('');
},
loadingProductSpinner: function(status) {
if (status) {
$('.page-title').append('<div class="quickorder-spinner"><i></i></div>');
} else {
$('.page-title').children('.quickorder-spinner').remove();
}
}
})
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,118 @@
(function (factory) {
// Module systems magic dance.
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS or Node: hard-coded dependency on "knockout"
factory(require("knockout"));
} else if (typeof define === "function" && define["amd"]) {
// AMD anonymous module with hard-coded dependency on "knockout"
define(["knockout"], factory);
} else {
// <script> tag: use the global `ko` object, attaching a `mapping` property
factory(ko);
}
}
(function (ko) {
ko.bindingHandlers.files = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
var loadedCallback, progressCallback, errorCallback, hoverClass, allowDrop, fileFilter, readAs, maxFileSize;
var filesBinding = allBindings.files;
if (typeof(ko.unwrap(filesBinding)) == "function")
{ loadedCallback = ko.unwrap(filesBinding); }
else
{
loadedCallback = ko.unwrap(filesBinding.onLoaded);
progressCallback = ko.unwrap(filesBinding.onProgress);
errorCallback = ko.unwrap(filesBinding.onError);
allowDrop = ko.unwrap(filesBinding.allowDrop);
hoverClass = ko.unwrap(filesBinding.hoverClass);
fileFilter = ko.unwrap(filesBinding.fileFilter);
maxFileSize = ko.unwrap(filesBinding.maxFileSize);
readAs = ko.unwrap(filesBinding.readAs);
}
if(typeof(loadedCallback) != "function")
{ return; }
var readFile = function(file) {
var reader = new FileReader();
reader.onload = function(fileLoadedEvent) {
loadedCallback(file, fileLoadedEvent.target.result);
};
if(typeof(progressCallback) == "function")
{
reader.onprogress = function(fileProgressEvent) {
progressCallback(file, fileProgressEvent.loaded, fileProgressEvent.total);
};
}
if(typeof(errorCallback) == "function")
{
reader.onerror = function(fileErrorEvent) {
errorCallback(file, fileErrorEvent.target.error);
};
}
if(readAs == "text")
{ reader.readAsText(file); }
else if(readAs == "array")
{ reader.readAsArrayBuffer(file); }
else if(readAs == "binary")
{ reader.readAsBinaryString(file); }
else
{ reader.readAsDataURL(file); }
};
var handleFileDrag = function(fileDragEvent) {
fileDragEvent.stopPropagation();
fileDragEvent.preventDefault();
if(fileDragEvent.type == "dragover")
{ fileDragEvent.target.classList.add(hoverClass); }
else
{ fileDragEvent.target.classList.remove(hoverClass); }
};
var handleDrop = function(fileDropEvent) {
handleFileDrag(fileDropEvent);
handleFileSelected(fileDropEvent);
}
var handleFileSelected = function(fileSelectionEvent) {
var files = fileSelectionEvent.target.files || fileSelectionEvent.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
if (typeof(fileFilter) != "undefined" && !f.type.match(fileFilter))
{
if(typeof(errorCallback) == "function")
{ errorCallback(f, "File type does not match filter"); }
continue;
}
if(typeof(maxFileSize) != "undefined" && f.size >= maxFileSize)
{
if(typeof(errorCallback) == "function")
{ errorCallback(f, "File exceeds file size limit"); }
continue;
}
readFile(f);
}
};
if (!document.addEventListener) {
return; //IE8 won't work with addEventListener, avoid JS error
}
element.addEventListener('change', handleFileSelected, false);
if(allowDrop) {
element.addEventListener('dragover', handleFileDrag, false);
element.addEventListener('dragleave', handleFileDrag, false);
element.addEventListener('drop', handleDrop, false);
}
}
};
}));
@@ -0,0 +1,192 @@
define([
'jquery',
'ko',
'underscore',
'mageUtils',
'mage/translate',
'Magezon_QuickOrder/js/jquery-ui'
], function($, ko, _, utils, $t) {
return function(data) {
var self = this;
this.uid = utils.uniqueid();
this.parent = data.parent;
this.search = ko.observable();
this.product = ko.observable(data['product'] ? data['product'] : '');
this.price = ko.observable(data['price'] ? data['price'] : 0);
this.qty = ko.observable(data['qty'] ? parseFloat(data['qty']) : 1);
this.options = ko.observable(data['options'] ? data['options'] : []);
this.optionsHtml = ko.observable(data['optionsHtml'] ? data['optionsHtml'] : '');
this.others = ko.observable(data['others'] ? data['others'] : '');
this.message = ko.observable(data['message'] ? data['message'] : '');
this.forceCheckValid = ko.observable(data.hasOwnProperty('forceCheckValid') ? data['forceCheckValid'] : true);
this.qtyVisible = ko.observable(data.hasOwnProperty('qtyVisible') ? data['qtyVisible'] : true);
this.products = ko.observableArray();
this.spinnerloading = ko.observable(false);
var quoteType = data['quoteType'];
if (!quoteType && data['product'] && data['product']['quoteTypes'] && data['product']['quoteTypes'][0]) {
quoteType = data['product']['quoteTypes'][0]['value'];
}
this.quoteType = ko.observable(quoteType);
console.log('item data: ', data)
self.getData = function() {
return {
product: self.product(),
price: self.price(),
qty: self.qty(),
options: self.options(),
optionsHtml: self.optionsHtml(),
message: self.message(),
forceCheckValid: self.forceCheckValid(),
quoteType: self.quoteType()
}
}
self.subtotal = ko.pureComputed(function() {
self.checkValid();
return (self.product() ? self.price() * self.qty() : 0);
});
self.parent.products.subscribe(function(products) {
if (self.parent.instantSearch) {
self.products(products);
}
});
self.products.subscribe(function() {
self.initAutoComplete();
})
self.search.subscribe(function(search) {
if (!self.parent.instantSearch && search.length >= self.parent.minLength) {
self.spinnerloading(true);
$.ajax({
url: self.parent.ajaxUrl,
data: { search: search,mode: self.parent.mode },
type: 'post',
dataType: 'json',
success: function (res) {
if (res.message) alert(res.message);
self.products(res.products);
self.spinnerloading(false);
$('#' + self.uid).autocomplete('search', search);
}
});
}
});
self.product.subscribe(function(product) {
self.options([]);
self.optionsHtml('');
if (product) {
self.price(product.price);
} else {
self.price(0);
}
});
self.forceCheckValid.subscribe(function(status) {
if (status) {
self.message('');
}
});
self.checkValid = function() {
if (!this.isValid()) {
self.message($t('Please specify product option(s).'));
} else {
self.message('');
}
}
self.isValid = function() {
var valid = false;
if (self.product() && self.product().canConfigure && !self.options().length) {
valid = false
} else {
valid = true;
}
if (self.product().type == 'grouped') {
self.qtyVisible(false);
}
return valid;
}
self.initAutoComplete = function() {
$('#' + self.uid).focus();
self._initAutoComplete();
}
self._initAutoComplete = function() {
if (self.parent.instantSearch) {
var products = self.parent.products();
} else {
var products = self.products();
}
console.log('self.products(): ', self.products())
var element = $('#' + self.uid);
element.autocomplete({
messages: {
noResults: '',
results: function() {
}
},
minLength: self.parent.minLength,
appendTo: '#mgz-quickorder-ui-' + this.uid,
source: products,
select: function( event, ui ) {
console.log('ui: ', ui)
event.preventDefault();
// if (ui.item.type=='grouped') {
// self.parent.addChildrens(ui.item, self);
// } else {
self.product(ui.item);
if (ui.item.options != '') {
self.options(ui.item.options);
}
if (self.product().canConfigure) {
self.forceCheckValid(false);
} else {
self.forceCheckValid(true);
}
if (self.parent.instantSearch) {
element.val(self.product().name);
}
if (!self.product().canConfigure && self.product().openmodal) {
self.parent.openPopup(self);
}
if (self.product().canConfigure) {
self.parent.openPopup(self);
}
self.forceCheckValid(true);
//}
},
focus: function(event, ui) {
event.preventDefault();
}
}).data( "ui-autocomplete" )._renderItem = function(ul, item) {
var $html = '<div class="ui-menu-item-wrapper">';
$html += '<div class="mgz-quickorder-item">';
if (item.img && self.parent.search.showImage) {
$html += '<div class="mgz-quickorder-item_left"><img src="' + item.img + '" alt="' + item.name + '"/></div>';
}
$html += '<div class="mgz-quickorder-item_right">';
$html += '<div class="mgz-quickorder-item_title"><a href="#"><span>' + item.name + '</span></a></div>';
if (self.parent.search.showSku) {
$html += '<div class="mgz-quickorder-item_sku"><b>SKU#: </b>' + item.sku + '</div>';
}
if (self.parent.search.showPrice) {
$html += '<div class="mgz-quickorder-item_price">' + item.priceHtml + '</div>';
}
$html += '</div>';
$html += '</div>';
$html += '</div>';
return $('<li class="ui-menu-item" data-label=' + item.name + '>').data("ui-autocomplete-item",item).append($html).appendTo( ul );
};
}
}
});
@@ -0,0 +1,92 @@
define([
'jquery'
], function ($) {
'use strict';
return function (widget) {
$.widget('mage.SwatchRenderer', widget, {
/**
* @private
*/
_create: function () {
var options = this.options,
gallery = $('[data-gallery-role=gallery-placeholder]'),
productData = this._determineProductData(),
$main = productData.isInProductView ?
this.element.parents('.column.main') :
this.element.parents('.product-item-info');
if (productData.isInProductView) {
gallery.data('gallery') ?
this._onGalleryLoaded(gallery) :
gallery.on('gallery:loaded', this._onGalleryLoaded.bind(this, gallery));
} else {
options.mediaGalleryInitial = [{
'img': $main.find('.product-image-photo').attr('src')
}];
}
this.productForm = this.element.parents(this.options.selectorProductTile).find('form:first');
this.inProductList = this.productForm.length > 0;
},
/**
* Update [gallery-placeholder] or [product-image-photo]
* @param {Array} images
* @param {jQuery} context
* @param {Boolean} isInProductView
*/
updateBaseImage: function (images, context, isInProductView) {
var justAnImage = images[0],
initialImages = this.options.mediaGalleryInitial,
gallery = $(this.options.mediaGallerySelector).data('gallery'),
imagesToUpdate,
isInitial;
// 每个产品图片添加caption信息
if(images.length){
images.forEach(function(img){
img.caption = initialImages[0].caption
});
}
if (isInProductView) {
imagesToUpdate = images.length ? this._setImageType($.extend(true, [], images)) : [];
isInitial = _.isEqual(imagesToUpdate, initialImages);
if (this.options.gallerySwitchStrategy === 'prepend' && !isInitial) {
imagesToUpdate = imagesToUpdate.concat(initialImages);
}
imagesToUpdate = this._setImageIndex(imagesToUpdate);
if (gallery) {
gallery.updateData(imagesToUpdate);
}
if ($(this.options.mediaGallerySelector).length) {
if (isInitial) {
$(this.options.mediaGallerySelector).AddFotoramaVideoEvents();
} else {
$(this.options.mediaGallerySelector).AddFotoramaVideoEvents({
selectedOption: this.getProduct(),
dataMergeStrategy: this.options.gallerySwitchStrategy
});
}
}
if (gallery) {
gallery.first();
}
} else if (justAnImage && justAnImage.img) {
context.find('.product-image-photo').attr('src', justAnImage.img);
}
}
});
return $.mage.SwatchRenderer;
}
});