/*
* Author: Clarence A Andaya
* Date: 31 Mar 2022
*/
//Only const Variable Here
(function () {
"use strict";
//Logic,Variables, Functions Here
var variation_list = [];
var variation_images = [];
var product_images = [];
var variation_attributes = [];
var selected_variation_key = null;
var myDzProductPhotos = null;
var myDzProductMainPhotos = null;
var myVariationList = null;
// Global default options
Dropzone.autoDiscover = false;
var selected_attributes = [];
function dzProductPhotos() {
myDzProductPhotos = new Dropzone("#dz_product_photo", {
url: "/admin/storage/upload", // If not using a form element
acceptedFiles: ".png,.jpg,.jpeg,.gif", //allowed filetypes
maxFilesize: 8,
maxFiles: 20,
clickable: true,
addRemoveLinks: true,
dictCancelUpload: "",
removedfile: function (file) {
// console.log(file);
if (selected_variation_key != null) {
// load images
//remove in varialist image array
$.each(
variation_list[selected_variation_key].images,
function (i, v) {
if (v.id == file.id) {
delete variation_list[selected_variation_key].images[i];
// clean and refresh variations attributes
variation_list[selected_variation_key].images = filterArray(
variation_list[selected_variation_key].images
);
}
}
);
//remove in current variation_images array only for already uploaded image (mock image)
$.each(variation_images, function (k, j) {
if (j.id == file.id) {
delete variation_images[k];
variation_images = filterArray(variation_images);
}
});
}
if (typeof file.upload != "undefined") {
$.each(variation_images, function (k, j) {
// console.log(j.uuid + ' ' + file.upload.uuid);
if (j.uuid == file.upload.uuid) {
delete variation_images[k];
variation_images = filterArray(variation_images);
}
});
}
//remove in variation_images array only for newly upload
// $.ajax({
// type: 'POST',
// url: '/admin/storage/remove',
// dataType: 'json',
// data: {
// id_or_name: file.upload.filename,
// dir: "products",
// csrf_token: $('#csrf_token').val()
// },
// sucess: function(data) {
// console.log('success: ' + data);
// }
// });
var _ref;
return (_ref = file.previewElement) != null
? _ref.parentNode.removeChild(file.previewElement)
: void 0;
},
init: function () {
this.on("maxfilesexceeded", function (file) {
// $("#proceed-button-vehicle").attr("disabled", false);
toast("error", "Only 20 images.");
$("#btn_save_variation").prop("disabled", false);
return 0;
});
this.on("error", function (file) {
toast("error", "Error has occured.");
$("#btn_save_variation").prop("disabled", false);
return;
});
this.on("success", function (file, response) {
if (response.status == 0) {
toast("error", response.message);
return false;
}
variation_images.push({
uuid: file.upload.uuid,
id: response.id,
path: response.path,
size: response.size,
name: response.name,
});
$("#btn_save_variation").prop("disabled", false);
// console.log(variation_images);
});
this.on("sending", function (file, xhr, formData) {
formData.append("dir", "products");
formData.append("csrf_token", $("#csrf_token").val());
});
this.on("addedfiles", function (files) {
$("#btn_save_variation").prop("disabled", true);
});
},
});
}
function dzProductPhotosMain() {
myDzProductMainPhotos = new Dropzone("#catalog_dz_product_photo", {
url: "/admin/storage/upload", // If not using a form element
acceptedFiles: ".png,.jpg,.jpeg,.gif", //allowed filetypes
maxFilesize: 8,
maxFiles: 3,
clickable: true,
addRemoveLinks: true,
dictCancelUpload: "",
removedfile: function (file) {
// console.log(file);
if (typeof file.upload != "undefined") {
$.each(product_images, function (k, j) {
if (j.uuid == file.upload.uuid) {
delete product_images[k];
product_images = filterArray(product_images);
}
});
} else {
//remove in current product_images array only for already uploaded image (mock image)
$.each(product_images, function (k, j) {
if (j.id == file.id) {
delete product_images[k];
product_images = filterArray(product_images);
}
});
}
var _ref;
return (_ref = file.previewElement) != null
? _ref.parentNode.removeChild(file.previewElement)
: void 0;
},
init: function () {
this.on("maxfilesexceeded", function (file) {
// $("#proceed-button-vehicle").attr("disabled", false);
toast("error", "Only 20 images.");
$("#btn_save_product").prop("disabled", false);
return 0;
});
this.on("error", function (file) {
toast("error", "Error has occured.");
$("#btn_save_product").prop("disabled", false);
return;
});
this.on("success", function (file, response) {
if (response.status == 0) {
toast("error", response.message);
return false;
}
product_images.push({
uuid: file.upload.uuid,
id: response.id,
path: response.path,
size: response.size,
name: response.name,
});
$("#btn_save_product").prop("disabled", false);
});
this.on("sending", function (file, xhr, formData) {
formData.append("dir", "products");
formData.append("csrf_token", $("#csrf_token").val());
});
this.on("addedfiles", function (files) {
$("#btn_save_product").prop("disabled", true);
});
},
});
}
function isDuplicateObject(object1, object2, key) {
var uniqueResultOne = object1.filter(function (obj) {
return !object2.some(function (obj2) {
return obj[key] == obj2[key];
});
});
//Find values that are in obj2 but not in obj1
var uniqueResultTwo = object2.filter(function (obj) {
return !object1.some(function (obj2) {
return obj[key] == obj2[key];
});
});
//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);
if (result.length) {
return false;
} else {
return true;
}
}
function isBelowZero($el, msg, focus = true) {
if ($el.val() != "") {
if (parseInt($el.val()) < 0) {
toast("error", msg);
if (focus) {
$el.trigger("focus");
}
return true;
}
}
return false;
}
function isBelowN($el, msg, num, focus = true) {
if ($el.val() != "") {
if (parseInt($el.val()) < num) {
toast("error", msg);
if (focus) {
$el.trigger("focus");
}
return true;
}
}
return false;
}
function checkDuplicateVariation() {
var isDuplicateVariation = false;
$.each(variation_list, function (i, v) {
var result1 = JSON.parse(JSON.stringify(v.attributes));
$.each(variation_list, function (j, k) {
if (i == j) {
return;
}
var result2 = JSON.parse(JSON.stringify(k.attributes));
if (isDuplicateObject(result1, result2, "child_id")) {
isDuplicateVariation = true;
}
});
});
return isDuplicateVariation;
}
function checkDuplicateAddVariation() {
var isDuplicateVariation = false;
var result1 = JSON.parse(JSON.stringify(variation_attributes));
$.each(variation_list, function (i, v) {
if (selected_variation_key != null) {
if (i == selected_variation_key) {
return;
}
}
var result2 = JSON.parse(JSON.stringify(v.attributes));
if (isDuplicateObject(result1, result2, "child_id")) {
isDuplicateVariation = true;
}
});
return isDuplicateVariation;
}
function variationForm() {
//clean attributes array (remove empty elements)
var filtered = filterArray(selected_attributes);
if (!filtered.length) {
toast("error", "No attributes selected.");
return false;
}
//ajax calling the variation form
$.ajax({
url: "/admin/products/variation",
data: {
attributes: filtered,
csrf_token: $("#csrf_token").val(),
},
type: "GET",
dataType: "json",
beforeSend: function () {
variation_images = [];
variation_attributes = [];
$(".modal_container").empty();
$("#btn_add_variation").prop("disabled", true);
},
success: function (result) {
$(".modal_container").html(result.data);
//show variant form
$("#modal_variation").modal("show");
//fill data to form if is update
if (selected_variation_key != null) {
// console.log(variation_list[selected_variation_key]);
//load fields
$.each(variation_list[selected_variation_key], function (i, v) {
if (!Array.isArray(v)) {
// alert('input[name="' + i + '"]');
$('input[name="' + i + '"]').val(v);
}
});
//load locations
var prod_loc = variation_list[selected_variation_key];
if (typeof prod_loc.warehouse != "undefined") {
var whOption = new Option(
prod_loc.warehouse.title,
prod_loc.warehouse.id,
true,
true
);
$('select[name="warehouse"]').append(whOption).trigger("change");
}
if (typeof prod_loc.floor != "undefined") {
var whOption = new Option(
prod_loc.floor.title,
prod_loc.floor.id,
true,
true
);
$('select[name="floor"]').append(whOption).trigger("change");
}
if (typeof prod_loc.rack != "undefined") {
var whOption = new Option(
prod_loc.rack.title,
prod_loc.rack.id,
true,
true
);
$('select[name="rack"]').append(whOption).trigger("change");
}
if (typeof prod_loc.bin != "undefined") {
var whOption = new Option(
prod_loc.bin.title,
prod_loc.bin.id,
true,
true
);
$('select[name="bin"]').append(whOption).trigger("change");
}
//load attributes
$.each(
variation_list[selected_variation_key].attributes,
function (i, v) {
$(
'select[name="attribute-' + v.parent_name.toLowerCase() + '"]'
).val(v.child_id);
}
);
}
//Initialze dropzone
// dzProductPhotos("#dz_product_photo");
dzProductPhotos();
//load images
if (selected_variation_key != null) {
// load images
$.each(
variation_list[selected_variation_key].images,
function (i, v) {
variation_images.push({
id: v.id,
path: v.path,
size: v.size,
name: v.name,
});
var mockFile = {
id: v.id,
name: v.name, //v.path,
size: v.size, //'12345' //v.unreadable_size
};
myDzProductPhotos.emit("addedfile", mockFile);
myDzProductPhotos.emit("complete", mockFile);
myDzProductPhotos.emit(
"thumbnail",
mockFile,
APP_DISK + "thumbnails/" + v.path
);
myDzProductPhotos.files.push(mockFile); // here you add them into the files array
}
);
}
//initialize datepicker
$(".datetimepicker").datetimepicker({
format: "MM/DD/YYYY hh:mm A",
// minDate: moment().subtract(1, "day"),
});
// $("[data-mask]").inputmask();
//init product location warehouse,floor,rack,bin
$('select[name="warehouse"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Select store and enter warehouse name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: "/admin/inventory/locations",
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
limit: 15,
store_id: $('select[name="catalog_store"]').val(),
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="floor"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Select warehouse and enter floor name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: "/admin/inventory/locations",
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
limit: 15,
parent_id: $('select[name="warehouse"]').val(),
type: "floor",
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="rack"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Select floor and enter rack name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: "/admin/inventory/locations",
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
limit: 15,
parent_id: $('select[name="floor"]').val(),
type: "rack",
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="bin"]').select2({
theme: "bootstrap4",
language: {
noResults: function () {
return "Select floor and enter bin name.";
},
},
escapeMarkup: function (markup) {
return markup;
},
placeholder: "Please Select",
ajax: {
url: "/admin/inventory/locations",
dataType: "json",
delay: 250,
data: function (data) {
return {
search: data.term,
limit: 15,
parent_id: $('select[name="rack"]').val(),
type: "bin",
};
},
processResults: function (response) {
return {
results: response,
};
},
cache: true,
},
});
$('select[name="warehouse"]').on("change", function () {
$('select[name="floor"]').val(null).trigger("change");
});
$('select[name="floor"]').on("change", function () {
$('select[name="rack"]').val(null).trigger("change");
});
$('select[name="rack"]').on("change", function () {
$('select[name="bin"]').val(null).trigger("change");
});
$("#modal_variation").on("hidden.bs.modal", function () {
//destroy all elements in modal
// myDzProductPhotos.destroy();
myDzProductPhotos.files = [];
$(this).remove();
});
$("#btn_add_variation").prop("disabled", false);
$("#btn_save_variation").on("click", function () {
//validations
if ($('input[name="price"]').val() == "") {
toast("error", "Price cannot be empty.");
$('input[name="price"]').trigger("focus");
return false;
}
if (
isBelowN(
$('input[name="price"]'),
"Price cannot be negative value.",
0
)
) {
return false;
}
if (
isBelowN(
$('input[name="min_order_qty"]'),
"Minimum order quantity must be equal or greater than 1",
1
)
) {
return false;
}
if (
isBelowN(
$('input[name="max_order_qty"]'),
"Maximum order quantity must be equal or greater than 1",
1
)
) {
return false;
}
if (
isBelowN(
$('input[name="sale_price"]'),
"Sale price cannot be negative value.",
0
)
) {
return false;
}
if (
isBelowN(
$('input[name="quantity"]'),
"Quantity price cannot be negative value.",
0
)
) {
return false;
}
if (
isBelowN(
$('input[name="max_quantity"]'),
"Max quantity price cannot be negative value.",
0
)
) {
return false;
}
if (
isBelowN(
$('input[name="order_quantity"]'),
"Order quantity price cannot be negative value.",
0
)
) {
return false;
}
var is_empty_attr = false;
$("[data-attribute]").each(function () {
if (!$(this).val()) {
$(this).trigger("focus");
is_empty_attr = true;
return false;
}
});
if (is_empty_attr) {
toast("error", "Invalid attribute value.");
return false;
}
//sales price validation
if (
($("#sale_price_start").val() && !$("#sale_price_end").val()) ||
(!$("#sale_price_start").val() && $("#sale_price_end").val()) ||
moment($("#sale_price_start").val()) >=
moment($("#sale_price_end").val())
) {
toast("error", "Invalid sale date range.");
$("#sale_price_start").trigger("focus");
return false;
}
if (
($("#sale_price_start").val() &&
!$('input[name="sale_price"]').val()) ||
($("#sale_price_end").val() && !$('input[name="sale_price"]').val())
) {
toast("error", "Sale price cannot be empty.");
$('input[name="sale_price"]').trigger("focus");
return false;
}
if (
parseInt($('input[name="price"]').val()) <=
parseInt($('input[name="sale_price"]').val())
) {
toast("error", "Sale price must not greater or equal than price.");
$('input[name="sale_price"]').trigger("focus");
return false;
}
if ($('input[name="max_order_qty"]').val() != "") {
if (
parseInt($('input[name="max_order_qty"]').val()) <
parseInt($('input[name="min_order_qty"]').val())
) {
toast(
"error",
"Minimum order quantity must not greater than max order quantity."
);
$('input[name="min_order_qty"]').trigger("focus");
return false;
}
}
if ($('input[name="max_quantity"]').val() != "") {
//deprecated
// if (
// parseInt($('input[name="max_quantity"]').val()) <
// parseInt($('input[name="min_order_qty"]').val())
// ) {
// toast(
// "error",
// "Minimum order quantity must not greater than max quantity."
// );
// $('input[name="min_order_qty"]').trigger("focus");
// return false;
// }
// if (
// parseInt($('input[name="max_quantity"]').val()) <
// parseInt($('input[name="max_order_qty"]').val())
// ) {
// toast(
// "error",
// "Maximum order quantity must not greater than max quantity."
// );
// $('input[name="max_order_qty"]').trigger("focus");
// return false;
// }
if (
parseInt($('input[name="max_quantity"]').val()) <
parseInt($('input[name="quantity"]').val())
) {
toast("error", "Quantity must not greater than max quantity.");
$('input[name="quantity"]').trigger("focus");
return false;
}
if (
parseInt($('input[name="max_quantity"]').val()) <
parseInt($('input[name="order_quantity"]').val())
) {
toast(
"error",
"Order quantity must not greater than max quantity."
);
$('input[name="order_quantity"]').trigger("focus");
return false;
}
}
variation_attributes = [];
var obj_data = formObj("data-obj", $("[data-obj]"));
// console.log(obj_data);
// return false;
// Add Locations
if (parseInt($('select[name="warehouse"]').val())) {
obj_data["warehouse"] = {
id: $('select[name="warehouse"]').val(),
title: $('select[name="warehouse"] option:selected').text(),
type: "wh",
};
}
if (parseInt($('select[name="floor"]').val())) {
obj_data["floor"] = {
id: $('select[name="floor"]').val(),
title: $('select[name="floor"] option:selected').text(),
type: "floor",
};
}
if (parseInt($('select[name="rack"]').val())) {
obj_data["rack"] = {
id: $('select[name="rack"]').val(),
title: $('select[name="rack"] option:selected').text(),
type: "rack",
};
}
if (parseInt($('select[name="bin"]').val())) {
obj_data["bin"] = {
id: $('select[name="bin"]').val(),
title: $('select[name="bin"] option:selected').text(),
type: "bin",
};
}
//Add attributes to variation
$("[data-attribute]").each(function () {
var attr_obj = {
parent_id: parseInt($(this).attr("data-id")),
parent_name: $(this).attr("data-name"),
child_id: $(this).val(),
child_name: $("option:selected", this).text(),
};
variation_attributes.push(attr_obj);
});
//Legacy code for checking if attributes is exist
// //start check if variations has equal attributes
// $.each(variation_list, function(i, v) {
// // console.log('error');
// var result1 = JSON.parse(JSON.stringify(variation_attributes));
// var result2 = JSON.parse(JSON.stringify(v.attributes));
// if (result1.length != result2.length) {
// var uniqueResultOne = result1.filter(function(obj) {
// return !result2.some(function(obj2) {
// return obj.parent_id == obj2.parent_id;
// });
// });
// //Find values that are in result2 but not in result1
// var uniqueResultTwo = result2.filter(function(obj) {
// return !result1.some(function(obj2) {
// return obj.parent_id == obj2.parent_id;
// });
// });
// //Combine the two arrays of unique entries
// var result = JSON.parse(JSON.stringify(uniqueResultOne)); //uniqueResultOne.concat(uniqueResultTwo);
// result[0].child_id = '';
// result[0].child_name = '';
// console.log('added');
// $.each(result, function(k, j) {
// variation_list[i].attributes.push(j);
// });
// }
// });
//start check duplicate variations
// var isDuplicateVariation = false;
// $.each(variation_list, function (i, v) {
// if (selected_variation_key != null) {
// if (i == selected_variation_key) {
// return;
// }
// }
// var result1 = JSON.parse(JSON.stringify(variation_attributes));
// var result2 = JSON.parse(JSON.stringify(v.attributes));
// //Find values that are in result1 but not in result2
// var uniqueResultOne = result1.filter(function (obj) {
// return !result2.some(function (obj2) {
// return obj.child_id == obj2.child_id;
// });
// });
// //Find values that are in result2 but not in result1
// var uniqueResultTwo = result2.filter(function (obj) {
// return !result1.some(function (obj2) {
// return obj.child_id == obj2.child_id;
// });
// });
// //Combine the two arrays of unique entries
// var result = uniqueResultOne.concat(uniqueResultTwo);
// if (!result.length) {
// isDuplicateVariation = true;
// return false;
// }
// });
// if (isDuplicateVariation) {
// toast("error", "This variation is already added.");
// return false;
// }
if (checkDuplicateAddVariation()) {
toast("error", "This variation is already added.");
return false;
}
//end check duplicate variations
obj_data["attributes"] = JSON.parse(
JSON.stringify(variation_attributes)
);
//Add images from dropzone
obj_data["images"] = JSON.parse(JSON.stringify(variation_images));
$("#modal_variation").modal("hide");
toast("success", "Variation save.");
if (selected_variation_key != null) {
obj_data["default"] =
variation_list[selected_variation_key]["default"];
obj_data["id"] = variation_list[selected_variation_key].id;
variation_list[selected_variation_key] = obj_data;
} else {
//Set default variation
if (variation_list.length <= 0) {
obj_data["default"] = 1;
} else {
obj_data["default"] = 0;
}
obj_data["id"] = "";
variation_list.push(obj_data);
}
// refresh variation table
variationList();
});
},
error: function () {
toast("error", "Error has occurred. Try again.");
$("#btn_add_variation").prop("disabled", false);
},
});
}
function variationList() {
console.log("List: ");
console.log(variation_list);
var variationTableId = "#tbl_variations";
if ($.fn.DataTable.isDataTable(variationTableId)) {
// $(variationTableId).dataTable();
myVariationList.clear();
myVariationList.destroy();
}
$(variationTableId + " tbody").empty();
$(variationTableId + " thead").empty();
if (variation_list.length <= 0) {
return false;
}
//Object to table logic & algorithm : Clrkz 04/19/22
//fix cols
var cols = [
{
title: "Image",
data: "image",
className: "align-middle p-1 dt-center",
render: function (data, type, row, meta) {
return (
`
`
);
},
width: "5%",
},
{
title: "Price",
data: "price",
className: "align-middle p-1 dt-center",
ordering: true,
width: "15%",
render: function (data, type, row, meta) {
var sale_price_end = moment(variation_list[row.key].sale_price_end);
// console.log(sale_price_end);
var date_now = moment();
// console.log(sale_price_end);
// console.log(date_now);
// date is past
var price =
CURRENCY_SYMBOL +
parseFloat(row.price).toLocaleString("en-US", {
minimumFractionDigits: 2,
});
var sale_price = variation_list[row.key].sale_price;
var final_sale_price =
CURRENCY_SYMBOL +
parseFloat(sale_price).toLocaleString("en-US", {
minimumFractionDigits: 2,
}) +
`
` +
price +
``;
if (sale_price_end.isValid()) {
if (sale_price_end > date_now) {
// var sale_price = variation_list[row.key].sale_price;
return final_sale_price;
}
} else {
if (sale_price) {
return final_sale_price;
}
}
return price;
},
},
{
title: "Default",
data: "default",
render: function (data, type, row, meta) {
return (
`