-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
573 lines (448 loc) · 15.4 KB
/
app.js
File metadata and controls
573 lines (448 loc) · 15.4 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// ================= DATABASE SETUP =================
let isNewBooking = false;
const APP_VERSION = 1;
const VERSION_URL = "https://raw.githubusercontent.com/CodeofAditya/Mira/refs/heads/main/version.txt";
const DB_NAME = "TransportDB";
const STORE_NAME = "bookings";
const DISPATCH_DB_NAME = "DispatchDB";
const DISPATCH_STORE = "dispatchBranchState";
let db;
const request = indexedDB.open(DB_NAME, 3);
request.onupgradeneeded = e => {
db = e.target.result;
if (!db.objectStoreNames.contains("bookings")) {
db.createObjectStore("bookings", { keyPath: "branch" });
}
if (!db.objectStoreNames.contains("counters")) {
const counterStore = db.createObjectStore("counters", { keyPath: "name" });
counterStore.put({ name: "receiptNo", value: 1200 });
}
};
request.onsuccess = e => {
db = e.target.result;
checkForAppUpdate();
if (document.getElementById("branchSelect")) initHomePage();
if (document.getElementById("branchFrom")) initBookingPage();
};
request.onerror = e => console.error("IndexedDB error:", e);
function getSelectedBranch() {
return localStorage.getItem("selectedBranch") || sessionStorage.getItem("selectedBranch");
}
function setSelectedBranch(branch) {
localStorage.setItem("selectedBranch", branch);
sessionStorage.setItem("selectedBranch", branch);
}
function initHomePage() {
const selectBtn = document.querySelector(".select-btn");
const branchSelect = document.getElementById("branchSelect");
const savedBranch = getSelectedBranch();
if (savedBranch) branchSelect.value = savedBranch;
selectBtn.onclick = () => {
if (!branchSelect.value) {
alert("Please select a branch");
return;
}
alert(`Branch set to ${branchSelect.value}`);
};
}
// ================= BOOKING INIT =================
function initBookingPage() {
const branch = getSelectedBranch();
const branchInput = document.getElementById("branchFrom");
const pickupFrom = document.getElementById("pickupFrom");
if (!branch) {
alert("No branch selected");
return;
}
branchInput.value = branch;
branchInput.readOnly = true;
// Sync pickup from here
pickupFrom.value = branch;
lockForm();
loadLatestBooking(branch);
setupButtons(branch);
setupEnterNavigation();
setupBookingFeeCalculations();
}
async function checkForAppUpdate() {
try {
const response = await fetch(`${VERSION_URL}?t=${Date.now()}`, {
cache: "no-store"
});
if (!response.ok) return;
const remoteVersion = Number.parseInt((await response.text()).trim(), 10);
if (Number.isNaN(remoteVersion) || remoteVersion <= APP_VERSION) return;
const shouldUpdate = window.confirm(
`A new app version (${remoteVersion}) is available. Update now?`
);
if (!shouldUpdate) return;
await forceRefreshApp();
} catch (error) {
console.warn("Version check failed:", error);
}
}
async function forceRefreshApp() {
if ("serviceWorker" in navigator) {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map(registration => registration.unregister()));
}
if ("caches" in window) {
const keys = await caches.keys();
await Promise.all(keys.map(key => caches.delete(key)));
}
location.href = `${location.pathname}?updated=${Date.now()}`;
}
// ================= LOCK / UNLOCK =================
function lockForm() {
document
.querySelectorAll(".booking-body input, .booking-body select")
.forEach(el => {
if (el.id !== "branchFrom") {
el.tagName === "SELECT"
? (el.disabled = true)
: (el.readOnly = true);
}
});
}
function unlockForm() {
document
.querySelectorAll(".booking-body input, .booking-body select")
.forEach(el => {
if (el.id !== "branchFrom") {
if (el.id === "freight" || el.id === "total") {
el.readOnly = true;
return;
}
el.tagName === "SELECT"
? (el.disabled = false)
: (el.readOnly = false);
}
});
}
function setupBookingFeeCalculations() {
const weightInput = document.getElementById("weight");
const freightRateInput = document.getElementById("freightExtra");
const freightInput = document.getElementById("freight");
const doorDeliveryInput = document.getElementById("doorDelivery");
const extraCharges1Input = document.getElementById("extraCharges1");
const extraCharges2Input = document.getElementById("extraCharges2");
const totalInput = document.getElementById("total");
if (
!weightInput ||
!freightRateInput ||
!freightInput ||
!doorDeliveryInput ||
!extraCharges1Input ||
!extraCharges2Input ||
!totalInput
) {
return;
}
freightInput.readOnly = true;
totalInput.readOnly = true;
const toNumber = value => {
const n = Number.parseFloat(value);
return Number.isFinite(n) ? n : 0;
};
const recalculate = () => {
const weight = toNumber(weightInput.value);
const freightRate = toNumber(freightRateInput.value);
const freight = weight * freightRate;
freightInput.value = freight ? freight : "";
const total =
freight +
toNumber(doorDeliveryInput.value) +
toNumber(extraCharges1Input.value) +
toNumber(extraCharges2Input.value);
totalInput.value = total ? total : "";
};
[
weightInput,
freightRateInput,
doorDeliveryInput,
extraCharges1Input,
extraCharges2Input
].forEach(input => {
input.addEventListener("input", recalculate);
});
recalculate();
}
// ================= NEW BOOKING =================
function newBooking() {
isNewBooking = true;
unlockForm();
document
.querySelectorAll(".booking-body input, .booking-body select")
.forEach(el => {
if (el.id !== "branchFrom") el.value = "";
});
// Re-sync pickup after clear
document.getElementById("pickupFrom").value =
document.getElementById("branchFrom").value;
const lr = document.getElementById("lrNo");
lr.readOnly = false;
lr.focus();
}
function getNextReceiptNo(callback) {
const tx = db.transaction("counters", "readwrite");
const store = tx.objectStore("counters");
const req = store.get("receiptNo");
req.onsuccess = () => {
const data = req.result || { name: "receiptNo", value: 1200 };
const next = data.value + 1;
data.value = next;
store.put(data);
callback(next);
};
req.onerror = () => {
alert("Failed to generate receipt number");
};
}
// ================= SAVE BOOKING =================
function saveData(branch) {
const booking = {};
document.querySelectorAll(".booking-body input, .booking-body select")
.forEach(el => {
if (el.id) booking[el.id] = el.value.trim();
});
booking.branchFrom = branch;
if (!booking.lrNo) {
alert("LR No is required");
return;
}
const doSave = receiptNo => {
if (receiptNo !== null) booking.receiptNo = receiptNo;
const tx = db.transaction(STORE_NAME, "readwrite");
const store = tx.objectStore(STORE_NAME);
const getReq = store.get(branch);
getReq.onsuccess = () => {
const data = getReq.result || { branch, bookings: {} };
// FIX: ensure bookings exists
if (!data.bookings) data.bookings = {};
if (isNewBooking && data.bookings[booking.lrNo]) {
alert("This LR No already exists");
return;
}
data.bookings[booking.lrNo] = booking;
const putReq = store.put(data);
putReq.onsuccess = () => {
isNewBooking = false;
lockForm();
alert("Booking saved successfully");
};
putReq.onerror = () => alert("Save failed");
};
};
if (isNewBooking) {
// NEW booking: get receipt number
getNextReceiptNo(doSave);
} else {
// EDIT existing: keep receipt number
doSave(booking.receiptNo || null);
}
}
function getDispatchDetailsForLr(branch, lrNo) {
return new Promise(resolve => {
if (!branch || !lrNo) {
resolve(null);
return;
}
const request = indexedDB.open(DISPATCH_DB_NAME, 1);
request.onsuccess = e => {
const dispatchDb = e.target.result;
const tx = dispatchDb.transaction(DISPATCH_STORE, "readonly");
const store = tx.objectStore(DISPATCH_STORE);
const req = store.get(branch);
req.onsuccess = () => {
const details = req.result?.dispatchDetailsByLr?.[lrNo] || null;
resolve(details);
};
req.onerror = () => resolve(null);
tx.oncomplete = () => dispatchDb.close();
};
request.onerror = () => resolve(null);
});
}
function applyDispatchDetailsToForm(details) {
const memo = document.getElementById("dispatchMemo");
const dispatchDate = document.getElementById("dispatchDate");
const vehicleNo = document.getElementById("vehicleNo");
if (!memo || !dispatchDate || !vehicleNo) return;
memo.value = details?.dispatchNo || "";
dispatchDate.value = details?.dispatchDate || "";
vehicleNo.value = details?.vehicleNo || "";
}
async function syncDispatchSectionForCurrentLr() {
const branch = getSelectedBranch();
const lrNo = document.getElementById("lrNo")?.value?.trim();
const details = await getDispatchDetailsForLr(branch, lrNo);
applyDispatchDetailsToForm(details);
}
// ================= LOAD LATEST =================
async function loadLatestBooking(branch) {
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get(branch);
req.onsuccess = async () => {
if (!req.result || !req.result.bookings) return;
const bookings = req.result.bookings;
const lastLR = Object.keys(bookings).sort().pop();
const data = bookings[lastLR];
Object.keys(data).forEach(id => {
const el = document.getElementById(id);
if (el) el.value = data[id];
});
lockForm();
await syncDispatchSectionForCurrentLr();
};
}
// ================= BUTTONS =================
function setupButtons(branch) {
document.getElementById("btnNew").onclick = newBooking;
document.getElementById("btnEdit").onclick = unlockForm;
document.getElementById("btnSave").onclick = () => saveData(branch);
document.getElementById("btnPrint").onclick = printReceipt;
document.getElementById("btnDelete").onclick = () => alert("Delete later");
document.getElementById("btnFind").onclick = openFindPopup;
document.getElementById("btnPreview").onclick = previewReceipt;
}
// ================= ENTER NAV =================
function setupEnterNavigation() {
const inputs = [...document.querySelectorAll(".booking-body input")];
inputs.forEach((input, i) => {
input.onkeydown = e => {
if (e.key === "Enter") {
e.preventDefault();
inputs[i + 1]?.focus();
}
};
});
}
// ================= PRINT =================
function printReceipt() {
const branch = getSelectedBranch();
const lrNo = document.getElementById("lrNo").value;
if (!lrNo) {
alert("Enter LR No to print");
return;
}
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get(branch);
req.onsuccess = () => {
const booking = req.result?.bookings?.[lrNo];
if (!booking) {
alert("No booking found");
return;
}
const html = generateReceiptHTML(booking);
receiptLeft.innerHTML = html;
receiptRight.innerHTML = html;
printArea.style.display = "block";
setTimeout(() => {
window.print();
printArea.style.display = "none";
}, 300);
};
}
function generateReceiptHTML(d) {
const tpl = document.getElementById("receiptTemplate").content.cloneNode(true);
tpl.querySelector("[data-booking-date]").textContent = d.bookingDate || "";
tpl.querySelector("[data-lr-no]").textContent = d.lrNo || "";
tpl.querySelector("[data-route]").textContent =
`${d.branchFrom || ""} TO ${d.branchTo || ""}`;
tpl.querySelector("[data-sender]").textContent = d.sender || "";
tpl.querySelector("[data-receiver]").textContent = d.receiver || "";
tpl.querySelector("[data-mobile]").textContent = d.mobile || "";
tpl.querySelector("[data-content]").textContent = d.content || "";
tpl.querySelector("[data-pkg]").textContent = d.pkgDetail || "";
tpl.querySelector("[data-packages]").textContent = d.packages || "";
tpl.querySelector("[data-weight]").textContent = d.weight || "";
tpl.querySelector("[data-total]").textContent = `TO PAY : ${d.total || ""}`;
const wrapper = document.createElement("div");
wrapper.appendChild(tpl);
return wrapper.innerHTML;
}
function previewReceipt() {
const branch = getSelectedBranch();
if (!branch) return alert("No branch selected");
const lrNo = document.getElementById("lrNo").value;
if (!lrNo) return alert("Enter LR No to preview");
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get(branch);
req.onsuccess = () => {
const data = req.result?.bookings?.[lrNo];
if (!data) return alert("No booking found");
const overlay = document.createElement("div");
overlay.className = "overlay";
const popup = document.createElement("div");
popup.className = "popup";
popup.innerHTML = generateReceiptHTML(data);
overlay.appendChild(popup);
document.body.appendChild(overlay);
overlay.onclick = e => {
if (e.target === overlay) document.body.removeChild(overlay);
};
};
}
function openFindPopup() {
const branch = getSelectedBranch();
if (!branch) return alert("No branch selected");
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get(branch);
req.onsuccess = () => {
const bookings = req.result?.bookings;
if (!bookings) return alert("No bookings found");
const tpl = document.getElementById("findPopupTemplate").content.cloneNode(true);
const overlay = tpl.querySelector(".overlay");
const list = tpl.querySelector("#lrList");
Object.keys(bookings).sort().forEach(lr => {
list.innerHTML += `<option value="${lr}">${lr}</option>`;
});
document.body.appendChild(tpl);
list.onchange = e =>
document.getElementById("findLR").value = e.target.value;
document.getElementById("findCancel").onclick = () =>
document.body.removeChild(overlay);
document.getElementById("findLoad").onclick = () => {
const lr = document.getElementById("findLR").value.trim();
if (!bookings[lr]) return alert("Invalid LR No");
loadBookingToForm(bookings[lr]);
document.body.removeChild(overlay);
};
};
}
async function loadBookingToForm(data) {
Object.keys(data).forEach(id => {
const el = document.getElementById(id);
if (el) el.value = data[id];
});
lockForm();
await syncDispatchSectionForCurrentLr();
}
const branchTo = document.getElementById("branchTo");
const deliveryTo = document.getElementById("deliveryTo");
if (branchTo && deliveryTo) {
branchTo.addEventListener("change", () => {
deliveryTo.value = branchTo.value;
});
}
document.querySelectorAll(".drop-btn").forEach(btn => {
const menu = btn.nextElementSibling;
if (!menu) return; // skip if no menu exists
btn.addEventListener("click", e => {
e.stopPropagation(); // prevent the document click handler immediately closing it
// Close other menus
document.querySelectorAll(".drop-menu").forEach(m => {
if (m !== menu) m.style.display = "none";
});
// Toggle this menu
menu.style.display = menu.style.display === "block" ? "none" : "block";
});
});
// Close all menus when clicking outside
document.addEventListener("click", () => {
document.querySelectorAll(".drop-menu").forEach(m => (m.style.display = "none"));
});