Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var itemsList = {},
- clientsList = {},
- prevRow,
- prevCol = 0,
- tableHeader = document.getElementById('table-header'),
- docsWrapper = document.getElementById('docsWrapper'),
- mainWrapper = document.getElementById('main-wrapper'),
- firstDateInput = document.getElementById('firstDate'),
- clientSelect = document.getElementById('clientSelect'),
- storesSelect = document.getElementById('storesSelect'),
- secDateInput = document.getElementById('secDate'),
- checkBox = document.getElementById('checkBox'),
- clientsWithDocsBtn = document.getElementById('all-clients-with-docs'),
- table = document.getElementById('table'),
- storesList,
- motherShip = [],
- store = {};
- var r1 = ['objects', 'ЛЕЙДИ СОФИЯ АД'],
- r2 = ['items', 'ЛЕЙДИ СОФИЯ АД', '{"warehouse":"ОБЕКТИ:10 НЕСТАНДАРТНА ПРОДУКЦИЯ"}'];
- sendRequestToServer(JSON.stringify(r1), storesList);
- //sendRequestToServer('ГОТОВА ПРОДУКЦИЯ', 'store');
- document.getElementById('test').onclick = function () {
- sendRequestToServer(JSON.stringify(['write', 'test', itemsList]));
- }
- function sendRequestToServer(arr, v, check) {
- var request = new XMLHttpRequest();
- request.onreadystatechange = function () {
- if (request.readyState == 4 && request.status == 200) {
- if (v == storesList) {
- storesList = request.responseText;
- storesList = JSON.parse(storesList);
- fillStoresSelect(storesList);
- }
- if (v == 'store') {
- v = request.responseText;
- v = v.replace(/""/g, '"');
- reformatString(v, 0, 0);
- v = JSON.parse(v);
- fillDocuments(v);
- changeStore(v);
- if (check) {
- var d2 = new Date();
- console.log(d2.valueOf());
- roundAllStores(motherShip);
- }
- }
- }
- }
- request.open("POST", "http://192.168.1.184:8000/pm", true);
- //request.open("POST", "http://127.0.0.1:8888/", true);
- request.send(arr);
- }
- function reformatString(str, indexA, indexB) {
- console.log(str);
- var right = str.match(/{/g),
- left = str.match(/}/g),
- newStr;
- if (right.length == left.length) return
- if (str.lastIndexOf('{') > str.lastIndexOf('}')) {
- newStr = str.slice(0, str.lastIndexOf(']')) + '}]';
- }
- if(str.lastIndexOf('}') == indexB) return
- var firstIndexOfRight = str.indexOf('{', indexA),
- firstIndexOfLeft = str.indexOf('}', firstIndexOfRight + 1),
- nextIndexOfRight = str.indexOf('{', firstIndexOfRight + 1);
- if (nextIndexOfRight < firstIndexOfLeft) {
- if (str.lastIndexOf(':', nextIndexOfRight) < str.lastIndexOf(',', nextIndexOfRight)) {
- var lastIndexOfQ = str.lastIndexOf('"', nextIndexOfRight);
- newStr = str.slice(0, lastIndexOfQ + 1) + '}' + str.slice(lastIndexOfQ + 1);
- }
- } else {
- newStr = str;
- }
- reformatString(newStr, firstIndexOfRight + 1, firstIndexOfLeft);
- }
- function fillStoresSelect(arr) {
- strArray = ['<option style="display:none;">Избери склад</option><option>Всички</option>'];
- for (var i = 0; i < arr.length; i++) {
- strArray.push("<option value='" + '{"warehouse":' + '"' + arr[i] + '"}' + "'>" + arr[i].slice(arr[i].lastIndexOf(':') + 1) + "</option>");
- }
- storesSelect.innerHTML += strArray.join('');
- }
- storesSelect.onchange = function () {
- var selected = this.value;
- console.log(selected);
- if (selected == 'Всички') {
- motherShip = [];
- var d1 = new Date();
- console.log(d1.valueOf());
- for (var i = 0; i < storesList.length; i++) {
- if (i == storesList.length - 1) {
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', storesList[i]]), 'store', true);
- } else {
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', storesList[i]]), 'store');
- }
- }
- return;
- } else {
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', selected]), 'store');
- }
- }
- function roundAllStores(arr) {
- var d3 = new Date();
- console.log(d3.valueOf());
- store = arr[0];
- for (var i = 1; i < arr.length; i++) {
- for (var key in arr[i]) {
- if (store[key]) {
- if (arr[i][key].quantity) {
- store[key].quantity = Number(store[key].quantity) + Number(arr[i][key].quantity);
- } else {
- store[key].quantity = 0;
- }
- } else {
- store[key] = {};
- if (arr[i][key].quantity) {
- store[key].quantity = Number(arr[i][key].quantity);
- } else {
- store[key].quantity = 0;
- }
- }
- }
- }
- var d4 = new Date();
- console.log(d4.valueOf());
- }
- //Extract all items and clients from the main JSON and put them into two associative arrays
- function generateRef(obj) {
- for (var a = 0; a < obj.length; a++) {
- var currentDate = obj[a].date;
- if (checkIfDateIsValid(currentDate.slice(6, currentDate.length), currentDate.slice(4, 6), currentDate.slice(0, 4))) {
- fillclientsList(obj[a].partner, obj[a]);
- for (var b = 0; b < obj[a].Items.length; b++) {
- checkItems(obj[a].partner, obj[a].Items[b]);
- }
- }
- }
- }
- //Convert store JSON into an object
- function changeStore(currentStore) {
- store = {};
- for (var i = 0; i < currentStore.length; i++) {
- store[currentStore[i].name] = currentStore[i];
- }
- motherShip.push(store);
- }
- //changeStore(storeFromJson);
- //on every merchandise if array fill clients that have it with whole quantity
- function checkItems(client, march) {
- var client = client.slice(client.lastIndexOf(':') + 1);
- if (itemsList[march.name]) {
- if (itemsList[march.name][client]) {
- itemsList[march.name][client] = Number(itemsList[march.name][client]) + Number(march.quantity);
- } else {
- itemsList[march.name][client] = Number(march.quantity);
- }
- } else {
- itemsList[march.name] = {};
- itemsList[march.name][client] = Number(march.quantity);
- }
- }
- //all clients with theys documents and full info on document
- function fillclientsList(name, obj) {
- var Items = {},
- name = name.slice(name.lastIndexOf(':') + 1);
- if (clientsList[name]) {
- if (clientsList[name][obj.docNumber]) {
- return;
- } else {
- clientsList[name][obj.docNumber] = {
- date: obj.date,
- };
- }
- } else {
- clientsList[name] = {};
- clientsList[name][obj.docNumber] = {
- date: obj.date,
- };
- }
- for (var i = 0; i < obj.Items.length; i++) {
- if (Items[obj.Items[i].name]) {
- Items[obj.Items[i].name].quantity += Number(obj.Items[i].quantity);
- } else {
- Items[obj.Items[i].name] = {};
- Items[obj.Items[i].name].quantity = Number(obj.Items[i].quantity);
- }
- }
- clientsList[name][obj.docNumber]['Items'] = Items;
- }
- function buildTable(reUse) {
- (function fillHeader() {
- var strArray = ['<div class="table-row"><div class="plain-cell"> </div><div class="plain-cell">No</div>'],
- docArr = ['<div class="table-row"><div class="plain-cell">Док. номер</div><div class="plain-cell"> </div>'],
- docDate = ['<div class="table-row"><div class="plain-cell">Док. дата</div><div class="plain-cell"> </div>'];
- for (var key in clientsList) {
- if (reUse) {
- for (var prop in clientsList[key]) {
- var date = clientsList[key][prop].date;
- strArray.push('<div class="plain-cell no-print">' + key + '</div>')
- docArr.push('<div class="plain-cell">' + prop + '</div>');
- docDate.push('<div class="plain-cell">' + date.substr(6, 2) + '.' + date.substr(4, 2) + '.' + date.substr(0, 4) + '</div>');
- }
- }
- else {
- strArray.push('<div class="plain-cell no-print">' + key + '</div>');
- }
- }
- docArr.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div></div>')
- docDate.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div></div>')
- strArray.push('<div class="plain-cell">Общо планирани</div><div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>');
- if (reUse) {
- docsWrapper.innerHTML = docArr.join('') + docDate.join('');
- }
- tableHeader.innerHTML = strArray.join('');
- resizeConteiners(tableHeader.children[0].children.length * 100 + 300);
- }());
- (function fillRows() {
- var strArray = [],
- counter = 1,
- totalRowItems = 0;
- for (var key in itemsList) {
- strArray.push('<div class="table-row"><div class="plain-cell">' + key + '</div><div class="plain-cell">' + counter + '</div>')
- for (var name in clientsList) {
- if (reUse) {
- var result = expandedRows(clientsList[name], key);
- strArray.push(result.html);
- totalRowItems += result.quantity;
- continue;
- }
- if (itemsList[key][name]) {
- strArray.push('<div class="plain-cell no-print">' + itemsList[key][name] + '</div>')
- totalRowItems += Number(itemsList[key][name]);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>')
- }
- }
- var storeQuantity = (store[key].quantity === undefined) ? 0 : store[key].quantity,
- storeBlocked = (store[key].blocked != undefined) ? store[key].blocked : 0;
- quantitydifference = Number(storeQuantity) - 0 - totalRowItems;
- strArray.push('<div class="plain-cell">' + totalRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
- '<div class="plain-cell">' + 0 + '</div>' +
- '<div class="plain-cell">' + quantitydifference + '</div></div>');
- counter++;
- totalRowItems = 0;
- }
- if (reUse) {
- table.innerHTML = setSerialNumberRow(clientsList, true);
- }
- else {
- table.innerHTML = setSerialNumberRow(clientsList, false);
- }
- table.innerHTML += strArray.join('');
- printTotalQuantity();
- }());
- }
- //Build row with serial number for each client or document
- function setSerialNumberRow(obj, isExpanded) {
- var strArr = [],
- prevProp,
- counter = 1;
- strArr.push('<div class="table-row no-print"><div class="plain-cell"> </div><div class="plain-cell">No</div>');
- for (var prop in obj) {
- strArr.push('<div class="plain-cell">' + counter + '</div>');
- counter++;
- if (isExpanded) {
- var countKeys = 0;
- for (var key in obj[prop]) {
- countKeys++;
- }
- for (var i = 0; i < countKeys - 1; i++) {
- strArr.push('<div class="plain-cell"> </div>');
- }
- }
- prevProp = prop;
- }
- strArr.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>');
- return strArr.join('');
- }
- //expands basic table after click on chechbox
- function expandedRows(obj, itemName) {
- var strArray = [];
- totalRowItems = 0;
- for (var key in obj) {
- if (obj[key].Items[itemName]) {
- strArray.push('<div class="plain-cell no-print">' + obj[key].Items[itemName].quantity + '</div>');
- totalRowItems += Number(obj[key].Items[itemName].quantity);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>');
- }
- }
- return {
- html: strArray.join(''),
- quantity: totalRowItems
- }
- }
- //Visualize all documents from client chosen by click on the header
- tableHeader.onclick = function (e) {
- var target = (typeof (event) != 'undefined') ? event.srcElement.outerText : e.target.innerHTML,
- checkBiggerWidth = 0;
- if (target == 'No' || target == 'Общо планирани' || target == 'Количество от склад' ||
- target == 'Блокирани' || target == 'Разлика' || target == '') {
- return;
- }
- if (target == 'Всички') {
- clientsWithDocsBtn.disabled = false;
- clientsWithDocsBtn.checked = false;
- if (!checkBox.checked) {
- checkBox.click();
- }
- docsWrapper.style.display = 'none';
- buildTable();
- return;
- }
- docsWrapper.style.display = '';
- changeHeaderAfterClick(target);
- clientsWithDocsBtn.disabled = true;
- resizeConteiners(docsWrapper.childNodes[0].children.length * 100 + 300)
- };
- //after click on some cell change color of a cell row and col
- table.onclick = function (ev) {
- var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
- if (target.className == 'plain-cell no-print') {
- var rows = document.querySelectorAll('#table .table-row');
- if (prevCol <= rows[0].children.length) {
- for (var z = 0; z < rows.length; z++) {
- rows[z].children[prevCol].style.backgroundColor = '';
- }
- }
- if (prevCol == Array.prototype.indexOf.call(target.parentNode.childNodes, target) && prevRow == target.parentNode) {
- prevRow.style.backgroundColor = '';
- prevCol = 0;
- return;
- }
- prevCol = Array.prototype.indexOf.call(target.parentNode.childNodes, target);
- for (var z = 0; z < rows.length; z++) {
- rows[z].children[prevCol].style.backgroundColor = 'lightBlue';
- }
- if (prevRow) {
- prevRow.style.backgroundColor = '';
- }
- prevRow = target.parentNode;
- prevRow.style.backgroundColor = 'lightblue';
- target.style.backgroundColor = '#bde0eb';
- }
- };
- //fill table with data for clicked client
- function fillTableAfterClick(targetName) {
- var strArray = [],
- invoiceNumber = [],
- invoiceDate = [],
- rowCounter = 1,
- iterationCounter = 0,
- countRowItems = 0;
- invoiceNumber.push('<div class="table-row no-print"><div class="plain-cell">Док.ном</div><div class="plain-cell"> </div>')
- invoiceDate.push('<div class="table-row no-print"><div class="plain-cell">Дата</div><div class="plain-cell"> </div>')
- var itemsArr = extractItemsFromClient(clientsList[targetName]);
- for (var name in itemsArr) {
- strArray.push('<div class="table-row"><div class="plain-cell">' + name + '</div><div class="plain-cell">' + rowCounter + '</div>');
- var clientKeys = 0;
- for (var keys in clientsList[targetName]) {
- clientKeys++;
- }
- for (var key in clientsList[targetName]) {
- if (iterationCounter < clientKeys) {
- var currentDate = clientsList[targetName][key].date;
- invoiceNumber.push('<div class="plain-cell">' + key + '</div>')
- invoiceDate.push('<div class="plain-cell">' + currentDate.slice(6, currentDate.length) + '.' + currentDate.slice(4, 6) + '.' + currentDate.slice(0, 4) + '</div>')
- }
- if (clientsList[targetName][key].Items[name]) {
- strArray.push('<div class="plain-cell no-print">' + clientsList[targetName][key].Items[name].quantity + '</div>');
- countRowItems += Number(clientsList[targetName][key].Items[name].quantity);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>');
- }
- iterationCounter++;
- }
- var storeQuantity = (store[name].quantity != undefined) ? store[name].quantity : 0,
- quantitydifference = Number(storeQuantity) - 0 - countRowItems;
- strArray.push('<div class="plain-cell">' + countRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
- '<div class="plain-cell">' + 0 + '</div><div class="plain-cell">' + quantitydifference + '</div>');
- strArray.push('</div>');
- countRowItems = 0;
- rowCounter++;
- }
- invoiceNumber.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>')
- invoiceDate.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>')
- docsWrapper.innerHTML = invoiceNumber.join('') + invoiceDate.join('');
- table.innerHTML = setSerialNumberRow(clientsList[targetName], false) + strArray.join('');
- printTotalQuantity();
- }
- //fill footer with calculated data from colums
- function printTotalQuantity() {
- var strArray = ['<div class="table-row"><div class="plain-cell">Общо</div><div class="plain-cell"> </div>'],
- sum = 0;
- for (var i = 2; i < table.children[0].children.length; i++) {
- for (var z = 1; z < table.children.length - 1; z++) {
- sum += Number(table.children[z].children[i].innerHTML == ' ' ? '' : table.children[z].children[i].innerHTML);
- }
- if (i < table.children[0].children.length - 4) {
- strArray.push('<div class="plain-cell no-print">' + sum + '</div>')
- }
- else {
- strArray.push('<div class="plain-cell">' + sum + '</div>')
- }
- sum = 0;
- }
- strArray.push('</div>');
- table.innerHTML += strArray.join('');
- }
- //extract only items that are in all clients
- function extractItemsFromClient(client) {
- var result = {};
- for (var doc in client) {
- for (var item in client[doc].Items) {
- if (!result[item]) result[item] = {};
- }
- }
- return result;
- }
- document.getElementById('show-reference').onclick = checkIfDatesInputAreActive;
- document.getElementById('firstDate').onchange = fillSelectWithClients;
- document.getElementById('secDate').onchange = fillSelectWithClients;
- function fillSelectWithClients() {
- var strArray = [];
- if (firstDateInput.value && secDateInput.value) {
- strArray.push('<option>Всички</option>');
- itemsList = {};
- clientsList = {};
- generateRef(json);
- for (var name in clientsList) {
- strArray.push('<option>' + name + '</option>');
- }
- }
- clientSelect.innerHTML = strArray.join('');
- }
- //change header with only clicked client name and empty cells; call fillTableAfterClick with client name
- function changeHeaderAfterClick(name) {
- tableHeader.innerHTML = '<div class="table-row"><div class="plain-cell"> </div><div class="plain-cell">No</div><div class="plain-cell no-print">' + name + '</div><div class="plain-cell no-print" id="empty-cell"></div><div class="plain-cell">Общо планирани</div>' +
- '<div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>';
- fillTableAfterClick(name);
- clientsWithDocsBtn.checked = true;
- clientsWithDocsBtn.disabled = true;
- tableHeader.childNodes[0].firstChild.innerHTML = 'Всички';
- }
- function checkIfDatesInputAreActive() {
- var clientSelectValue = clientSelect.options[clientSelect.selectedIndex].value;
- if (firstDateInput.value && secDateInput.value) {
- checkBox.disabled = false;
- if (clientSelectValue != 'Всички') {
- docsWrapper.style.display = '';
- changeHeaderAfterClick(clientSelectValue);
- if (!checkBox.checked) {
- checkBox.click();
- }
- resizeConteiners(docsWrapper.children[0].children.length * 100 + 300)
- return;
- }
- clientsList = {};
- itemsList = {};
- generateRef(json);
- if (!checkBox.checked) {
- checkBox.click();
- }
- if (clientsWithDocsBtn.disabled) {
- clientsWithDocsBtn.disabled = false;
- }
- if (clientsWithDocsBtn.checked) {
- clientsWithDocsBtn.checked = false;
- }
- docsWrapper.style.display = 'none';
- buildTable();
- }
- }
- //find only dates that are in range
- function checkIfDateIsValid(day, month, year) {
- var firstDateInput = document.getElementById('firstDate'),
- secDateInput = document.getElementById('secDate'),
- regEx = /[0-9]+/g,
- firstDateArray,
- secDateArray;
- firstDateArray = firstDateInput.value.match(regEx);
- secDateArray = secDateInput.value.match(regEx);
- if (firstDateArray && secDateArray) {
- var prevDate = new Date(firstDateArray[0], (firstDateArray[1] - 1), firstDateArray[2], 0, 0, 0, 0);
- var currentDate = new Date(secDateArray[0], (secDateArray[1] - 1), secDateArray[2], 0, 0, 0, 0);
- if (prevDate > currentDate) {
- return;
- }
- var productDate = new Date(year, (Number(month) - 1), Number(day), 0, 0, 0, 0);
- if (productDate.valueOf() >= prevDate.valueOf() && productDate.valueOf() <= currentDate.valueOf()) {
- return true;
- } else {
- return false;
- }
- }
- }
- checkBox.onclick = function () {
- if (!this.checked) {
- document.head.innerHTML += '<style>.no-print{display:none}</style>';
- resizeConteiners(table.offsetWidth);
- docsWrapper.style.display = 'none';
- }
- else {
- document.head.removeChild(document.querySelectorAll('style')[0]);
- resizeConteiners(table.children[0].children.length * 100 + 300);
- if (clientsWithDocsBtn.checked) {
- docsWrapper.style.display = '';
- } else {
- docsWrapper.style.display = 'none';
- }
- }
- if (prevRow) {
- prevRow.style.backgroundColor = '';
- }
- };
- clientsWithDocsBtn.onclick = function () {
- if (this.checked) {
- buildTable(true)
- docsWrapper.style.display = '';
- if (!checkBox.checked) checkBox.click();
- }
- else {
- buildTable();
- resizeConteiners(table.offsetWidth);
- docsWrapper.style.display = 'none';
- }
- };
- function resizeConteiners(size) {
- docsWrapper.style.width = size + 'px';
- mainWrapper.style.width = size + 2 + 'px';
- tableHeader.childNodes[0].style.width = size + 'px';
- if (docsWrapper.children.length == 0) {
- return;
- }
- if (!document.getElementById('empty-cell')) {
- return;
- }
- document.getElementById('empty-cell').style.width = (docsWrapper.offsetWidth - 1000) + 'px';
- if (docsWrapper.children[0].children.length <= 7) {
- document.getElementById('empty-cell').style.display = 'none'
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement