-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathosda_efilling_editor.js
More file actions
483 lines (407 loc) · 15.6 KB
/
osda_efilling_editor.js
File metadata and controls
483 lines (407 loc) · 15.6 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
(() => {
const CATEGORY_MAP = {
"ใช้สอย": "general",
"ตอบแทน": "people",
"วัสดุ": "materials",
"ครุภัณฑ์": "articles",
"สาธารณูปโภค": "utilities",
};
const CATEGORY_KEYS = Object.values(CATEGORY_MAP);
let expState = null;
let formsState = null;
let fundingState = null;
let draggedItemInfo = null;
function getVueInstance(el) {
return el.__vue__ || (el.__vnode && el.__vnode.context);
}
function isValidExpensesModel(obj) {
return (
obj &&
typeof obj === "object" &&
CATEGORY_KEYS.every((key) => Array.isArray(obj[key]))
);
}
function findActiveTable() {
let allTables = document.querySelectorAll("table.table-striped");
return (
Array.from(allTables).find((t) => t.textContent.includes("หมวดค่า")) ||
allTables[allTables.length - 1]
);
}
function getRowItemIndex(row) {
let index = 0;
let prev = row.previousElementSibling;
while (prev) {
if (prev.querySelector("strong")) break;
if (prev.children.length >= 10) index++;
prev = prev.previousElementSibling;
}
return index;
}
function setDropIndicator(targetRow, direction) {
targetRow.querySelectorAll("td").forEach((td) => {
td.style.borderTop = direction === "top" ? "2px solid #007bff" : "";
td.style.borderBottom = direction === "bottom" ? "2px solid #007bff" : "";
});
}
function clearDropIndicator(targetRow) {
targetRow.querySelectorAll("td").forEach((td) => {
td.style.borderTop = "";
td.style.borderBottom = "";
});
}
function ensureConnection() {
if (!window.location.href.includes("/budget/edit")) {
expState = null;
formsState = null;
return false;
}
let table = findActiveTable();
if (!table) {
expState = null;
formsState = null;
return false;
}
if (expState && formsState) {
let currEl = table;
let stillValid = false;
while (currEl && !stillValid) {
let vm = getVueInstance(currEl);
if (vm && vm.$data && (vm.$data.forms === formsState || vm.$data.form === formsState)) {
stillValid = true;
}
currEl = currEl.parentElement;
}
if (!stillValid) {
expState = null;
formsState = null;
} else {
return true;
}
}
let currEl = table;
while (currEl && (!expState || !formsState)) {
let vm = getVueInstance(currEl);
if (vm) {
if (vm.$data && vm.$data.forms) formsState = vm.$data.forms;
else if (vm.$data && vm.$data.form) formsState = vm.$data.form;
let queue = [vm.$data, vm.$props];
let visited = new Set();
while (queue.length > 0) {
let curr = queue.shift();
if (!curr || typeof curr !== "object" || visited.has(curr)) continue;
visited.add(curr);
if (isValidExpensesModel(curr)) {
if (CATEGORY_KEYS.some((key) => curr[key].length > 0)) {
expState = curr;
break;
}
if (!expState) expState = curr;
}
if (curr && typeof curr === "object" && "isNotUse" in curr && "amount" in curr) {
fundingState = curr;
} else if (curr && curr.funding && typeof curr.funding === "object" && "isNotUse" in curr.funding) {
fundingState = curr.funding;
}
for (let k in curr) {
if (k.startsWith("$") || k.startsWith("_")) continue;
try {
let val = curr[k];
if (val && typeof val === "object") queue.push(val);
} catch (e) {}
}
}
}
currEl = currEl.parentElement;
}
return !!(expState && formsState);
}
function handleAutoFillFunding() {
let inputs = document.querySelectorAll('input[type="number"], input[type="text"]');
let fundingInput = null;
for (let input of inputs) {
let expr = null;
if (input.__vnode && input.__vnode.data && input.__vnode.data.directives) {
let vmodel = input.__vnode.data.directives.find((d) => d.name === "model");
if (vmodel) expr = vmodel.expression;
}
if (!expr && input.__vue__ && input.__vue__.$vnode && input.__vue__.$vnode.data && input.__vue__.$vnode.data.model) {
expr = input.__vue__.$vnode.data.model.expression;
}
if (
expr &&
expr.toLowerCase().includes("funding") &&
(expr.toLowerCase().includes("amount") || expr.toLowerCase().includes("osda"))
) {
fundingInput = input;
break;
}
}
if (!fundingInput) return;
let parent = fundingInput.parentElement;
let existingBtn = parent.querySelector(".osda-autofill-btn");
let isDisabled = fundingInput.disabled || fundingInput.readOnly;
if (!existingBtn) {
let btn = document.createElement("button");
btn.type = "button";
btn.className = "btn btn-outline-info btn-sm osda-autofill-btn";
btn.innerHTML = "✨ ดึงยอดรวมอัตโนมัติ";
btn.style.marginLeft = "8px";
btn.style.whiteSpace = "nowrap";
btn.onclick = () => {
let grandTotal = 0;
if (expState) {
CATEGORY_KEYS.forEach((cat) => {
if (expState[cat]) {
expState[cat].forEach((item) => {
let q = item.qty !== undefined && item.qty !== null && item.qty !== "" ? parseFloat(item.qty) : 1;
let p = parseFloat(item.amountEach || item.amount || item.price) || 0;
grandTotal += q * p;
});
}
});
}
let domTotal = 0;
let tables = document.querySelectorAll("table");
let summaryTable = Array.from(tables).find((t) => t.textContent.includes("จัดสรรแล้ว") || t.textContent.includes("รวมทั้งสิ้น"));
if (summaryTable) {
let text = summaryTable.textContent.replace(/,/g, "");
let matches = text.match(/(\d+\.\d{2})/g);
if (matches && matches.length > 0) {
let numbers = matches.map((m) => parseFloat(m));
domTotal = Math.max(...numbers);
}
}
let finalTotal = expState ? grandTotal : domTotal;
fundingInput.value = finalTotal;
fundingInput.dispatchEvent(new Event("input", { bubbles: true }));
fundingInput.dispatchEvent(new Event("change", { bubbles: true }));
if (fundingInput.__vue__) {
fundingInput.__vue__.$emit("input", finalTotal);
fundingInput.__vue__.$emit("update", finalTotal);
fundingInput.__vue__.$emit("change", finalTotal);
}
if (fundingState) {
fundingState.amount = finalTotal;
}
let oldHtml = btn.innerHTML;
btn.innerHTML = "รวม " + finalTotal.toLocaleString("en-US", { minimumFractionDigits: 2 }) + " บ.";
btn.classList.replace("btn-outline-info", "btn-success");
btn.classList.add("text-white");
setTimeout(() => {
btn.innerHTML = oldHtml;
btn.classList.replace("btn-success", "btn-outline-info");
btn.classList.remove("text-white");
}, 2000);
};
if (parent.classList.contains("input-group")) {
let appendDiv = document.createElement("div");
appendDiv.className = "input-group-append osda-autofill-btn-container";
btn.style.marginLeft = "0";
btn.classList.remove("btn-sm");
appendDiv.appendChild(btn);
parent.appendChild(appendDiv);
} else {
parent.style.display = "flex";
parent.style.alignItems = "center";
parent.appendChild(btn);
}
existingBtn = btn;
}
let container = existingBtn.closest(".osda-autofill-btn-container") || existingBtn;
container.style.display = isDisabled ? "none" : "";
}
function handleDragAndDrop(row, activeCatKey) {
if (row.dataset.osdaDragEnabled) return;
row.dataset.osdaDragEnabled = "true";
row.draggable = true;
let tds = row.children;
if (tds[0]) {
tds[0].style.cursor = "grab";
let handle = document.createElement("span");
handle.innerHTML = "☰ ";
handle.style.color = "#ccc";
handle.style.marginRight = "8px";
tds[0].insertBefore(handle, tds[0].firstChild);
}
row.addEventListener("dragstart", (e) => {
let fromIdx = getRowItemIndex(row);
draggedItemInfo = { catKey: activeCatKey, rowElement: row };
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", fromIdx);
setTimeout(() => (row.style.opacity = "0.4"), 0);
});
row.addEventListener("dragover", (e) => {
e.preventDefault();
if (draggedItemInfo && draggedItemInfo.catKey === activeCatKey && draggedItemInfo.rowElement !== row) {
let bounding = row.getBoundingClientRect();
let midpoint = bounding.top + bounding.height / 2;
if (e.clientY < midpoint) setDropIndicator(row, "top");
else setDropIndicator(row, "bottom");
}
});
row.addEventListener("dragleave", (e) => {
clearDropIndicator(row);
});
row.addEventListener("drop", (e) => {
e.preventDefault();
clearDropIndicator(row);
if (draggedItemInfo && draggedItemInfo.catKey === activeCatKey && draggedItemInfo.rowElement !== row) {
let fromIdx = getRowItemIndex(draggedItemInfo.rowElement);
let toIdx = getRowItemIndex(row);
let bounding = row.getBoundingClientRect();
let midpoint = bounding.top + bounding.height / 2;
if (e.clientY >= midpoint) toIdx++;
if (fromIdx < toIdx) toIdx--;
if (fromIdx !== toIdx) {
let list = expState[activeCatKey];
let itemToMove = list.splice(fromIdx, 1)[0];
list.splice(toIdx, 0, itemToMove);
}
}
});
row.addEventListener("dragend", (e) => {
row.style.opacity = "1";
draggedItemInfo = null;
document.querySelectorAll("tbody tr").forEach((r) => clearDropIndicator(r));
});
}
function handleRowEditing(row, boundItem, activeCatKey, capturedIndex, targetFormState) {
let tds = row.children;
let actionCell = tds[tds.length - 1];
if (actionCell.dataset.osdaEditEnabled || !actionCell.querySelector("button")) return;
actionCell.dataset.osdaEditEnabled = "true";
let editBtn = document.createElement("button");
editBtn.type = "button";
editBtn.className = "btn btn-outline-info btn-sm";
editBtn.style.marginLeft = "4px";
editBtn.innerText = "แก้ไข";
editBtn.onclick = () => {
let scanRow = row.nextElementSibling;
let targetAddRow = null;
while (scanRow) {
if (scanRow.dataset.osdaAddRow === "true") {
targetAddRow = scanRow;
break;
}
if (scanRow.querySelector("strong")) break;
scanRow = scanRow.nextElementSibling;
}
if (!targetAddRow) return;
document.querySelectorAll(".osda-custom-save-btn").forEach((btn) => btn.remove());
document.querySelectorAll(".osda-native-add-btn").forEach((btn) => (btn.style.display = ""));
let nativeAddBtn = targetAddRow.querySelector("button");
let nativeSelect = targetAddRow.querySelector("select");
if (!nativeAddBtn || !nativeSelect) return;
if (targetFormState) {
targetFormState.selected = boundItem.title;
setTimeout(() => {
for (let k in boundItem) {
if (k !== "title" && boundItem[k] !== null && boundItem[k] !== undefined) {
targetFormState[k] = boundItem[k];
}
}
}, 50);
}
nativeAddBtn.classList.add("osda-native-add-btn");
nativeAddBtn.style.display = "none";
if (nativeSelect && !nativeSelect.dataset.osdaChangeFix) {
nativeSelect.dataset.osdaChangeFix = "true";
nativeSelect.addEventListener("change", (e) => {
if (e.isTrusted && nativeAddBtn.style.display === "none") {
let targetFormStateLocal = formsState[activeCatKey];
let snapshot = {};
for (let k in targetFormStateLocal) {
if (k !== "selected" && k !== "options" && typeof targetFormStateLocal[k] !== "object") {
snapshot[k] = targetFormStateLocal[k];
}
}
setTimeout(() => {
for (let k in snapshot) {
if (snapshot[k] !== null && snapshot[k] !== undefined) {
targetFormStateLocal[k] = snapshot[k];
}
}
}, 50);
}
}, true);
}
let saveBtn = document.createElement("button");
saveBtn.type = "button";
saveBtn.className = "btn btn-success btn-sm osda-custom-save-btn";
saveBtn.style.marginLeft = "8px";
saveBtn.innerText = "บันทึกการแก้ไข";
let cancelBtn = document.createElement("button");
cancelBtn.type = "button";
cancelBtn.className = "btn btn-secondary btn-sm osda-custom-save-btn";
cancelBtn.style.marginLeft = "4px";
cancelBtn.innerText = "ยกเลิก";
saveBtn.onclick = () => {
let updatedItem = JSON.parse(JSON.stringify(boundItem));
if (targetFormState) {
updatedItem.title = targetFormState.selected;
for (let k in targetFormState) {
if (k !== "selected" && k !== "options" && typeof targetFormState[k] !== "object" && targetFormState[k] !== null) {
updatedItem[k] = targetFormState[k];
}
}
}
expState[activeCatKey].splice(capturedIndex, 1, updatedItem);
saveBtn.remove();
cancelBtn.remove();
nativeAddBtn.style.display = "";
if (targetFormState) targetFormState.selected = "";
};
cancelBtn.onclick = () => {
saveBtn.remove();
cancelBtn.remove();
nativeAddBtn.style.display = "";
if (targetFormState) targetFormState.selected = "";
};
nativeAddBtn.parentNode.appendChild(saveBtn);
nativeAddBtn.parentNode.appendChild(cancelBtn);
targetAddRow.scrollIntoView({ behavior: "smooth", block: "center" });
};
actionCell.appendChild(editBtn);
}
function renderOperations() {
if (!ensureConnection()) return;
let table = findActiveTable();
if (!table) return;
handleAutoFillFunding();
let rows = table.querySelectorAll("tbody tr");
let activeCatKey = null;
let itemIndexCounter = 0;
rows.forEach((row) => {
if (row.childElementCount === 1 && row.querySelector("strong")) {
let cellText = row.textContent || "";
activeCatKey = null;
for (let thWord in CATEGORY_MAP) {
if (cellText.includes(thWord)) {
activeCatKey = CATEGORY_MAP[thWord];
break;
}
}
if (activeCatKey) {
itemIndexCounter = 0;
}
return;
}
if (row.childElementCount === 1 && row.querySelector("select") && row.querySelector("button")) {
if (!row.dataset.osdaAddRow) row.dataset.osdaAddRow = "true";
return;
}
let tds = row.children;
if (tds.length >= 10 && activeCatKey) {
let boundItem = expState[activeCatKey] ? expState[activeCatKey][itemIndexCounter] : null;
let capturedIndex = itemIndexCounter;
itemIndexCounter++;
if (!boundItem) return;
let targetFormState = formsState[activeCatKey];
handleRowEditing(row, boundItem, activeCatKey, capturedIndex, targetFormState);
handleDragAndDrop(row, activeCatKey);
}
});
}
setInterval(renderOperations, 300);
})();