EchoTex_Payroll/HRM.UI/ClientApp/src/app/hrmopen-ai/hrmopen-ai-test/hrmopen-aiteast.component.ts

573 lines
24 KiB
TypeScript

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ApiService } from 'src/app/app.api.service';
import { DataTransferService } from 'src/app/data.transfer.service';
import { Router, ActivatedRoute } from '@angular/router';
import { SearchEmployee } from 'src/app/_models/Employee/searchEmployee';
import { HRMNotificationService } from 'src/app/app.notification.service';
import { loadingPanelService } from 'src/app/hrm-loding panel/loding.panel.service';
import { Courses } from 'src/app/_models/LearningManagement/courses';
import { Lessons } from 'src/app/_models/LearningManagement/lessons';
import { LessonContent } from 'src/app/_models/LearningManagement/lesson-content';
import { LMSService } from 'src/app/_services/LearningManagement/lms.service';
import { EnumAccessLevel, EnumAIChartType, EnumContentType, EnumDifficultyLevel, EnumFileType, EnumReportGroupType, EnumStatus, EnumTemplateType } from 'src/app/_models/enums';
import { CourseType } from 'src/app/_models/LearningManagement/course-type';
import { LMSTemplate } from 'src/app/_models/LearningManagement/lmstemplate';
import { HRMOpenAIService } from 'src/app/_services/HRMOpenAI/hrmopen-ai.service';
import { OpenAIQueryLog } from 'src/app/_models/OpenAIQueryLog/OpenAIQueryLog';
import { OpenAIResponseWithData } from 'src/app/_models/OpenAI BO/OpenAIResponseWithData';
import { Pipe, PipeTransform } from '@angular/core';
import { HostListener } from '@angular/core';
import { saveAs } from "@progress/kendo-file-saver";
import { ChartComponent } from "@progress/kendo-angular-charts";
import { exportPDF, fit, geometry, Group } from "@progress/kendo-drawing";
function mm(val: number): number {return val * 2.8347;}
const PAGE_RECT = new geometry.Rect([0, 0], [mm(210 - 20), mm(297 - 20)]);
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-hrmopen-aiteast',
templateUrl: './hrmopen-aiteast.component.html',
styleUrls: ['./hrmopen-aiteast.component.scss'],
//standalone: false,
animations: [
trigger('fadeInOut', [
transition('* => changed', [
style({ opacity: 0 }),
animate('500ms ease-in', style({ opacity: 1 }))
])
])
]
})
export class HRMOpenAITestComponent implements OnInit{
constructor(public apiService : ApiService,
public notificationService: HRMNotificationService,
public loadingpanelService: loadingPanelService, public opeAiService : HRMOpenAIService) {
this.apiService.selectedMenuName = "HRM AI";
}
inputUserCommand : string = "";
public gridData: any[] = []; // data for the grid
public gridColumns: any[] = [];
public gridColumnsForChart: any[] = []; // columns for dynamic grid
public output: any = "";
public reportGroups : any[] = [];
public chartGroups : any[] = [];
public reportColumnDefinition: any[] = [];
public tableColumnDefinition: ReportColumnDefinition[] = [];
public selectedReportGroup: EnumReportGroupType | null;
public selectedChartGroup: EnumReportGroupType | null;
public isShowAvailableInfo: boolean = false;
public isShowCurrentUserAllQueryLog: boolean = false;
public invalidQueryMessage : string = "The AI can provide information when you ask about HR.";
public currentUserAllQueryLog : OpenAIQueryLog[] = [];
public filteredSuggestions: OpenAIQueryLog[] = [];
public OpenAIResponce: any = {};
public openAIResponseWithData: OpenAIResponseWithData = new OpenAIResponseWithData();
public chartData: any[] = [];
public isShowChart: boolean = false;
public isShowChartOption: boolean = false;
public chartMerge : string = "";
public chartName : string = "";
public selectedColumnX : any;
public selectedColumnY : any;
public searchText: string = "";
public querySearchText: string = "";
public excelFileName: string = "OpenAIQueryLog.xlsx";
public pdfFileName: string = "OpenAIQueryLog.pdf";
public pdfFileNameForChart: string = "OpenAIQueryLog.pdf";
public pngFilename: string = "OpenAIQueryLog.png";
public chartTransitions = false;
public isUserPromptIsNotRelated = false;
public messageState: string = '';
public isDisabledShared : boolean = true;
public currentChat : OpenAIQueryLog | undefined;
public deletedColumns: any[] = [];
@ViewChild('deletedContainer', { static: false }) deletedContainer!: ElementRef;
@ViewChild("chart")
private chart: ChartComponent;
private setInvalidQueryMessage(msg: string) {
this.invalidQueryMessage = msg;
this.messageState = "changed";
setTimeout(() => (this.messageState = ""), 500);
}
ngOnInit(){
this.deletedColumns = [];
this.isUserPromptIsNotRelated = false;
this.currentChat = undefined;
this.invalidQueryMessage = "The AI can provide information when you ask about HR."
this.reportGroups = [
{description : "Employee", value : EnumReportGroupType.Employee},
{description : "Leave", value : EnumReportGroupType.Leave},
{description : "Attendance", value : EnumReportGroupType.Attendance},
{description : "Salary", value : EnumReportGroupType.Salary},
{description : "Performance", value : EnumReportGroupType.Performance},
{description : "Training", value : EnumReportGroupType.Training},
];
this.chartGroups = [
{description : "Bar Chart", value : EnumAIChartType.BarChart},
{description : "Line Graph", value : EnumAIChartType.LineGraph},
{description : "Pie Chart", value : EnumAIChartType.PieChart},
{description : "Scatter Plot", value : EnumAIChartType.ScatterPlot},
{description : "Area Chart", value : EnumAIChartType.AreaChart},
{description : "Histogram", value : EnumAIChartType.Histogram},
{description : "Waterfall Chart", value : EnumAIChartType.WaterfallChart},
{description : "Gant Chart", value : EnumAIChartType.GantChart},
{description : "Radar Chart", value : EnumAIChartType.RadarChart},
{description : "Activity Diagram", value : EnumAIChartType.ActivityDiagram},
];
this.selectedReportGroup = EnumReportGroupType.Employee
this.onReportGroupChange(this.selectedReportGroup);
}
LoadCurrentUserAllQueryLog(reportGroupType : EnumReportGroupType){
this.loadingpanelService.ShowLoadingPanel = true;
this.opeAiService.GetCurrentUserAllQueryLog(reportGroupType).subscribe(
(resp: any) => {
this.currentUserAllQueryLog = resp;
},
(err: any) => {
this.loadingpanelService.ShowLoadingPanel = false;
this.notificationService.showError(err.error, "Error");
},
() => {
this.loadingpanelService.ShowLoadingPanel = false;
this.currentChat = undefined;
if(this.currentUserAllQueryLog && this.currentUserAllQueryLog.length > 0){
if(this.inputUserCommand !== ""){
let queryLog : OpenAIQueryLog = this.currentUserAllQueryLog.find(x => x.userPrompt.toLowerCase() === this.inputUserCommand.toLowerCase()) ?? undefined;
if(queryLog != undefined){
if(queryLog.isCommon === false){
this.currentChat = queryLog;
this.isDisabledShared = false;
}
else{
this.isDisabledShared = true;
}
}
else{
this.isDisabledShared = true;
}
}
else{
this.isDisabledShared = true;
}
}
});
}
ShowAllQueryLog(){
this.querySearchText = "";
this.isShowCurrentUserAllQueryLog = true;
this.LoadCurrentUserAllQueryLog(this.selectedReportGroup);
}
onInputChange() {
const text = this.inputUserCommand?.toLowerCase().trim() || '';
if (!text) {this.filteredSuggestions = [];return;}
this.filteredSuggestions = this.currentUserAllQueryLog
.filter(item => item.userPrompt.toLowerCase().startsWith(text))
.slice(0, 10);
}
closeSuggestions() {
this.filteredSuggestions = [];
}
clearInput() {
this.inputUserCommand = '';
this.filteredSuggestions = [];
this.gridData = this.gridColumns = [];
this.OpenAIResponce = {};
this.currentChat = undefined;
this.isDisabledShared = true;
}
@HostListener('document:click', ['$event'])
handleClickOutside(event: MouseEvent) {
const target = event.target as HTMLElement;
if (!target.closest('.suggestion-wrapper')) {
this.closeSuggestions();
}
}
selectSuggestion(item: OpenAIQueryLog) {
this.isUserPromptIsNotRelated = false;
this.invalidQueryMessage = "No data returned from AI."
this.inputUserCommand = item.userPrompt;
this.filteredSuggestions = [];
this.OpenAIPreviousQueryExecution(item.id); // or any other action
}
handleEnterKey(event: KeyboardEvent): void {
event.preventDefault();
if (this.inputUserCommand?.trim()) {
this.onCallOpenAI_One();
}
}
onCallOpenAI_One(){
this.deletedColumns = [];
this.isUserPromptIsNotRelated = false;
this.currentChat = undefined;
this.invalidQueryMessage = "No data returned from AI."
if(this.selectedReportGroup && this.inputUserCommand && this.inputUserCommand !== "" &&
(this.selectedReportGroup === EnumReportGroupType.Employee || this.selectedReportGroup === EnumReportGroupType.Salary
|| this.selectedReportGroup === EnumReportGroupType.Performance || this.selectedReportGroup === EnumReportGroupType.Training
|| this.selectedReportGroup === EnumReportGroupType.Leave || this.selectedReportGroup === EnumReportGroupType.Attendance)){
const data = {userPrompt: this.inputUserCommand,reportGroup: this.selectedReportGroup}
this.gridData = this.gridColumns = [];
this.OpenAIResponce = {};
this.isShowChart = false;
if(this.CheckUserPromptFromPreviousQueryLog(this.inputUserCommand)){
let OpenAIQueryLog: OpenAIQueryLog = this.currentUserAllQueryLog.find(x => x.userPrompt.toLowerCase() === this.inputUserCommand.toLowerCase()) ?? undefined;
if(OpenAIQueryLog != undefined){
this.OpenAIPreviousQueryExecution(OpenAIQueryLog.id);
}
return;
}
this.isUserPromptIsNotRelated = false;
this.loadingpanelService.ShowLoadingPanel = true;
this.opeAiService.AskOpenAI(data).subscribe(
(resp: any) => {
this.OpenAIResponce = JSON.parse(resp);
},
(err: any) => {
this.loadingpanelService.ShowLoadingPanel = false;
this.isUserPromptIsNotRelated = false;
if (err.error && (err.error as string).includes("Sorry, I can only help with retrieving data. I am not allowed to update or delete any records.")) {
this.setInvalidQueryMessage("Sorry, I can only help with retrieving data. I am not allowed to update or delete any records.");
}
else if (err.error && (err.error as string).includes("I can only help with questions related to")) {
this.showOutOfScopeNotice();
}
else{
this.notificationService.showError(err.error, "Error");
}
},
() => {
this.loadingpanelService.ShowLoadingPanel = false;
this.ProcessOpenAIData();
this.LoadCurrentUserAllQueryLog(this.selectedReportGroup);
});
}
}
CheckUserPromptFromPreviousQueryLog(userPrompt: string): boolean {
return this.currentUserAllQueryLog.some(item => item.userPrompt.toLowerCase() === userPrompt.toLowerCase());
}
get chartCategories(): string[] {
if (!this.chartData) return [];
return this.chartData.map(d => d.category);
}
public scatterLabelContent(e: any): string {
return `(${e.dataItem.x}, ${e.dataItem.y})`;
}
ProcessOpenAIData() {
this.deletedColumns = [];
if (!this.OpenAIResponce) {
this.invalidQueryMessage = "No data returned from AI.";
return;
}
this.openAIResponseWithData = this.OpenAIResponce as OpenAIResponseWithData;
if (!this.openAIResponseWithData) { return; }
// --- CHART handling (kept mostly same as your original logic) ---
if (this.openAIResponseWithData.IsChart && this.openAIResponseWithData.ChartType && this.openAIResponseWithData.ChartType !== "") {
if (this.openAIResponseWithData.ChartType === 'line' || this.openAIResponseWithData.ChartType === 'area') {
this.openAIResponseWithData.LabelPosition = 'above';
} else {
this.openAIResponseWithData.LabelPosition = 'outsideEnd';
}
this.isShowChart = true;
this.chartData = [];
if (this.openAIResponseWithData.ChartType === 'scatter') {
this.chartData = this.openAIResponseWithData.Labels.map((label, index) => ({
x: label,
y: this.openAIResponseWithData.Values[index]
}));
} else {
this.chartData = this.openAIResponseWithData.Labels.map((label, index) => ({
category: label,
value: this.openAIResponseWithData.Values[index]
}));
}
}
// --- TABLE parsing and normalization ---
try {
const parsed = JSON.parse(this.openAIResponseWithData.TableData);
let allRows: any[] = [];
if (Array.isArray(parsed)) {
// If parsed is an array of tables with Rows properties
allRows = parsed.flatMap(t => t.Rows ?? []);
} else if (parsed && Array.isArray(parsed.Rows)) {
allRows = parsed.Rows;
} else {
// fallback: if parsed itself is an array of row objects
allRows = Array.isArray(parsed) ? parsed : [];
}
if (!allRows || allRows.length === 0) {
this.gridData = [];
this.gridColumns = [];
this.gridColumnsForChart = [];
return;
}
// Use keys from first row as canonical columns
const keys = Object.keys(allRows[0]);
// Build gridColumns with safe field names and non-empty titles
this.gridColumns = keys.map(k => {
const safeKey = k.replace(/\s+/g, '_');
return {
field: safeKey,
title: (k && k.toString().trim()) ? k.toString() : safeKey,
editing: false
};
});
// Normalize each row: convert keys to safeKey, replace null/object with readable value
this.gridData = allRows.map(row => {
const normalized: any = {};
for (const k of keys) {
const safeKey = k.replace(/\s+/g, '_');
let val = row[k];
if (val === null || val === undefined || typeof val === 'object') {
normalized[safeKey] = '-';
} else {
normalized[safeKey] = val;
}
}
return normalized;
});
// Columns for chart control:
if (this.gridColumns && this.gridColumns.length > 0) {
this.gridColumnsForChart = this.gridColumns.map(col => ({ description: col.title, value: col.field }));
} else {
this.gridColumnsForChart = [];
}
} catch (e) {
console.error('Parse error in ProcessOpenAIData', e);
this.notificationService.showError("Failed to parse OpenAI response.", "Parse Error");
}
}
saveHeader(index: number) {
if (!this.gridColumns || !this.gridColumns[index]) { return; }
const col = this.gridColumns[index];
if (!col.title || col.title.toString().trim() === '') {
col.title = col.field;
}
col.editing = false;
delete col._oldTitle;
}
cancelHeader(index: number) {
if (!this.gridColumns || !this.gridColumns[index]) { return; }
const col = this.gridColumns[index];
if (col._oldTitle !== undefined) {
col.title = col._oldTitle;
}
col.editing = false;
delete col._oldTitle;
}
deleteColumn(index: number) {
const removed = this.gridColumns.splice(index, 1)[0];
this.deletedColumns.push({ ...removed, index });
}
scrollDeleted(direction: number) {
if (this.deletedContainer && this.deletedContainer.nativeElement) {
const el = this.deletedContainer.nativeElement;
const scrollAmount = 150;
el.scrollBy({ left: direction * scrollAmount, behavior: 'smooth' });
}
}
startEdit(index: number) {
if (!this.gridColumns || !this.gridColumns[index]) { return; }
const col = this.gridColumns[index];
col._oldTitle = col.title;
col.editing = true;
setTimeout(() => {
const selector = `.header-container[data-col-index="${index}"] .header-input`;
const el = document.querySelector(selector) as HTMLInputElement | null;
if (el) {
el.focus();
}
}, 0);
}
restoreColumn(idx: number) {
const col = this.deletedColumns.splice(idx, 1)[0];
this.gridColumns.splice(col.index, 0, col);
}
onHeaderBlur(index: number) {
this.saveHeader(index);
}
openAvailableInfoDialog(){
this.isShowAvailableInfo = true;
}
onReportGroupChange(group : any){
this.isUserPromptIsNotRelated = false;
this.invalidQueryMessage = "The AI can provide information when you ask about HR."
if(this.selectedReportGroup &&
(this.selectedReportGroup === EnumReportGroupType.Employee
|| this.selectedReportGroup === EnumReportGroupType.Salary
|| this.selectedReportGroup === EnumReportGroupType.Performance
|| this.selectedReportGroup === EnumReportGroupType.Training
|| this.selectedReportGroup === EnumReportGroupType.Attendance
|| this.selectedReportGroup === EnumReportGroupType.Leave)){
this.loadingpanelService.ShowLoadingPanel = true;
this.reportColumnDefinition = [];
this.tableColumnDefinition = [];
this.opeAiService.GetReportColumnDefinition(this.selectedReportGroup).subscribe(
(resp: any) => {
this.reportColumnDefinition = resp as any[];
},
(err: any) => {
this.loadingpanelService.ShowLoadingPanel = false;
this.notificationService.showError(err.error, "Error");
},
() => {
this.loadingpanelService.ShowLoadingPanel = false;
this.gridData = [];
if (this.reportColumnDefinition && this.reportColumnDefinition.length > 0) {
const excludedNormalizedCaptions = new Set(['employeeid']);
const excludedNormalizedCaptionsSalaryMonthlyID = new Set(['salarymonthlyid']);
const groupedMap = new Map<string, ReportColumnDefinition>();
this.reportColumnDefinition.forEach(item => {
const normalized = this.normalizeCaption(item.caption);
if (!excludedNormalizedCaptions.has(normalized) && !excludedNormalizedCaptionsSalaryMonthlyID.has(normalized)) {
const rawTableName = item.tablename || '';
const cleanedTableName = rawTableName.startsWith('vw') ? rawTableName.substring(2) : rawTableName;
if (!groupedMap.has(cleanedTableName)) {
groupedMap.set(cleanedTableName, {
tableName: cleanedTableName,
fields: []
});
}
groupedMap.get(cleanedTableName)!.fields.push(item.caption);
}
});
this.tableColumnDefinition = Array.from(groupedMap.values());
}
this.LoadCurrentUserAllQueryLog(this.selectedReportGroup);
});
}
}
normalizeCaption(caption: string): string {
return caption.replace(/\s+/g, '').toLowerCase().trim();
}
OpenAIPreviousQueryExecution(id : number){
this.isUserPromptIsNotRelated = false;
this.invalidQueryMessage = "No data returned from AI."
if(id && id > 0){
let oQueryLog : OpenAIQueryLog = this.currentUserAllQueryLog.find(x => x.id === id) ?? undefined;
if(oQueryLog != undefined){
this.isShowCurrentUserAllQueryLog = false
this.loadingpanelService.ShowLoadingPanel = true;
this.inputUserCommand = oQueryLog.userPrompt;
this.selectedReportGroup = oQueryLog.reportGroup;
if(oQueryLog.title && oQueryLog.title !== ""){
this.pdfFileName = `${oQueryLog.title}.pdf`;
this.excelFileName = `${oQueryLog.title}.xlsx`;
this.pngFilename = `${oQueryLog.title}_Chart.png`;
this.pdfFileNameForChart = `${oQueryLog.title}_Chart.pdf`;
}
else{
this.pdfFileName = 'FileData.pdf';
this.excelFileName = 'FileData.xlsx';
this.pngFilename = 'FileData_Chart.png';
this.pdfFileNameForChart = 'FileData_Chart.pdf';
}
const data = {
oQueryLog: oQueryLog
}
this.gridData = [];
this.gridColumns = [];
this.gridData = this.gridColumns = [];
this.OpenAIResponce = {};
this.isShowChart = false;
this.opeAiService.OpenAIPreviousQueryExecution(data).subscribe(
(resp: any) => {
this.OpenAIResponce = JSON.parse(resp);
},
(err: any) => {
this.isShowCurrentUserAllQueryLog = false
this.loadingpanelService.ShowLoadingPanel = false;
this.notificationService.showError(err.error, "Error");
},
() => {
this.isShowCurrentUserAllQueryLog = false
this.loadingpanelService.ShowLoadingPanel = false;
this.ProcessOpenAIData();
this.LoadCurrentUserAllQueryLog(this.selectedReportGroup);
});
}
else{
this.isShowCurrentUserAllQueryLog = false
}
}
else{
this.isShowCurrentUserAllQueryLog = false
}
}
ShowChart(){
this.isShowChartOption = true;
}
onChartGroupChange(group : any){
}
showOutOfScopeNotice() {
const msg = this.scopeMessages[this.selectedReportGroup] ?? "I can only help with questions related to this section.";
this.setInvalidQueryMessage(msg);
this.isUserPromptIsNotRelated = true;
}
filteredQueryLog(): OpenAIQueryLog[] {
if (!this.querySearchText) return this.currentUserAllQueryLog;
const search = this.querySearchText.toLowerCase();
return this.currentUserAllQueryLog.filter(item =>
item.userPrompt.toLowerCase().includes(search)
);
}
exportChartImage(chart: ChartComponent) {
this.chartTransitions = false;
setTimeout(() => {
chart.exportImage().then((dataURI: string) => {
saveAs(dataURI, this.pngFilename);
this.chartTransitions = true;
});
});
}
exportSizedChart(chart: ChartComponent): void {
const visual = chart.exportVisual({width: PAGE_RECT.size.width,});
this.exportElement(visual);
}
exportElement(element: Group): void {
exportPDF(element, {paperSize: "A4",margin: "1cm",}).then((dataURI) => {saveAs(dataURI, this.pdfFileNameForChart);});
}
private scopeMessages: Record<number, string> = {
[EnumReportGroupType.Employee]: "I can only help with questions related to Employee information.",
[EnumReportGroupType.Salary]: "I can only help with questions related to Employee Salary.",
[EnumReportGroupType.Performance]:"I can only help with questions related to Employee Performance.",
[EnumReportGroupType.Training]: "I can only help with questions related to Employee Training."
};
ShareThisChatWithOthers(queryLog : OpenAIQueryLog){
this.currentChat = undefined;
this.currentChat = queryLog;
this.ShareThisChat();
}
ShareThisChat(){
if(this.currentChat !== undefined){
this.currentChat.isCommon = !this.currentChat.isCommon;
const data = {
oQueryLog : this.currentChat
}
this.loadingpanelService.ShowLoadingPanel = true;
this.opeAiService.ChatShareWithOthers(data).subscribe(
(resp: any) => {
},
(err: any) => {
this.loadingpanelService.ShowLoadingPanel = false;
this.notificationService.showError(err.error, "Error");
},
() => {
this.loadingpanelService.ShowLoadingPanel = false;
this.LoadCurrentUserAllQueryLog(this.selectedReportGroup);
this.notificationService.showSuccess("Successfully Shared");
});
}
}
}
export class ReportColumnDefinition {
tableName: string;
fields: string[] = [];
}