Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $(document).ready(function () {
- var CLASS_SWITCHER_ACTIVE = 'switcher__item_active',
- CLASS_USER_FORM_ACTIVE = 'user-form_active',
- MAX_LENGTH_ROW = 500,
- TITLE_FOR_MODAL_WINDOW = 'Предупреждение',
- ERROR_MSG_HAS_NOT_CHECKED_ITEMS = 'Не выбрано ни одной позиции. Выберите позиции с помощью галочек.';
- var $wrapper = $('#main'),
- $mobileContent = $('#mobileContent'),
- $switcher = $('#switcher'),
- $buttonsSwitcher = $switcher.find('.switcher__item'),
- $headline = $('#headline'),
- $wrapButtonsHeadline = $headline.find('.headline__buttons-wrap'),
- $buttonParseFile = $headline.find('.js-headline-buttons[data-type="parseFile"]'),
- $userForm = $('#userForm'),
- $userFormElements = $userForm.find('.js-user-form'),
- $userFormFile = $userForm.find('.js-user-form[data-type="file"]'),
- $inputsColumns = $userFormFile.find('.js-input-columns'),
- latestColumns = getItemInLocalStorage('latestColumns') || false,
- $userFormClipboard = $userForm.find('.js-user-form[data-type="clipboard"]'),
- $buttonSendClipboardValues = $userFormClipboard.find('.js-send-clipboard-values'),
- $inputClipboard = $userForm.find('.js-clipboard-input'),
- $tableWrap = $('#tableWrap'),
- $buttonAddToCart = $tableWrap.find('.js-add-to-cart'),
- $buttonMainDelete = $tableWrap.find('.js-main-delete'),
- $buttonCheckItem = $tableWrap.find('.js-check-item'),
- $alerts = $tableWrap.find('#alert'),
- $errorsBlock = $alerts.find('.js-alert-error'),
- $errorsList = $errorsBlock.find('.js-alert-error-list'),
- $warningsBlock = $alerts.find('.js-alert-warning'),
- $warningsList = $warningsBlock.find('.js-alert-warning-list'),
- $table = $('#table'),
- $tableHeader = $table.find('.js-table-header'),
- $buttonMainCheckBox = $tableHeader.find('.js-main-checkbox'),
- $tableBody = $table.find('.js-table-body'),
- $modalSendFile = $('#loadFileModal'),
- $buttonSendFile = $modalSendFile.find('.js-load'),
- $inputFile = $modalSendFile.find('#inputFile'),
- pageContext = $('#pageContextPath').val();
- var preloader = {
- hidePreloader: function (element) {
- $(element).preloader('hide');
- },
- showPreloader: function (element, width) {
- $(element).preloader({
- overlayBackground: 'rgba(255, 255, 255, .6)',
- showOverlay: true,
- contentsWidth: width + 'px',
- contentsHtml: '<img src=" ' + changeStaticLink($('#constantEndecaPath').val() +
- '/static/img/assets/product-card/preloader.gif') +
- ' " class="preloader__image" alt="" role="presentation">',
- delay: 0
- });
- },
- showMsg: function (msg, title, typeValue) {
- var modal = $('#cartModal');
- $('#cartBody').html(msg);
- $('#cartTitle').text('Предупреждение');
- modal.attr('data-type', typeValue);
- modal.modal();
- setTimeout(function () {
- $('#cartModal').modal('hide');
- }, 10000);
- }
- };
- togglePageContent(getWindowSize());
- if (latestColumns) {
- var valueEtmCode = validateColumnsValue(latestColumns.etmCode),
- valueProductCode = validateColumnsValue(latestColumns.code),
- valueClientCode = validateColumnsValue(latestColumns.clientCode),
- valueVendorCode = validateColumnsValue(latestColumns.vendorCode),
- valueQuantity = validateColumnsValue(latestColumns.quantity);
- filterInputs($inputsColumns, 'code').val(valueProductCode);
- filterInputs($inputsColumns, 'etm-code').val(valueEtmCode);
- filterInputs($inputsColumns, 'client-code').val(valueClientCode);
- filterInputs($inputsColumns, 'vendor-code').val(valueVendorCode);
- filterInputs($inputsColumns, 'quantity').val(valueQuantity);
- }
- $buttonsSwitcher.on('click', function () {
- var $self = $(this),
- type = $self.attr('data-type');
- if ($self.hasClass(CLASS_SWITCHER_ACTIVE)) {
- return;
- }
- $self.addClass(CLASS_SWITCHER_ACTIVE).siblings().removeClass(CLASS_SWITCHER_ACTIVE);
- $wrapButtonsHeadline.fadeToggle(160);
- toggleUserForm(type);
- });
- $buttonParseFile.on('click', function () {
- var MSG_ERROR_COLUMNS = 'Исправьте порядок колонок';
- if (!isValidColumnsValues()) {
- showModalWindow(MSG_ERROR_COLUMNS, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- $('#loadFileModal').modal('show');
- });
- $buttonSendFile.on('click', function () {
- var ERROR_MSG_EMPTY_INPUT_COLUMN = 'Укажите номер столбца для поиска товара.',
- ERROR_MSG_EQUALS_COLUMNS = 'Несколько одинаковых значений не могут находиться в одном столбце.';
- var file = $inputFile.prop('files')[0],
- code = filterInputs($inputsColumns, 'code').val().trim(),
- etmCode = filterInputs($inputsColumns, 'etm-code').val().trim(),
- clientCode = filterInputs($inputsColumns, 'client-code').val().trim(),
- vendorCode = filterInputs($inputsColumns, 'vendor-code').val().trim(),
- quantity = filterInputs($inputsColumns, 'quantity').val().trim(),
- columns = validateColumns(code, etmCode, clientCode, vendorCode, quantity),
- $errorRows = getErrorLines(),
- startNumberRow = getStartNumberRow();
- if (!code && !clientCode && !vendorCode && !etmCode) {
- showModalWindow(ERROR_MSG_EMPTY_INPUT_COLUMN, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- if (hasEqualValues(columns)) {
- showModalWindow(ERROR_MSG_EQUALS_COLUMNS, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- setItemInLocalStorage('latestColumns', columns);
- setLoadingStateButton($buttonParseFile);
- showPreloader();
- requestFile(file, columns, startNumberRow).then(
- function success(response) {
- if (!response.error) {
- var linesLength = $tableBody.find('.js-table-row').length;
- if ($errorRows.length === linesLength) {
- $tableBody.empty();
- }
- var items = response.items;
- showTableRows(items, linesLength);
- setDefaultStateButton($buttonParseFile);
- hidePreloader();
- } else {
- var text = response.message;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow(
- 'При отправке файла произошла ошибка! Попробуйте позднее или обратитесь в поддержку.',
- TITLE_FOR_MODAL_WINDOW
- );
- }
- hidePreloader();
- setDefaultStateButton($buttonParseFile);
- }
- },
- function error(response) {
- var text = response.responseText;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow(
- 'При отправке файла произошла ошибка! Попробуйте позднее или обратитесь в поддержку.',
- TITLE_FOR_MODAL_WINDOW
- );
- }
- hidePreloader();
- setDefaultStateButton($buttonParseFile);
- }
- );
- });
- $('.js-merge-lines').on('click', function () {
- var lines = $tableBody.find('.js-table-row'),
- linesByProductCode = buildLinesByProductCode(lines);
- mergeLines(linesByProductCode);
- var linesAfterMerge = $tableBody.find('.js-table-row');
- setNumberRow(linesAfterMerge);
- toggleWarning(linesAfterMerge);
- });
- $inputFile.on('change', function () {
- var file = $(this).prop('files')[0];
- if (!file) {
- $buttonSendFile.prop('disabled', true);
- } else {
- $buttonSendFile.prop('disabled', false);
- }
- });
- $buttonMainCheckBox.on('change', function () {
- var isChecked = isCheckedCheckbox(this);
- if (isChecked) {
- $tableBody.find('.js-table-checkbox:not(:checked)').prop('checked', true);
- } else {
- $tableBody.find('.js-table-checkbox:checked').prop('checked', false);
- }
- });
- $buttonMainDelete.on('click', function () {
- var $lines = $tableBody.find('.js-table-row'),
- $checkedLines = getCheckedLines($lines);
- if (!$checkedLines.length) {
- showModalWindow(ERROR_MSG_HAS_NOT_CHECKED_ITEMS, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- $checkedLines.remove();
- $lines = $tableBody.find('.js-table-row');
- if (!$lines.length) {
- $tableWrap.hide();
- }
- setNumberRow($lines);
- showErrorMsgess();
- toggleWarning($lines);
- });
- $buttonAddToCart.on('click', function () {
- var ERROR_MSG_MAX_LENGTH = 'Число добавляемых позиций не может превышать 500';
- var $lines = $tableBody.find('.js-table-row'),
- $selectedRows = getCheckedLines($lines),
- lengthSelectedRows = $selectedRows.length,
- itemsParams = getParams($selectedRows);
- if (!lengthSelectedRows) {
- showModalWindow(ERROR_MSG_HAS_NOT_CHECKED_ITEMS, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- if (lengthSelectedRows > MAX_LENGTH_ROW) {
- showModalWindow(ERROR_MSG_MAX_LENGTH, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- showPreloader();
- requestAddToCart(itemsParams).then(
- function success(response) {
- var isSuccess = response.success,
- errorMsg = response.error || 'При добавлении в корзину произошла ошибка! Попробуйте позднее или обратитесь в поддержку.',
- data = response.data;
- hidePreloader();
- if (isSuccess) {
- var products = data || {},
- yaProducts = [];
- for (var productsKey in products) {
- var productsByKey = products[productsKey];
- productsByKey.forEach(function (product) {
- yaProducts.push(buildYaProduct(
- product.id,
- validateStringLength(product.description, 50),
- 0,
- product.brand,
- product.quantity
- ));
- });
- }
- pushElementToDataLayerForAddingElements(yaProducts);
- window.location.href = pageContext + '/cart.htm';
- } else if (data) {
- updateLines($lines, data);
- return;
- } else {
- showModalWindow(errorMsg, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- });
- });
- $buttonCheckItem.on('click', function () {
- var $lines = $tableBody.find('.js-table-row'),
- $checkedLines = getCheckedLines($lines),
- products = getParams($checkedLines),
- numberRowsNotValidProduct = getNumberRowNotValidProducts(products);
- if (!$checkedLines.length) {
- showModalWindow(ERROR_MSG_HAS_NOT_CHECKED_ITEMS, TITLE_FOR_MODAL_WINDOW);
- return;
- }
- if (numberRowsNotValidProduct.length) {
- showModalWindow(buildEmptyRowsMsg(numberRowsNotValidProduct), TITLE_FOR_MODAL_WINDOW);
- return;
- }
- showPreloader();
- requestSendClipboardValues(products).then(
- function success(response) {
- if (!response.error) {
- var $lines = $tableBody.find('.js-table-row');
- var items = response.items;
- updateLines($lines, items);
- setNumberRow($tableBody.find('.js-table-row'));
- hidePreloader();
- } else {
- hidePreloader();
- var text = response.message;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow('При проверке позиций произошла ошибка! Попробуйте позднее или обратитесь в поддержку.', TITLE_FOR_MODAL_WINDOW);
- }
- }
- },
- function error(response) {
- hidePreloader();
- var text = response.responseText;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow('При проверке позиций произошла ошибка! Попробуйте позднее или обратитесь в поддержку.', TITLE_FOR_MODAL_WINDOW);
- }
- }
- );
- });
- $buttonSendClipboardValues.on('click', function () {
- var clipboardValues = $inputClipboard.val().trim(),
- selectedType = $userFormClipboard.find('.js-clipboard-radio:checked').attr('data-type'),
- $lines = $tableBody.find('.js-table-row'),
- $errorRows = getErrorLines(),
- params = parseClipboardValues(clipboardValues, selectedType);
- $inputClipboard.removeClass('border-red');
- setLoadingStateButton($buttonSendClipboardValues);
- showPreloader();
- requestSendClipboardValues(params).then(
- function success(response) {
- if (!response.error) {
- if ($errorRows.length === $lines.length) {
- $tableBody.empty();
- }
- var listRows = response.items;
- showTableRows(listRows, $lines.length);
- setDefaultStateButton($buttonSendClipboardValues);
- hidePreloader();
- } else {
- hidePreloader();
- var text = response.message;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow('При проверке позиций произошла ошибка! Попробуйте позднее или обратитесь в поддержку.', TITLE_FOR_MODAL_WINDOW);
- }
- }
- },
- function error(response) {
- hidePreloader();
- setDefaultStateButton($buttonSendClipboardValues);
- var text = response.responseText;
- if (!isHtml(text)) {
- showModalWindow(text, TITLE_FOR_MODAL_WINDOW);
- } else {
- showModalWindow('При отправке позиций произошла ошибка! Попробуйте позднее или обратитесь в поддержку.', TITLE_FOR_MODAL_WINDOW);
- }
- });
- });
- $tableBody.on('change', '.js-select-box', function () {
- var $self = $(this),
- $row = $self.closest('.js-table-row'),
- selectedUomCode = $self.find('option:selected').attr('data-code');
- $row.attr('data-uom-id', selectedUomCode);
- });
- $tableBody.on('change', '.js-table-checkbox', function () {
- toggleMainCheckBox();
- });
- $tableBody.on('click', '.js-table-delete-row', function () {
- var $self = $(this),
- $row = $self.closest('.js-table-row');
- $row.remove();
- var $lines = $tableBody.find('.js-table-row');
- if (!$lines.length) {
- $tableWrap.hide();
- }
- setNumberRow($lines);
- showErrorMsgess();
- toggleWarning($lines);
- });
- $userFormFile.on('input', '.js-input-columns', function () {
- var $self = $(this),
- value = $self.val();
- $self.val(validateNumber(value));
- });
- $tableBody.on('input', '.js-table-input', function () {
- var $self = $(this),
- type = $self.attr('data-type'),
- $row = $self.closest('.js-table-row');
- if (type === 'quantity' || type === 'code') {
- $self.val(validateNumber($self.val()));
- }
- $row.attr('data-' + type, $self.val());
- });
- $(window).on('resize', function () {
- togglePageContent(getWindowSize());
- });
- function mergeLines(linesByProductCode) {
- for (var productCode in linesByProductCode) {
- var linesList = linesByProductCode[productCode] || [];
- if (linesList.length <= 1) {
- continue;
- }
- var quantity = calculateLinesQuantity(linesList),
- linesForDelete = linesList.slice(1, linesList.length);
- $(linesList[0])
- .attr('data-quantity', quantity)
- .find('.js-table-input[data-type="quantity"]')
- .val(quantity);
- deleteLines(linesForDelete);
- }
- }
- function deleteLines(lines) {
- lines.forEach(function (line) {
- $(line).remove();
- });
- }
- function calculateLinesQuantity(lines) {
- return lines.reduce(function (sum, line) {
- var lineQuantity = Number($(line).find('.js-table-input[data-type="quantity"]').val().trim()) || 1;
- return sum + lineQuantity;
- }, 0);
- }
- function buildLinesByProductCode(lines) {
- return lines.toArray().reduce(function (part, line) {
- var productCode = $(line).attr('data-code'),
- linesList = part[productCode];
- if (linesList) {
- linesList.push(line);
- } else {
- part[productCode] = [line];
- }
- return part;
- }, {});
- }
- function updateLines($linesForUpdate, newLines) {
- for (var numberRow in newLines) {
- var linesForRow = newLines[numberRow],
- html = '';
- linesForRow.forEach(function (item) {
- html += getTableRow(numberRow, item.clientCode, item.vendorCode,
- item.code, item.uoms, item.link,
- item.description, item.quantity, item.balance, item.outOfStock,
- item.multiplicity, item.analyticalCategory, item.selectedUomCode,
- item.hasError, item.hasEqualCodes, item.id, item.errorMsg,
- item.etmCode);
- });
- $linesForUpdate.eq(--numberRow).replaceWith(html);
- }
- initStyleElement();
- var $lines = $tableBody.find('.js-table-row');
- toggleMainCheckBox();
- $tableWrap.show();
- showErrorMsgess();
- toggleWarning($lines);
- }
- function getEmptyCellsMsg(numberRow) {
- return '<div>Строка ' + numberRow + ' : Укажите хотя бы 1 столбец для проверки позиции.</div>';
- }
- function filterInputs($inputs, type) {
- return $inputs.filter('[data-type="' + type + '"]');
- }
- function validateNumber(value) {
- if (!value) {
- return null;
- }
- return value.replace(/\D/g, '');
- }
- function hasEqualValues(object) {
- var values = getObjectValues(object);
- return values.some(function (element) {
- return element !== null && values.indexOf(element) !== values.lastIndexOf(element);
- });
- }
- function getObjectValues(object) {
- var values = [];
- for (var key in object) {
- values.push(object[key]);
- }
- return values;
- }
- function getStartNumberRow() {
- return ++$tableBody.find('.js-table-row').length;
- }
- function getWindowSize() {
- return $(window).width();
- }
- function togglePageContent(windowSize) {
- var MIN_WINDOW_SIZE_FOR_CONTENT = 768;
- if (windowSize < MIN_WINDOW_SIZE_FOR_CONTENT) {
- $mobileContent.show();
- $headline.hide();
- $switcher.hide();
- $wrapper.hide();
- } else {
- $mobileContent.hide();
- $headline.show();
- $switcher.show();
- $wrapper.show();
- }
- }
- function validateErrorMsg(message) {
- if (!message.includes('Снятый')) {
- return message;
- }
- var SEPARATOR = '.';
- var msgElements = message.split(SEPARATOR);
- return msgElements[0] + msgElements[1];
- }
- function validateColumnsValue(value) {
- if (value === null) {
- return '';
- }
- return ++value || '';
- }
- function showTableRows(items, startNumberRow) {
- $tableBody.append(getHtmlRows(items, startNumberRow));
- initStyleElement();
- var $lines = $tableBody.find('.js-table-row');
- toggleMainCheckBox();
- $tableWrap.show();
- showErrorMsgess();
- toggleWarning($lines);
- }
- function isValidColumnsValues() {
- var notValidColumns = $userFormFile.find('.js-input-columns.border-red');
- return notValidColumns.length === 0;
- }
- function toggleWarning($lines) {
- var linesWithEqualCodes = $lines.filter('[data-equal-codes="true"]'),
- html = '',
- uniqueMsgs = {};
- if (!linesWithEqualCodes.length) {
- $warningsBlock.hide();
- return;
- }
- linesWithEqualCodes.each(function (index, element) {
- var msg = $(element).attr('data-error-msg');
- uniqueMsgs[msg] = '';
- });
- Object.keys(uniqueMsgs).forEach(function (msg) {
- html += getHtmlWarningItem(msg);
- });
- $warningsList.html(html);
- $warningsBlock.show();
- }
- function showErrorMsgess() {
- var $errorLines = getErrorLines();
- $errorsList.empty();
- if (!$errorLines.length) {
- $errorsBlock.hide();
- return;
- }
- createErrorRows($errorLines);
- $errorsBlock.show();
- }
- function createErrorRows(rows) {
- var html = '';
- $(rows).each(function (indexRow, row) {
- var $row = $(row),
- numberRow = $row.find('.js-table-number-row').text(),
- errMsg = validateErrorMsg($row.attr('data-error-msg'));
- html += getHtmlErrorRow(numberRow, errMsg);
- });
- $errorsList.append(html);
- }
- function getErrorLines() {
- return $tableBody.find('.js-table-row[data-has-error="true"]');
- }
- function getHtmlErrorRow(numberRow, errorMsg) {
- return '<div data-number-row="' + numberRow + '" class="js-alerts-error-row alerts__errors-item alerts__errors-item_dec">' +
- '<span class="alerts__errors-number-row alerts__errors-number-row_dec">Строка <span class="js-alert-error-number-row">' + numberRow + '</span> : </span>' +
- '<span class="alerts__errors-text alerts__errors-text_dec"> ' + errorMsg + '</span>' +
- '</div>';
- }
- function setLoadingStateButton(button) {
- $(button).button('loading');
- }
- function setDefaultStateButton(button) {
- $(button).button('reset');
- }
- function parseClipboardValues(value, columnName) {
- var REG_EXP_LINE_BREAK = /\n/g;
- var rows = value.split(REG_EXP_LINE_BREAK),
- $lines = $tableBody.find('.js-table-row'),
- length = $lines.length,
- parseResult = [];
- rows.forEach(function (row) {
- var rowTrimmed = row.trim(),
- clipboardRow = parseClipboardRow(rowTrimmed, columnName);
- parseResult.push(buildItem(++length,
- clipboardRow.code, clipboardRow.clientCode,
- clipboardRow.vendorCode, clipboardRow.etmCode,
- null, clipboardRow.quantity));
- });
- return parseResult;
- }
- function parseClipboardRow(row, columnName) {
- var REG_EXP_TAB = /\t+/g,
- REG_EXP_SPACE = /\s+/g;
- if (isFoundSymbolInString(row, REG_EXP_TAB)) {
- return parseForSeveralColumns(row, REG_EXP_TAB, columnName);
- }
- if (isFoundSymbolInString(row, REG_EXP_SPACE)) {
- return parseForSeveralColumns(row, REG_EXP_SPACE, columnName);
- }
- return parseForOneColumn(row, columnName);
- }
- function isFoundSymbolInString(string, regExp) {
- return string.match(regExp) !== null;
- }
- function parseForSeveralColumns(string, separator, columnName) {
- var stringItems = string.split(separator),
- lengthItems = getLengthPrimitive(stringItems),
- lastItem = stringItems[lengthItems - 1],
- values = {};
- if (lengthItems === 2 && !isNumber(stringItems[1])) {
- values[columnName] = stringItems.join(" ");
- values.quantity = "1";
- return values;
- }
- if (lengthItems === 2) {
- values[columnName] = stringItems[0];
- values.quantity = stringItems[1];
- return values;
- }
- if (stringItems.length > 2 && !isNumber(lastItem)) {
- values[columnName] = stringItems.join(" ");
- values.quantity = "1";
- return values;
- }
- if (stringItems.length > 2 && isNumber(lastItem)) {
- values[columnName] = stringItems.slice(0, lengthItems - 1).join(" ");
- values.quantity = lastItem;
- }
- return values;
- }
- function parseForOneColumn(string, columnName) {
- var values = {};
- values[columnName] = string;
- return values;
- }
- function getParams($selectedLines) {
- var params = [];
- $selectedLines.each(function (index, line) {
- params.push(buildItemFromDomLine($(line)));
- });
- return params;
- }
- function getNumberRowNotValidProducts(products) {
- var numberRows = [];
- products.forEach(function (product) {
- if (product.code === null && product.clientCode === null && product.vendorCode === null && product.etmCode === null) {
- numberRows.push(product.numberRow);
- }
- });
- return numberRows;
- }
- function buildEmptyRowsMsg(numberRows) {
- var text = '';
- numberRows.forEach(function (numberRow) {
- text += getEmptyCellsMsg(numberRow);
- });
- return text;
- }
- function buildItemFromDomLine($line) {
- var numberRow = $line.attr('data-number-row') || null,
- code = $line.attr('data-code') || null,
- clientCode = $line.attr('data-client-code') || null,
- vendorCode = $line.attr('data-vendor-code') || null,
- etmCode = $line.attr('data-etm-code') || null,
- selectedUomCode = $line.attr('data-uom-id') || null,
- quantity = $line.attr('data-quantity') || null;
- return buildItem(numberRow, code, clientCode, vendorCode, etmCode, selectedUomCode, quantity);
- }
- function getCheckedLines($lines) {
- return $lines.find('.js-table-checkbox:checked').closest('.js-table-row');
- }
- function setNumberRow($lines) {
- var startNumberRow = 0;
- $lines.find('.js-table-number-row').text(function (index, value) {
- var $line = $lines.eq(index),
- numberRow = ++startNumberRow;
- $line.attr('data-number-row', numberRow);
- return numberRow;
- });
- }
- function getLengthCollection(element) {
- return $(element).length;
- }
- function getLengthPrimitive(value) {
- return value.length;
- }
- function isCheckedCheckbox(element) {
- return $(element).prop('checked');
- }
- function getMultiplicity(multiplicity, analyticalCategory) {
- var CATEGORY_ORDERED = 'Заказной';
- return CATEGORY_ORDERED === analyticalCategory && isValidMultiplicity(multiplicity) ? multiplicity : '';
- }
- function isValidMultiplicity(value) {
- return value && Number(value) !== 1;
- }
- function getBalance(balance) {
- return balance >= 0 ? balance : '';
- }
- function validateColumns(productCode, etmCode, clientCode, vendorCode, quantity) {
- return {
- 'code': productCode ? --productCode : null,
- 'etmCode': etmCode ? --etmCode : null,
- 'clientCode': clientCode ? --clientCode : null,
- 'vendorCode': vendorCode ? --vendorCode : null,
- 'quantity': quantity ? --quantity : null
- };
- }
- function toggleMainCheckBox() {
- var rowsLength = getLengthCollection($tableBody.find('.js-table-row')),
- checkedCheckBoxesLength = getLengthCollection($tableBody.find('.js-table-checkbox:checked'));
- return rowsLength === checkedCheckBoxesLength ? $buttonMainCheckBox.prop('checked', true) : $buttonMainCheckBox.prop('checked', false);
- }
- function toggleUserForm(dataType) {
- $userFormElements.removeClass(CLASS_USER_FORM_ACTIVE);
- $userForm.find('.js-user-form[data-type=' + dataType + ']').addClass(CLASS_USER_FORM_ACTIVE);
- }
- function setItemInLocalStorage(key, value) {
- localStorage.setItem(key, JSON.stringify(value));
- }
- function getItemInLocalStorage(key) {
- return JSON.parse(localStorage.getItem(key));
- }
- function getSelectBox(uoms, selectedUom) {
- if (!uoms) {
- return '';
- }
- return uoms.length > 1 ? getHtmlSelectBox(uoms, selectedUom) : getHtmlDisabledSelectBox(uoms);
- }
- function validateValue(value) {
- return value || '';
- }
- function getHtmlDisabledSelectBox(uoms) {
- return '<label class="table__row-label table__row-label_dec">' +
- '<select disabled class="js-styled-select SumoUnder" tabindex="-1">' +
- getOptions(uoms) +
- '</select>' +
- '</label>';
- }
- function getHtmlSelectBox(uoms, selectedUom) {
- return '<label class="table__row-label table__row-label_dec">' +
- '<select data-type="active" class="js-select-box js-styled-select SumoUnder" tabindex="-1">' +
- getOptions(uoms, selectedUom) +
- '</select>' +
- '</label>';
- }
- function getOptions(uoms, selectedUom) {
- var options = '';
- uoms.forEach(function (uom) {
- var isSelectedUom = selectedUom === uom.uomCode;
- options += getHtmlOption(uom.uomCode, uom.uomName, isSelectedUom);
- });
- return options;
- }
- function getHtmlOption(code, value, selected) {
- if (selected) {
- return '<option selected data-code="' + code + '">' + value + '</option>';
- }
- return '<option data-code="' + code + '">' + value + '</option>';
- }
- function getHtmlInput(value, type) {
- return '<label class="table__row-label table__row-label_dec">' +
- '<input data-type="' + type + '" type="text" value="' + validateValue(value) + '" class="js-table-input table__row-input table__row-input_dec">' +
- '</label>';
- }
- function getHtmlRows(items, startNumberRow) {
- var html = '';
- for (var numberRow in items) {
- var rowItems = items[numberRow];
- rowItems.forEach(function (item) {
- html += getTableRow(++startNumberRow, item.clientCode, item.vendorCode,
- item.code, item.uoms, item.link,
- item.description, item.quantity, item.balance, item.outOfStock,
- item.multiplicity, item.analyticalCategory, item.selectedUomCode,
- item.hasError, item.hasEqualCodes, item.id, item.errorMsg,
- item.etmCode);
- });
- }
- return html;
- }
- function getHtmlCheckbox() {
- return '<label class="check table__row-label-checkbox table__row-label-checkbox_dec">' +
- '<input checked type="checkbox" class="js-table-checkbox table__row-checkbox table__row-checkbox_dec">' +
- '<span></span>' +
- '</label>';
- }
- function showModalWindow(text, title) {
- preloader.showMsg(text, title);
- }
- function hidePreloader() {
- $('#resultPreloader').hide();
- }
- function showPreloader() {
- $('#resultPreloader').show();
- }
- function getClassEqualsRow(hasEqualsVendorCode) {
- return hasEqualsVendorCode ? 'info' : '';
- }
- function getClassErrorRow(rowHasError) {
- return rowHasError ? 'danger' : '';
- }
- function getBackgroundLine(hasError, hasEqualCodes) {
- return hasError ? getClassErrorRow(hasError) : getClassEqualsRow(hasEqualCodes);
- }
- function getHtmlLink(link, description) {
- if (!link || !description) {
- return '';
- }
- return '<a target="_blank" href="' + pageContext + link + '" title="' + description + '" class="table__row-link table__row-link_dec">' +
- description +
- '</a>';
- }
- function isNumber(value) {
- console.log(value);
- return !isNaN(parseFloat(value)) && isFinite(value) && !~value.indexOf('-') && !~value.indexOf('+');
- }
- function isHtml(value) {
- return value.startsWith('<!DOCTYPE');
- }
- function getHtmlWarningItem(msg) {
- return '<div class="alerts__warnings-item alerts__warnings-item_dec">' +
- msg +
- '</div>';
- }
- function getTableRow(numberRow, clientCode, vendorCode,
- code, uoms, link,
- description, quantity, balance, outOfStock,
- multiplicity, analyticalCategory, selectedUom,
- hasError, hasEqualCodes, productId, errorMsg, etmCode) {
- return '<tr data-number-row="' + numberRow + '" data-has-error="' + validateValue(hasError) + '" data-quantity="' + validateValue(quantity) + '" ' +
- 'data-uom-id="' + validateValue(selectedUom) + '" data-product-id="' + validateValue(productId) + '" ' +
- 'data-equal-codes="' + validateValue(hasEqualCodes) + '" ' +
- 'data-etm-code="' + validateValue(etmCode) + '" ' +
- 'data-code="' + validateValue(code) + '" ' + 'data-client-code="' + validateValue(clientCode) + '" ' +
- 'data-vendor-code="' + validateValue(vendorCode) + '" ' + 'data-error-msg=\'' + validateValue(errorMsg) + '\' ' +
- 'class="js-table-row row table__row table__row_dec ' + getBackgroundLine(hasError, hasEqualCodes) + '">' +
- '<td class="js-table-number-row col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- numberRow +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlCheckbox() +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlInput(clientCode, 'client-code') +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlInput(vendorCode, 'vendor-code') +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlInput(code, 'code') +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlInput(etmCode, 'etm-code') +
- '</td>' +
- '<td class="js-table-selectbox col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getSelectBox(uoms, selectedUom) +
- '</td>' +
- '<td class="col-sm-2 col-md-2 table__row-item table__row-item_dec">' +
- '<div class="js-table-link table__row-link-wrap table__row-link-wrap_dec">' +
- getHtmlLink(link, description) +
- '</div>' +
- '</td>' +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getHtmlInput(quantity, 'quantity') +
- '</td>' +
- (outOfStock === 'N' ?
- '<td class="js-table-balance col-sm-1 col-md-1 table__row-item table__row-item_dec"' +
- ' colspan="2" style="font-weight: bold; font-size: 16px;">' +
- 'Нет в продаже' +
- '</td>'
- :
- '<td class="js-table-balance col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getBalance(balance) +
- '</td>' +
- '<td class="js-table-multiplicity col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- getMultiplicity(multiplicity, analyticalCategory) +
- '</td>'
- ) +
- '<td class="col-sm-1 col-md-1 table__row-item table__row-item_dec">' +
- '<button type="button" class="js-table-delete-row table__row-icon table__row-icon_dec">' +
- 'u' +
- '</button>' +
- '</td>' +
- '</tr>';
- }
- function buildItem(numberRow, code, clientCode, vendorCode, etmCode, selectedUomCode, quantity) {
- var validQuantity = quantity || 1;
- if (clientCode) {
- return {
- 'numberRow': numberRow,
- 'code': null,
- 'clientCode': clientCode,
- 'vendorCode': null,
- 'etmCode': null,
- 'selectedUomCode': selectedUomCode,
- 'quantity': validQuantity
- };
- }
- if (code) {
- return {
- 'numberRow': numberRow,
- 'code': code,
- 'clientCode': null,
- 'vendorCode': null,
- 'etmCode': null,
- 'selectedUomCode': selectedUomCode,
- 'quantity': validQuantity
- };
- }
- if (vendorCode) {
- return {
- 'numberRow': numberRow,
- 'code': null,
- 'clientCode': null,
- 'vendorCode': vendorCode,
- 'etmCode': null,
- 'selectedUomCode': selectedUomCode,
- 'quantity': validQuantity
- };
- }
- if (etmCode) {
- return {
- 'numberRow': numberRow,
- 'code': null,
- 'clientCode': null,
- 'vendorCode': null,
- 'etmCode': etmCode,
- 'selectedUomCode': selectedUomCode,
- 'quantity': validQuantity
- };
- }
- return {
- 'numberRow': numberRow,
- 'code': null,
- 'clientCode': null,
- 'vendorCode': null,
- 'etmCode': null,
- 'selectedUomCode': selectedUomCode,
- 'quantity': validQuantity
- }
- }
- function requestFile(file, columns, startNumberRow) {
- return new Promise(function (resolve, reject) {
- var formData = new FormData;
- formData.append('columns', JSON.stringify(columns));
- formData.append('file', file);
- formData.append('startNumberRow', JSON.stringify(startNumberRow));
- $.ajax({
- method: "POST",
- url: '/positionEntryFile',
- processData: false,
- contentType: false,
- enctype: 'multipart/form-data',
- data: formData,
- success: function (data) {
- resolve(tryParseJSON(data));
- },
- error: function (response) {
- reject(response);
- }
- });
- });
- }
- function requestAddToCart(items) {
- return new Promise(function (resolve, reject) {
- $.ajax({
- method: "POST",
- url: '/positionEntryAddToCart',
- data: 'items=' + JSON.stringify(items),
- success: function (data) {
- resolve(tryParseJSON(data));
- },
- error: function (response) {
- reject(response);
- }
- });
- });
- }
- function requestSendClipboardValues(params) {
- return new Promise(function (resolve, reject) {
- $.ajax({
- method: "POST",
- url: '/positionEntrySearchItem',
- data: 'items=' + JSON.stringify(params),
- success: function (response) {
- resolve(tryParseJSON(response));
- },
- error: function (response) {
- reject(response);
- }
- });
- });
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement