Skip to content

Instantly share code, notes, and snippets.

@x5gtrn
Created July 21, 2018 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x5gtrn/fc97f4beaaad9988b4077fd8a22f1679 to your computer and use it in GitHub Desktop.
Save x5gtrn/fc97f4beaaad9988b4077fd8a22f1679 to your computer and use it in GitHub Desktop.
/*
* 共通
*/
class TypeElement {
constractor(type, name, rule) {
this.type = type;
this.name = name;
this.rule = rule;
}
toJSON() {
JSON.stringify({
type: this.type,
name: this.name,
rule: this.rule,
})
}
}
class Images extends TypeElement {
constractor(type, name, rule) {
this.path = new Array();
super.constractor(type, name, rule);
}
}
class Variation {
constractor() {
this.variationProductId = new TypeElement('item', 'バリエーション管理番号', { maxLength: 64, type: "productId" });
this.variationName = new TypeElement('variation', 'バリエーション名', { maxLength: 64, type: "name" });
this.stock = new TypeElement('variation', '在庫', { min: 0, max: 65535, type: "number" });
this.images = new Images('variation', '画像', { maxLength: 65535 })
}
}
const variations = [];
function noticeInit() {
$('.error').css('display', 'none');
$('.error div').empty();
$('.success').css('display', 'none');
$('.success div').empty();
}
/*
* ファイルアップロード
*/
let cancelEvent = event => {
event.preventDefault();
event.stopPropagation();
return false;
};
$(window).bind('dragenter', cancelEvent);
$(window).bind('dragover', cancelEvent);
$(document).on('dragenter', '.item_icon_section', e => {
cancelEvent(e);
});
$(document).on('dragover', '.item_icon_section', e => {
cancelEvent(e);
});
//画像がドロップされてきた場合、検査して問題なければS3に仮登録。
$(document).on("drop", ".item_icon_section", e => {
cancelEvent(e);
noticeInit();
const iconSection = $(e.target);
const id = $(e.target).attr("id");
if (variations[id].images.path.length < 5) {
const reader = new FileReader();
const file = e.originalEvent.dataTransfer.files[0];
reader.readAsDataURL(file);
reader.onload = e2 => {
const result = e2.target.result;
const uploadErrors = [];
const acceptFileTypes = /^image\/(jpe?g|png)$/i;
if (file.name.charAt(0) !== ".") {
if (!acceptFileTypes.test(file['type'])) {
uploadErrors.push('アップロードされたファイルが画像ではないため登録できませんでした。jpg形式とpng形式の画像を登録可能です');
}
if (!file['size'].length && file['size'] > 1048576) {
uploadErrors.push('アップロードされたファイルのサイズが大きすぎます。登録可能な画像のサイズは1MBまでです');
}
if (uploadErrors.length > 0) {
$.each(uploadErrors, (i, v) => {
errorNotice(v);
});
} else {
const img = new Image();
img.onload = function () {
if (this.width / this.height === 1) {
$('#uploadedImage' + id).append('<li class="ui-state-default item-icon-img"><img src="' + result + '" width="40px"><span class="icon_cancel_button"><i class="fa fa-fw fa-close"></i></span></li>');
imageFileUpload(file, id);
} else {
errorNotice('画像が登録できませんでした。アスペクト比が1対1の画像のみ登録可能です');
}
};
img.src = result;
}
}
};
reader.onerror = () => {
errorNotice('ファイルが読み込めませんでした。' + file.fileName);
};
} else {
errorNotice('画像は1バリエーションにつき、五件まで登録可能です。');
}
});
function imageFileUpload(f, id) {
const formData = new FormData();
formData.append('image', f);
$.ajax({
type: 'POST',
contentType: false,
processData: false,
url: '/item/import/image',
data: formData,
dataType: 'json',
success: (data, status, xhr) => {
if (xhr.status === 200) {
if (variations[id].images.path.length < 5) {
variations[id].images.path.push(data.path);
}
} else {
errorNotice('画像の登録に失敗しました。');
}
}
});
}
/*
* アイテムカテゴリの大小セレクトボックス
*/
$(function () {
$('#bigCategorySelect').change(function () {
const parent_id = $('#bigCategorySelect').val();
const count = $('#smallCategorySelect').children().length;
for (let i = 0; i < count; i++) {
const s_category_op = $('#smallCategorySelect option:eq(' + i + ')');
if (s_category_op.attr("parent") === parent_id || s_category_op.attr("parent") === "") {
s_category_op.show();
} else {
s_category_op.hide();
}
$('#smallCategorySelect').val("");
$("#smallCategoryId").val("")
}
})
});
$(function () {
$('#smallCategorySelect').change(function () {
const selectedSmallCategory = $('#smallCategorySelect').val();
$("#smallCategoryId").val(selectedSmallCategory)
})
});
/*
* バリエーションのタブ管理
*/
let variationTabIndex = 0;
let variationTabCount = 0;
$(".nav-tabs").on("click", "a", function (e) {
e.preventDefault();
if (!$(this).hasClass('add-variation')) {
$(this).tab('show');
}
});
$('.add-variation').click(function (e) {
e.preventDefault();
if (variationTabCount > 20) {
return;
}
const id = variationTabIndex;
const tabId = 'variation_' + id;
const navTabId = 'variationNavTab_' + id;
$('.add-variation').closest('li').before('<li id="' + navTabId + '"><a href="#variation_' + id + '">' + (id + 1) + '</a></li>');
const variationRemoval = id === 0 ? '' : '<a href="#" onclick="removeVariation(' + id + ');">このバリエーションを削除する</a><br/>'
$('.tab-content').append('' +
'<div class="tab-pane" id="' + tabId + '">\n' +
' <div class="box-body">\n' +
' <div class="form-group clearfix">\n' +
' <label>画像ファイルアップロードと並び替え</label><br/><br/>' +
' アスペクト比が1対1のJPEG・PNG画像を5つまでアップロードできます\n' +
' <table class="table table-hover"><tbody><tr><td class="item-icon"><div class="item_icon_section" id="' + id + '"><div>ここに画像ファイルをドラッグ</div></div></td></tr></tbody></table>\n' +
' <ul class="sortable" id="uploadedImage' + id + '">\n' +
' </ul>\n' +
' </div>\n' +
' <div class="form-group">\n' +
' <label>バリエーション管理番号</label>\n' +
' <input type="text" name="variationProductId[]" class="form-control" value="">\n' +
' </div>\n' +
' <div class="form-group">\n' +
' <label>バリエーション名</label>\n' +
' <input type="text" name="variationName[]" class="form-control" value="">\n' +
' </div>\n' +
' <div class="form-group">\n' +
' <label>在庫</label>\n' +
' <input type="number" name="stock[]" class="form-control" value="">\n' +
' </div>\n' +
' ' + variationRemoval + '\n' +
' ※タブの数字は操作上表示しているものであり、登録されません<br/>\n' +
' ※バリエーションの並び替えは、登録した後に<strong>商品編集</strong>から行えます<br/>\n' +
' </div>' +
'</div>');
$('.nav-tabs li:nth-last-child(2) a').click();
variations[id] = new Variation();
variationTabIndex++;
variationTabCount++;
});
function removeVariation(id) {
if (id === 0) {
alert("1番目のバリエーションは削除できません");
return;
}
if (!confirm("このバリエーションを削除してよろしいですか?")) {
return;
}
const tabId = 'variation_' + id;
const navTabId = 'variationNavTab_' + id;
$('#' + tabId).remove();
$('#' + navTabId).remove();
delete variations[id];
variationTabCount--;
$('.nav-tabs li:first-child a').click();
}
/*
* 登録
*/
function registerItem() {
let i = 0;
variations.forEach(function(v) {
v.variationProductId.textValue = $('input[name="variationProductId"]').eq(i);
v.variationName.textValue = $('input[name="variationName"]').eq(i);
v.stock = $('input[name="stock"]').eq(i);
i++;
});
console.log(variations);
}
/*
* ロード後に行う処理
*/
function initialize() {
box.find('.box-footer').remove();
box.css('display', 'none');
$('.error').css('display', 'none');
$('.error div').empty();
$('.success').css('display', 'none');
$('.success div').empty();
}
$(function(){
$('#bigCategorySelect').trigger("change");
$('.nav-tabs .add-variation').click();
initialize();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment