-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuiRenderer.js
More file actions
1806 lines (1531 loc) · 70 KB
/
uiRenderer.js
File metadata and controls
1806 lines (1531 loc) · 70 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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const moneyFmt = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2, // always “.00”
maximumFractionDigits: 2
});
/**
* Safely converts a value to a number, handling strings with currency symbols.
* @param {*} val - The value to convert.
* @returns {number} The converted number, or 0 if conversion fails.
*/
function toNumber(val) {
if (typeof val === 'number') {
return isFinite(val) ? val : 0;
}
if (typeof val === "string") {
// Remove characters that aren't digits, decimal point, or negative sign.
const sanitized = val.replace(/[^0-9.-]/g, '');
const num = parseFloat(sanitized);
return isFinite(num) ? num : 0;
}
return 0;
}
function getCountryName(code) {
const map = {
CN: "China",
ES: "Spain",
GB: "England",
CH: "Switzerland"
};
return map[code] || code; // fallback to code if not found
}
function fmtPrice(value) {
// Guard against undefined / blank cells
const num = Number(value);
return isFinite(num) ? moneyFmt.format(num) : "-";
}
function asLink(url) {
if (!url) return "N/A";
const safe = url.startsWith("http") ? url : `https://www.${url}`;
return `<a href="${safe}" target="_blank" rel="noopener">${safe.replace(/^https?:\/\//, "")}</a>`;
}
function emailLink(addr) {
if (!addr) return "N/A";
// Outlook Web deeplink — opens the user’s O355 / personal account
const url = `https://outlook.office.com/mail/deeplink/compose?to=${encodeURIComponent(addr)}`;
return `<a href="${url}" target="_blank" rel="noopener">${addr}</a>`;
}
/* keep one Chart.js instance per tab load */
let salesChart = null;
function drawSalesChart(salesByYearObj) {
const safe = salesByYearObj || {};
const today = new Date();
const currentYear = today.getFullYear();
const startOfYear = new Date(today.getFullYear(), 0, 0);
const diff = today - startOfYear;
const oneDay = 1000 * 60 * 60 * 24;
const dayOfYear = Math.floor(diff / oneDay);
const isLeap = new Date(currentYear, 1, 29).getMonth() === 1;
const daysInYear = isLeap ? 366 : 365;
const labels = [];
const actualValues = [];
const projectedValues = [];
// Get all years from the data and sort them
const yearsInData = Object.keys(safe).sort();
yearsInData.forEach(yearStr => {
const year = parseInt(yearStr, 10);
const num = safe[yearStr];
labels.push(yearStr);
actualValues.push(num);
if (year === currentYear && dayOfYear > 0 && dayOfYear < daysInYear) {
const runRate = num / (dayOfYear / daysInYear);
const projection = runRate - num;
projectedValues.push(projection > 0 ? projection : 0);
} else {
projectedValues.push(0);
}
});
if (labels.length === 0) {
if (salesChart) salesChart.destroy();
return;
}
const ctx = document.getElementById("salesByYearChart");
if (!ctx) return;
if (salesChart) salesChart.destroy();
salesChart = new Chart(ctx, {
type: "bar",
data: {
labels: labels,
datasets: [{
label: 'Actual',
data: actualValues,
backgroundColor: 'rgba(54, 162, 235, 0.8)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}, {
label: 'Projected',
data: projectedValues,
backgroundColor: 'rgba(255, 159, 64, 0.8)',
borderColor: 'rgba(255, 159, 64, 1)',
borderWidth: 1
}]
},
options: {
plugins: {
legend: { display: true, position: 'bottom', labels: { boxWidth: 12, font: { size: 10 } } },
tooltip: {
callbacks: {
label: function (context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y);
}
return label;
}
}
}
},
scales: {
x: { stacked: true, ticks: { font: { size: 10 } } },
y: { stacked: true, display: false, beginAtZero: true }
}
}
});
}
// Global variable to store the current customer's full order history
window.currentOrderHistory = null;
// Global variable to store the current customer's full customer info
window.currentCustomerInfo = null;
// Handle the Customer search dropdown and selection for the Search tab
document.getElementById("customerSearch").addEventListener("input", async (e) => {
const query = e.target.value.trim();
const dropdown = document.getElementById("customerDropdown");
if (!query) {
dropdown.innerHTML = "";
dropdown.classList.remove('show');
return;
}
try {
const results = await searchCustomers(query);
const uniqueResults = [...new Set(results)];
if (uniqueResults.length > 0) {
dropdown.innerHTML = uniqueResults
.map(name => {
// Escape single quotes in the company name to prevent Syntax Errors
const safeName = name.replace(/'/g, "\\'");
return `<li><a class="dropdown-item" href="#" onclick="selectCustomer('${safeName}')">${name}</a></li>`;
})
.join("");
// Manually show the dropdown
dropdown.classList.add('show');
} else {
dropdown.innerHTML = "";
dropdown.classList.remove('show');
}
} catch (error) {
console.error("Error performing customer search:", error);
dropdown.classList.remove('show');
}
});
// Handle the Customer search dropdown and selection for the Customer Info tab
document.getElementById("customerInfoSearch").addEventListener("input", async (e) => {
const query = e.target.value.trim();
const dropdown = document.getElementById("customerInfoDropdown");
if (!query) {
dropdown.innerHTML = "";
dropdown.classList.remove('show');
// Hide customer details if search is cleared
document.getElementById("customerOrderHistoryContainer").classList.add('customer-info-content-hidden');
document.getElementById("customerFieldsContainer").classList.add('customer-info-content-hidden');
document.getElementById("contactCardsContainer").classList.add('customer-info-content-hidden');
return;
}
try {
const results = await searchCustomers(query);
const uniqueResults = [...new Set(results)];
if (uniqueResults.length > 0) {
dropdown.innerHTML = uniqueResults
.map(name => {
// Escape single quotes in the company name to prevent Syntax Errors
const safeName = name.replace(/'/g, "\\'");
return `<li><a class="dropdown-item" href="#" onclick="selectCustomerInfo('${safeName}')">${name}</a></li>`;
})
.join("");
dropdown.classList.add('show');
} else {
dropdown.innerHTML = "";
dropdown.classList.remove('show');
document.getElementById("customerOrderHistoryContainer").classList.add('customer-info-content-hidden');
document.getElementById("customerFieldsContainer").classList.add('customer-info-content-hidden');
document.getElementById("contactCardsContainer").classList.add('customer-info-content-hidden');
}
} catch (error) {
console.error("Error performing customer info search:", error);
dropdown.classList.remove('show');
}
});
// Hide dropdowns when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('#customerSearch') && !e.target.closest('#customerDropdown')) {
document.getElementById("customerDropdown").classList.remove('show');
}
if (!e.target.closest('#productSearch') && !e.target.closest('#productDropdown')) {
document.getElementById("productDropdown").classList.remove('show');
}
if (!e.target.closest('#customerInfoSearch') && !e.target.closest('#customerInfoDropdown')) {
document.getElementById("customerInfoDropdown").classList.remove('show');
}
});
// Helper function to update the pricing table based on pricing toggle and selected product
function updatePricingTable(partNumber) {
const pricingData = window.dataStore["Pricing"]?.dataframe || [];
const pricingEntry = pricingData.find(row => String(row["Product"]).trim() === partNumber);
const isB2B = document.getElementById("pricingToggle").checked;
const tableBody = document.getElementById("priceTable"); // This is the <tbody>
// Get the parent table element
const parentTable = tableBody.closest('table');
if (parentTable) {
// Apply/remove a class to the whole table for styling
if (isB2B) {
parentTable.classList.add("b2b-pricing-active");
} else {
parentTable.classList.remove("b2b-pricing-active");
}
}
let tableHTML = "";
if (pricingEntry) {
const priceFB = isB2B ? pricingEntry["DISTR FB"] : pricingEntry["USER FB"];
const priceHB = isB2B ? pricingEntry["DISTR HB"] : pricingEntry["USER HB"];
const priceLTB = isB2B ? pricingEntry["DISTR LTB"] : pricingEntry["USER LTB"];
tableHTML = `
<tr>
<td>${fmtPrice(priceFB)}</td>
<td>${fmtPrice(priceHB)}</td>
<td>${fmtPrice(priceLTB)}</td>
</tr>
`;
} else {
tableHTML = `<tr><td colspan="3" class="text-muted fst-italic">No pricing data available for product ${partNumber}</td></tr>`;
}
tableBody.innerHTML = tableHTML;
}
// Helper function to update the order table based on filter state and selected product
function updateOrderTable(targetTableId = "orderHistoryTable") {
const orderHistory = window.currentOrderHistory;
if (!orderHistory) {
document.getElementById(targetTableId).innerHTML = `<tr><td colspan="5" class="text-muted fst-italic">
select a customer to display order history
</td></tr>`;
return; // No customer selected
}
const filterToggle = document.getElementById("filterOrdersToggle").checked;
const productValue = document.getElementById("productSearch").value.trim();
let filteredOrders = orderHistory;
// If the toggle is on and a product has been selected, filter orders.
if (filterToggle && productValue) {
console.log("Filtering orders for product:", productValue);
filteredOrders = orderHistory.filter(order => {
const orderProduct = String(order.Product_Service).trim();
console.log("Comparing order product:", orderProduct, "to selected product:", productValue);
return orderProduct === productValue;
});
}
const tableBody = document.getElementById(targetTableId);
if (filteredOrders.length > 0) {
tableBody.innerHTML = filteredOrders
.map(order => `
<tr class="order-row" data-product="${order.Product_Service}" data-quantity="${order.Quantity}" data-price="${order.Sales_Price}" onclick="UIrenderer.orderRowClicked(this)">
<td>${new Date(order.Date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })}</td>
<td>${order.Product_Service}</td>
<td>${order.Memo_Description}</td>
<td>${order.Quantity}</td>
<td>$${order.Sales_Price}</td>
</tr>
`)
.join("");
} else {
tableBody.innerHTML = `<tr><td colspan="5" class="text-muted fst-italic">
No orders found for product ${productValue}.
</td></tr>`;
}
}
function orderRowClicked(rowElement) {
// Remove any existing highlight from order rows
document.querySelectorAll("#orderHistoryTable tr").forEach(tr => tr.classList.remove("selected-row"));
document.querySelectorAll("#customerInfoOrderHistoryTable tr").forEach(tr => tr.classList.remove("selected-row"));
// Highlight the clicked row
rowElement.classList.add("selected-row");
// Retrieve data from the row's data attributes
const product = rowElement.dataset.product.trim();
const quantity = rowElement.dataset.quantity;
const price = rowElement.dataset.price;
// Set the product search input to the product
document.getElementById("productSearch").value = product;
// Call selectProduct, passing the extra info from the order
selectProduct(encodeURIComponent(product), { quantity, price });
}
// Handle Customer Selection for Search Tab
async function selectCustomer(customerName) {
document.getElementById("customerSearch").value = customerName;
document.getElementById("customerDropdown").innerHTML = "";
const orderHistory = await getOrderHistory(customerName);
// Save full order history for later filtering
window.currentOrderHistory = orderHistory;
// store the current customer name
window.currentCustomer = customerName;
// Sort orders by ascending date if needed
orderHistory.sort((a, b) => new Date(b.Date) - new Date(a.Date));
// Render orders (this will apply filtering if the toggle is on)
updateOrderTable("orderHistoryTable");
const details = await contactUtils.getCustomerDetails(customerName);
if (details) {
const toggle = document.getElementById("pricingToggle");
const isDistributor = String(details.business).trim().toLowerCase() === "distributor";
toggle.checked = isDistributor;
// Update the label based on the toggle state
toggle.dispatchEvent(new Event('change'));
// Optionally update pricing table if product is already selected
if (window.currentProduct) updatePricingTable(window.currentProduct);
}
}
/**
* Handles the logic for merging/updating contacts when the user confirms.
* This version is designed to work with the accordion UI.
* @param {HTMLElement} buttonElement - The button that was clicked.
* @param {string} correctCompanyName - The company name from Sales data.
* @param {string} mismatchedCompanyName - The company name found in the GAL.
*/
async function handleContactMerge(buttonElement, correctCompanyName, mismatchedCompanyName) {
const actionDiv = buttonElement.parentElement;
if (!actionDiv) return;
// 1. Show spinner UI
actionDiv.innerHTML = `
<div class="d-flex align-items-center text-primary">
<div class="spinner-border spinner-border-sm me-2" role="status"></div>
<span>Updating contacts...</span>
</div>`;
try {
// 2. Delegate data logic to dataLoader
await contactUtils.mergeOrganizationContacts(correctCompanyName, mismatchedCompanyName);
// 3. Handle Success UI
actionDiv.innerHTML = `<div class="text-success fw-bold"><i class="fas fa-check-circle me-2"></i>Contacts updated successfully!</div>`;
const accordionItem = actionDiv.closest('.accordion-item');
if (accordionItem) {
const headerButton = accordionItem.querySelector('.accordion-button');
headerButton.classList.add('text-muted');
headerButton.innerHTML += ` <span class="badge bg-success ms-auto">Updated</span>`;
}
} catch (error) {
// 4. Handle Error UI
console.error("Failed to update contacts:", error);
const safeCorrectName = correctCompanyName.replace(/'/g, "\\'");
const safeMismatchedName = mismatchedCompanyName.replace(/'/g, "\\'");
actionDiv.innerHTML = `
<div class="text-danger">
<i class="fas fa-times-circle me-2"></i>Update Failed.
<button class="btn btn-sm btn-outline-secondary ms-2" onclick="UIrenderer.handleContactMerge(this, '${safeCorrectName}', '${safeMismatchedName}')">Retry</button>
</div>`;
}
}
/**
* Handles the user clicking "Save" on the AI-suggested details.
* @param {string} customerName - The name of the customer being updated.
* @param {object} finalDetails - The complete, merged details object to save.
*/
async function confirmAndSaveChanges(customerName, finalDetails) {
const confirmationBox = document.getElementById('aiConfirmationBox');
if (!confirmationBox) return;
// 1. Show a saving state
// (Static HTML is safe to set via innerHTML)
confirmationBox.innerHTML = `
<div class="d-flex align-items-center text-primary">
<div class="spinner-border spinner-border-sm me-2" role="status"></div>
<span>Saving details...</span>
</div>`;
try {
// 2. Call the contactUtils function to perform the update
await contactUtils.updateCustomerDetails(customerName, finalDetails);
// 3. Update the global state
window.currentCustomerInfo = finalDetails;
// 4. Show success and then fade out
confirmationBox.innerHTML = `
<div class="text-success fw-bold">
<i class="fas fa-check-circle me-2"></i>Details Saved!
</div>`;
setTimeout(() => {
confirmationBox.style.opacity = '0';
setTimeout(() => {
confirmationBox.style.display = 'none';
confirmationBox.innerHTML = ''; // Clear content
}, 300);
}, 2000);
} catch (error) {
console.error("Failed to save customer details:", error);
// 5. Show an error state (Refactored for Best Practice)
// Create the container div
const errorContainer = document.createElement('div');
errorContainer.className = 'text-danger';
// Add the static text and icon
errorContainer.innerHTML = '<i class="fas fa-times-circle me-2"></i>Save Failed.';
// Create the button programmatically
const retryBtn = document.createElement('button');
retryBtn.className = 'btn btn-sm btn-outline-secondary ms-2';
retryBtn.textContent = 'Retry';
// Attach the event listener directly.
// This safely uses the variables from the outer scope without string escaping.
retryBtn.onclick = function() {
UIrenderer.confirmAndSaveChanges(customerName, finalDetails);
};
// Assemble and render
errorContainer.appendChild(retryBtn);
confirmationBox.replaceChildren(errorContainer);
}
}
// Handle Customer Selection for Customer Info Tab
async function selectCustomerInfo(customerName) {
document.getElementById("customerInfoSearch").value = customerName;
document.getElementById("customerInfoDropdown").innerHTML = "";
// Show the content containers
document.getElementById("customerOrderHistoryContainer").classList.remove('customer-info-content-hidden');
document.getElementById("customerFieldsContainer").classList.remove('customer-info-content-hidden');
document.getElementById("contactCardsContainer").classList.remove('customer-info-content-hidden');
// Hide and clear the confirmation box from any previous selection
const confirmationBox = document.getElementById('aiConfirmationBox');
confirmationBox.style.display = 'none';
confirmationBox.innerHTML = '';
// --- IMMEDIATE UI UPDATES ---
// Fetch and display everything we already have, right away.
// 1. Fetch and display order history
const orderHistory = await getOrderHistory(customerName);
window.currentOrderHistory = orderHistory;
orderHistory.sort((a, b) => new Date(b.Date) - new Date(a.Date));
updateOrderTable("customerInfoOrderHistoryTable");
// 2. Fetch existing details and display them immediately
let customerDetails = (await contactUtils.getCustomerDetails(customerName)) || {};
window.currentCustomerInfo = customerDetails;
document.getElementById("customerLocation").textContent = customerDetails.location || "N/A";
document.getElementById("customerBusiness").textContent = customerDetails.business || "N/A";
document.getElementById("customerType").textContent = customerDetails.type || "N/A";
document.getElementById("customerRemarks").textContent = customerDetails.remarks || "N/A";
document.getElementById("customerWebsite").innerHTML = asLink(customerDetails.website);
// 3. Render Sales Chart
const salesByYear = (window.dataStore.Sales?.dataframe || [])
.filter(sale => sale.Customer === customerName)
.reduce((acc, sale) => {
const date = new Date(sale.Date);
if (!isNaN(date)) {
const year = date.getFullYear();
const amount = toNumber(sale.Total_Amount);
acc[year] = (acc[year] || 0) + amount;
}
return acc;
}, {});
drawSalesChart(salesByYear);
// 4. Render Contacts
renderContactCards(customerName);
// --- ASYNCHRONOUS ENHANCEMENT ---
// Now, check if we need to fetch more data in the background.
const needsResearch = !customerDetails.location || !customerDetails.business || !customerDetails.type || !customerDetails.website;
if (needsResearch) {
// --- UI CUE: Show spinners for fields that are being researched ---
const fieldsToResearch = {
location: !customerDetails.location,
business: !customerDetails.business,
type: !customerDetails.type,
website: !customerDetails.website
};
Object.keys(fieldsToResearch).forEach(fieldKey => {
if (fieldsToResearch[fieldKey]) {
const el = document.getElementById(`customer${fieldKey.charAt(0).toUpperCase() + fieldKey.slice(1)}`);
if (el) {
el.innerHTML = `
<div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>`;
}
}
});
// This async function runs in the background without blocking the UI
(async () => {
try {
console.log(`[selectCustomerInfo] Missing info for ${customerName}. Starting background research.`);
const researchResults = await contactUtils.getCompanyResearch(customerName);
// If research fails or returns nothing, just reset the UI to original state (remove spinners).
if (!researchResults) {
document.getElementById("customerLocation").textContent = customerDetails.location || "N/A";
document.getElementById("customerBusiness").textContent = customerDetails.business || "N/A";
document.getElementById("customerType").textContent = customerDetails.type || "N/A";
document.getElementById("customerWebsite").innerHTML = asLink(customerDetails.website);
return;
}
let updated = false;
const updatedFields = {};
// Map research results
if (!customerDetails.website && researchResults.website) { updatedFields.website = researchResults.website; updated = true; }
if (!customerDetails.business && researchResults.businessType) { updatedFields.business = researchResults.businessType; updated = true; }
else if (!customerDetails.business && researchResults.description) { updatedFields.business = researchResults.description; updated = true; }
if (!customerDetails.location && researchResults.country) { updatedFields.location = researchResults.country; updated = true; }
if (!customerDetails.type && researchResults.industry) { updatedFields.type = researchResults.industry; updated = true; }
if (updated) {
const disclaimer = "AI-suggested data may be inaccurate.";
updatedFields.remarks = customerDetails.remarks ? `${customerDetails.remarks}\n${disclaimer}` : disclaimer;
const finalDetails = { ...customerDetails, ...updatedFields };
// Update UI immediately with the *suggested* data
console.log("[selectCustomerInfo] Research complete. Displaying suggestions:", updatedFields);
document.getElementById("customerLocation").textContent = finalDetails.location || "N/A";
document.getElementById("customerBusiness").textContent = finalDetails.business || "N/A";
document.getElementById("customerType").textContent = finalDetails.type || "N/A";
document.getElementById("customerRemarks").textContent = finalDetails.remarks || "N/A";
document.getElementById("customerWebsite").innerHTML = asLink(finalDetails.website);
confirmationBox.innerHTML = ''; // Clear previous content
const wrapper = document.createElement('div');
wrapper.className = 'd-flex justify-content-between align-items-center';
const textDiv = document.createElement('div');
textDiv.innerHTML = '<i class="fas fa-robot me-2 text-primary"></i><span class="fw-bold">AI found new details. Are they correct?</span>';
const saveBtn = document.createElement('button');
saveBtn.className = 'btn btn-sm btn-primary';
saveBtn.innerHTML = '<i class="fas fa-save me-1"></i> Save';
// Directly attach the event listener.
// 'customerName' and 'finalDetails' are captured from the closure safely.
saveBtn.onclick = () => UIrenderer.confirmAndSaveChanges(customerName, finalDetails);
wrapper.appendChild(textDiv);
wrapper.appendChild(saveBtn);
confirmationBox.appendChild(wrapper);
confirmationBox.style.display = 'block';
confirmationBox.style.opacity = '1';
} else {
// No updates were found, so just reset the UI to its original state (remove spinners)
document.getElementById("customerLocation").textContent = customerDetails.location || "N/A";
document.getElementById("customerBusiness").textContent = customerDetails.business || "N/A";
document.getElementById("customerType").textContent = customerDetails.type || "N/A";
document.getElementById("customerWebsite").innerHTML = asLink(customerDetails.website);
}
} catch (error) {
console.error("Error during background company research:", error);
// On error, also reset the UI to its original state (remove spinners)
document.getElementById("customerLocation").textContent = customerDetails.location || "N/A";
document.getElementById("customerBusiness").textContent = customerDetails.business || "N/A";
document.getElementById("customerType").textContent = customerDetails.type || "N/A";
document.getElementById("customerWebsite").innerHTML = asLink(customerDetails.website);
}
})();
}
}
/**
* Renders the contact cards, including the logic for fuzzy matching and suggesting merges.
* This is separated to be called after the initial customer details are rendered.
* @param {string} customerName The name of the customer.
*/
function renderContactCards(customerName) {
const contactCardsContainer = document.getElementById("contactCardsContainer");
const orgContacts = window.dataStore.OrgContacts; // This is a Map
const companyKey = customerName.trim().toLowerCase();
if (orgContacts && orgContacts.has(companyKey)) {
const contacts = orgContacts.get(companyKey);
contactCardsContainer.innerHTML = contacts.map(c => `
<div class="contact-card">
<h6>${c.Name || "N/A"}</h6>
<p><strong>Title:</strong> ${c.Title || "N/A"}</p>
<p><strong>Email:</strong> ${emailLink(c.Email)}</p>
</div>
`).join("");
} else {
// Fuzzy search for potential mismatches
if (orgContacts && orgContacts.size > 0) {
const matches = contactUtils.findPotentialMatches(customerName, orgContacts);
if (matches.length > 0) {
const safeCorrectName = customerName.replace(/'/g, "\\'");
const accordionId = `mergeAccordion-${safeCorrectName.replace(/[^a-zA-Z0-9]/g, '')}`;
const accordionItemsHTML = matches.map((match, index) => {
const mismatchedName = match.item;
const contactsUnderMismatch = orgContacts.get(mismatchedName);
const safeMismatchedName = mismatchedName.replace(/'/g, "\\'");
const contactCount = contactsUnderMismatch.length;
const contactOrContacts = contactCount === 1 ? 'contact' : 'contacts';
const collapseId = `collapse-${accordionId}-${index}`;
return `
<div class="accordion-item">
<h2 class="accordion-header" id="heading-${collapseId}">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#${collapseId}" aria-expanded="false" aria-controls="${collapseId}">
<strong>${mismatchedName}</strong> (${contactCount} ${contactOrContacts} found)
</button>
</h2>
<div id="${collapseId}" class="accordion-collapse collapse" aria-labelledby="heading-${collapseId}" data-bs-parent="#${accordionId}">
<div class="accordion-body">
<p>The following contacts will be updated to match the sales name "<strong>${customerName}</strong>":</p>
<div class="mb-3">
${contactsUnderMismatch.map(c => `
<div class="contact-card bg-light border-warning mb-2 py-2">
<h6>${c.Name}</h6>
<p class="mb-0 small"><strong>Email:</strong> ${c.Email}</p>
</div>
`).join('')}
</div>
<div class="merge-actions">
<button class="btn btn-primary" onclick="UIrenderer.handleContactMerge(this, '${safeCorrectName}', '${safeMismatchedName}')">
<i class="fas fa-sync-alt me-2"></i>Update ${contactCount} ${contactOrContacts}
</button>
</div>
</div>
</div>
</div>`;
}).join('');
const mergeUIHTML = `
<div class="card mt-3">
<div class="card-header bg-light">
<i class="fas fa-search me-2 text-primary"></i>
<strong>No exact contact match found. Did you mean?</strong>
</div>
<div class="accordion" id="${accordionId}">
${accordionItemsHTML}
</div>
</div>`;
contactCardsContainer.innerHTML = mergeUIHTML;
} else {
contactCardsContainer.innerHTML = '<p class="text-muted fst-italic">No contacts found in GAL for this company.</p>';
}
} else {
contactCardsContainer.innerHTML = '<p class="text-muted fst-italic">Contact data is not available.</p>';
}
}
}
/**
* Calculates and returns YOY sales data for a specific product.
* @param {string} partNumber - The product's part number.
* @returns {object} An object containing { totalLast12, totalPrior12, percentChange }
*/
function calculateYoYSales(partNumber) {
const salesData = window.dataStore?.Sales?.dataframe || [];
if (!salesData.length) {
return { totalLast12: 0, totalPrior12: 0, percentChange: 0 };
}
const today = new Date();
const last12Start = new Date();
last12Start.setFullYear(today.getFullYear() - 1);
const prior12Start = new Date();
prior12Start.setFullYear(today.getFullYear() - 2);
let totalLast12 = 0;
let totalPrior12 = 0;
salesData.forEach(sale => {
if (sale.Product_Service !== partNumber) return;
const saleDate = new Date(sale.Date);
const quantity = parseInt(sale.Quantity) || 0;
if (saleDate >= last12Start && saleDate <= today) {
totalLast12 += quantity;
} else if (saleDate >= prior12Start && saleDate < last12Start) {
totalPrior12 += quantity;
}
});
let percentChange = 0;
if (totalPrior12 > 0) {
percentChange = ((totalLast12 - totalPrior12) / totalPrior12) * 100;
} else if (totalLast12 > 0) {
percentChange = 100; // Indicate growth from zero
}
return { totalLast12, totalPrior12, percentChange };
}
let productInfoModalInstance = null;
let productSalesChartInstance = null; // Chart instance for the modal
// Event listener to draw chart AFTER modal is visible ---
// This is a one-time setup
document.addEventListener('DOMContentLoaded', () => {
const modalEl = document.getElementById('productInfoModal');
if (modalEl) {
modalEl.addEventListener('shown.bs.modal', () => {
// 'productSalesData' is attached to the element in showProductInfoModal
const productSales = modalEl.productSalesData;
if (productSales) {
drawProductSalesChart(productSales);
}
});
}
});
/**
* NEW: Draws the monthly sales chart inside the product modal.
* @param {object[]} productSales - Array of sales data filtered for this product.
*/
function drawProductSalesChart(productSales) {
const ctx = document.getElementById('productSalesChart');
if (!ctx) return;
if (productSalesChartInstance) {
productSalesChartInstance.destroy();
}
// Aggregate data by month for the last 24 months
const salesByMonth = {};
const labels = [];
const today = new Date();
const cutOff = new Date(today.getFullYear() - 2, today.getMonth(), 1); // 24 months ago
for (let i = 23; i >= 0; i--) {
const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
const label = d.toLocaleDateString('en-US', { year: 'numeric', month: 'short' });
labels.push(label);
salesByMonth[label] = 0;
}
productSales.forEach(sale => {
const saleDate = new Date(sale.Date);
if (saleDate >= cutOff) {
const label = saleDate.toLocaleDateString('en-US', { year: 'numeric', month: 'short' });
const amount = toNumber(sale.Total_Amount);
if (salesByMonth.hasOwnProperty(label)) {
salesByMonth[label] += amount;
}
}
});
const data = labels.map(label => salesByMonth[label]);
productSalesChartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Monthly Revenue',
data: data,
backgroundColor: 'rgba(54, 162, 235, 0.7)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animations: {
y: {
duration: 600,
easing: 'easeOutCubic'
// no `from` here
}
// if you really want, you can also tweak x:
// x: { duration: 0 }
},
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
label: function (context) {
return `Revenue: ${moneyFmt.format(context.parsed.y)}`;
}
}
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function (value) {
return moneyFmt.format(value).replace('.00', '');
}
}
},
x: {
ticks: {
maxRotation: 90,
minRotation: 70,
font: { size: 10 }
}
}
}
}
});
}
// --- NEW: Toggle Logic for Product History ---
// Listen for toggle changes globally (delegated)
document.addEventListener('change', (e) => {
if (e.target && e.target.id === 'historyToggle') {
renderProductHistory();
}
});
function renderProductHistory() {
const modalEl = document.getElementById('productInfoModal');
const toggle = document.getElementById("historyToggle");
const tbody = document.getElementById("productHistoryTableBody");
const entityHeader = document.getElementById("histColEntity");
if (!modalEl || !toggle || !tbody) return;
const showSales = toggle.checked;
const data = showSales ? (modalEl.productSales || []) : (modalEl.productPurchases || []);
// Update Header
if (entityHeader) entityHeader.textContent = showSales ? "Customer" : "Vendor";
// Sort by Date Descending
const sortedData = [...data].sort((a, b) => new Date(b.Date) - new Date(a.Date));
if (sortedData.length === 0) {
tbody.innerHTML = `<tr><td colspan="3" class="text-muted text-center small fst-italic py-3">No ${showSales ? 'sales' : 'purchase'} history found.</td></tr>`;
return;
}
tbody.innerHTML = sortedData.map((row, index) => {
// Determine fields based on type
let dateStr = "N/A";
if (row.Date) {
const d = new Date(row.Date);
if (!isNaN(d)) dateStr = d.toLocaleDateString('en-US', { year: '2-digit', month: '2-digit', day: '2-digit' });
}
const entity = (showSales ? row.Customer : row.Vendor) || "N/A";
// Product column removed from display, but data still available for expansion details
const qty = toNumber(row.Quantity);
const total = toNumber(row.Total_Amount);
// Try to get price directly, else calculate
let price = 0;
if (showSales) {
price = toNumber(row.Sales_Price);
} else {
// For purchases, look for cost/rate or calc
if (row.Cost) price = toNumber(row.Cost);
else if (row.UnitCost) price = toNumber(row.UnitCost);
else if (row.Rate) price = toNumber(row.Rate);
else if (qty !== 0) price = total / qty;
}
const desc = row.Memo_Description || row.Description || row.Memo || "N/A";
return `
<tr class="history-row" onclick="UIrenderer.toggleHistoryRow(this)" style="cursor:pointer;">
<td>${dateStr}</td>
<td class="text-truncate" style="max-width: 140px;" title="${entity}">${entity}</td>
<td class="text-end">${moneyFmt.format(price)}</td>
</tr>
<tr class="d-none bg-light history-detail-row">
<td colspan="3">
<div class="p-2 small border-start border-4 border-primary">
<div class="mb-1"><strong>Description:</strong> ${desc}</div>
<div class="d-flex justify-content-between">
<span><strong>Qty:</strong> ${qty}</span>
<span><strong>Total:</strong> ${moneyFmt.format(total)}</span>
</div>
</div>
</td>
</tr>
`;
}).join("");
}
function toggleHistoryRow(row) {
const nextRow = row.nextElementSibling;
if (nextRow && nextRow.classList.contains('history-detail-row')) {
nextRow.classList.toggle('d-none');
}
}
/**
* Finds all data for a given product and displays it in the new dashboard modal.
* @param {string} encodedPartNumber - The URI-encoded part number of the product.
*/
function showProductInfoModal(encodedPartNumber) {
const partNumber = decodeURIComponent(encodedPartNumber).toString().trim();
const inventoryData = window.dataStore["DB"]?.dataframe || [];
const salesData = window.dataStore["Sales"]?.dataframe || [];
const product = inventoryData.find(item => String(item["PartNumber"]).trim() === partNumber);
const pricingData = window.dataStore["Pricing"]?.dataframe || [];
const pricingEntry = pricingData.find(row => String(row["Product"]).trim() === partNumber);
if (pricingEntry && pricingEntry["DISCOUNT UNIT COST"]) {
product["DiscountedCost"] = toNumber(pricingEntry["DISCOUNT UNIT COST"]);
}
if (!product) {
console.error("Could not find product details for modal:", partNumber);