Как исправить расчет маржи и импорт чистой/чистой цены на основе CSV в веб-приложении JavaScript? [закрыто]Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Как исправить расчет маржи и импорт чистой/чистой цены на основе CSV в веб-приложении JavaScript? [закрыто]

Сообщение Anonymous »

Расчет маржи кажется неверным
Я рассчитываю маржу, как это: < /p>
const margin = ((totalBruttoWithCommission - (netNetNetPrice * 0.65)) / totalBruttoWithCommission) * 100;
< /code>
Но это иногда приводит к значениям более 100%или отрицательным значениям, даже если данные выглядят правильно. Я подозреваю, что формула или базовые значения могут быть выключены. Я пытаюсь обнаружить это так: < /p>
const netNetNetPriceIdx = headers.findIndex(h => h.replace(/[^a-zA-Z]/g, '').toLowerCase().includes('netnetnet'));
< /code>
При чтении значений: < /p>
let rawNetNetNetPrice = row[netNetNetPriceIdx].trim();
rawNetNetNetPrice = rawNetNetNetPrice.replace(/[^0-9,\.]/g, '').replace(',', '.');
netNetNetPrice = parseFloat(rawNetNetNetPrice);

Но многие значения выходят как NAN, особенно когда они содержат валютные символы или пространства. size. < /p>
< /li>
Используйте его в расчете полей. /> Очистка значений с помощью reply (). < /p>
< /li>
оценивая цену как 65% от чистой, если значение CSV является недействительным. < /p>
< /li>
< /ul>
все еще, значения MARGIN OFF, и данные не являются данными. class = "lang-html prettyprint-override">html lang="pl">et charset="UTF-8" /> {const val = parseInt(sizet.value);if (va >= 1) {packConfigs[index].size = vapackCgs = sortPackConigs(packConfigs);renderDiscountTable();rnderTabl;sizeTd.appendChild(sizeInput);// Raba %const distTd = document.reateElemet('td');const discountInput documereateElement('input');dicountInput.type = 'number';discountt.min= 0;discountInput.max = 100;discoutInput.step = 00intInput.value = (pack.discout * 100).toFixed(2);discountInpuyle.widh = '80px';discountInpt.addEventitener('change', () => {let rseoat(discoutInput.value);val < 0) val = 0;if (val > 100 val = 100;packConfigs[index].discountal / 100;disountInput.value = val.toFixed();renderTable();})discou.appendChild(discontInput);// Usuńconst delTd = document.createElement();const delBtn = docuent.createElement('button');deltn.textContent = ń';delBtn.className = 'delete-bn';delBtn.addEventListener('click' ( {packConfigs.slice(index, 1);renderDiscuntTable();renderTable();});delppendhild(delBtn);tr.appendChild(sizeTd);t.appendChild(dscontTd);appendChild(delTd);return trfunctio renderDiscounte() {discountTableBody.inerHTML = '';packConfigs = sortPanfigs(packConfis);packConfigs.forEach((ack, index) => {discountTabdy.apendChild(createThresholdRow(pack, inex));});}function sortPonfigsarr) {return arr.sort(a,b) => a.size- bsize);}fuon renderTabl) {const baseBrutto = prseFloat(basePriceInput.e 0;const vatRate = paeFloat(vataInput.value) || 0;const commnRate = (parseFloat(csInput.value || 0) / 100;conatFactor = 1 + (vatRate/ ;st baseNetto = baseBrutto / vctor;pckTable.innML = '';packConfigs.forEpack => {const netUnitPrce etto * (1 - pack.discount);s netUnitWithCommission = netPrice * (1 + cmssionRate);t bruttoUitPrice = netUnitPr* vc // Cena jednostkowa brutt bez prowizjicotalBruttoWithCommission = bruttoUnitPice+ssionRate) * pack.sizeOblicz net/net/net: najpierw sprdź CSV, poticz jako 65% ceny nettolet netNetNetPrice;const cEan eanInput.value.trim()e.log(productMap[tEan])neNetNetPrice = producurrentEan].netNetNetPrice * pac;// Calculate marginconst margin = ((totalthCommission - netNetNetPrice *0.65)) ruttoWithCommiss;const row = document.createE');le totalWeight = '-';if (currentEan &&p[currentEan] && producntEan].weight !{eighroductMap[currentEan].weight * iFixed(3) + }row.innerHTL = `${pack.siz} szt. 50){const ow = document.ceateElement('tr');extraRow.innerDodatkow wiersz dla ilośc ${pack.size}`;e.appendChl(extraRow);}rgin 18) {const marginCell = dcument.ement('td');const marginInput = ocumteElement('inpuargi.type = 'numer';marginInput.value = mt(2);marut.stye.width = '80px';marginInput.addEvenner('change', ()=> {const newMargin = parseFloinnput.value);if (!isNanen)) {const newProfi = totalBrutCommission * (newMargin / 10);const newtPrce = totalBruttoWithCommisewProfit;// Update throw with new ao.cn[5].textContent = `${ewNettoFixed()} zł`;row.chi6].textContent = `${newMarixed(2)}%`;// PrzerendaenderSummarle}marginCell.appendChild(mrginInpow.appendChild(margnCell);}});nderuj tabelę posumowania finansowegorenderyTable();}funtion renderSummaryTabonst baseBrutto = pareFloat(basePriceInut.value) || 0;const v = pFlvteInput.value) || 0;const comiate = (parseFloat(commissionInput.value) ||/ statFactor = 1 + (vatRa00);const baseNetto = baseBrutto / vatFactor;summaryTaerHTML = '';packConfigs.forEach(pack => {consnetice = baseNetto * (1 - ack.discount);const bruttoUnitPrice = baseBrutnalBruttoWithomision = bruttoUnitPric + commissionRate)* pack.size;// bcze najpierw sprawdź CSV, potio 65% ceny nettolet netNetNetonst currentEan = eanIput.value.trim();if (currentEaductap[currentEan] && productMap[currentEan].netNetNetPrice == nu Użyj wartości z CSV (cea jednostkowa * rozmiar paczki)netNetNetPce = productMap[curreeetNetPrice * pack.size;} else{// Oblicz jako 65% ceny nettonetNetNetPrice = ete* pack.size;}const profit = totalBruttoWithCommission - netNetNetPrice;conn = ((profit) / totaithComssion) * 100;const row = documenElement('tr');row.innrHTML = ` 0) {maxSie = Math.max(...packConfigs.map(p=p.size));}// Dodóg z rozmiarem max+1 i rabatem 0%packConfis.push({ size: maxSize + 1, discou;scountTab();ren;});// Aktualizuj tabelęrzyzmianie bazowych anychbasePriceInpu.addner('input', renderTable);vatRateInput.adener('nput', renderTable);commissionInput.addEventinput, renderTable);/CSVcsvFileInpu.adEventListener('change{const fles=rray.from(e.taes)iles.length) retrn;files.( {const reder = new ();reader.onload = function(vent) {const textarget.result;parseCSVdaj plik do lit zaimportowanych plikówconst listItem =document.cr'liem.textContent = file.name;liste.t.5rem';// Ddaj uwaaconst deleteButton = document.createElemen);deeteButton.textContent = 'Usuń';deleteButton.l'delete-btn';deleteButton.stLeft = '1rem'deleteButton.addEventLisck', () => {listItem.move);})m.appendChild(deleteButton);importdFilesList.listItem);};reader.readAsText(file);});})eProductDta(existingDataor (cont [key, value] of Object.entries(ewData)) {if (!existineistingData[key] = value;} else {// Sprawdź, czy ierwsze 4 inadzająconst existing = existingData[key]s = (eisting.price ==value.price &&exsting.margin === value.mang.image === value.mage &&existing.name === value.nam &geight);if (matches) brakjące daneexisti= xist|| valueprice,margin: existing.marge.margin,mage: existing.imaue,nx.name || value.name,weigh: existing.weightlue.weight,;}}} Zano funkcję parseCSVuncionarcsvText) {const lines = csvText.split(/\r?\n/).filter((l)trim() !== '');if (ines.length < 2) {alert('Plik Ct pustylub niepprawny.');return;}// Wykryj separatr: jeśli w nagjęcej przecinków niż średików, użyj prz, w przeciwnym razi średnikconst headerLl];let separator = ';';if ((Ltch(//g) || []).length > (heamatch(/;/g) | ).length) {separator = ',';}/ Fu bezpiecznego splitowana linii CSV łowamifunction spltCSVLine(line, sep) {cost result = [];let curent = '';let inQfr (let i = 0; i h === 'cena srp');const arginIdx = headedarża');let imageIdx = headers.findIndex((h) => === 'zdjif (imageIdx === -1) imagIdx = headers.findndex((h) => h ==it nameIdx = headers.findIndex((h) => h ==kt_nzwa');const = headersfindIndex((h) => a');const gramatraIdx = headers.findIndex((h) = hse().includes('gramatura');// Kolmny encjiconst cmeitionNameIdx = ndInde((h) => h === kkurenc');ompetitionPriceIdx = haders.fix((h h kurencja_cena');const competitionShopIdx = headerIndex((h) = h === 'konkurencep');const compeUrlIdx = haders.findIndex((h)= 'konkurencja_url');// Kolumnadla ceny net/net/nezugłówka zawierjącego 3x 'net' (niezależnie od wielliter, spacji, ukośników itp.)console.log('Headers:',rs);const netNetNetPri= headers.findI((h)h 'cena net/net/net');console.log(ntNetNetPriceIdx)consrcodeHeader = heaers.findIndex((h) => h === 'kod kresk);if (barcodeHeader === -1) {headers.ph('kod kres');}fr (let i = 1; i < lines.length; i++) {const rosCSVLine(lines[ieparator);const ean = row[eanIdx]?.trim();if (erow[bacodeHeader] = ean;}}for (let i < lines.length; i++) {if sim()) coninue;const row SVLine(lines, separator);letull;if (eanIdx ! -1 && row.lengx) {const rawEAN = row[eanIdx].tr= parseEAN(rawEA ll;if (priceIdx !== -1 && row.length > priceIraPrice = row[priceIdx].trim(;rawPrice = rawace(/[^0-9,\.]/g, '').replace(',',ce = parseloat(rawPrice);}let marginfx ! -1 && row.length > malet rawMargin = row[marginIdx].trim();rwMargin = rawlace(/[^0-9,\.-]/g, '').replace(',argin=arseFloat(rawMargin);if (isNa {margin = ull; // Jeśli wartość nie j, ustawna null}}let imgUrl = '';if (imae& row.length > imaggUrlg();}ltpdName = '';if (nameId& row.length nameIdx) {prodName= row[.trlet weight = null;if (pe &&ig/sługa ormatów typu "6 szt (60g)", "3x(20 g)", "12 itd.const sztGramMatch = prodName.matc(/(\d+)\s*(sz-9]*(\d+[\.,]?\d*)\s*(kg|gsztGramMatch) {const szt =t(sztGramonst val = sztGramMatch[3].replace(',', '.');const unit = szt4].toLowerCas(const num = parseFif (!isNaN(num) & {cnst singleWeight = unit === ': num / 100;weight = singleWeight // Fallback — np. "250g" bez licif (!weight) {const wagMatch =math(/(\d+[\.,]?\d*)\s*(kg|g)/i)MattaMatch[1].repla;contut = wagaMatch[2]);const num = parseFl!isNaN(num)) {wit = unit === 'kg' 000;}}}}if (weight === null && wei& row.length > weigtIdx) {const raweihtIdx].trim();const wagaMatch =ch(/(\d+[\.,]?\d*)\s*(kg|g)/i);if (wagat vatpl',);sit = wagaMatch[2].toLowerCase();t num = parseFloat(val);if ((num)) {weight = nit === 'kg' ? num :num / 1000;}}}if (weightull && gramaturaIdx != w.length > gramaturaIdx) {const awGramatura =maturIdm(saturaMatch = rwGramatura.match(/(\d+[\.,]?\d*)\s*(kg|g)/i)if (gramaturaMatch) {cst val = gramaturaMatch[1].replac '.');const uit = gramatura2].toLowerCase();con = parseFloat(val);if (!isNaN(num)) weight = unit === 'kg' ? num: num / 1000;}}netNetNetPrice = ieiceIdx !== -1) {console.log'eNttPriceIdx:', netNetNetPricconsole.log('row[netNetNetPrceIdx[netNetNetPriceIdx]awetNetNetPrice =NetNetPriceIdx]?.trim(rawNetNetNePrice = rawNetNetNetPrice.r/g, '').replace(',', 'e(/[\d.]/g, '').rep');consol.log('Raw nie:', rawNetNetNetPrice);const parsed (rawNteNPrice);cParsed netNetN parsed);ice = parsed;} =`p{i}`;if (!poductMap[productMap[key]rirmage: imgUrl, name: prodName, weight, netNrice };} else {productap[key] = {price: prouctMap[key].price || price,margin: prap[ke].margin || margin,image: productMap[ke].image || imgUme: prouctMap[key].name | prodName,weight: productMap[key]t || weigtnetNetNetPrice: productMap[key].netNeNetPricetNetNetPrice,};}// Obsługa danych konkuencjiif (compnNameIdx !== -1 && competitionPriceIdx !== -1 && competitionShopIdx !== -1)st copName = row[competitionNameIdx]?.trim();const compPriceRaw[competitionPriceIdx]?.tri();const compShop = row[compethopIdx]?.trim(;const compUrl = competitionUrlId !== -1 ? row[competitionUrlIdx]?.tr (ompName & compPriceRawmpShop) {const compPriceClean = compPriceRaw.replace(/[^0-9,\.]/g, '')replace(');const compPrice parseFloat(compPriceClean);if (!isNaNcompPrice)) {// ź czy ten produkt jż istnieje w danych konkurencjiconst existingIndex = competata.findIndex(tem => item.name === compName && itm.shop === compShop);isdex === -1) {competitionData.puame: omNe,price: compPrice,shop: comphop,url: compUrl || ''});}}}}}alert(`Wczytano ct.keys(productMap).length} produkpliku CSV.`);console.log('Załadowane produkty:', roductMap); // Debugif (coionData.length > 0) {rnderComo();alert(`Dodatkowo wczytano ${comptitionData.length} pozycji konkur`);}}// Zamienia np. 5,2 lub 5.90534E+12 na normalny EA function parseEANraw) {if (!raw) retur// Usuń cudzysłowy i spacjeraw = raw.replace(/.trim()// Spróbuj zinterpretowliczbę, jeśnotacji nauwejlet num =raac if (!isaN(num)) {// Zamień na string bjilet str = num.toFixed0);if gth >= 8 && str.length a.pce(idex1);renderCompetiionTable(CeldendtionsCell);competitonTableBody.appendChild(rw);});}function aionItem() {const na = competitionNameI.trim();constprice = parseFloat(competitionPriceInput.lue);p = competitionShe.trim();consturl = competitionUrlIput.vaif (!name || isNaN(pce) || !shop) {alj wszystkie wymagae pola (naklep).');return;}ata.pus({name: name,price: price,shop: rlycmupameInput.value = '';competitionPriceInput.value = '';competionShopInput';competitionUrlInput.value = '';renerCompee();}function searchCompetitionByEan(){const ean = competitionEanI.trim(;if (!ea) {aEAN produktu.');return;/ Pokaż wskaźnik ładhStatus.style.display = 'block';earchMessage ' produktów w internZablokuj rzycisk wyszukiwaniasarchCompetab;mptntent = 'Wyszukiwanie...';lacjawyszukiwania w internecieuctsOnline(ean).th(results => {if (results.length =archMssaennerHTML = '❌ Nie znaeziono produktów o podanym EAecie.';stTimeout(() => {searchStatus.style.display = 'none';return;}// Dodaj wszystkie zalezione produkty do tabeli konkurncjilet addedCount = 0;results.forEac(productprawdź czy produkt już istnieje tabelikonkurencjiongProduct competitionDta.find(item => itemproduct.name & item.shop === product.shop);ingroduct) {competition{re product.price,shop: product.sp,oduct.url});adCountrenderCompetitionTable();// Poaż komunikat o sukcesiesearchMessag.innerHTML `✅ Znaleresults.duktów,dano ${addych pozycji do tabeli konkurencji.`;/formulaz danymi z pierwszego produktuif gth > 0) {const firstProduct = results[ionNameInput.value firstProduct.nme;riceInput.value = firstProuct.price.toFixtitionShopInput.alue = firstProduct.shop;competitonUrlInput.valPro;rs po 5 sekundachsetTimeout(()archStatus.style.display = 'none';}, 5000);).catch(error => {onsole.error('Błąd podczaania:', errr);searhssage.innerHTML = '❌ Wystąodczas wyszukiwania produktów.';seTimeout(() => {seasyle.display = 'none';}, 3000);}).finally(() =>okuj przycisk wyszukiwaniaseachCompetitionBtn.disabled = false;searchCometitt'Wyszukaj';});}// Funkcja do pobierania rokcie z API bacodeasync function getProductIfoFromBarcode(ean) {try {//mweg API UPC Dtabaseconst response = awtsemdb.com/prod/trial/looku;cnst data = await response.json();if (data.code === 'OK' && data.items.length > 0) {const item = datitems[0]; item.title || item.brand || `rodukt ${ean},brd |iiption || '',image: item.imges.length > 0 ? item.i} catch (eror)Błąd podczas pobiektu:', error);}// Symulacja wyszuk w ic rcnl {n oresolve) => {/ Symulacja opóźnienia zapytnia do APIsetTimeut(() => {//dź czy mamy dane dla tego EAN w nasej baziecst localPr= productap[ean];const productNaalProduct ? localPoduct.nrodukt EAN: ${ean}`;// Symulowane dane z różnych sklepówcont mockResultsn pcece: 15.99,shop: 'Allegro',rl: `http://allegro.pl/search?string=${ean}`},ame: roductName,price: shop: 'OLX',url: `htww.olx.pl/oferty/q-${ean}/ame oductName,price: 14.25,shopel: `https://www.ceneopl/search;szukaj-${ean}`},{name: productNamee: 6.80,hop: 'Amazon',url: `https//wzon.pl/s?k=${ean}`e: productName,price: 13.99,hik',url: `https://www.empearch?q=$an}`},{name: productName,price: 18.45, '',url: `htps://www.morele.net/search/q=${ean}`},{name: productName,pri.75,shop: 'Euo RTV AGD',url: `htps:/u.pl/search.bhkedan}`}];if (localroduct) {// Użyjczywistej ceny jako bazowej i ddaj losową wariaonst basePrice = localProduct.prce;mockResulth(result => {result.price =b + (Mathm(5) * 8;esult.price = Mathesult.pric; // Nie może być jemnaresult.price = Math.round(esult.price * 100) / Zaokrąglij do 2 miejsc po przecinkuse {/Jeśli nie ma lokalnych danycpodstawoyą losowościąmockesults.forEach(r> {result.price 10 + Math.random() * 20e10 do 30 złresult.prie = Math.round(resut * 100 / 100;esolv(mockResults);} // Symulacja 1 sekuny opóźnienia});}/ Funkcja do reczywzukiwania (wymaga API kec searchProductsOnlinRelenst results = [];try {// rzykład wwania Awymaga API key)// const allegroespoawtch(`http://api.allegr.pl/serch?ean=$);// const ala = await alleroeponse.json();kład yszukiwania w Ceno (wymaga APIub web sc// const ceneoResponse =awihttps://www.ceneo.l/api/sarch?ean=`)oneoData =awaiteoReson();// Dodaj wi do tablc rults}ch (error) {coor('Błąd podczas wyszukiwania:'ror);}return results;}functionompetitionData(ascending = tru) {coi.sort((a, b) => {f (ascending) {return a b.price;}else {return b.price - a.pricmpetitionTable();}// Evet listenery dla sekurencjisearchCompetitionBtn.addEvner('click', searchCompetit)pettiontn.addEventListener('click', addCompeti);sortAscBtn.adEventListener('click', ( => stitionData(true));sortDescBeer('click', () =>sortCompetitionData(false));matyczne wyszukiwaie przy zmianiepetitonEanInput.addEventLii) => {const en =cpetitionEanInput.value.trnsole.log('WyszuN:', ean); // Debugconsole.log('Dostępne ect.keys(oductap));if (ean && productMap[est produc = productMap[ean];og('Znaleziono produkt:', pr// Debugct.name) {ompetitionNameIne t.name;}if (product.priceeceInput.value = product.price.toFixed(2);}// Usślną nazwę sklepuif (!competitionShopInput.value.trcompetitionShopInput.value = 'Na';}} else / Wyczyść pola jeśli został znezionycompetiionNameInput.valuepetitionPriceInput.vau= '';if nsole.lgNie znaleziono dlaean); // Debug}}});// Atomatycukiwanie przynaciśnięciu EnteetitionEanInput.adEventLitener('keypr(e) i.=== 'nter') {searchCometion);}});


Подробнее здесь: https://stackoverflow.com/questions/797 ... n-javascri
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как исправить расчет маржи и импорт чистой/чистой цены на основе CSV в веб-приложении JavaScript? [закрыто]
    Anonymous » » в форуме Html
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Как предотвратить разрушение маржи без изменения маржи?
    Anonymous » » в форуме Javascript
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • Как предотвратить разрушение маржи без изменения маржи?
    Anonymous » » в форуме Html
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Как предотвратить разрушение маржи без изменения маржи?
    Anonymous » » в форуме CSS
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • Расчет цены товара в корзине на основе выбранного настраиваемого поля «дни» в Woocommerce.
    Anonymous » » в форуме Php
    0 Ответы
    92 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»