Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
334 lines (272 loc) · 9.92 KB
/
Copy pathscript.js
File metadata and controls
334 lines (272 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
* FuelSim - Professional Gas Station Simulator
* Modular Architecture
*/
const FuelSim = (() => {
// --- Configuration ---
const CONFIG = {
PUMP_UPDATE_INTERVAL_MS: 50,
FLOW_RATE_LITERS_PER_SEC: 1.5,
PRICES: {
petrol: 111.20,
diesel: 97.83,
xfuel: 120.40
},
IDLE_TIMEOUT_MS: 120000,
PRICE_UPDATE_INTERVAL_MS: 10000
};
// --- Application State ---
const state = {
selectedFuel: 'petrol',
calcMode: 'liters', // 'liters' or 'price'
targetAmount: 0,
dispensedVolume: 0,
totalCost: 0,
isPumping: false,
intervalId: null,
idleTimerId: null
};
// --- DOM Elements ---
const elements = {
body: document.body,
// Inputs
fuelBtns: document.querySelectorAll('.fuel-btn'),
calcMode: document.getElementById('calcMode'),
amountInput: document.getElementById('amountInput'),
// Action Buttons
startBtn: document.getElementById('startBtn'),
stopBtn: document.getElementById('stopBtn'),
resetBtn: document.getElementById('resetBtn'),
printBtn: document.getElementById('printBtn'),
copyCryptoBtn: document.getElementById('copyCryptoBtn'),
// Displays
displayFuel: document.getElementById('displayFuel'),
displayPrice: document.getElementById('displayPrice'),
displayVolume: document.getElementById('displayVolume'),
displayTotal: document.getElementById('displayTotal'),
// Modal
receiptModal: document.getElementById('receiptModal'),
closeReceiptBtn: document.getElementById('closeReceiptBtn'),
// Receipt fields
receiptDate: document.getElementById('receiptDate'),
receiptFuel: document.getElementById('receiptFuel'),
receiptUnitPrice: document.getElementById('receiptUnitPrice'),
receiptVolume: document.getElementById('receiptVolume'),
receiptTotal: document.getElementById('receiptTotal'),
};
// --- Formatting Utilities ---
const formatters = {
currency: (value) => `₹${value.toFixed(2)}`,
volume: (value) => `${value.toFixed(2)} L`,
capitalize: (str) => str.charAt(0).toUpperCase() + str.slice(1)
};
// --- Core Logic ---
const getPrice = () => CONFIG.PRICES[state.selectedFuel];
const updateDisplays = () => {
elements.displayFuel.textContent = formatters.capitalize(state.selectedFuel);
elements.displayPrice.textContent = formatters.currency(getPrice());
elements.displayVolume.textContent = formatters.volume(state.dispensedVolume);
elements.displayTotal.textContent = formatters.currency(state.totalCost);
};
const setFuelType = (type) => {
if (state.isPumping) return;
// Auto reset if switching fuels and we have dispensed or targeted amount
if (state.selectedFuel !== type && (state.dispensedVolume > 0 || state.targetAmount > 0)) {
resetPump();
}
state.selectedFuel = type;
elements.body.setAttribute('data-fuel', type);
elements.fuelBtns.forEach(btn => {
btn.classList.toggle('active', btn.dataset.type === type);
});
recalculateDerivedState();
updateDisplays();
};
const setCalcMode = (mode) => {
if (state.isPumping) return;
state.calcMode = mode;
if (mode === 'liters') {
elements.amountInput.placeholder = "Enter target volume (L)";
elements.amountInput.step = "0.01";
} else {
elements.amountInput.placeholder = "Enter target price (₹)";
elements.amountInput.step = "1";
}
};
const recalculateDerivedState = () => {
// If not pumping, ensure volume and cost match
if (!state.isPumping) {
if (state.dispensedVolume > 0) {
state.totalCost = state.dispensedVolume * getPrice();
}
}
};
const resetPump = () => {
if (state.isPumping) stopPump();
state.targetAmount = 0;
state.dispensedVolume = 0;
state.totalCost = 0;
elements.amountInput.value = '';
elements.amountInput.disabled = false;
elements.calcMode.disabled = false;
elements.startBtn.disabled = false;
elements.stopBtn.disabled = true;
elements.printBtn.disabled = true;
updateDisplays();
};
const startPump = () => {
if (state.isPumping) return;
const inputValue = parseFloat(elements.amountInput.value);
if (isNaN(inputValue) || inputValue <= 0) {
elements.amountInput.focus();
// Brief error indication
elements.amountInput.style.borderColor = 'var(--color-error)';
setTimeout(() => elements.amountInput.style.borderColor = '', 1000);
return;
}
state.targetAmount = inputValue;
state.isPumping = true;
// Lock inputs
elements.amountInput.disabled = true;
elements.calcMode.disabled = true;
// Toggle buttons
elements.startBtn.disabled = true;
elements.stopBtn.disabled = false;
elements.printBtn.disabled = true;
// Start interval
const updateStep = CONFIG.PUMP_UPDATE_INTERVAL_MS / 1000; // seconds
const volumeIncrement = CONFIG.FLOW_RATE_LITERS_PER_SEC * updateStep;
state.intervalId = setInterval(() => {
pumpTick(volumeIncrement);
}, CONFIG.PUMP_UPDATE_INTERVAL_MS);
};
const stopPump = () => {
if (!state.isPumping) return;
clearInterval(state.intervalId);
state.isPumping = false;
elements.startBtn.disabled = false;
elements.stopBtn.disabled = true;
elements.printBtn.disabled = false; // Transaction complete, can print
};
const pumpTick = (volumeIncrement) => {
const currentPrice = getPrice();
let isComplete = false;
if (state.calcMode === 'liters') {
state.dispensedVolume += volumeIncrement;
state.totalCost = state.dispensedVolume * currentPrice;
if (state.dispensedVolume >= state.targetAmount) {
state.dispensedVolume = state.targetAmount;
state.totalCost = state.dispensedVolume * currentPrice;
isComplete = true;
}
} else {
// mode === 'price'
const priceIncrement = volumeIncrement * currentPrice;
state.totalCost += priceIncrement;
state.dispensedVolume = state.totalCost / currentPrice;
if (state.totalCost >= state.targetAmount) {
state.totalCost = state.targetAmount;
state.dispensedVolume = state.totalCost / currentPrice;
isComplete = true;
}
}
updateDisplays();
if (isComplete) {
stopPump();
}
};
// --- Receipt Modal ---
const showReceipt = () => {
if (state.dispensedVolume === 0) return;
elements.receiptDate.textContent = new Date().toLocaleString();
elements.receiptFuel.textContent = formatters.capitalize(state.selectedFuel);
elements.receiptUnitPrice.textContent = `${formatters.currency(getPrice())}/L`;
elements.receiptVolume.textContent = formatters.volume(state.dispensedVolume);
elements.receiptTotal.textContent = formatters.currency(state.totalCost);
elements.receiptModal.classList.add('active');
};
const hideReceipt = () => {
elements.receiptModal.classList.remove('active');
};
// --- Copy Crypto ---
const copyCryptoAddress = async () => {
const address = "0xCd47D300a28E18443D19759D9957c347B86C2E27";
try {
await navigator.clipboard.writeText(address);
const span = elements.copyCryptoBtn.querySelector('span:last-child');
const originalText = span.textContent;
span.textContent = "(Copied!)";
span.style.color = "var(--color-success)";
setTimeout(() => {
span.textContent = originalText;
span.style.color = "";
}, 2000);
} catch (err) {
console.error('Failed to copy', err);
}
};
// --- Background Tasks (Idle Timer & Live Prices) ---
const resetIdleTimer = () => {
if (state.idleTimerId) clearTimeout(state.idleTimerId);
state.idleTimerId = setTimeout(() => {
// Auto reset meters after 120s of inactivity
if (state.dispensedVolume > 0 || state.targetAmount > 0) {
resetPump();
console.log("Pump auto-reset due to 120s inactivity.");
}
}, CONFIG.IDLE_TIMEOUT_MS);
};
const startLivePrices = () => {
setInterval(() => {
// Simulate real-time market fluctuations (+/- 0.05 to 0.15)
Object.keys(CONFIG.PRICES).forEach(fuel => {
const fluctuation = (Math.random() - 0.5) * 0.3;
CONFIG.PRICES[fuel] = Math.max(10, CONFIG.PRICES[fuel] + fluctuation);
});
// Only update UI if not currently pumping to avoid layout shifts/distractions
if (!state.isPumping) {
updateDisplays();
}
}, CONFIG.PRICE_UPDATE_INTERVAL_MS);
};
// --- Initialization & Event Binding ---
const init = () => {
// Bind Fuel Buttons
elements.fuelBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
setFuelType(e.target.dataset.type);
});
});
// Bind Calc Mode
elements.calcMode.addEventListener('change', (e) => {
setCalcMode(e.target.value);
});
// Bind Actions
elements.startBtn.addEventListener('click', startPump);
elements.stopBtn.addEventListener('click', stopPump);
elements.resetBtn.addEventListener('click', resetPump);
elements.printBtn.addEventListener('click', showReceipt);
// Bind Modal Close
elements.closeReceiptBtn.addEventListener('click', hideReceipt);
elements.receiptModal.addEventListener('click', (e) => {
if (e.target === elements.receiptModal) hideReceipt();
});
// Support / Copy
if (elements.copyCryptoBtn) {
elements.copyCryptoBtn.addEventListener('click', copyCryptoAddress);
}
// Activity bindings for idle timer
['mousemove', 'keydown', 'click', 'scroll', 'touchstart'].forEach(evt => {
document.addEventListener(evt, resetIdleTimer, { passive: true });
});
// Start background tasks
resetIdleTimer();
startLivePrices();
// Initial render
setCalcMode(state.calcMode);
updateDisplays();
};
return { init };
})();
// Initialize on DOM load
document.addEventListener('DOMContentLoaded', FuelSim.init);