-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2895 lines (2694 loc) · 147 KB
/
Copy pathapp.js
File metadata and controls
2895 lines (2694 loc) · 147 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 vendorLabels = {
bluebeam: "Bluebeam",
digeplan: "DigEplan",
general: "General",
};
const roleLabels = {
admin: "Administrator",
coordinator: "Coordinator",
reviewer: "Reviewer",
};
const suggestedQuestions = {
general: [
"How do I set up fees in EPL?",
"How do I set up contact types?",
"How do I manage a review?",
"How do I reassign a review?",
"How do I set up a review in the software?",
"How do I set up Review Coordinator?",
],
bluebeam: [
"How do I set up eReviews with Bluebeam?",
"How do I manage a review?",
"How do I reassign a review?",
"What if a user forgot their Bluebeam password?",
],
digeplan: [
"How do I set up DigEplan?",
"How do I set up DigEplan SSO?",
"How do reviewers work in DigEplan?",
"How do coordinators manage DigEplan reviews?",
],
};
const roleSuggestedQuestions = {
admin: [
"How do I set up fees in EPL?",
"How do I set up contact types?",
"How do I set up Review Coordinator?",
],
coordinator: [
"How do I work a Review New Files task?",
"How do I set up Review Coordinator?",
],
reviewer: [
"How do I manage a review?",
"How do I reassign a review?",
"How do reviewers add corrections and recommendations?",
],
};
const synonymMap = {
bluebeam: ["bluebeam", "revu", "studio", "session"],
digeplan: ["digeplan", "project"],
sso: ["sso", "single sign on", "okta", "corpdev", "identity", "login"],
onboarding: ["onboarding", "implement", "implementation", "go live"],
migration: ["migration", "migrate", "switch", "cutover", "live client"],
resubmittal: ["resubmittal", "resubmit", "resubmission", "submit again"],
correction: ["correction", "corrections", "issue", "issues"],
recommendation: ["recommendation", "recommendations", "notes"],
review: ["review", "reviews", "reviewer", "reviewers"],
coordinator: ["coordinator", "intake", "review coordinator"],
setup: ["setup", "configure", "configuration", "prerequisite", "install"],
team: ["team", "teams", "team lead", "assignment"],
workflow: ["workflow", "step", "action", "template"],
attachment: ["attachment", "attachments", "file", "files"],
markup: ["markup", "markups", "comment", "comments", "annotate", "annotation"],
dashboard: ["dashboard", "summary", "tile", "chart"],
};
const stopWords = new Set([
"a",
"an",
"and",
"are",
"do",
"for",
"how",
"i",
"in",
"is",
"me",
"my",
"of",
"or",
"the",
"to",
"we",
"what",
"with",
]);
const state = {
vendor: "",
role: "",
kb: null,
pendingUserMessage: null,
};
const guideIdAliases = {
"review-management-setup": "review-management",
"workflow-setup": "workflow",
"manage-my-reviews-digeplan": "manage-my-reviews-dig-eplan",
};
const suggestionUsageStorageKey = "epl-assistant-suggestion-usage-v1";
const answerFeedbackStorageKey = "epl-assistant-answer-feedback-v1";
const chatLog = document.querySelector("#chat-log");
const chatForm = document.querySelector("#chat-form");
const questionInput = document.querySelector("#question");
const suggestions = document.querySelector("#suggestions");
function normalize(text) {
return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ");
}
function tokenize(text) {
return normalize(text)
.split(/\s+/)
.filter((token) => token && !stopWords.has(token));
}
function expandTokens(tokens) {
const expanded = new Set(tokens);
for (const token of tokens) {
for (const [root, variants] of Object.entries(synonymMap)) {
if (variants.includes(token) || token === root) {
expanded.add(root);
variants.forEach((variant) => expanded.add(variant));
}
}
}
return [...expanded];
}
function sentenceCaseVendor(vendor) {
return vendorLabels[vendor] || vendor;
}
function setVendor(vendor) {
state.vendor = vendor;
renderSuggestions();
addBotMessage(
`You’re set to ${sentenceCaseVendor(vendor)}. Ask any EPL question and I’ll use the shared EPL guides plus the ${sentenceCaseVendor(vendor)}-specific material when it applies.`
);
}
function setRole(role) {
state.role = role;
renderSuggestions();
addBotMessage(`Role set to ${roleLabels[role]}. I’ll prioritize ${role.toLowerCase()} workflows and procedures.`);
}
function renderSuggestions() {
const rolePrompts = state.role ? roleSuggestedQuestions[state.role] : [];
const vendorPrompts = state.vendor ? suggestedQuestions[state.vendor] : [];
const seededPrompts = [...suggestedQuestions.general, ...rolePrompts, ...vendorPrompts]
.filter((prompt, index, all) => all.indexOf(prompt) === index);
const trackedPrompts = topTrackedQuestions()
.filter((prompt) => !seededPrompts.includes(prompt));
const prompts = [...trackedPrompts, ...seededPrompts].slice(0, 10);
suggestions.innerHTML = "";
for (const prompt of prompts) {
const button = document.createElement("button");
button.type = "button";
button.className = "suggestion";
button.textContent = prompt;
button.addEventListener("click", () => {
questionInput.value = prompt;
chatForm.requestSubmit();
});
suggestions.appendChild(button);
}
}
function readSuggestionUsage() {
try {
return JSON.parse(localStorage.getItem(suggestionUsageStorageKey) || "{}");
} catch {
return {};
}
}
function writeSuggestionUsage(usage) {
try {
localStorage.setItem(suggestionUsageStorageKey, JSON.stringify(usage));
} catch {}
}
function readAnswerFeedback() {
try {
const parsed = JSON.parse(localStorage.getItem(answerFeedbackStorageKey) || "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function writeAnswerFeedback(entries) {
try {
localStorage.setItem(answerFeedbackStorageKey, JSON.stringify(entries));
} catch {}
}
function normalizeQuestionForFeedback(question) {
return normalize(question).replace(/\s+/g, " ").trim();
}
function getQuestionFeedbackProfile(question) {
const normalizedQuestion = normalizeQuestionForFeedback(question);
const matching = readAnswerFeedback().filter(
(entry) => normalizeQuestionForFeedback(entry.question || "") === normalizedQuestion
);
return matching.reduce(
(profile, entry) => {
if (entry.vote === "up") {
profile.up += 1;
}
if (entry.vote === "down") {
profile.down += 1;
}
return profile;
},
{ up: 0, down: 0 }
);
}
function shouldPreferImprovedAnswer(question) {
const profile = getQuestionFeedbackProfile(question);
return profile.down > profile.up;
}
function isTrulyAmbiguousQuestion(question) {
const lowered = question.toLowerCase().trim();
return (
/^how do i set this up\??$/.test(lowered) ||
/^how does this work\??$/.test(lowered) ||
/^how do i do this\??$/.test(lowered)
);
}
function buildAnswerFingerprint(question, answerText) {
const raw = `${question}||${answerText.slice(0, 1200)}`;
let hash = 0;
for (let index = 0; index < raw.length; index += 1) {
hash = (hash * 31 + raw.charCodeAt(index)) >>> 0;
}
return `fb-${hash.toString(16)}`;
}
function saveAnswerFeedback({ fingerprint, question, vote, answerPreview }) {
const entries = readAnswerFeedback().filter((entry) => entry.fingerprint !== fingerprint);
entries.unshift({
fingerprint,
question,
vote,
answerPreview,
createdAt: new Date().toISOString(),
});
writeAnswerFeedback(entries.slice(0, 250));
}
function attachCopyButton(messageEl, answerText) {
if (!messageEl || messageEl.querySelector(".copy-button")) {
return;
}
const copyButton = document.createElement("button");
copyButton.className = "copy-button";
copyButton.type = "button";
copyButton.innerHTML = '<span>📋 Copy</span>';
copyButton.setAttribute("aria-label", "Copy answer to clipboard");
copyButton.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(answerText);
copyButton.classList.add("copied");
copyButton.innerHTML = '<span>✓ Copied!</span>';
setTimeout(() => {
copyButton.classList.remove("copied");
copyButton.innerHTML = '<span>📋 Copy</span>';
}, 2000);
} catch (error) {
console.error("Failed to copy:", error);
}
});
messageEl.appendChild(copyButton);
}
function generateFollowUpQuestions(question, answerText) {
const lowered = question.toLowerCase();
const followUps = [];
if (/setup|configure|set up/i.test(lowered)) {
followUps.push("What are best practices for this setup?");
followUps.push("How do I test this configuration?");
}
if (/bluebeam/i.test(lowered)) {
followUps.push("What if a user forgot their Bluebeam password?");
followUps.push("How do I manage a review in Bluebeam?");
}
if (/digeplan/i.test(lowered)) {
followUps.push("How do I set up DigEplan SSO?");
followUps.push("How do coordinators manage DigEplan reviews?");
}
if (/review|reviewer/i.test(lowered)) {
followUps.push("How do I reassign a review?");
followUps.push("How do reviewers add corrections and recommendations?");
}
if (/coordinator/i.test(lowered)) {
followUps.push("How do I work a Review New Files task?");
followUps.push("How do I set up Review Coordinator?");
}
if (/fee/i.test(lowered)) {
followUps.push("How do I set up contact types?");
followUps.push("How do I manage workflow setup?");
}
if (!followUps.length) {
followUps.push("How do I set up fees in EPL?");
followUps.push("How do I manage a review?");
}
return followUps.slice(0, 3);
}
function attachFollowUpQuestions(messageEl, question, answerText) {
if (!messageEl || messageEl.querySelector(".follow-up-questions")) {
return;
}
const followUps = generateFollowUpQuestions(question, answerText);
if (!followUps.length) {
return;
}
const container = document.createElement("div");
container.className = "follow-up-questions";
container.innerHTML = `
<div class="follow-up-label">Related Questions</div>
<ul class="follow-up-list">
${followUps.map(q => `<li class="follow-up-item" data-question="${q.replace(/"/g, '"')}">${q}</li>`).join('')}
</ul>
`;
const items = container.querySelectorAll(".follow-up-item");
items.forEach((item) => {
item.addEventListener("click", () => {
const followUpQuestion = item.getAttribute("data-question");
if (followUpQuestion) {
questionInput.value = followUpQuestion;
questionInput.focus();
chatForm.dispatchEvent(new Event("submit"));
}
});
});
messageEl.appendChild(container);
}
function attachAnswerFeedback(messageEl, question, answerText) {
if (!messageEl || messageEl.querySelector(".feedback-controls")) {
return;
}
const fingerprint = buildAnswerFingerprint(question, answerText);
const savedVote = readAnswerFeedback().find((entry) => entry.fingerprint === fingerprint)?.vote || "";
const controls = document.createElement("div");
controls.className = "feedback-controls";
controls.innerHTML = `
<span class="feedback-label">Was this answer helpful?</span>
<div class="feedback-buttons">
<button type="button" class="feedback-button${savedVote === "up" ? " selected" : ""}" data-vote="up" aria-label="Thumbs up answer">👍</button>
<button type="button" class="feedback-button${savedVote === "down" ? " selected" : ""}" data-vote="down" aria-label="Thumbs down answer">👎</button>
</div>
<span class="feedback-status">${savedVote ? "Saved" : ""}</span>
`;
const status = controls.querySelector(".feedback-status");
const buttons = [...controls.querySelectorAll(".feedback-button")];
buttons.forEach((button) => {
button.addEventListener("click", () => {
const vote = button.getAttribute("data-vote");
if (!vote) {
return;
}
saveAnswerFeedback({
fingerprint,
question,
vote,
answerPreview: answerText.slice(0, 500),
});
buttons.forEach((candidate) => {
candidate.classList.toggle("selected", candidate === button);
});
if (status) {
status.textContent = vote === "up" ? "Saved as helpful" : "Saved for improvement";
}
});
});
messageEl.appendChild(controls);
}
function trackQuestionUsage(question) {
const trimmed = question.trim();
if (!trimmed) {
return;
}
const usage = readSuggestionUsage();
usage[trimmed] = (usage[trimmed] || 0) + 1;
writeSuggestionUsage(usage);
}
function topTrackedQuestions(limit = 5) {
const usage = readSuggestionUsage();
return Object.entries(usage)
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, limit)
.map(([question]) => question);
}
function addMessage(role, html, options = {}) {
const wrapper = document.createElement("article");
wrapper.className = `message ${role}`;
wrapper.innerHTML = html;
if (options.after && options.after.parentNode === chatLog) {
options.after.insertAdjacentElement("afterend", wrapper);
} else {
chatLog.prepend(wrapper);
}
chatLog.scrollTop = 0;
return wrapper;
}
function addBotMessage(text, sources = [], question = "") {
let insertedMessage;
const pendingQuestion = question || state.pendingUserMessage?.innerText?.trim() || "";
if (text.trim().startsWith("<")) {
insertedMessage = addMessage("bot", text, { after: state.pendingUserMessage });
} else {
let html = text
.split("\n\n")
.map((paragraph) => `<p>${paragraph.replace(/\n/g, "<br>")}</p>`)
.join("");
if (sources.length) {
const sourceText = sources
.map((source) => `${source.guide_title}, p. ${source.page}`)
.join(" • ");
html += `<p class="sources"><strong>Sources:</strong> ${sourceText}</p>`;
}
insertedMessage = addMessage("bot", html, { after: state.pendingUserMessage });
}
state.pendingUserMessage = null;
if (insertedMessage && !insertedMessage.querySelector(".copy-button")) {
const textToCopy = insertedMessage.innerText.trim();
const actions = document.createElement("div");
actions.className = "message-actions";
const button = document.createElement("button");
button.type = "button";
button.className = "copy-button";
button.textContent = "Copy Checklist";
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(textToCopy);
button.textContent = "Copied";
setTimeout(() => {
button.textContent = "Copy Checklist";
}, 1200);
} catch {
button.textContent = "Copy failed";
setTimeout(() => {
button.textContent = "Copy Checklist";
}, 1200);
}
});
actions.appendChild(button);
insertedMessage.appendChild(actions);
}
insertedMessage?.querySelectorAll?.(".inline-question").forEach((button) => {
button.addEventListener("click", () => {
const followUp = button.getAttribute("data-question");
if (!followUp) {
return;
}
questionInput.value = followUp;
chatForm.requestSubmit();
});
});
attachAnswerFeedback(insertedMessage, pendingQuestion, insertedMessage?.innerText?.trim() || text);
attachFollowUpQuestions(insertedMessage, pendingQuestion, insertedMessage?.innerText?.trim() || text);
}
function addUserMessage(text) {
state.pendingUserMessage = addMessage("user", `<p>${text}</p>`);
}
function detectVendorSwitch(question) {
const normalized = normalize(question);
if (normalized.includes("bluebeam")) {
return "bluebeam";
}
if (normalized.includes("digeplan")) {
return "digeplan";
}
return "";
}
function detectRoleSwitch(question) {
const normalized = normalize(question);
if (/(admin|administrator|setup|configure|configuration)/.test(normalized)) {
return "admin";
}
if (/(coordinator|task|review new files|failed submittal|approved submittal)/.test(normalized)) {
return "coordinator";
}
if (/(reviewer|manage my reviews|reassign|resubmittal|recommendation|correction)/.test(normalized)) {
return "reviewer";
}
return "";
}
function questionWantsDetailedProcedure(question) {
return /sso|single sign on|setup|onboarding|configure|configuration|migration|migrate|switch|how do i set|how do we set/i.test(
question
);
}
function buildStepHtml(stepNumber, title, detail, source) {
return `
<li>
<strong>${stepNumber}. ${title}</strong><br>
<span class="step-detail">${detail}</span>
</li>
`;
}
function buildSimpleStepHtml(stepNumber, detail) {
return `
<li>
<span class="step-detail">${detail}</span>
</li>
`;
}
function buildBulletList(items) {
return `<ul>${items.map((item) => `<li>${item}</li>`).join("")}</ul>`;
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function buildPlaybookSection(title, body) {
return `
<section class="answer-section">
<h3>${title}</h3>
${body}
</section>
`;
}
function buildInlineSteps(items) {
return `<ul class="inline-steps">${items
.map((item) => item.replace(/^\d+\.\s*/, ""))
.map((item) => `<li>${item}</li>`)
.join("")}</ul>`;
}
function cleanInstructionText(text) {
return text
.replace(/\s+/g, " ")
.replace(/\bFor more information, please refer to[^.]*\.?/gi, "")
.replace(/\bThis image[^.]*\.?/gi, "")
.replace(/\bEPL displays[^.]*\.?/gi, "")
.trim();
}
function extractInstructionSentences(text, maxSentences = 8) {
const cleaned = cleanInstructionText(text);
const sentences = cleaned.match(/[^.!?]+[.!?]+|[^.!?]+$/g) || [cleaned];
return sentences
.map((sentence) => sentence.trim())
.filter(Boolean)
.slice(0, maxSentences);
}
function questionTopicLabel(question) {
const lowered = question.toLowerCase();
if (/\bfees?\b/.test(lowered)) return "fees";
if (/\bpermits?\b/.test(lowered)) return "permits";
if (/\bcontacts?\b/.test(lowered)) return "contacts";
if (/\bworkflow\b/.test(lowered)) return "workflow";
if (/\breviews?\b/.test(lowered)) return "reviews";
if (/\binspections?\b/.test(lowered)) return "inspections";
if (/\bcivic access\b/.test(lowered)) return "Civic Access";
if (/\bbluebeam\b/.test(lowered)) return "Bluebeam";
if (/\bdigeplan\b/.test(lowered)) return "DigEplan";
if (/\bcoordinator\b/.test(lowered)) return "review coordinator work";
return "your question";
}
function chunkInstructionItems(chunk, maxItems = 8) {
const directSteps = extractProceduralSteps(chunk.text).slice(0, maxItems);
if (directSteps.length) {
return directSteps;
}
return extractInstructionSentences(chunk.text, maxItems);
}
function isGenericSectionLabel(section) {
if (!section) {
return true;
}
return /^section\s+\d+$/i.test(section) || /^page\s+\d+$/i.test(section);
}
function friendlyStepTitle(question, chunk) {
const topic = questionTopicLabel(question);
const guideTitle = (chunk.guide_title || "")
.replace(/\b20\d{2}(?:\.\d+)?\b/g, "")
.replace(/\b(user guide|setup guide|admin guide|guide)\b/gi, "")
.replace(/\s+/g, " ")
.trim();
if (!isGenericSectionLabel(chunk.section)) {
return chunk.section;
}
if (/manage my reviews/i.test(guideTitle)) return "Manage My Reviews";
if (/review coordinator/i.test(guideTitle)) return "Review Coordinator";
if (/review management/i.test(guideTitle)) return "Review Management";
if (/workflow/i.test(guideTitle)) return "Workflow Setup";
if (/contact management/i.test(guideTitle)) return "Contact Management";
if (/permit management/i.test(guideTitle)) return "Permit Management";
if (/fee/i.test(guideTitle)) return "Fee Setup";
if (/inspection/i.test(guideTitle)) return "Inspection Setup";
if (/civic access/i.test(guideTitle)) return "Civic Access";
switch (topic) {
case "fees":
return "Fee Setup";
case "permits":
return "Permit Setup";
case "contacts":
return "Contact Setup";
case "workflow":
return "Workflow Setup";
case "reviews":
return "Review Setup";
case "inspections":
return "Inspection Setup";
case "Civic Access":
return "Civic Access";
default:
return guideTitle || "EPL Setup";
}
}
function bestPracticeItemsForTopic(topic) {
if (topic === "fees") {
return [
"Reuse fee templates where possible instead of building one-off fee logic for every case type.",
"Test calculated, percentage, CPI, proration, and condition-based fees in a non-production record before rollout.",
"Keep the work class assignment clean, because that is what determines which fees users and applicants actually see.",
];
}
if (topic === "permits") {
return [
"Finalize the work class design early, because workflow, custom fields, fees, and contact behavior are attached there.",
"Test one real permit scenario after setup so you can verify the end-to-end user experience instead of only checking configuration screens.",
"Avoid changing key type or work class design after records are already in use unless the team has a migration plan.",
];
}
if (topic === "contacts") {
return [
"Standardize contact types and validation rules before attaching them to multiple work classes.",
"Test contact validation with a sample case so you can confirm certification or license rules behave as expected.",
"Keep naming and usage consistent across modules so staff know which contact type to use.",
];
}
if (topic === "workflow") {
return [
"Build and test workflow actions and steps in a lower environment before attaching the template broadly.",
"Keep workflow templates as reusable as possible so similar case types do not drift apart unnecessarily.",
"Validate workflow from the user-facing case, not just from the setup app, so you catch missing actions or bad routing.",
];
}
if (topic === "reviews") {
return [
"Test assignment behavior with the real department, team, and reviewer structure the client plans to use.",
"Confirm both coordinator and reviewer experiences work before calling the setup complete.",
"Use structured corrections and recommendations consistently so reviewers communicate outcomes clearly.",
];
}
if (topic === "inspections") {
return [
"Validate inspection setup with scheduling, status updates, and downstream workflow behavior together.",
"Keep inspection types and case types clearly named so staff can pick the correct option quickly.",
"Test both back-office and field or mobile scenarios if inspectors will work outside the office.",
];
}
if (topic === "Civic Access") {
return [
"Always test the applicant-facing experience after configuration, not just the admin settings.",
"Confirm online visibility, payment behavior, and file rules with a sample public workflow before rollout.",
"Keep online forms and options as simple as possible so customers do not run into avoidable confusion.",
];
}
return [
"Test the configuration with one realistic sample record before rollout.",
"Keep naming, templates, and setup choices consistent so staff can support the process more easily.",
"Validate the setup from the user experience, not just from the admin screen.",
];
}
function buildGenericDetailedAnswer(question, chunks) {
const topic = questionTopicLabel(question);
const selected = chunks.slice(0, 5).map((chunk) => ({
chunk,
items: chunkInstructionItems(chunk, 8),
})).map((entry) => ({
...entry,
items: entry.items.filter((item) => {
const cleaned = cleanInstructionText(item);
if (!cleaned) {
return false;
}
if (/^note\b/i.test(cleaned)) {
return false;
}
if (cleaned.length < 25) {
return false;
}
return true;
}),
})).filter((entry) => entry.items.length);
if (!selected.length) {
return `
<p>Here are the detailed steps I found for ${topic} in EPL.</p>
<p>I found relevant guide material, but not enough procedural text to build a reliable step-by-step answer from the current chunks.</p>
`;
}
let stepNumber = 1;
const sourceEntries = [];
const steps = selected
.map(({ chunk, items }) => {
const sourceLabel = buildSourceWithLink(chunk.guide_id, chunk.section, chunk.page);
sourceEntries.push(sourceLabel);
return items.map((item) =>
buildStepHtml(
stepNumber++,
friendlyStepTitle(question, chunk),
item,
sourceLabel
)
).join("");
})
.join("");
const prepItems = selected
.map(({ chunk }) => {
const text = cleanInstructionText(chunk.text);
const sentences = extractInstructionSentences(text, 2);
if (!sentences.length) {
return "";
}
return `${sentences.join(' ')} Source: ${buildSourceWithLink(chunk.guide_id, chunk.section, chunk.page)}`;
})
.filter(Boolean)
.slice(0, 5);
return `
<p>Here are the detailed step-by-step instructions for ${topic} in EPL. I’m using the most relevant guide sections and turning them into a procedure you can follow in the software.</p>
${buildPlaybookSection(
"Before You Start",
prepItems.length
? buildBulletList(prepItems)
: "<p>No separate prerequisites were called out in the guide sections matched for this question.</p>"
)}
${buildPlaybookSection("Step-By-Step", `<ol>${steps}</ol>`)}
${buildPlaybookSection(
"Validation",
buildBulletList([
`Open the EPL app or setup area mentioned in the steps and confirm each field, tab, or action is available where expected.`,
`Save the configuration or complete the action, then reopen the record to confirm the change persisted.`,
`If this affects a case type, work class, workflow, or user-facing process, run one test record to confirm the outcome behaves as expected.`,
`Check that all related records (like fees, contacts, workflows) are properly linked and functioning together.`,
`Verify user permissions allow access to all necessary screens and actions.`,
])
)}
${buildPlaybookSection(
"Common Issues & Troubleshooting",
buildBulletList([
`<strong>Configuration not showing:</strong> Clear browser cache, rebuild cache in System Settings, or recycle app pools if changes don’t appear.`,
`<strong>Missing fields or options:</strong> Verify user role permissions include access to the specific module and features.`,
`<strong>Changes not saving:</strong> Check for required fields, validation rules, or workflow prerequisites that must be met first.`,
`<strong>Integration issues:</strong> Confirm Windows Service tasks are enabled and running, check API credentials, verify network connectivity.`,
`<strong>Workflow not triggering:</strong> Validate the workflow template is attached to the correct case type/work class and conditions are met.`,
])
)}
${buildPlaybookSection(
"Best Practices",
buildBulletList(bestPracticeItemsForTopic(topic))
)}
${buildDrillDownSection("Want More Detail?", suggestedDrillDownPrompts(question, chunks))}
${buildPlaybookSection(
"Sources",
buildBulletList([...new Set(sourceEntries)])
)}
`;
}
function guideMetaById(guideId) {
const guides = state.kb?.guides || [];
const normalized = (guideIdAliases[guideId] || guideId).toLowerCase();
const matches = guides.filter((guide) => {
const id = guide.id.toLowerCase();
const family = (guide.family || "").toLowerCase();
return id === normalized || id.startsWith(`${normalized}-`) || family === normalized;
});
if (!matches.length) {
return null;
}
matches.sort((a, b) => {
const aPreferred = a.is_preferred_source ? 1 : 0;
const bPreferred = b.is_preferred_source ? 1 : 0;
if (aPreferred !== bPreferred) {
return bPreferred - aPreferred;
}
if ((a.source_priority || 0) !== (b.source_priority || 0)) {
return (b.source_priority || 0) - (a.source_priority || 0);
}
const aVersion = (a.version_sort || []).join(".");
const bVersion = (b.version_sort || []).join(".");
return bVersion.localeCompare(aVersion, undefined, { numeric: true });
});
return matches[0];
}
function guideIdMatches(actualGuideId, expectedGuideId) {
const actual = (actualGuideId || "").toLowerCase();
const expected = ((guideIdAliases[expectedGuideId] || expectedGuideId) || "").toLowerCase();
return actual === expected || actual.startsWith(`${expected}-`);
}
function guideHref(guideId) {
const guide = guideMetaById(guideId);
if (!guide) {
return "#";
}
return `./Guides/${guide.filename}`;
}
function guideLinkLabel(guideId) {
const guide = guideMetaById(guideId);
return guide ? guide.title : guideId;
}
function buildSourceWithLink(guideId, section, page) {
const href = guideHref(guideId);
const label = guideLinkLabel(guideId);
return `<a href="${href}" target="_blank" rel="noopener">${label}</a> -> ${section} (section ${page})`;
}
function buildGroupedSources(sourceRefs) {
const grouped = new Map();
sourceRefs.forEach(({ guideId, section, page }) => {
const key = guideId;
if (!grouped.has(key)) {
grouped.set(key, []);
}
const entry = `${section} (section ${page})`;
if (!grouped.get(key).includes(entry)) {
grouped.get(key).push(entry);
}
});
return buildBulletList(
[...grouped.entries()].map(
([guideId, refs]) =>
`<a href="${guideHref(guideId)}" target="_blank" rel="noopener">${guideLinkLabel(guideId)}</a> -> ${refs.join("; ")}`
)
);
}
function buildDigeplanSsoAnswer() {
const source = buildSourceWithLink(
"digeplan-client-onboarding",
"DigEplan SSO Setup",
5
);
const validationSource = buildSourceWithLink(
"digeplan-client-onboarding",
"Validating SSO",
5
);
return `
<p>If you are a consultant who has never set this up before, use this as your working sequence. The goal is to get the client's identity details registered through CorpDev, hand those credentials to DigEplan, and then verify the SSO button actually works in the tenant.</p>
<p><strong>Before you start</strong><br>You will need access to the CorpDev request form, enough client identity information to know whether they use customer Okta or Tyler Gateway, and a safe way to receive credentials because the guide says CorpDev sends them through Kiteworks.</p>
<ol>
${buildStepHtml(
1,
"Open a CorpDev Support ticket for the DigEplan SSO request",
"This is the official starting point for SSO setup. The onboarding guide says clients who want DigEplan SSO should begin by submitting a CorpDev Support ticket.",
source
)}
${buildStepHtml(
2,
"Fill in the core ticket values exactly as documented",
"Use Product team(s) = EnerGov (All), Identity Client Request Type = New Client, and TCP Environment(s) = PROD - TylerPortico. These fields tell CorpDev what product and environment the identity client is for.",
source
)}
${buildStepHtml(
3,
"Choose the correct identity client type",
"Set Identity Client Type = Authorization Code Flow (uses secret). If you are new to this, the important point is that DigEplan expects a client setup that uses a secret rather than a public client flow.",
source
)}
${buildStepHtml(
4,
"Choose the right identity provider",
"Set Identity Provider to either Customer TID-W Tenant (Okta) or Gateway (Tyler Gateway), depending on how the client authenticates. If you are unsure, confirm that with the client before the ticket is submitted.",
source
)}
${buildStepHtml(
5,
"Name the identity client using the required convention",
"Use <<CustomerNameWithoutSpaces>>-<<Selected TCPEnvironment>>-epl-digeplan-<<testtrainprod>>. The guide warns that the ticket will be rejected if the naming convention is wrong, so this is worth double-checking before submission.",
source
)}
${buildStepHtml(
6,
"Enter the DigEplan redirect URIs for both stage and production",
"The guide provides specific sign-in and sign-out redirect URIs for stage and prod. Use those exact values in the request rather than guessing or reusing another application's callback URL.",
source
)}
${buildStepHtml(
7,
"Submit the ticket and wait for CorpDev to return credentials through Kiteworks",
"Once the request is complete, CorpDev provides the credentials through Kiteworks. As the consultant, treat that handoff as the checkpoint that lets you move from identity setup to DigEplan-side configuration.",
source
)}
${buildStepHtml(
8,
"Send DigEplan Support the CorpDev credentials and the client's Okta URL",
"Email support@digeplan.com and include the credentials from CorpDev plus the Okta URL used to log into the client's apps. This is the handoff DigEplan needs to complete their side of the SSO configuration.",
source
)}
${buildStepHtml(
9,
"Have DigEplan complete the SSO configuration in the tenant",
"The guide explicitly says DigEplan completes the SSO configuration after they receive the identity information. As a consultant, this is the point where you should track status with DigEplan Support rather than trying to finish it entirely inside EPL.",
source
)}
${buildStepHtml(
10,
"Validate the login experience from an actual DigEplan link",
"Open a DigEplan project link or the tenant link provided by DigEplan Support. The login screen should display the SSO option. Click Continue to verify that authentication succeeds.",
validationSource
)}
${buildStepHtml(
11,
"Confirm the user is marked as an SSO user after login",
"After the user signs in successfully with SSO, check that the SSO User toggle is turned on in DigEplan settings. This is a practical confirmation that the SSO path is wired correctly for that user.",
source
)}
</ol>
<p><strong>Consultant tip</strong><br>If SSO is the client's long-term goal but not a same-day blocker, the onboarding guide says it can be requested after deployment. That gives you the option to separate core DigEplan integration setup from identity rollout if the project timeline is tight.</p>
`;
}
function buildDigeplanSetupAnswer() {