PageSourceSearch

https://infinitepay-embeds.onrender.com/calculadora-de-desconto/script.js

js infinitepay-embeds.onrender.com collected 2026-10-03 11:41:00 UTC 7,537 bytes, 187 lines download raw bytes

1document.addEventListener('DOMContentLoaded', function() {
2  const productCostInput = document.getElementById('productCost');
3  const directCostsInput = document.getElementById('directCosts');
4  const indirectCostsInput = document.getElementById('indirectCosts');
5  const profitMarginInput = document.getElementById('profitMargin');
6  const resultsWrapper = document.getElementById('resultsWrapper');
7  
8    // Set initial values for the input fields
9  productCostInput.value = '';
10  directCostsInput.value = '';
11  indirectCostsInput.value = '';
12  profitMarginInput.value = '';
13
14 	// Function to check if all inputs are filled
15  function areAllInputsFilled() {
16    const inputs = [productCostInput, directCostsInput, indirectCostsInput, profitMarginInput];
17    return inputs.every(input => input.value.trim() !== '');
18  }
19
20  // Function to format values as currency (Brazilian Real)
21  function formatCurrency(value) {
22    let rawValue = value.replace(/[^0-9]/g, '');
23    if (rawValue.length === 1) {
24      return '0,0' + rawValue;
25    } else if (rawValue.length === 2) {
26      return '0,' + rawValue;
27    } else {
28      let integerPart = rawValue.slice(0, -2);
29      let decimalPart = rawValue.slice(-2);
30      integerPart = parseInt(integerPart, 10).toLocaleString('pt-BR');
31      return `${integerPart},${decimalPart}`;
32    }
33  }
34  
35  function formatAsCurrency(number) {
36    return new Intl.NumberFormat('pt-BR', {
37        style: 'currency',
38        currency: 'BRL',
39    }).format(number);
40	}
41
42  // Function to parse currency formatted as Brazilian Real to float
43  function parseCurrencyBRL(value) {
44    return parseFloat(value.replace(/\./g, '').replace(',', '.'));
45  }
46
47  // Function to limit value to 999,999.99
48  function limitValue(value) {
49    let rawValue = value.replace(/\D/g, '');
50    if (parseInt(rawValue, 10) > 9999999) {
51      return '999.999,99';
52    }
53    return value;
54  }
55  
56  function formatInputValue(input) {
57    // Check if the input's value is empty or not a number
58    if (input.value.trim() === '' || isNaN(parseCurrencyBRL(input.value))) {
59      input.value = ''; // Clear the input field to show the placeholder
60    } else {
61      // Format the value and check if it's zero
62      let formattedValue = limitValue(formatCurrency(input.value));
63      let numericValue = parseCurrencyBRL(formattedValue);
64      if (numericValue === 0) {
65        input.value = ''; // Clear the input field to show the placeholder
66      } else {
67        input.value = formattedValue; // Set the formatted value if it's not zero
68      }
69    }
70  }
71
72  // Function to calculate and update results
73  function calculateAndUpdateResults() {
74  
75    if (!areAllInputsFilled()) {
76      return; // Stop the function if validation fails
77    }
78    // Call formatInputValue for each input field before calculation
79    formatInputValue(productCostInput);
80    formatInputValue(directCostsInput);
81    formatInputValue(indirectCostsInput);
82
83    // Use raw value for profitMarginInput without any formatting
84    const profitMargin = parseFloat(profitMarginInput.value) / 100;
85    const currentPrice = parseCurrencyBRL(productCostInput.value);
86    const directCosts = parseCurrencyBRL(directCostsInput.value);
87    const indirectCosts = parseCurrencyBRL(indirectCostsInput.value);
88
89    const totalCost = directCosts + indirectCosts;
90    const currentProfitMargin = ((currentPrice - totalCost) / currentPrice) * 100;
91    const profitPerProduct = currentPrice - totalCost;
92    let minimumSalePrice;
93    // Check if the profit margin is 100% or less
94    if (profitMargin <= 1) {
95      minimumSalePrice = totalCost / (1 - profitMargin);
96    } else {
97      // For profit margin above 100%, the sale price is cost multiplied by (1 + profit margin)
98      minimumSalePrice = totalCost * (profitMargin + 1);
99    }
100    
101    // Get the elements by their IDs
102    const actualMarginLabel = document.getElementById('actualMarginLabel');
103    const actualProfitLabel = document.getElementById('actualProfitLabel');
104    const profitPriceResult = document.getElementById('profitPriceResult');
105		
106    if (profitMargin < 0 || profitPerProduct < 0) {
107      // Update the UI for the no profit scenario
108      actualMarginLabel.innerText = "Sua margem de lucro atual é negativa: ";
109      actualProfitLabel.innerText = "perde ";
110    	profitPriceResult.innerText = formatAsCurrency(profitPerProduct);
111    } else {
112      // Update the UI for the profit scenario
113      actualMarginLabel.innerText = "Sua margem de lucro atual é de ";
114      actualProfitLabel.innerText = "ganha ";
115    	profitPriceResult.innerText = formatAsCurrency(profitPerProduct);
116    }
117
118    document.getElementById('productCostResult').innerText = formatAsCurrency(totalCost);
119		document.getElementById('profitMarginResult').innerText = `${currentProfitMargin.toFixed(2).replace('.', ',')}`;
120		document.getElementById('idealPriceResult').innerText = formatAsCurrency(minimumSalePrice);
121		
122    if (marginPercentageResult) {
123      // Check if the inputted value represents an integer
124      let profitMarginValue = profitMarginInput.value.replace(',', '.');
125      if (profitMarginValue.endsWith('.00') || profitMarginValue === parseInt(profitMarginValue, 10).toString()) {
126        // It's an integer, remove the decimal part
127        marginPercentageResult.innerText = parseInt(profitMarginValue, 10);
128      } else {
129        // It's not an integer, display as is with a percent sign
130        marginPercentageResult.innerText = profitMarginInput.value;
131    	}
132  	}
133  }
134
135  // Event listeners for each input to format its value as the user types or leaves the input field
136  [productCostInput, directCostsInput, indirectCostsInput].forEach(input => {
137    input.addEventListener('keyup', function() {
138      formatInputValue(input);
139    });
140    input.addEventListener('blur', function() {
141      formatInputValue(input);
142    });
143  });
144
145  // Select all calculate buttons by their class name
146  const calculateButtons = document.querySelectorAll('.calculatebutton');
147  calculateButtons.forEach(button => {
148    button.addEventListener('click', function() {
149      calculateAndUpdateResults();
150    });
151  });
152
153
154   // Define the function to clear all inputs and reset specific result fields
155  function clearAllInputs() {
156    // Clear all text input fields
157    const inputs = document.querySelectorAll('input[type=text]');
158    inputs.forEach(input => {
159        input.value = ''; // This will clear the input and show the placeholder
160    });
161    // Reset specific result fields to "R$ 0,00"
162    const currencyResultsToReset = [document.getElementById('productCostResult'), 
163                                    document.getElementById('profitPriceResult'),
164                                    document.getElementById('idealPriceResult')];
165    currencyResultsToReset.forEach(resultElement => {
166        if (resultElement) {
167            resultElement.innerText = 'R$ 0,00';
168        }
169    });
170    // Reset percentage result fields to "0%"
171    const percentageResultsToReset = [document.getElementById('profitMarginResult'), 
172                                      document.getElementById('marginPercentageResult')];
173    percentageResultsToReset.forEach(resultElement => {
174        if (resultElement) {
175            resultElement.innerText = '0';
176        }
177    });
178	}
179  
180  // Select all clear buttons by their class name
181  const clearButtons = document.querySelectorAll('.clearinputs');
182  // Add the event listener to the clear button
183	clearButtons.forEach(button => {
184      button.addEventListener('click', clearAllInputs);
185  });
186  
187});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.