/** * @license * Copyright 2022 Superflow.dev * SPDX-License-Identifier: MIT */ import { LitElement, html, css, PropertyValueMap } from 'lit'; import { customElement, query, queryAssignedElements, property } from 'lit/decorators.js'; // import {customElement, query, property} from 'lit/decorators.js'; import Util from './util'; import { SfIForm } from 'sf-i-form'; import { SfIUploader } from 'sf-i-uploader'; import { Chart, ChartItem, registerables } from 'chart.js'; import { exportBackgroundPlugin } from './exportBackgroundPlugin'; import { SfIElasticText } from 'sf-i-elastic-text'; import { SfIMultitextarea } from 'sf-i-multitextarea'; import { SfIReporting } from 'sf-i-reporting'; import { SfMultiselectSearch } from 'sf-multiselect-search'; import { SfISelect } from 'sf-i-select'; // import {LitElement, html, css} from 'lit'; // import {customElement} from 'lit/decorators.js'; /* Modes: View, Add, Edit, Delete, Admin DB: partitionKey, rangeKey, values */ /** * SfIEvents element. * @fires renderComplete - When the list is populated * @fires valueChanged - When the value is changed * @property apiId - backend api id * @property label - input label * @property name - name of the input * @property mode - mode of operation * @property selectedId - id to preselect * @property selectedValue - callback function */ @customElement('sf-i-events') export class SfIEvents extends LitElement { SEARCH_BLOCK_SIZE = 10; FLOW_GRAPH_COMPLETENESS = "completeness"; FLOW_GRAPH_TIMELINESS = "timeliness"; FLOW_GRAPH_COMPLIANCE = "compliance"; FLOW_GRAPH_RISKAREAS = "riskarea"; FLOW_GRAPH_RISKSEVERITY = "risk"; FLOW_GRAPH_LOCATION = "locationname"; FLOW_GRAPH_FUNCTION = "functions"; FLOW_GRAPH_OBLIGATIONTYPE = "obligationtype"; FLOW_GRAPH_JURISDICTION = "jurisdiction"; FLOW_GRAPH_FREQUENCY = "frequency"; FLOW_GRAPH_SUBCATEGORY = "subcategory"; TAB_GROUP_BUSINESS_UNDERSTANDING = "businessunderstanding"; TAB_GROUP_GOVERNANCE_MAPPING = "governancemapping"; TAB_GROUP_CUSTOMIZATION = "customize"; TAB_GROUP_ROLLOUT = "rollout"; TAB_GROUP_GOVERNANCE = "governance"; TAB_YEAR = "year"; TAB_FIND = "find"; TAB_STREAM = "stream"; TAB_UPCOMING = "upcoming"; TAB_THIS = "this"; TAB_PAST = "past"; TAB_CUSTOM = "custom"; TAB_ADHOC = "adhoc"; TAB_REGISTERS = "registers"; TAB_ALL_ROLES = "allroles"; TAB_REPORTER = "reporter"; TAB_APPROVER = "approver"; TAB_FUNCTION_HEAD = "functionhead"; TAB_AUDITOR = "auditor"; TAB_VIEWER = "viewer"; TAB_STATUTES = "statutes"; TAB_COMPLIANCES = "compliances"; TAB_NOTICES = "notices"; TAB_ENTITIES = "entities"; TAB_LOCATIONS = "locations"; TAB_TAGS = "tags"; TAB_REPORTERS = "reporters"; TAB_APPROVERS = "approvers"; TAB_FUNCTION_HEADS = "functionheads"; TAB_MAKER_CHECKERS = "makercheckers"; TAB_AUDITORS = "auditors"; TAB_DOCS = "docs"; TAB_VIEWERS = "viewers"; TAB_DUEDATES = "duedates"; TAB_EXTENSIONS = "extensions"; TAB_TRIGGERS = "triggers"; TAB_ALERTSCHEDULES = "alertschedules"; TAB_ACTIVATIONS = "activations"; TAB_INVALIDATION = "invalidations"; TAB_INTERNALCONTROLS = "internalcontrols"; TAB_REPORTEDLOCATIONS = "reportedlocations"; TAB_SIGNOFF = "signoff"; TAB_GOV_LOCATIONS = "govlocations"; TAB_GOV_USERS = "govusers"; TAB_FUNCTIONS = "functions"; TAB_COUNTRIES = "countries"; TAB_CALENDAR = "calendar"; TAB_SUSPENSE = "suspense"; TAB_RCM_COMPLIANCES = "compliances"; TAB_RCM_PROJECTS = "projects"; TAB_RCM_DATE = "date"; TAB_RCM_CONFIRM = "confirm"; TAB_RCM_JOBS = "jobs"; TAB_ALL = "all"; TAB_PENDING_ON_ME = "pending on me"; TAB_PENDING_ON_REPORTER = "pending on reporter"; TAB_PENDING_ON_APPROVER = "pending on approver"; TAB_DONE = "done"; COLOR_APPROVED = "#50cf01"; COLOR_NOT_STARTED = "#A4A9AD"; COLOR_PENDING_APPROVAL = "#ffe505" COLOR_REJECTED = "#C80036" COLOR_PAST_DUE_DATE = "#ffe505"; COLOR_LATE_EXECUTED = "#840B0F"; COLOR_LATE_APPROVED = "#EE2F36"; COLOR_LATE_REPORTED = "#Ef9C66"; COLOR_SCHEDULED = "#888888"; COLOR_NOT_COMPLIED = "#C80036"; COLOR_PARTIALLY_COMPLIED = "#F79256"; COLOR_COMPLIED = "#50cf01"; COLOR_COMPLIED_WITH_EXCEPTION = "#ffe505"; COLOR_REPORTED_NON_COMPLIANCE = "#840B0F"; STATUS_NOT_STARTED = "not-started"; STATUS_PENDING_APPROVAL = "pending-approval"; STATUS_REJECTED = "rejected"; STATUS_APPROVED = "approved"; CERTIFICATE_HTML = `

Certificate

I, PERSON_NAME, working as PERSON_DESIGNATION in PERSON_COMPANY, hereby declare that I am entrusted with the responsibility of ensuring compliance with various laws applicable to the company in the administration of business and the affairs of the company

After having examined and considered all relevant information and based on the information furnished by the concerned officers, I, do hereby certify that the Finance / Technical / Administration / Legal wings / department of PERSON_COMPANY for the period PERSON_PERIOD, has in the conduct of business:

  1. Complied with all applicable laws, enactments, orders, rules, regulations, and other statutory requirements of the Central, State and other Statutory and local authorities concerning the business and affairs of the company;
  2. Paid all applicable statutory dues on due dates;
  3. Maintained proper registers, records, documents and books and filed proper returns, forms and statements and furnished necessary particulars to the relevant authorities; and
  4. Not done or committed any act or entered into any transactions in violation of any statutory provisions


Date: PERSON_DATE
Criteria: PERSON_CRITERIA
Name: PERSON_NAME
Role: PERSON_DESIGNATION


Compliance Status

PERSON_COMPLIANCE_STATUS

Compliances List

PERSON_COMPLIANCES `; COMPLIANCES_HTML = `

Compliance Report

Report generated for PROJECT_NAME on REPORT_DATE
FILTERS_DATA

PERSON_COMPLIANCES
`; MAPPING_HTML = ` TABLE_DATA `; TAGGING_HTML = ` TABLE_DATA `; AUTOSAVE_FLAG = true; EXCLUDE_COLS_FROM_REGS: Array = ["updatetype", "question", "invalidations", "activations", "alertschedule", "clientquestion", "countryname", "countryid", "entityname", "entityid", "locationname", "locationid", "reporters", "approvers", "timeframe", "responsedays", "execmodule", "functions", "shortid", "shortnumid", "countries", "tagsmap", "reportersmap", "approversmap", "functionheadsmap", "auditorsmap", "viewersmap", "approved", "documents", "comments", "lastupdated", "dateofcompletion", "mmdd", "completeness", "timeliness", "compliance", "delta", "triggers", "lastmodifiedby", "lastmodifiedtime"] COLS_REGS: Array = ["jurisdiction", "subcategory", "obligationtype", "obligationtitle", "applicability", "obligation", "reporters", "approvers", "risk"] CHARTS_LIST_BY_MODULES: { [key: string]: Array } = { "compliances": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "notices": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "contracts": ["compliance", "timeliness", "completeness", "location"], "licenses": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "rcmresources": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"] }; chartSelectedLegend: Array = []; selectedFilters: any = null; barCharDataSet2: Array = []; barCharDataSet2Arr: Array = []; barCharDataSet3: Array = []; barCharDataSet3Arr: Array = []; barCharDataSet4: Array = []; barCharDataSet4Arr: Array = []; getallcountryevetsParams: string = ""; @query('#decrypt-container') _SfDecryptContainer: any; @query('#sf-i-project-decrypt') _SfDecryptProjectInput: any; @query('#input-decrypt') _SfDecryptFileInput: any; @query('#button-decrypt') _SfDecryptButton: any; @property() decryptProjectId: string = ""; @property() decryptFileName: string = ""; @property() filteronboarding: string = '[]'; getfilterOnboarding = () => { return JSON.parse(this.filteronboarding); } getFilterOnboardingString = () => { const jsonFilterOnboarding = JSON.parse(this.filteronboarding); var html = ''; html += '
Mapped Locations
' html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; let count = 0; for (var i = 0; i < jsonFilterOnboarding.length; i++) { var country = jsonFilterOnboarding[i].country; if (jsonFilterOnboarding[i].locations != null && Object.keys(jsonFilterOnboarding[i].locations).length > 0) { for (var j = 0; j < Object.keys(jsonFilterOnboarding[i].locations).length; j++) { const state = Object.keys(jsonFilterOnboarding[i].locations)[j]; var classBg = ''; if (count % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; html += ''; html += ''; html += ''; html += ''; count++; } } } html += '
'; html += 'Country' html += ''; html += 'State' html += ''; html += 'Location' html += '
'; html += country; html += ''; html += state; html += ''; //console.log('gettinglocations', (jsonFilterOnboarding[i]['locations'][state])); var tempHtml = ''; for (var k = 0; k < (jsonFilterOnboarding[i]['locations'][state]).length; k++) { const location = (jsonFilterOnboarding[i]['locations'][state])[k]; tempHtml += location; if (k < ((jsonFilterOnboarding[i]['locations'][state]).length - 1)) { tempHtml += ', '; } } html += ('
'); html += '
'; html += '
Mapped Laws
' html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; for (var i = 0; i < jsonFilterOnboarding.length; i++) { var classBg = ''; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; } html += '
'; html += 'Country' html += ''; html += 'State' html += ''; html += 'Subcategory' html += ''; html += 'Exclusions' html += ''; html += 'Inclusions' html += '
'; html += jsonFilterOnboarding[i].country; html += ''; for (var j = 0; j < jsonFilterOnboarding[i].states.length; j++) { html += ('
' + (jsonFilterOnboarding[i].states[j].length === 0 ? 'Federal' : jsonFilterOnboarding[i].states[j]) + '
'); } html += '
'; for (var j = 0; j < jsonFilterOnboarding[i].subcategories.length; j++) { html += ('
' + jsonFilterOnboarding[i].subcategories[j] + '
'); } html += '
'; if (jsonFilterOnboarding[i].excludestatutes != null) { for (var j = 0; j < jsonFilterOnboarding[i].excludestatutes.length; j++) { html += ('
'); } } html += '
'; if (jsonFilterOnboarding[i].includestatutes != null) { for (var j = 0; j < jsonFilterOnboarding[i].includestatutes.length; j++) { html += ('
'); } } html += '
'; return html; } @property() locations!: string; getLocations = () => { return JSON.parse(this.locations); } getLocationsByCountry = (country: string, statute: string) => { let locations = []; if (this.getLocations()[country] != null) { const states = Object.keys(this.getLocations()[country]); for (var i = 0; i < states.length; i++) { if (this.getfilterOnboarding().length === 0) { locations.push(...this.getLocations()[country][states[i]]); } else { for (var j = 0; j < this.getLocations()[country][states[i]].length; j++) { for (var k = 0; k < this.getfilterOnboarding().length; k++) { if (this.getfilterOnboarding()[k]['country'] == country) { if (this.getfilterOnboarding()[k]['locations'] != null) { if (this.getfilterOnboarding()[k]['locations'][states[i]] != null) { var push = true; if (this.getfilterOnboarding()[k]['locations'][states[i]].includes(this.getLocations()[country][states[i]][j])) { if (this.getfilterOnboarding()[k]['excludelocations'] == null) { } else { if (this.getfilterOnboarding()[k]['excludelocations'][statute] == null) { } else { if (this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]] == null) { } else { if (statute == "Information Technology Act, 2000") { //console.log("getLocationsByCountry", push, this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]], this.getLocations()[country][states[i]][j], this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]].includes(this.getLocations()[country][states[i]][j])); } if (this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]].includes(this.getLocations()[country][states[i]][j])) { //console.log("getLocationsByCountry", 'setting false'); push = false; } } } if (statute == "Information Technology Act, 2000") { //console.log("getLocationsByCountry", push, this.getLocations()[country][states[i]][j]); } } } else { push = false; } } else { push = false; } } else { push = false; } if (push) { locations.push(this.getLocations()[country][states[i]][j]); } } } } } } } return locations; } getLocationsByState = (country: string, state: string, statute: string) => { //console.log('getting getLocationsByState', country, state, this.getfilterOnboarding()); let locations = []; if (this.getLocations()[country] != null) { if (this.getLocations()[country][state] != null) { if (this.getLocations()[country][state] != null) { if (this.getfilterOnboarding().length === 0) { locations.push(...this.getLocations()[country][state]); } else { for (var k = 0; k < this.getfilterOnboarding().length; k++) { if (this.getfilterOnboarding()[k]['country'] == country) { for (var i = 0; i < this.getLocations()[country][state].length; i++) { var push = true; if (this.getfilterOnboarding()[k]['locations'] != null) { if (this.getfilterOnboarding()[k]['locations'][state] != null) { if (this.getfilterOnboarding()[k]['locations'][state].includes(this.getLocations()[country][state][i])) { if (this.getfilterOnboarding()[k]['excludelocations'] == null) { } else { if (this.getfilterOnboarding()[k]['excludelocations'][statute] == null) { } else { if (this.getfilterOnboarding()[k]['excludelocations'][statute][state] == null) { } else { if (this.getfilterOnboarding()[k]['excludelocations'][statute][state].includes(this.getLocations()[country][state][i])) { push = false; } } } } } else { push = false; } } else { push = false; } } else { push = false; } if (push) { locations.push(this.getLocations()[country][state][i]); } } } } } } } } //console.log('getting getLocationsByState return ', locations); return locations; } @property({ type: Array }) selectedCbs: Array = []; @property() projectId!: string; @property() contractStartDate: string = ""; @property() name!: string; @property() disableflagggrcresponse: string = ""; @property() disablesave: string = ""; @property() disableclientresponse: string = ""; @property() disablesignoff: string = ""; @property() apiId!: string; @property() apiId2!: string; @property() apiIdStatutes!: string; @property() apiIdDefinitions!: string; @property() apiidReportformats!: string; @property() apiIdProjects!: string; @property() apiIdCompliances!: string; @property() apiIdList!: string; @property() apiIdDetail!: string; @property() apiIdUsers!: string; @property() apiIdTags!: string; @property() apiIdUserProfiles!: string; @property() apiIdNotices!: string; @property() apiIdAgreements!: string; @property() apiIdLicenses!: string; @property() apiIdRCMResources!: string; @property() apiIdModules!: string; @property() apiIdDashboard!: string; @property() apiIdUpload!: string; @property() apiRegionUpload!: string; @property() apiMethodList!: string; @property() apiMethodDetail!: string; @property() apiBodyList!: string; @property() apiBodyDetail!: string; @property() userProfileId!: string; @property() graphParam: string = ""; @property() entityId: string = ""; @property() locationId: string = ""; @property() showRegisterExport: string = "false"; @property() countryId: string = ""; @property() functionId: string = ""; @property() tagId: string = ""; @property() userName!: string; @property() projectName!: string; @property() selectedCriteria!: string; @property() apiResponseFieldList!: string; @property() rcmSelectedCompliance!: any; @property() rcmSelectedProjects!: any; @property() rcmSelectedDate!: any; @property() rcmSelectedMessage!: any; @property() myOnboardingTab: string = ""; @property() myOnboardingTabGroup: string = ""; @property() myRcmTab: string = this.TAB_RCM_COMPLIANCES; @property() myNoticesTab: string = this.TAB_COMPLIANCES; @property() myRole: string = ""; @property() chart: any = null; @property() chartBase64: any = null; @property() chart2: any = null; @property() chart2Base64: any = null; @property() chart3: any = null; @property() chart3Base64: any = null; @property() chart4: any = null; @property() chart4Base64: any = null; @property() calendarStartDD!: string; @property() calendarStartMM!: string; @property() calendarStartYYYY!: string; @property({ type: Array }) calendar: Date[] = []; @property() mappedValuesDueDates: any = {}; @property() mappedValuesUsers: any = {}; @property() mappedValuesTags: any = {}; @property() unmappedEvents: any = null; @property() mappings: any = null; @property() triggers: any = null; @property({ type: Array }) monthNames: string[] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; @property() events: any = null; @property() nextEvents: any = null; @property() registerEvents: any = null; @property() registerSelectedIds: any = []; @property() notices: any = null; @property() statistics: any = null; @property() statisticsMeta: any = null; @property() statisticsFiltersData: any = null; @property() streamIndex: any = null; @property() eventsInWindow: any = null; @property() eventHideFields: any = null; getEventHideFields = () => { return JSON.parse(this.eventHideFields); } @property() eventPreviewFields: any = null; getEventPreviewFields = () => { return JSON.parse(this.eventPreviewFields); } @property() eventFields: any = null; getEventFields = () => { return JSON.parse(this.eventFields ?? "[]"); } @property() eventFieldDependencies: any = null; getEventFieldDependencies = () => { return JSON.parse(this.eventFieldDependencies); } getApiBodyList = () => { //console.log('calendar api body list', this.apiBodyList); try { return JSON.parse(this.apiBodyList); } catch (e: any) { return {}; } } getApiBodyDetail = () => { return JSON.parse(this.apiBodyDetail); } @property() csvDataRegisters: string = ""; @property() csvDataCompliances: string = ""; @property() csvTableData: string = ""; @property() csvDataStats: string = ""; @property() csvGraphStats: string = ""; @property() csvCompletenessStats: string = ""; @property() csvTimelinessStats: string = ""; @property() csvComplianceStats: string = ""; @property() htmlDataCompliances: string = ""; @property() htmlDataStats: string = ""; @property() htmlDataSummary: string = ""; @property() htmlStatsFilter: string = ""; @property() period: string = ""; @property() mode!: string; @property({ type: Number }) flowRcmNotification: number = 0; @property() flowGraph: string = ""; @property() flow: string = ""; @property() fill: string = "solid"; @property({ type: Array }) filterTags: string[] = []; @property() subfilter: string = ""; @property() riskAreasData: any = null; @property() riskAreasPartStatusData: any = null; @property() riskAreasLateStatusData: any = null; @property() riskAreasComplianceStatusData: any = null; @property() riskSeverityData: any = null; @property({ type: Array }) arrCols: Array = ["country", "state", "obligationtitle", "statute", "category"]; @property({ type: Array }) arrRcmProjectCols: Array = ["name"]; @property() riskSeverityPartStatusData: any = null; @property() riskSeverityLateStatusData: any = null; @property() riskSeverityComplianceStatusData: any = null; @property() functionData: any = null; @property() functionPartStatusData: any = null; @property() functionLateStatusData: any = null; @property() functionComplianceStatusData: any = null; @property() obligationTypeData: any = null; @property() obligationTypePartStatusData: any = null; @property() obligationTypeLateStatusData: any = null; @property() obligationTypeComplianceStatusData: any = null; @property() jurisdictionData: any = null; @property() jurisdictionPartStatusData: any = null; @property() jurisdictionLateStatusData: any = null; @property() jurisdictionComplianceStatusData: any = null; @property() currentColumnIndex: string = ""; @property() frequencyData: any = null; @property() frequencyPartStatusData: any = null; @property() frequencyLateStatusData: any = null; @property() frequencyComplianceStatusData: any = null; @property() subcategoryData: any = null; @property() subcategoryPartStatusData: any = null; @property() subcategoryLateStatusData: any = null; @property() subcategoryComplianceStatusData: any = null; @property() locationData: any = null; @property() locationPartStatusData: any = null; @property() locationLateStatusData: any = null; @property() locationComplianceStatusData: any = null; @property() suspenseCount: number = 0; @property({ type: Array }) selectedItemIds: Array = []; @property({ type: Array }) selectedItems: Array = []; @property() selectedStatus: string = ""; @property() selectedTab: string = ""; @property({ type: Number }) selectedCountryTab: number = -1; @property() restrictToMapping: string = ""; @property() enableDeleteLatestReport: string = ""; @property() stream: string = this.TAB_STREAM; @property() myroles: string = "[]"; @property() blocksize: string = "5"; @property() features: string = "[]" getFeatures = () => { return ['compliances', ...JSON.parse(this.features)] } selectedFeatures: string[] = ['compliances'] nextPage: number = 0; nextTabRole: string = ""; nextTabStatus: string = ""; @property() sdate: string = ""; @property() edate: string = ""; lastupdated: string = ""; changedOnboardingItemIds: string[] = []; selectedCountryIndex: number = 0; selectedRegisterIndex: number = -1; showReportedLocations: boolean = false; @property() selectallblock: string = "100"; graphFilter: string = ""; recentlyReported: any = {} registerFilters: { [key: string]: { [key: string]: boolean } } = {}; suspenseFlag: boolean = false; tablecols: string[] = [] reportedLocationsVals: any[] = [] minRiskMitigated: number = 0; minRiskResidual: number = 0; maxRiskMitigated: number = 0; maxRiskResidual: number = 0; finRiskCurrency: string = ""; reportingSuggestions: string[] = [ "Done", "Done on time", "Completed" ] reportingSuggestionsNotApplicable: string[] = [ "Although legally applicable, the compliance is not relevant for this period" ] flagAdhoc: boolean = true static override styles = css` .bg-white { background-color: white; } .proposed-users-table { width: 150px; } .lds-dual-ring1 { display: inline-block; width: 15px; height: 15px; } .lds-dual-ring1:after { content: " "; display: block; width: 15px; height: 15px; margin: 0px; border-radius: 50%; border: 2px solid #fff; border-color: #666 #ddd #666 #ddd; animation: lds-dual-ring 0.8s linear infinite; } @keyframes lds-dual-ring1 { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } sf-i-uploader::part(button-icon) { border-width: 0px; border-radius: 5px; color: #fff; background: #c15c83; box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6); border-top: solid 1px rgba(255, 255, 255, 0.3); border-left: solid 1px rgba(255, 255, 255, 0.3); border-bottom: solid 1px rgba(0, 0, 0, 0.1); border-right: solid 1px rgba(0, 0, 0, 0.1); } #calendar-tab-next span { font-size: 80%; } .justify-evenly { justify-content: space-evenly; } #detail-container { z-index: 101; } #detail-list-container { z-index: 100; } .plain-filter-icon { cursor: pointer; } .pos-fixed { display: flex; justify-content: center; align-items: center; position: fixed; top: 0px; left: 0px; width: 100%; min-height: 100%; z-index: 101; } .sub-button { font-size: 80%; } .sub-button span { font-size: 80%; } .pos-fixed-scroll { display: flex; justify-content: center; align-items: center; position: fixed; bottom: 50px; right: 50px; z-index: 99; } .cover-slide { position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background-color: black; opacity: 0.4; } .detail-list-container, .detail-container, .report-summary-container { width: 60%; height: 400px; background-color: #efefef; overflow-y: auto; border-radius: 10px; z-index: 102; } .sf-i-form-modal-container { position: fixed; width: 80%; height: 80%; top: 10%; right: 10%; background-color: white; border: 1px solid #888; overflow: scroll; z-index: 100 } @media (orientation: portrait) { .detail-container, .report-summary-container { width: 80%; height: 400px; background-color: #efefef; overflow-y: auto; border-radius: 10px; } } .box-large { height: 150px; width: 100%; background: linear-gradient(-45deg, transparent 10%, #ccc 5%, transparent 60%); background-size: 300%; background-position-x: 100%; animation: shimmer 1.5s infinite linear; margin-top: 20px; margin-bottom: 20px; } .box { margin-top: 20px; height: 10px; width: 100%; background: linear-gradient(-45deg, transparent 10%, #ccc 5%, transparent 60%); background-size: 300%; background-position-x: 100%; animation: shimmer 1.5s infinite linear; margin-bottom: 20px; } .chosen { background-color: #E5FAD4 !important; } @keyframes shimmer { to { background-position-x: 0% } } .truncate { display: none } @media (orientation: landscape) { .chart-container { width: 100%; overflow-x: scroll; } .chart-item { min-width: 40%; } } @media (orientation: portrait) { .chart-container { width: 100%; overflow-x: scroll; } .chart-item { width: 100%; } } @media (orientation: portrait) { #tab-container { position: fixed; bottom: 0px; left: 0px; background-color: #efefef; padding-left: 10px; padding-right: 10px; padding-top: 10px; overflow-x: auto; width: 100%; max-width: 100%; justify-content: start; box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6); z-index: 101; } } @media (orientation: landscape) { .mobile-only { display: none; } .desktop-only { display: flex; } } .title-byline { font-size: 90%; } @media (orientation: portrait) { .mobile-only { display: flex; } .desktop-only { display: none; } } .SfIEventsC { display: flex; flex-direction: column; align-items: stretch; justify-content: space-between; } .td-dark { background-color: #e9e9e9; } .td-dark-selected { background-color: #e3e0c8; } .td-light { background-color: #f6f6f6; } .td-light-selected { background-color: #f5f2d9; } .invisible { visibility: hidden; } .scroll-x { overflow-x: auto; } .mw-140 { max-width: 140% } .no-shrink { flex-shrink: 0; } .p-10 { padding: 10px; } .cursor { cursor: pointer; } .commentbox { padding: 10px; border: solid 1px gray; border-radius: 10px; } .reporterbox { width: 90%; margin-right: 10%; } .approverbox { width: 90%; margin-left: 5%; } .pr-5 { padding-right: 5px; } .pt-5 { padding-top: 5px; } .pb-5 { padding-bottom: 5px; } .pb-20 { padding-bottom: 20px; } .m-20 { margin: 20px; } .m-10 { margin: 10px; } .text-start { text-align: start; } .text-center { text-align: center; } .mb-0 { margin-bottom: 0px; } .mt-0 { margin-top: 0px; } .pl-0-imp { padding-left: 0px !important; } .ml-0 { margin-left: 0px; } .mr-0 { margin-right: 0px; } .mb-100 { margin-bottom: 100px; } .mb-10 { margin-bottom: 10px; } .mb-5 { margin-bottom: 5px; } .mt-5 { margin-top: 5px; } #button-back-add-mapping { bottom: 10px; z-index: 98; position: sticky; width: 96%; margin-left: 2%; margin-right: 2%; } .fixed-bottom { position: fixed; bottom: 0px; left: 0px; width: 100%; z-index: 99; } .div-graph-complete { background-color: #50cf01; height: 100%; width: 0%; } .div-graph-pending { background-color: #ffe505; height: 100%; width: 100%; } .badge-success { padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 2px; border-radius: 7px; color: white; background-color: #50cf01; } .badge-warning { padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 2px; border-radius: 7px; color: black; background-color: #ffe505; } .badge-error { padding-left: 5px; padding-right: 5px; padding-top: 5px; padding-bottom: 2px; border-radius: 7px; color: white; background-color: #C80036; } input:not([type='radio'], [type="file"]) { border-width: 0px; border-radius: 5px; color: #666; background: #efefef; box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6); border-top: solid 1px rgba(255, 255, 255, 0.3); border-left: solid 1px rgba(255, 255, 255, 0.3); border-bottom: solid 1px rgba(0, 0, 0, 0.1); border-right: solid 1px rgba(0, 0, 0, 0.1); padding: 10px; } .bg-pending { background-color: #ffe505; } .bg-done { background-color: #50cf01; } .color-pending { color: #ffe505; } .color-pending-approval { color: #ffe505; } .color-not-started { color: #888888; } .color-not-complied { color: #C80036; } .color-partially-complied { color: #F79256; } .color-complied { color: #50cf01; } .color-complied-with-gaps { color: #ffe505; } .color-reported-non-compliance { color: #840B0F; } .color-scheduled { color: #888888; } .color-done { color: #50cf01; } .color-rejected { color: #C80036; } .color-approved { color: #50cf01; } .color-past-due-date { color: #ffe505; } .color-late-executed { color: #840B0F; } .color-late-approved { color: #EE2F36; } .color-late-reported { color: #Ef9C66; } .pr-10 { padding-right: 10px; } .pt-10 { padding-top: 10px; } .pt-20 { padding-top: 20px; } .pb-10 { padding-bottom: 10px; } .bg-left { border-top: solid 1px #dcdcdc; padding-right: 5px; } .bg-left-no-border { padding-right: 5px; } .m-0 { margin: 0px; } .mt-10 { margin-top: 10px; } .mt-5 { margin-top: 5px; } .ml-5 { margin-left: 5px; } .ml-10 { margin-left: 10px; } .ml-10-m-0 { margin-left: 10px; } .mt-20 { margin-top: 20px; } .ml-20 { margin-left: 20px; } .ml-20-m-0 { margin-left: 20px; } .mr-20 { margin-right: 20px; } .mb-20 { margin-bottom: 20px; } .flex-grow { flex-grow: 1; } .flex-wrap { flex-wrap: wrap; } .left-sticky { left: 0px; position: sticky; z-index: 100; } .link { text-decoration: underline; cursor: pointer; } .accordian-head { cursor: pointer; } .button-submit { font-weight: 800; font-size: 110%; } .mr-10 { margin-right: 10px; } .pl-5 { padding-left: 5px; } .pl-10 { padding-left: 10px; } .pr-10 { padding-right: 10px; } .pl-20 { padding-left: 20px; } .pr-20 { padding-right: 20px; } .gone { display: none } .loader-element { position: fixed; right: 30px; top: 30px; margin-left: 5px; z-index: 102 } #row-unmapped-graph { width: 300px; height: 10px; } #stream-container { padding: 0%; } #custom-container { padding: 0%; } #adhoc-container { padding: 0%; } #upcoming-container { padding: 0%; } .container-mapping-event { overflow-x: auto; } #this-container { padding: 2%; } #past-container { padding: 2%; } .stream-event-list { margin-left: 0px; padding: 10px; } .stream-events-container { overflow-x: auto; width: 100% } .stream-event-list-container { width: 200px; } .stream-event-selected { padding-left: 20px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; } .stream-event-not-selected { padding-left: 20px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; color: #aaa; font-size: 80%; } .stream-event-not-selected-hidden { padding-left: 20px; padding-right: 10px; padding-top: 5px; padding-bottom: 5px; color: #aaa; line-height: 0.05; } .stream-month-selected { padding: 10px; text-align: center; } .stream-month-not-selected { padding: 10px; text-align: center; } .calendar-left-col { width: 30%; } @media (orientation: portrait) { .calendar-right-data { width: 100%; } .ml-10-m-0 { margin-left: 0px; } .ml-20-m-0 { margin-left: 0px; } } @media (orientation: landscape) { .calendar-right-data { width: 70%; } } .day-item { width: 14%; margin-bottom: 5px; text-align: center; } .date-item { font-size: 80%; color: #333; } .date-item-before { font-size: 80%; color: #999; } .dot { height: 4px; border-radius: 3px; } .title-item { padding: 5px; margin-bottom: 20px; } .title-item-date { padding-right: 5px; margin-bottom: 20px; } .calendar-item { padding: 8px; width: 90%; margin-bottom: 20px; } .muted { color: gray; } .td-head { text-transform: capitalize; } .tab-button { padding: 10px; padding-left: 15px; padding-right: 15px; font-size: 105%; margin-left: 5px; margin-right: 5px; } .tab-button-small { padding: 5px; padding-left: 7px; padding-right: 7px; font-size: 95%; margin-left: 5px; margin-right: 5px; } .td-body { padding: 5px; } .td-dark { background-color: #e9e9e9; } .td-highlight { background-color: black; color: white; } .td-light { background-color: #f6f6f6; } td { white-space: nowrap; } .w-100 { width: 100%; } .m-w-200 { min-width: 200px; } .w-90 { width: 90%; } .fw-100 { font-weight: 100; } .fw-200 { font-weight: 200; } .fw-300 { font-weight: 300; } .fw-600 { font-weight: 600; } .align-start { align-items: flex-start; } .align-stretch { align-items: stretch; } .align-baseline { align-items: baseline; } .align-end { align-items: flex-end; } .align-center { align-items: center; } .align-self-start { align-self: flex-start; } .lds-text { position: absolute; left: 0px; top: 0px; margin-top: 2px; margin-left: 2px; width: 50px; height: 50px; color: gray; } .lds-text-c { display: flex; width: 100%; height: 100%; justify-content: center; align-items: center; margin-top: 40px; font-size: 90%; } .lds-dual-ring { display: inline-block; width: 50px; height: 50px; } .lds-dual-ring:after { content: " "; display: block; width: 50px; height: 50px; margin: 0px; border-radius: 50%; border: 2px solid #fff; border-color: #888 #ddd #888 #ddd; background-color: white; animation: lds-dual-ring 0.8s linear infinite; } .lds-dual-ring-lg { display: inline-block; width: 30px; height: 30px; } .lds-dual-ring-lg:after { content: " "; display: block; width: 30px; height: 30px; margin: 0px; border-radius: 50%; border: 3px solid #fff; border-color: #888 #ddd #888 #ddd; animation: lds-dual-ring 0.8s linear infinite; } .div-row-error { display: flex; justify-content: center; position: fixed; position: fixed; top: 0px; right: 0px; margin-top: 20px; margin-right: 20px; display: none; align-items:center; background-color: white; border: dashed 1px red; padding: 20px; z-index: 102; } .div-row-error-message { color: red; padding: 5px; background-color: white; text-align: center; } .div-row-success { display: flex; flex-direction: column; justify-content: center; position: fixed; top: 0px; right: 0px; margin-top: 20px; margin-right: 20px; display: none; align-items:stretch; background-color: white; border: dashed 1px green; padding: 20px; z-index: 102; } .div-row-success-message { color: green; padding: 5px; background-color: white; text-align: center; } .div-row-success-message-btn-container { background-color: white; display: flex; flex-direction: row; justify-content: end; align-items: center; } .d-flex { display: flex; } .flex-col { flex-direction: column; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .justify-end { justify-content: flex-end; } @keyframes lds-dual-ring { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .hide { display: none; } .lb { width: 5% } .rb { width: 5% } .main-container { width: 90%; overflow-x: auto; } .filter-list-container{ position: absolute; right: 5px; background-color: white; border: solid 1px #888; border-radius: 5px; width: max-content; } .filter-button-container{ position: relative; } .max-width-100{ max-width: 100% } @media (orientation: landscape) { .lb { width: 30% } .rb { width: 30% } .calendar-item { width: 20%; margin: 2%; padding: 8px; } .main-container { width: 40%; } } #button-refresh { display: none; position: fixed; bottom: 10px; right: 10px } #button-background-process { cursor: pointer } .small-icon { font-size: 98% } .new-feature{ display: block; width: fit-content; } `; @query('.SfIEventsC') _SfIEventsC: any; @query('.div-row-error') _SfRowError: any; @query('.div-row-error-message') _SfRowErrorMessage: any; @query('.div-row-success') _SfRowSuccess: any; @query('.div-row-success-message') _SfRowSuccessMessage: any; @query('.div-row-success-message-btn-container') _SfRowSuccessMessageBtnContainer: any; @query('.loader-element') _SfLoader: any; @query('#calendar-container') _SfCalendarContainer: any; @query('#button-generate') _SfButtonGenerate: any; @query('.button-search') _SfButtonSearch: any; @query('.button-save') _SfButtonSave: any; @query('.button-next') _SfButtonNext: any; @query('.button-prev') _SfButtonPrev: any; @query('.input-search') _SfInputSearch: any; @query('#button-sync-chosen-project') _SfButtonSyncChosenProject: any; @query('#button-map-chosen-project') _SfButtonMapChosenProject: any; @query('#button-back-chosen-project') _SfButtonBackChosenProject: any; @query('#button-back-calendar-mapping') _SfButtonBackCalendarMapping: any; @query('#button-back-sync-mapping') _SfButtonBackSyncMapping: any; @query('#button-back-chosen-mapping') _SfButtonBackChosenMapping: any; @query('#title-chosen-project') _SfTitleChosenProject: any; @query('#title-chosen-mapping') _SfTitleChosenMapping: any; @query('#container-chosen-project') _SfContainerChosenProject: any; @query('#container-project-select') _SfContainerProjectSelect: any; @query('#container-project-actions') _SfContainerProjectActions: any; @query('#stream-container') _SfStreamContainer: any; @query('#upcoming-container') _SfUpcomingContainer: any; @query('#detail-container') _SfDetailContainer: any; @query('#detail-list-container') _SfDetailListContainer: any; @query('#report-summary-container') _SfReportSummaryContainer: any; @query('#this-container') _SfThisContainer: any; @query('#past-container') _SfPastContainer: any; @query('#custom-container') _SfCustomContainer: any; @query('#adhoc-container') _SfAdhocContainer: any; @query('#find-container') _SfFindContainer: any; @query('#register-container') _SfRegisterContainer: any; @query('#mapping-container') _SfMappingContainer: any; @query('#stream-event-status') _SfStreamEventStatus: any; @query('#tab-container') _SfTabContainer: any; @query('#mapping-tab-container') _SfMappingTabContainer: any; @query('#role-tab-container') _SfRoleTabContainer: any; @query('#status-tab-container') _SfStatusTabContainer: any; @query('#onboarding-tab-container') _SfOnboardingTabContainer: any; @query('#onboarding-status-container') _SfOnboardingStatusContainer: any; @query('#rcm-container') _SfRcmContainer: any; @query('#rcm-container-list') _SfRcmContainerList: any; @query('#rcm-tab-container') _SfRcmTabContainer: any; @query('#statutes-list-container') _SfOnboardingStatutesListContainer: any; @query('#rcm-compliance-container') _SfRcmComplianceContainer: any; @query('#rcm-projects-container') _SfRcmProjectsContainer: any; @query('#rcm-date-container') _SfRcmDateContainer: any; @query('#rcm-confirm-container') _SfRcmConfirmContainer: any; @query('#rcm-jobs-container') _SfRcmJobsContainer: any; @query('#statutes-container') _SfOnboardingStatutesContainer: any; @query('#compliances-list-container') _SfOnboardingCompliancesListContainer: any; @query('#compliances-container') _SfOnboardingCompliancesContainer: any; @query('#entities-list-container') _SfOnboardingEntitiesListContainer: any; @query('#entities-container') _SfOnboardingEntitiesContainer: any; @query('#functions-container') _SfOnboardingFunctionsContainer: any; @query('#functions-list-container') _SfOnboardingFunctionsListContainer: any; @query('#countries-container') _SfOnboardingCountriesContainer: any; @query('#countries-list-container') _SfOnboardingCountriesListContainer: any; @query('#locations-list-container') _SfOnboardingLocationsListContainer: any; @query('#locations-container') _SfOnboardingLocationsContainer: any; @query('#tags-list-container') _SfOnboardingTagsListContainer: any; @query('#tags-container') _SfOnboardingTagsContainer: any; @query('#reporters-list-container') _SfOnboardingReportersListContainer: any; @query('#reporters-container') _SfOnboardingReportersContainer: any; @query('#approvers-container') _SfOnboardingApproversContainer: any; @query('#functionheads-container') _SfOnboardingFunctionHeadsContainer: any; @query('#makercheckers-container') _SfOnboardingMakerCheckersContainer: any; @query('#docs-container') _SfOnboardingDocsContainer: any; @query('#auditors-container') _SfOnboardingAuditorsContainer: any; @query('#extensions-container') _SfOnboardingExtensionsContainer: any; @query('#viewers-container') _SfOnboardingViewersContainer: any; @query('#approvers-list-container') _SfOnboardingApproversListContainer: any; @query('#makercheckers-list-container') _SfOnboardingMakerCheckersListContainer: any; @query('#docs-list-container') _SfOnboardingDocsListContainer: any; @query('#functionheads-list-container') _SfOnboardingFunctionHeadsListContainer: any; @query('#auditors-list-container') _SfOnboardingAuditorsListContainer: any; @query('#viewers-list-container') _SfOnboardingViewersListContainer: any; @query('#duedates-list-container') _SfOnboardingDuedatesListContainer: any; @query('#extensions-list-container') _SfOnboardingExtensionsListContainer: any; @query('#duedates-container') _SfOnboardingDuedatesContainer: any; @query('#alertschedules-list-container') _SfOnboardingAlertSchedulesListContainer: any; @query('#alertschedules-container') _SfOnboardingAlertSchedulesContainer: any; @query('#activations-list-container') _SfOnboardingActivationListContainer: any; @query('#activations-container') _SfOnboardingActivationsContainer: any; @query('#invalidations-list-container') _SfOnboardingInvalidationListContainer: any; @query('#invalidations-container') _SfOnboardingInvalidationsContainer: any; @query('#triggers-container') _SfOnboardingTriggersContainer: any; @query('#triggers-list-container') _SfOnboardingTriggersListContainer: any; @query('#internalcontrols-list-container') _SfOnboardingInternalControlsListContainer: any; @query('#internalcontrols-container') _SfOnboardingInternalControlsContainer: any; @query('#reportedlocations-list-container') _SfOnboardingReportedLocationsListContainer: any; @query('#reportedlocations-container') _SfOnboardingReportedLocationsContainer: any; @query('#signoff-container') _SfOnboardingSignoffContainer: any; @query('#calendar-list-container') _SfOnboardingCalendarListContainer: any; @query('#calendar-container') _SfOnboardingCalendarContainer: any; @query('#suspense-container') _SfOnboardingSuspenseContainer: any; @query('#gov-locations-container') _SfOnboardingGovLocationsContainer: any; @query('#gov-users-container') _SfOnboardingGovUsersContainer: any; @query('#onboarding-tab-group-0') _SfOnboardingTabGroup0: any; @query('#onboarding-tab-group-1') _SfOnboardingTabGroup1: any; @query('#onboarding-tab-group-2') _SfOnboardingTabGroup2: any; @query('#onboarding-tab-group-3') _SfOnboardingTabGroup3: any; @query('#onboarding-tab-group-button-0') _SfOnboardingTabGroupButton0: any; @query('#onboarding-tab-group-button-1') _SfOnboardingTabGroupButton1: any; @query('#onboarding-tab-group-button-2') _SfOnboardingTabGroupButton2: any; @query('#onboarding-tab-group-button-3') _SfOnboardingTabGroupButton3: any; @query('#onboarding-tab-group-button-4') _SfOnboardingTabGroupButton4: any; @queryAssignedElements({ slot: 'project' }) _SfProject: any; @queryAssignedElements({ slot: 'uploader' }) _SfUploader: any; @queryAssignedElements({ slot: 'reporting' }) _SfReporting: any; isSelectedLegend = (value: number): any => { return this.chartSelectedLegend.includes(value); } removeFromSelectedLegend = (value: number) => { const index = this.chartSelectedLegend.indexOf(value); if (index > -1) { // only splice array when item is found this.chartSelectedLegend.splice(index, 1); // 2nd parameter means remove one item only } } clearSelectedLegend = () => { this.chartSelectedLegend = []; if (this.chart != null) { this.chart.data.datasets[0].data.forEach((_d: any, i: any) => { //console.log(d); this.chart.getDatasetMeta(0).data[i].hidden = false; this.chart.update(); }) } if (this.chart2 != null && this.chart3 != null && this.chart4 != null) { if (this.barCharDataSet2Arr.length > 0 && this.barCharDataSet3Arr.length > 0 && this.barCharDataSet4Arr.length > 0) { do { this.chart2.data.datasets = this.barCharDataSet2Arr.pop(); this.chart3.data.datasets = this.barCharDataSet3Arr.pop(); this.chart4.data.datasets = this.barCharDataSet4Arr.pop(); } while (this.barCharDataSet2Arr.length > 0) } else { if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) { this.barCharDataSet2.pop(); this.barCharDataSet3.pop(); this.barCharDataSet4.pop(); } } } this.selectedFilters = null; } clearSelectedGraphParam = () => { //console.log('clickonbar clearing graph param', this.chart, this.chart2, this.chart3); this.graphParam = ""; if (this.chart != null) { this.chart.update(); } if (this.chart2 != null && this.chart3 != null && this.chart4 != null) { if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) { this.chart2.data.datasets = this.barCharDataSet2.pop(); this.chart3.data.datasets = this.barCharDataSet3.pop(); this.chart4.data.datasets = this.barCharDataSet4.pop(); } } else { if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) { this.barCharDataSet2.pop(); this.barCharDataSet3.pop(); this.barCharDataSet4.pop(); } } console.log('calling processGraphFilter 1') this.processGraphFilter(this.graphFilter); this.selectedFilters = null; } getEventField = (field: string) => { for (var i = 0; i < this.getEventFields().length; i++) { if (this.getEventFields()[i].field == field) { return this.getEventFields()[i]; } } } getParentFieldFromDepedencies = (field: string) => { for (var i = 0; i < this.getEventFieldDependencies().length; i++) { if (this.getEventFieldDependencies()[i].type == "foreignkey" && this.getEventFieldDependencies()[i].child == field) { return this.getEventFieldDependencies()[i].parent; } } return null; } getEventTexts = (field: string, selectedId: Array, row: any) => { console.log('get event texts', field, selectedId, row); if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-select") { var selectedIds = ""; selectedIds += '['; for (var i = 0; i < selectedId.length; i++) { selectedIds += ('"' + selectedId[i] + '"'); if (i < selectedId.length - 1) { selectedIds += ','; } } selectedIds += ']'; return '' } if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-sub-select") { const parentField = this.getParentFieldFromDepedencies(field); //console.log('parentfield', parentField); var selectedIds = ""; selectedIds += '['; for (var i = 0; i < selectedId.length; i++) { selectedIds += ('"' + selectedId[i] + '"'); if (i < selectedId.length - 1) { selectedIds += ','; } } selectedIds += ']'; const filterId = JSON.parse(row[parentField])[0]; //console.log(''); return '' } if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-form") { //console.log(''); return '' } return ""; } clearTabs = () => { (this._SfCalendarContainer as HTMLDivElement).style.display = 'none'; (this._SfStreamContainer as HTMLDivElement).style.display = 'none'; (this._SfUpcomingContainer as HTMLDivElement).style.display = 'none'; (this._SfThisContainer as HTMLDivElement).style.display = 'none'; (this._SfPastContainer as HTMLDivElement).style.display = 'none'; (this._SfCustomContainer as HTMLDivElement).style.display = 'none'; (this._SfAdhocContainer as HTMLDivElement).style.display = 'none'; (this._SfFindContainer as HTMLDivElement).style.display = 'none'; (this._SfRegisterContainer as HTMLDivElement).style.display = 'none'; } enableCalendar = () => { this.clearTabs(); (this._SfCalendarContainer as HTMLDivElement).style.display = 'flex'; } enableStream = () => { this.clearTabs(); (this._SfStreamContainer as HTMLDivElement).style.display = 'flex'; } enableUpcoming() { this.clearTabs(); (this._SfUpcomingContainer as HTMLDivElement).style.display = 'flex'; } enableThis() { this.clearTabs(); (this._SfThisContainer as HTMLDivElement).style.display = 'flex'; } enablePast() { this.clearTabs(); (this._SfPastContainer as HTMLDivElement).style.display = 'flex'; } enableCustom() { this.clearTabs(); (this._SfCustomContainer as HTMLDivElement).style.display = 'flex'; } enableFind() { this.clearTabs(); (this._SfFindContainer as HTMLDivElement).style.display = 'flex'; } enableAdhoc() { this.clearTabs(); (this._SfAdhocContainer as HTMLDivElement).style.display = 'flex'; } enableRegisters() { this.clearTabs(); (this._SfRegisterContainer as HTMLDivElement).style.display = 'flex'; } prepareXhrPresigned = async (data: any, url: string, loaderElement: any, loaderText: string = '') => { if (loaderElement != null) { loaderElement.innerHTML = '
'; loaderElement.innerHTML += ('
' + loaderText + '
'); } return await Util.callApiPresigned(url, data); } prepareXhrPresignedGet = async (url: string, loaderElement: any, loaderText: string = '') => { if (loaderElement != null) { loaderElement.innerHTML = '
'; loaderElement.innerHTML += ('
' + loaderText + '
'); } return await Util.callApiPresignedGet(url); } prepareXhrPresignedDelete = async (url: string, loaderElement: any, loaderText: string = '') => { if (loaderElement != null) { loaderElement.innerHTML = '
'; loaderElement.innerHTML += ('
' + loaderText + '
'); } return await Util.callApiPresignedDelete(url); } prepareXhr = async (data: any, url: string, loaderElement: any, authorization: any, loaderText: string = '') => { if (loaderElement != null) { loaderElement.innerHTML = '
'; loaderElement.innerHTML += ('
' + loaderText + '
'); } return await Util.callApi(url, data, authorization); } clearMessages = () => { this._SfRowError.style.display = 'none'; this._SfRowErrorMessage.innerHTML = ''; this._SfRowSuccess.style.display = 'none'; this._SfRowSuccessMessage.innerHTML = ''; this._SfRowSuccessMessageBtnContainer.innerHTML = ''; } setError = (msg: string) => { this._SfRowError.style.display = 'flex'; this._SfRowErrorMessage.innerHTML = msg; this._SfRowSuccess.style.display = 'none'; this._SfRowSuccessMessage.innerHTML = ''; this._SfRowSuccessMessageBtnContainer.innerHTML = ''; } setSuccess = (msg: string) => { this._SfRowError.style.display = 'none'; this._SfRowErrorMessage.innerHTML = ''; this._SfRowSuccess.style.display = 'flex'; this._SfRowSuccessMessage.innerHTML = msg; this._SfRowSuccessMessageBtnContainer.innerHTML = ''; } setSuccessBtn = (msg: string, btnCaptions: string[], btnCallbacks: Function[]) => { this._SfRowError.style.display = 'none'; this._SfRowErrorMessage.innerHTML = ''; this._SfRowSuccess.style.display = 'flex'; this._SfRowSuccessMessage.innerHTML = msg; let btnHtml = '' for (let [i, caption] of btnCaptions.entries()) { btnHtml += '' } this._SfRowSuccessMessageBtnContainer.innerHTML = btnHtml for (let [i, callback] of btnCallbacks.entries()) { let btn = this._SfRowSuccessMessageBtnContainer.querySelector('#successbtn-' + i) as HTMLButtonElement btn.addEventListener('click', () => { callback() }) } } getLastDayOfLastMonth = (month: number, year: number) => { const date = new Date(year, month, 0); return date.getDate() } getLastDayOfMonth = (month: number, year: number): number => { const date = new Date(year, month + 1, 0); return date.getDate() } getFirstDateOfLastWeek = (startDate: Date): Date => { const sd = new Date(startDate.getTime()); var first = sd.getDate() - sd.getDay(); var firstday = new Date(sd.setDate(first)); for (var i = 0; i < 7; i++) { firstday.setDate(firstday.getDate() - 1); } return firstday; } getFirstDayOfLastMonth(yourDate: Date) { var d = new Date(yourDate); d.setDate(1); d.setMonth(d.getMonth() - 1); return d; } getFirstDateOfWeek = (startDate: Date): Date => { const sd = new Date(startDate.getTime()); var first = sd.getDate() - sd.getDay(); var firstday = new Date(sd.setDate(first)); return firstday; } getBlanks = (month: number, year: number) => { const date = new Date(("0" + (month + 1)).slice(-2) + '/01/' + year); const day = date.getDay(); return day; } getMonthStatus = (month: number, year: number) => { //html += '
'; // const currMonth = new Date().getMonth(); // const currDate = new Date().getDate(); //console.log('currmonth', currMonth, 'currdate', currDate); var approved = 0; var pendingApproval = 0; var rejected = 0; var notStarted = 0; var total = 0; for (var i = 0; i < this.getLastDayOfMonth(month, year); i++) { const mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2); if (month === 1 && i === (this.getLastDayOfMonth(month, year) - 1)) { //console.log('getLastDayOfMonth', month, this.getLastDayOfMonth(month, year), mmdd); } if (this.events[mmdd] != null) { for (var j = 0; j < this.events[mmdd].length; j++) { total++; const partStatus = this.getCompletenessStatus(this.events[mmdd][j]); if (partStatus == "approved") { approved++ } if (partStatus == "not-started") { notStarted++ } if (partStatus == "pending-approval") { pendingApproval++ } if (partStatus == "rejected") { rejected++ } } } } //console.log('month-status', approved, pendingApproval, rejected, notStarted, total); var percApproved = (approved * 100) / total; var percPendingApproval = (pendingApproval * 100) / total; var percRejected = (rejected * 100) / total; var percNotStarted = (notStarted * 100) / total; return { percNotStarted: percNotStarted, percPendingApproval: percPendingApproval, percApproved: percApproved, percRejected: percRejected }; } insertDates = (month: number, year: number) => { var html = ""; html += '
'; const dateNumber = this.getLastDayOfLastMonth(month, year); for (var i = 0; i < this.getBlanks(month, year); i++) { html += '
'; html += dateNumber - (this.getBlanks(month, year) - i - 1); html += '
'; } const currMonth = new Date().getMonth(); const currDate = new Date().getDate(); //console.log('currmonth', currMonth, 'currdate', currDate); for (i = 0; i < this.getLastDayOfMonth(month, year); i++) { const mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2); var partName = ""; if (this.events[mmdd] != null) { partName = "event-calendar-day-with-event"; html += '
'; if (month === currMonth && (i + 1) === currDate) { html += '
' html += (i + 1); html += '
' } else { html += '
' html += (i + 1); html += '
' } var approved = 0; var pendingApproval = 0; var rejected = 0; var notStarted = 0; var total = 0; for (var j = 0; j < this.events[mmdd].length; j++) { total++; const partStatus = this.getCompletenessStatus(this.events[mmdd][j]); if (partStatus == "approved") { approved++; } if (partStatus == "pending-approval") { pendingApproval++; } if (partStatus == "rejected") { rejected++; } if (partStatus == "not-started") { notStarted++; } } var percApproved = (approved * 100) / total; var percPendingApproval = (pendingApproval * 100) / total; var percNotStarted = (notStarted * 100) / total; var percRejected = (rejected * 100) / total; //console.log('percentages', mmdd, percApproved, percPendingApproval, percRejected, percNotStarted) html += '
' //html += '
' html += '
' html += '
' html += '
' html += '
' html += '
' html += '
'; } else { partName = "event-calendar-day-without-event"; html += '
'; // html += '
' // html += (i + 1); // html += '
' if (month === currMonth && (i + 1) === currDate) { html += '
' html += (i + 1); html += '
' } else { html += '
' html += (i + 1); html += '
' } html += '
'; } } for (i = 0; i < 42 - (this.getBlanks(month, year) + this.getLastDayOfMonth(month, year)); i++) { html += '
'; html += (i + 1); html += '
'; } html += '
'; return html; } insertDayNames = () => { var html = ""; html += '
'; html += '
'; html += 'S'; html += '
'; html += '
'; html += 'M'; html += '
'; html += '
'; html += 'T'; html += '
'; html += '
'; html += 'W'; html += '
'; html += '
'; html += 'T'; html += '
'; html += '
'; html += 'F'; html += '
'; html += '
'; html += 'S'; html += '
'; html += '
'; return html; } // getYearFromMonthAndCalendarStart = (mm: string) => { // var yyyy = ""; // var currMonth = new Date().getMonth() + 1; // console.log('CurrentMonth', currMonth, "MM", mm); // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 0); // yyyy = parseInt(this.calendarStartYYYY) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 1); // yyyy = (parseInt(this.calendarStartYYYY) - 1) + ""; // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 2); // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 3); // yyyy = (parseInt(this.calendarStartYYYY)) + ""; // } // return yyyy; // } getYearFromMonthAndCalendarStart = (mm: string) => { var yyyy = ""; if (parseInt(mm) < parseInt(this.calendarStartMM)) { yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; } else { yyyy = parseInt(this.calendarStartYYYY) + ""; } return yyyy; } getAboutToExpire = (event: any) => { // console.log('about to expire', mmdd, event.duedate) let dateArr = event.duedate.split('/') const dd = dateArr[0]; const mm = dateArr[1]; var yyyy = this.getYearFromMonthAndCalendarStart(mm); var date = new Date(); date.setMonth(parseInt(mm) - 1); date.setDate(parseInt(dd)); date.setFullYear(parseInt(yyyy)); const tsDoc = date.getTime(); const tsCurr = new Date().getTime(); // console.log('about to expire', mmdd, date, tsDoc, tsCurr) if ((tsDoc - tsCurr) < (30 * 24 * 60 * 60 * 1000)) { // less than 60 days //console.log('late executed', true) return true; } // console.log('about to expire', tsDoc - tsCurr, (30 * 24 * 60 * 60 * 1000), event.duedate) return false; } getPastDueDate = (mmdd: string) => { const dd = mmdd.substring(3, 5); const mm = mmdd.substring(0, 2); //console.log('getpastduedate', mmdd, dd, mm); // var yyyy = ""; // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 0); // yyyy = parseInt(this.calendarStartYYYY) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 1); // yyyy = (parseInt(this.calendarStartYYYY) - 1) + ""; // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 2); // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // //console.log('getpastduedate returning', 3); // yyyy = (parseInt(this.calendarStartYYYY)) + ""; // } var yyyy = this.getYearFromMonthAndCalendarStart(mm); var date = new Date(); date.setMonth(parseInt(mm) - 1); date.setDate(parseInt(dd)); date.setFullYear(parseInt(yyyy)); var currDate = new Date(); if (currDate.getTime() > date.getTime()) { //console.log('getpastduedate returning true', yyyy); return true; } return false; } getLateExecuted = (mmdd: string, event: any) => { //console.log('late executed', mmdd, event.dateofcompletion) const tsDoc = new Date(parseInt(event.dateofcompletion)).getTime(); const dd = mmdd.substring(3, 5); const mm = mmdd.substring(0, 2); // var yyyy = ""; // var currMonth = new Date().getMonth() + 1; // // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // // yyyy = new Date().getFullYear() + ""; // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() - 1) + ""; // // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() + 1) + ""; // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() + 1) + ""; // // } // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // yyyy = parseInt(this.calendarStartYYYY) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) - 1) + ""; // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } var yyyy = this.getYearFromMonthAndCalendarStart(mm); var date = new Date(); date.setMonth(parseInt(mm) - 1); date.setDate(parseInt(dd)); date.setFullYear(parseInt(yyyy)); const tsCurr = date.getTime(); //console.log('late executed', mmdd, tsDoc, tsCurr) if (tsDoc > tsCurr) { //console.log('late executed', true) return true; } return false; } getLateReported = (mmdd: string, event: any) => { const dd = mmdd.substring(3, 5); const mm = mmdd.substring(0, 2); var yyyy = this.getYearFromMonthAndCalendarStart(mm); var date = new Date(); date.setMonth(parseInt(mm) - 1); date.setDate(parseInt(dd)); date.setFullYear(parseInt(yyyy)); const tsCurr = date.getTime(); for (var i = event.comments.length - 1; i >= 0; i--) { const comment = event.comments[i]; const tsComment = new Date(comment.timestamp); const authorComment = comment.author; if (authorComment == "Reporter" && tsComment.getTime() > tsCurr) { return true; } } return false; } getLateApproved = (mmdd: string, event: any) => { const dd = mmdd.substring(3, 5); const mm = mmdd.substring(0, 2); var yyyy = this.getYearFromMonthAndCalendarStart(mm); var date = new Date(); date.setMonth(parseInt(mm) - 1); date.setDate(parseInt(dd)); date.setFullYear(parseInt(yyyy)); const tsCurr = date.getTime(); for (var i = event.comments.length - 1; i >= 0; i--) { const comment = event.comments[i]; const tsComment = new Date(comment.timestamp); const authorComment = comment.author; if (authorComment == "Approver" && tsComment.getTime() > tsCurr) { return true; } } return false; // //console.log('get late approved', event.obligationtitle, event.lastupdated, mmdd, event.lastupdated); // const tsLastUpdated = new Date((event.lastupdated)).getTime(); // //console.log('get late approved', tsLastUpdated); // const dd = mmdd.substring(3, 5); // const mm = mmdd.substring(0, 2); // var yyyy = this.getYearFromMonthAndCalendarStart(mm); // var date = new Date(); // date.setMonth(parseInt(mm) - 1); // date.setDate(parseInt(dd)); // date.setFullYear(parseInt(yyyy)); // const tsCurr = date.getTime(); // //console.log('get late approved', tsCurr); // if(tsLastUpdated > tsCurr) { // //console.log('late approved', true) // return true; // } // return false; } updateGraphStats = (arr: Array, arrData: any, arrPartData: any, arrLateData: any, arrComplianceData: any, partStatus: string, lateStatus: string, complianceStatus: string) => { for (var i = 0; i < arr.length; i++) { if (arrData == null) { arrData = {}; } const name = arr[i].split(';')[0].trim().replace(/ *\([^)]*\) */g, "") if (arrData[name] == null) { arrData[name] = 1; } else { arrData[name]++; } // if(name.toLowerCase().indexOf('na - corp sec') >= 0) { // console.log('arrData[corpsec]', name, arrData[name]); // } } for (var i = 0; i < arr.length; i++) { if (arrLateData == null) { arrLateData = {}; } if (arrPartData == null) { arrPartData = {}; } if (arrComplianceData == null) { arrComplianceData = {}; } const name = arr[i].split(';')[0].trim().replace(/ *\([^)]*\) */g, "") if (arrLateData[name] == null) { arrLateData[name] = {}; } if (arrPartData[name] == null) { arrPartData[name] = {}; } if (arrComplianceData[name] == null) { arrComplianceData[name] = {}; } if (arrPartData[name]["not-started"] == null) { arrPartData[name]["not-started"] = 0; } if (arrPartData[name]["pending-approval"] == null) { arrPartData[name]["pending-approval"] = 0; } if (arrPartData[name]["rejected"] == null) { arrPartData[name]["rejected"] = 0; } if (arrPartData[name]["approved"] == null) { arrPartData[name]["approved"] = 0; } arrPartData[name][partStatus]++; if (arrLateData[name]["late-executed"] == null) { arrLateData[name]["late-executed"] = 0; } if (arrLateData[name]["late-reported"] == null) { arrLateData[name]["late-reported"] = 0; } if (arrLateData[name]["late-approved"] == null) { arrLateData[name]["late-approved"] = 0; } if (arrLateData[name]["past-due-date"] == null) { arrLateData[name]["past-due-date"] = 0; } if (arrLateData[name]["in-time"] == null) { arrLateData[name]["in-time"] = 0; } arrLateData[name][lateStatus]++; if (arrComplianceData[name]["scheduled"] == null) { arrComplianceData[name]["scheduled"] = 0; } if (arrComplianceData[name]["not-complied"] == null) { arrComplianceData[name]["not-complied"] = 0; } if (arrComplianceData[name]["partially-complied"] == null) { arrComplianceData[name]["partially-complied"] = 0; } if (arrComplianceData[name]["complied"] == null) { arrComplianceData[name]["complied"] = 0; } if (arrComplianceData[name]["complied-with-gaps"] == null) { arrComplianceData[name]["complied-with-gaps"] = 0; } if (arrComplianceData[name]["reported-non-compliance"] == null) { arrComplianceData[name]["reported-non-compliance"] = 0; } arrComplianceData[name][complianceStatus]++; } return { arrData: arrData, arrPartData: arrPartData, arrLateData: arrLateData, arrComplianceData: arrComplianceData } } updateJurisdictionStats = (jurisdictions: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(jurisdictions, this.jurisdictionData, this.jurisdictionPartStatusData, this.jurisdictionLateStatusData, this.jurisdictionComplianceStatusData, partStatus, lateStatus, complianceStatus); this.jurisdictionData = result.arrData; this.jurisdictionLateStatusData = result.arrLateData; this.jurisdictionPartStatusData = result.arrPartData; this.jurisdictionComplianceStatusData = result.arrComplianceData; } updateSubcategoryStats = (subcategories: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(subcategories, this.subcategoryData, this.subcategoryPartStatusData, this.subcategoryLateStatusData, this.subcategoryComplianceStatusData, partStatus, lateStatus, complianceStatus); this.subcategoryData = result.arrData; this.subcategoryLateStatusData = result.arrLateData; this.subcategoryPartStatusData = result.arrPartData; this.subcategoryComplianceStatusData = result.arrComplianceData; } updateFrequencyStats = (frequencies: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(frequencies, this.frequencyData, this.frequencyPartStatusData, this.frequencyLateStatusData, this.frequencyComplianceStatusData, partStatus, lateStatus, complianceStatus); this.frequencyData = result.arrData; this.frequencyLateStatusData = result.arrLateData; this.frequencyPartStatusData = result.arrPartData; this.frequencyComplianceStatusData = result.arrComplianceData; } updateLocationStats = (location: string, partStatus: string, lateStatus: string, complianceStatus: string) => { //console.log('location', location); if (this.locationData == null) { this.locationData = {}; } const locationName = location.replace(/ *\([^)]*\) */g, "") if (this.locationData[locationName] == null) { this.locationData[locationName] = 1; } else { this.locationData[locationName]++; } if (this.locationLateStatusData == null) { this.locationLateStatusData = {}; } if (this.locationPartStatusData == null) { this.locationPartStatusData = {}; } if (this.locationComplianceStatusData == null) { this.locationComplianceStatusData = {}; } if (this.locationLateStatusData[locationName] == null) { this.locationLateStatusData[locationName] = {}; } if (this.locationPartStatusData[locationName] == null) { this.locationPartStatusData[locationName] = {}; } if (this.locationComplianceStatusData[locationName] == null) { this.locationComplianceStatusData[locationName] = {}; } if (this.locationPartStatusData[locationName]["not-started"] == null) { this.locationPartStatusData[locationName]["not-started"] = 0; } if (this.locationPartStatusData[locationName]["pending-approval"] == null) { this.locationPartStatusData[locationName]["pending-approval"] = 0; } if (this.locationPartStatusData[locationName]["rejected"] == null) { this.locationPartStatusData[locationName]["rejected"] = 0; } if (this.locationPartStatusData[locationName]["approved"] == null) { this.locationPartStatusData[locationName]["approved"] = 0; } this.locationPartStatusData[locationName][partStatus]++; if (this.locationLateStatusData[locationName]["late-reported"] == null) { this.locationLateStatusData[locationName]["late-reported"] = 0; } if (this.locationLateStatusData[locationName]["late-executed"] == null) { this.locationLateStatusData[locationName]["late-executed"] = 0; } if (this.locationLateStatusData[locationName]["late-approved"] == null) { this.locationLateStatusData[locationName]["late-approved"] = 0; } if (this.locationLateStatusData[locationName]["past-due-date"] == null) { this.locationLateStatusData[locationName]["past-due-date"] = 0; } if (this.locationLateStatusData[locationName]["in-time"] == null) { this.locationLateStatusData[locationName]["in-time"] = 0; } this.locationLateStatusData[locationName][lateStatus]++; if (this.locationComplianceStatusData[locationName]["not-complied"] == null) { this.locationComplianceStatusData[locationName]["not-complied"] = 0; } if (this.locationComplianceStatusData[locationName]["complied"] == null) { this.locationComplianceStatusData[locationName]["complied"] = 0; } if (this.locationComplianceStatusData[locationName]["partially-complied"] == null) { this.locationComplianceStatusData[locationName]["partially-complied"] = 0; } if (this.locationComplianceStatusData[locationName]["scheduled"] == null) { this.locationComplianceStatusData[locationName]["scheduled"] = 0; } this.locationComplianceStatusData[locationName][complianceStatus]++; } updateFunctionStats = (functions: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(functions, this.functionData, this.functionPartStatusData, this.functionLateStatusData, this.functionComplianceStatusData, partStatus, lateStatus, complianceStatus); this.functionData = result.arrData; this.functionLateStatusData = result.arrLateData; this.functionPartStatusData = result.arrPartData; this.functionComplianceStatusData = result.arrComplianceData; } updateRiskAreaStats = (riskAreas: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(riskAreas, this.riskAreasData, this.riskAreasPartStatusData, this.riskAreasLateStatusData, this.riskAreasComplianceStatusData, partStatus, lateStatus, complianceStatus); this.riskAreasData = result.arrData; this.riskAreasLateStatusData = result.arrLateData; this.riskAreasPartStatusData = result.arrPartData; this.riskAreasComplianceStatusData = result.arrComplianceData; } updateRiskSeverityStats = (riskSeverities: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { console.log('updateRiskSeverityStats', riskSeverities, complianceStatus) const result = this.updateGraphStats(riskSeverities, this.riskSeverityData, this.riskSeverityPartStatusData, this.riskSeverityLateStatusData, this.riskSeverityComplianceStatusData, partStatus, lateStatus, complianceStatus); this.riskSeverityData = result.arrData; this.riskSeverityLateStatusData = result.arrLateData; this.riskSeverityPartStatusData = result.arrPartData; this.riskSeverityComplianceStatusData = result.arrComplianceData; //console.log('updateRiskSeverityStats', JSON.stringify(result.arrComplianceData)) } updateObligationTypeStats = (obligationTypes: Array, partStatus: string, lateStatus: string, complianceStatus: string) => { const result = this.updateGraphStats(obligationTypes, this.obligationTypeData, this.obligationTypePartStatusData, this.obligationTypeLateStatusData, this.obligationTypeComplianceStatusData, partStatus, lateStatus, complianceStatus); this.obligationTypeData = result.arrData; this.obligationTypeLateStatusData = result.arrLateData; this.obligationTypePartStatusData = result.arrPartData; this.obligationTypeComplianceStatusData = result.arrComplianceData; //console.log('Updating obligationtype stats', this.obligationTypeLateStatusData); } getReporterStringFromEvent = (event: any) => { let reporterStr = ''; for (var k = 0; k < event.reporters.length; k++) { reporterStr += '
' + (event.reporters[k].split(';')[0]) + '
'; } return reporterStr; } getReporterDetailStringFromEvent = (event: any) => { let reporterStr = ''; for (var k = 0; k < event.reporters.length; k++) { reporterStr += '
' + (event.reporters[k].split(';')[0]) + '
'; } return reporterStr; } getApproverStringFromEvent = (event: any) => { let approverStr = ''; for (var k = 0; k < event.approvers.length; k++) { approverStr += '
' + (event.approvers[k].split(';')[0]) + '
'; } return approverStr; } getApproverDetailStringFromEvent = (event: any) => { let approverStr = ''; for (var k = 0; k < event.approvers.length; k++) { approverStr += '
' + (event.approvers[k].split(';')[0]) + '
'; } return approverStr; } renderLatestCompliance = (mmddyyyy: string, event: any) => { var lastMax = 0; for (var k = 0; k < event.compliances.length; k++) { const tsOfEvent = new Date(mmddyyyy).getTime(); const tsOfCompliance = parseInt(event.compliances[k].complianceid.S); if (tsOfCompliance > lastMax && tsOfCompliance <= tsOfEvent) { event['specificity'] = JSON.parse(event.compliances[k].data.S)['specificity']; event['reference'] = JSON.parse(event.compliances[k].data.S)['reference']; event['obligation'] = JSON.parse(event.compliances[k].data.S)['obligation']; event['penalty'] = JSON.parse(event.compliances[k].data.S)['penalty']; event['authority'] = JSON.parse(event.compliances[k].data.S)['authority']; event['frequency'] = JSON.parse(event.compliances[k].data.S)['frequency']; event['obligationtype'] = JSON.parse(event.compliances[k].data.S)['obligationtype']; event['duedate'] = JSON.parse(event.compliances[k].data.S)['duedate']; event['applicability'] = JSON.parse(event.compliances[k].data.S)['applicability']; event['form'] = JSON.parse(event.compliances[k].data.S)['form']; event['internalcontrols'] = JSON.parse(event.compliances[k].data.S)['internalcontrols']; event['firstlineofdefence'] = JSON.parse(event.compliances[k].data.S)['firstlineofdefence']; event['risk'] = JSON.parse(event.compliances[k].data.S)['risk']; event['riskarea'] = JSON.parse(event.compliances[k].data.S)['riskarea']; } } return event; } getCompletenessStatus = (event: any) => { if (event.comments == null || event.comments.length === 0) { return "not-started"; } else { if (event.approved != null && event.approved) { return "approved"; } else { if (event.comments[event.comments.length - 1].author == "Reporter") { return "pending-approval"; } else { return "rejected"; } } } } getTimelinessStatus = (mmdd: string, event: any, completeness: string) => { // if(event.module == "contract"){ // if (completeness == "not-started") { // if (this.getPastDueDate(mmdd)) { // return "past-due-date"; // } else { // return "in-time" // } // } else if (completeness == "pending-approval" || completeness == "rejected") { // } // } if (completeness == "not-started") { if (this.getPastDueDate(mmdd)) { return "past-due-date"; } else { return "in-time" } } else if (completeness == "pending-approval" || completeness == "rejected") { if (this.getLateExecuted(mmdd, event)) { return "late-executed"; } else if (this.getLateReported(mmdd, event)) { return "late-reported"; } else if (this.getPastDueDate(mmdd)) { return "past-due-date"; } else { return "in-time"; } } else { if (this.getLateExecuted(mmdd, event)) { return "late-executed"; } else if (this.getLateReported(mmdd, event)) { return "late-reported"; } else if (this.getLateApproved(mmdd, event)) { return "late-approved"; } else { return "in-time"; } } } getComplianceStatus = (completeness: string, timeliness: string, percentage?: string, event: any = {}) => { if (event.module == "contract") { console.log('compliance status', event.terminated, completeness, timeliness) if (event.terminated) { return "terminated" } if (completeness == "not-started") { if (timeliness == "in-time") { if (this.getAboutToExpire(event)) { console.log('returning aboutt to expire') return "about-to-expire"; } else { return "active"; } } else { return "expired"; } } else if (completeness == "pending-approval") { if (timeliness == "in-time") { if (this.getAboutToExpire(event)) { return "about-to-expire"; } else { return "active"; } } else { return "expired"; } } else if (completeness == "rejected") { if (timeliness == "in-time") { if (this.getAboutToExpire(event)) { return "about-to-expire"; } else { return "active"; } } else { return "expired"; } } else { if (timeliness == "in-time" || timeliness == "late-reported" || timeliness == "late-approved") { return "complied"; } else { return "expired"; } } } if (completeness == "not-started") { if (timeliness == "in-time") { return "scheduled"; } else { return "not-complied"; } } else if (completeness == "pending-approval") { if (timeliness == "in-time") { return "scheduled"; } else if (timeliness == "past-due-date" || timeliness == "late-executed") { return "not-complied"; } else { return "partially-complied"; } } else if (completeness == "rejected") { if (timeliness == "in-time") { return "scheduled"; } else { return "not-complied"; } } else { if (timeliness == "in-time" || timeliness == "late-reported" || timeliness == "late-approved") { if (percentage != null && parseInt(percentage) == 0) { console.log('reported non compliance') return "reported-non-compliance" } else if (percentage != null && parseInt(percentage) < 100) { return "complied-with-gaps" } else { return "complied"; } } else { return "not-complied"; } } } numcalled: number = 0; updateStats = (event: any, partStatus: string, lateStatus: string, complianceStatus: string) => { if (event['riskarea'] != null) { this.updateRiskAreaStats(event['riskarea'], partStatus, lateStatus, complianceStatus); } if (event['risk'] != null) { this.updateRiskSeverityStats(event['risk'], partStatus, lateStatus, complianceStatus); } if (event['functions'] != null) { this.updateFunctionStats(event['functions'], partStatus, lateStatus, complianceStatus) } if (event['obligationtype'] != null) { this.updateObligationTypeStats(event['obligationtype'], partStatus, lateStatus, complianceStatus) } if (event['jurisdiction'] != null) { this.updateJurisdictionStats(event['jurisdiction'], partStatus, lateStatus, complianceStatus) } if (event['frequency'] != null) { this.updateFrequencyStats(event['frequency'], partStatus, lateStatus, complianceStatus) } //console.log('updateLocationStats', event['locationname'], event.duedate, event.id); if (event['locationname'] != null) { this.updateLocationStats(event['locationname'], partStatus, lateStatus, complianceStatus) } if (event['subcategory'] != null) { this.updateSubcategoryStats(event['subcategory'], partStatus, lateStatus, complianceStatus) } } renderCalendarGraphs = (showGraph: boolean, parametersTitle: string, showBackgroundButton: boolean) => { //console.log('flowGraph', this.flowGraph); var html = ''; html += '
'; html += '

' + parametersTitle + '

' if (this.getFeatures().length > 1) { html += '
' html += '
' html += '
' // html += `
= (this.getFeatures().length) ? 'checked' : ''} id="input-select-feature-all" part="input-select-feature" name="all">
` // html += `
= 0 ? 'checked' : ''} id="input-select-feature-compliances" part="input-select-feature" name="compliances">
` for (let [index, feature] of this.getFeatures().entries()) { console.log('rendering features', feature, this.selectedFeatures); html += `
= 0 ? 'checked' : ''} id="input-select-feature-${index}" name="features" part="input-select-feature" value="${feature}">
` } html += '
' } html += '
'; if (showBackgroundButton) { html += '
    Synchronizing in the background
' } else { html += '
update  Last Updated on ' + this.lastupdated + '
'; } // html += '
Show reporting daviations
'; if (showGraph) { html += '
'; html += '
Select Chart
'; html += '
'; if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("completeness") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("timeliness") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("compliance") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("riskArea") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("riskSeverity") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("location") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("function") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("obligationType") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("jurisdiction") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("frequency") >= 0) { html += '
'; html += '
'; } if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("subCategory") >= 0) { html += '
'; html += '
'; } html += '' html += '
'; html += '
'; html += '
'; html += '
' html += '
' html += '' html += '
' html += '' html += '
'; html += '
'; html += '
' html += '' html += '' html += '
'; html += '
'; html += '
'; html += `
Financial Risk FIN_RISK_CURRENCY
Lower
Addressed FIN_RISK_MITIGATED_MIN
Pending FIN_RISK_RESIDUAL_MIN
Higher
Addressed FIN_RISK_MITIGATED_MAX
Pending FIN_RISK_RESIDUAL_MAX
` // html += '
Financial Risk
' // html += '' // html += '' // html += '
Risk StatusMinimum RiskMaximum Risk
ResidualFIN_RISK_RESIDUAL_MINFIN_RISK_RESIDUAL_MAX
MitigatedFIN_RISK_MITIGATED_MINFIN_RISK_MITIGATED_MAX
' html += '
' html += '
' html += '
' } else { html += '
'; } html += '
'; return html; } renderCalendarStatisticsGraphs = (showGraph: boolean, parametersTitle: string) => { //console.log('flowGraph', this.flowGraph); var html = ''; html += '
'; html += '

' + parametersTitle + '

' if (this.getFeatures().length > 1) { html += '
' html += '
' html += '
' // html += `
= (this.getFeatures().length) ? 'checked' : ''} id="input-select-feature-all" part="input-select-feature" name="all">
` // html += `
= 0 ? 'checked' : ''} id="input-select-feature-compliances" part="input-select-feature" name="compliances">
` for (let [index, feature] of this.getFeatures().entries()) { console.log('rendering features statistics', feature, this.selectedFeatures); html += `
= 0 ? 'checked' : ''} id="input-select-feature-${index}" name="features" part="input-select-feature" value="${feature}">
` } html += '
' } html += '
'; html += '
update  Last Updated on ' + this.lastupdated + '
'; if (showGraph) { html += '
'; html += '
'; html += `
Financial Risk FIN_RISK_CURRENCY
Lower
Addressed FIN_RISK_MITIGATED_MIN
Pending FIN_RISK_RESIDUAL_MIN
Higher
Addressed FIN_RISK_MITIGATED_MAX
Pending FIN_RISK_RESIDUAL_MAX
` // html += '
Financial Risk
' // html += '' // html += '' // html += '
Risk StatusMinimum RiskMaximum Risk
ResidualFIN_RISK_RESIDUAL_MINFIN_RISK_RESIDUAL_MAX
MitigatedFIN_RISK_MITIGATED_MINFIN_RISK_MITIGATED_MAX
' html += '
' html += '
' html += '
' } else { html += '
'; } html += '
'; return html; } renderCalendarContainerDivStart = (index: number) => { var html = ''; html += '
'; return html; } renderCalendarContainerDivEnd = () => { var html = ''; html += '
'; return html; } renderCalendarEventSummary = () => { var html = ''; html += '
'; html += '
Total: DASHBOARD_TOTAL
'; html += '
schedule  Not Started: DASHBOARD_NOT_STARTED
'; html += '
pending  Pending Approval: DASHBOARD_PENDING_APPROVAL
'; html += '
block  Rejected: DASHBOARD_REJECTED
'; html += '
check_circle  Approved: DASHBOARD_APPROVED
'; html += `
question_mark  Suspense: DASHBOARD_SUSPENSE
`; html += '
schedule  In Time: DASHBOARD_IN_TIME
'; html += '
timer  Past Due Date: DASHBOARD_PAST_DUE_DATE
'; html += '
report_off  Late Reported: DASHBOARD_LATE_REPORTED
'; html += '
remove_done  Late Approved: DASHBOARD_LATE_APPROVED
'; html += '
running_with_errors  Late Executed: DASHBOARD_LATE_EXECUTED
'; if (this.selectedFeatures.indexOf("contracts") >= 0) { html += '
schedule  Active: DASHBOARD_ACTIVE
'; html += '
disabled_by_default  About To Expire: DASHBOARD_ABOUT_TO_EXPIRE
'; html += '
rule  Expired: DASHBOARD_EXPIRED
'; html += '
sweep  Terminated: DASHBOARD_TERMINATED
'; html += '
'; } else { html += '
schedule  Scheduled: DASHBOARD_SCHEDULED
'; html += '
disabled_by_default  Not Complied: DASHBOARD_NOT_COMPLIED
'; html += '
rule  Partially Complied: DASHBOARD_PARTIALLY_COMPLIED
'; html += '
sweep  Complied: DASHBOARD_COMPLIED
'; html += '
rule  Complied With Gaps: DASHBOARD_COMPLIED_WITH_GAPS
'; html += '
rule  Reported Non Compliance: DASHBOARD_REPORTED_NON_COMPLIANCE
'; html += '
'; } html += '
'; return html; } renderCalendarEventSummaryViewer = () => { var html = ''; html += '
'; html += '
Total: DASHBOARD_TOTAL
DASHBOARD_TOTAL_SUBFILTER
'; html += '
schedule  Not Started: DASHBOARD_NOT_STARTED
DASHBOARD_NOT_STARTED_SUBFILTER
'; html += '
pending  Pending Approval: DASHBOARD_PENDING_APPROVAL
DASHBOARD_PENDING_APPROVAL_SUBFILTER
'; html += '
block  Rejected: DASHBOARD_REJECTED
DASHBOARD_REJECTED_SUBFILTER
'; html += '
check_circle  Approved: DASHBOARD_APPROVED
DASHBOARD_APPROVED_SUBFILTER
'; html += '
schedule  In Time: DASHBOARD_IN_TIME
'; html += '
timer  Past Due Date: DASHBOARD_PAST_DUE_DATE
'; html += '
report_off  Late Reported: DASHBOARD_LATE_REPORTED
'; html += '
remove_done  Late Approved: DASHBOARD_LATE_APPROVED
'; html += '
running_with_errors  Late Executed: DASHBOARD_LATE_EXECUTED
'; html += '
schedule  Scheduled: DASHBOARD_SCHEDULED
'; html += '
disabled_by_default  Not Complied: DASHBOARD_NOT_COMPLIED
'; html += '
rule  Partially Complied: DASHBOARD_PARTIALLY_COMPLIED
'; html += '
sweep  Complied: DASHBOARD_COMPLIED
'; html += '
rule  Complied With Gaps: DASHBOARD_COMPLIED_WITH_GAPS
'; html += '
rule  Reported Non Compliance: DASHBOARD_REPORTED_NON_COMPLIANCE
'; html += '
'; html += '
'; return html; } renderStatisticsFiltersTableStart = () => { var html = ''; html += '
' html += ''; return html; } renderStatisticsFiltersTableRow = (index: number, filterUser: boolean = false, isLocation: boolean = false) => { var html = ''; html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += ''; return html; } renderStatisticsFiltersTableEnd = () => { var html = ''; html += '
FILTER_CRITERIA_NAME
DASHBOARD_FILTER_NAME
' if (filterUser) { html += '
Last Access
DASHBOARD_LAST_ACTIVE
Last Action
DASHBOARD_LAST_ACTION
' } html += '
schedule  Not Started
DASHBOARD_NOT_STARTED
pending  Pending Approval
DASHBOARD_PENDING_APPROVAL
block  Rejected
DASHBOARD_REJECTED
check_circle  Approved
DASHBOARD_APPROVED
Total
DASHBOARD_TOTAL
'; return html; } getCalendarRowHide = (events: any, i: number, lastDay: number, month: number, firstDate: any = null, currDate: any = null) => { var hide = true; if (events != null) { hide = false; } else if (i === 1) { hide = false; } else if (i === lastDay) { hide = false; } else { if (firstDate == null) { const mmddPrev = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i - 1)).slice(-2); const mmddNext = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2); //console.log('hide', i, hide); if ((this.events[mmddPrev] != null || this.events[mmddNext] != null)) { hide = false; } } else { const startNextDate = new Date(currDate.getTime()); startNextDate.setDate(currDate.getDate() + 1); const startPrevDate = new Date(currDate.getTime()); startPrevDate.setDate(currDate.getDate() - 1); const mmddNext = ("0" + (startNextDate.getMonth() + 1)).slice(-2) + "/" + ("0" + (startNextDate.getDate())).slice(-2); const mmddPrev = ("0" + (startPrevDate.getMonth() + 1)).slice(-2) + "/" + ("0" + (startPrevDate.getDate())).slice(-2); //console.log('hide', i, hide, startNextDate, startPrevDate, mmddNext, mmddPrev); if ((this.events[mmddPrev] != null || this.events[mmddNext] != null)) { hide = false; } } } return hide; } renderCalendarRowDivStart = (i: number, firstDate: any = null, ddmm: string = "") => { var html = ''; html += '
'; html += '
' + (firstDate != null ? ddmm : ("0" + i).slice(-2)) + ' |
'; html += '
' return html; } renderCalendarRowDivEnd = () => { var html = ''; html += '
' html += '
'; return html; } renderCalendarRowDivItemDivStart = (mmdd: string, event: any, itemNumber: number, partStatus: string, bgStatus: string, fromDrilldown: boolean) => { var html = ''; var remarks = ""; var occurrenceDate = ""; const arrMmdd = mmdd.split("/"); const ddmm = arrMmdd[1] + "/" + arrMmdd[0]; if (event.triggers != null && event.triggers.length > 0 && event.triggers != "[]") { const arrTriggers = JSON.parse(event.triggers); for (var i = 0; i < arrTriggers.length; i++) { const targetDates = arrTriggers[i].targetDates; for (var j = 0; j < targetDates.length; j++) { // console.log('comparing', targetDates[j], ddmm); if (targetDates[j].indexOf(ddmm) >= 0) { remarks = arrTriggers[i].remarks; occurrenceDate = arrTriggers[i].occurrenceDate; // console.log('remarks', mmdd) } } } } let lastUpdated: string = ''; // console.log('lastUpdated', event.lastupdated); if (event.lastupdated != null && event.lastupdated.length > 0) { lastUpdated = Util.getDateTimeStrings(new Date(event.lastupdated).getTime()); } html += '
'; html += '
' + JSON.stringify(event['tags']) + '
' html += '
not filtered
' // html += '
' + ' 0) || (event.isbulk != null && event.isbulk == true) || (event.customreporting != null)) ? "reportformat" : "") + '" class="button-select mr-10 ' + (((event.reportformat != null && event.reportformat.length > 0) || (event.isbulk != null && event.isbulk == true) || (event.customreporting != null)) ? 'hide' : '') + '" type="checkbox"/>' + (event.isbulk != null && event.isbulk == true ? '
' : '') + '' + event.concise == null ? ('') : ('
' + event.locationname.replace(/ *\([^)]*\) */g, "") + '
' + event.risk[0] + '
') + (((event.reportformat != null && event.reportformat.length > 0) || (event.customreporting != null)) ? '' : ('')) + ((event.concise == null && lastUpdated.length > 0) ? ('  
' + lastUpdated + '
') : "") + '
'; const isBulk = event.isbulk === true; const hasReportFormat = event.reportformat?.length > 0; const hasCustomReporting = event.customreporting != null; const hasMakerCheckers = event.makercheckers?.length > 0; const hasDocs = event.docs?.length > 0; const moduleType = event.module ?? 'compliance'; const partStatusSanitized = partStatus.replace(/-/g, '_'); const entityIdSanitized = event.entityid.replace(/-/g, '_'); const locationIdSanitized = (event.locationid ?? "").replace(/-/g, '_'); const eventIdSanitized = event.id.replace(/-/g, '_'); const mmddSanitized = mmdd.replace(/\//g, '-'); const dueDateParts = event.duedate.split('/'); const isReportedLocation = event.reportedlocationsflag == true const isSuspense = event.suspense == true const isReviewed = event.review == true const showCheckbox = !(hasReportFormat || isBulk || hasCustomReporting || isReportedLocation); // const showReportingButton = !hasReportFormat && !hasCustomReporting && event.reporters == null; const showReportingButton = !hasReportFormat && !hasCustomReporting && event.concise != null && !isReportedLocation && !fromDrilldown; const showLocationRisk = event.concise != null; const configHome = Util.getProjectConfigHome(); const showReview = event.concise != null && configHome.features != null && configHome.features.indexOf("understood") >= 0; const showLastUpdated = event.concise == null && lastUpdated.length > 0; // console.log('showReportingButton', showReportingButton) console.log('isReportedLocation', isReportedLocation, 'showCheckbox', showCheckbox, 'showReportingButton', showReportingButton, 'showLocationRisk', showLocationRisk, 'showLastUpdated', showLastUpdated); html += `
${isBulk ? '
' : ''} ${(isReportedLocation && !isSuspense) ? '
arrow_or_edge
' : ''} ${showLocationRisk ? `
${event.locationname.replace(/ *\([^)]*\) */g, "")}
${event.risk[0]}
` : ''} ${showReportingButton ? ` ` : ''} ${showReview ? ` ${isReviewed ? `` : ``} ` : ''} ${showLastUpdated ? `   
${lastUpdated}
` : ''}
`; // ${this.finRiskCurrency == event['localcurrency'] ? `
${event['minlocal'] ?? ""}
` : `
${event['minglobal'] ?? ""}
`} // ${this.finRiskCurrency == event['localcurrency'] ? `
${((event['maxlocal'] < event['minlocal']) ? event['minlocal'] : event['maxlocal']) ?? ""}
` : `
${((event['maxglobal'] < event['minglobal']) ? event['minglobal'] : event['maxglobal']) ?? ""}
`} if (event.concise == null && remarks.length > 0) { html += '
' + remarks + ', occurred on ' + occurrenceDate + '
'; } // console.log('returning divstarthtml', html); return html; } renderCalendarRowDivItemDivEnd = () => { var html = ''; html += '
'; return html; } renderCalendarBlankRowDiv = (hide: boolean, slice: number, i: number, firstDate: any = null, ddmm: string = "") => { var html = ''; //console.log('hidedecision', ddmm, hide); if (!hide) { html += '
'; html += '
' + (firstDate != null ? ddmm : ("0" + i).slice(-2)) + '
'; html += '
'; slice = 2; } else { if (i % slice === 0) { html += '
'; //html += '
'+("0" + i).slice(-2)+' |
'; html += '
.
'; html += '
'; slice += 3; } } return { html: html, slice: slice }; } renderCalendarRowDivItemDivTableHead = (event: any, partStatus: string) => { var html = ''; html += ''; html += ''; if (event.reportedlocationsflag != true) { html += ''; } html += ''; html += '' if (event.entityname != null) { html += '' } if (event.countryname != null) { html += '' } if (event.functions != null) { html += '' } if (event.risk != null) { html += '' } for (var k = 0; k < Object.keys(event).length; k++) { if (this.getEventPreviewFields().includes(Object.keys(event)[k])) { html += ''; } if (event.comments != null && (event.comments).length > 0) { html += ''; } // console.log('rendering last updated', event.lastupdated) if (event.lastupdated != null && (event.lastupdated).length > 0) { html += ''; } if (event.makercheckers != null && (event.makercheckers).length > 0) { html += '' } if (event.docs != null && (event.docs).length > 0) { html += '' } if (event.obligationtype != null && (event.obligationtype[0].toLowerCase() == "quality indicator confirmatory" || event.obligationtype[0].toLowerCase() == "quality indicator percentage")) { if (event.comments != null && (event.comments).length > 0) { html += '' } } html += ''; // console.log('event.obligationtype', event.obligationtype[0].toLowerCase()); return html; } renderCalendarRowDivItemDivTableBody = (event: any, partStatus: string, lateStatus: string, complianceStatus: string, mmdd: string, i: number, j: number) => { var html = ''; html += ''; if (event.reportedlocationsflag != true) { html += ''; html += ''; if (event["locationname"] != null) { html += ''; } if (event["entityname"] != null) { html += ''; } if (event["countryname"] != null) { html += ''; } if (event["functions"] != null) { var functions = ''; for (const element of event["functions"]) { functions += (element.split(';')[0].replace(/ *\([^)]*\) */g, "") + ","); } functions = functions.replace(/,\s*$/, ""); html += ''; } if (event["risk"] != null) { html += ''; } for (var k = 0; k < Object.keys(event).length; k++) { if (this.getEventPreviewFields().includes(Object.keys(event)[k])) { html += ''; } } if (event["countryname"] != null && event.documents != null && event.documents != null && (event.documents).length > 0) { html += ''; } if (event["countryname"] != null && event.comments != null && event.comments != null && (event.comments).length > 0) { html += ''; } if (event.lastupdated != null && event.lastupdated != null && (event.lastupdated).length > 0) { html += ''; } if (event.makercheckers != null && (event.makercheckers).length > 0) { html += ''; } if (event["countryname"] != null && event.docs != null && (event.docs).length > 0) { html += '' } if (event.obligationtype != null && (event.obligationtype[0].toLowerCase() == "quality indicator confirmatory" || event.obligationtype[0].toLowerCase() == "quality indicator percentage")) { if (event.comments != null && (event.comments).length > 0) { html += '' } } html += ''; html += '
'; // if(event.isbulk == null || event.isbulk == false) html += 'Open' html += 'Open' html += ''; html += 'Status' html += ''; html += 'Location' html += ''; html += 'Entity' html += ''; html += 'Country' html += ''; html += 'Function' html += ''; html += 'Risk' html += ''; html += Object.keys(event)[k]; } } //console.log('listing docs',event.documents ) if (event.documents != null && (event.documents).length > 0) { html += ''; html += 'Docs' html += ''; html += 'Comments' html += ''; html += 'Updated' html += ''; html += '' html += ''; html += '' html += ''; html += '' html += '
'; if (event.isbulk == null || !event.isbulk) { html += '' } else { html += '
'; } } html += '
'; html += this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i); html += '
' + event["risk"][0] + '
'; if (event[Object.keys(event)[k]].indexOf("[") >= 0) { html += this.getEventTexts(Object.keys(event)[k], JSON.parse(event[Object.keys(event)[k]]), event); } else { html += ' '; } html += ''; html += 'description' html += (event.documents).length html += ''; html += 'forum' html += (event.comments).length html += ''; html += Util.timeSince(new Date(event.lastupdated).getTime()) html += ''; html += 'done_all' html += ''; html += 'scan_delete' html += ''; for (var n = (event.comments.length - 1); n >= 0; n--) { if (event.comments[n].author == "Reporter") { const reportedValue = ((event.comments[n].comment).replace(/ *\([^)]*\) */g, "").trim()); console.log((event.comments[n].comment).replace(/ *\([^)]*\) */g, "").trim(), reportedValue, event.comments[n]); let badge: string = ""; if (event.obligationtype[0].toLowerCase() == "quality indicator percentage") { if (parseInt(reportedValue) > 98) { badge = "badge-success"; } else if (parseInt(reportedValue) > 90) { badge = "badge-warning"; } else { badge = "badge-error"; } } else { if (reportedValue.toLowerCase() == "yes") { badge = "badge-success"; } else { badge = "badge-error"; } } html += ('' + reportedValue + ''); break; } } html += '
'; return html; } renderStatusHtml = (partStatus: string, lateStatus: string, complianceStatus: string, i: number) => { var html = ''; html += (complianceStatus == "scheduled" ? 'schedule' : ''); html += (complianceStatus == "not-complied" ? 'disabled_by_default' : ''); html += (complianceStatus == "partially-complied" ? 'rule' : ''); html += (complianceStatus == "complied" ? 'sweep' : ''); html += (complianceStatus == "complied-with-gaps" ? 'rule' : ''); html += (complianceStatus == "reported-non-compliance" ? 'rule' : ''); html += (partStatus == "not-started" ? 'schedule' : ''); html += (partStatus == "pending-approval" ? 'pending' : ''); html += (partStatus == "rejected" ? 'block' : ''); html += (partStatus == "approved" ? 'check_circle' : ''); html += (lateStatus == "in-time" ? 'schedule' : ''); html += (lateStatus == "past-due-date" ? 'timer' : ''); html += (lateStatus == "late-reported" ? 'report_off' : ''); html += (lateStatus == "late-approved" ? 'remove_done' : ''); html += (lateStatus == "late-executed" ? 'running_with_errors' : ''); html.trim().replace(/ \s*$/, ""); return html; } renderStatusString = (partStatus: string, lateStatus: string, complianceStatus: string) => { var str: string = ''; str += (partStatus == "not-started" ? 'not-started ' : ''); str += (partStatus == "pending-approval" ? 'pending-approval ' : ''); str += (partStatus == "rejected" ? 'rejected ' : ''); str += (partStatus == "approved" ? 'approved ' : ''); str += (lateStatus == "in-time" ? 'in-time ' : ''); str += (lateStatus == "past-due-date" ? 'past-due-date ' : ''); str += (lateStatus == "late-reported" ? 'late-reported ' : ''); str += (lateStatus == "late-approved" ? 'late-approved ' : ''); str += (lateStatus == "late-executed" ? 'late-executed ' : ''); str += (complianceStatus == "scheduled" ? 'scheduled ' : ''); str += (complianceStatus == "complied" ? 'complied ' : ''); str += (complianceStatus == "not-complied" ? 'not-complied ' : ''); str += (complianceStatus == "partially-complied" ? 'partially-complied ' : ''); return str.trim(); } getGraphParam = (event: any) => { let graphParam = ''; //console.log('getGraphParam', this.flowGraph, event); if (Array.isArray(event[this.flowGraph])) { graphParam = event[this.flowGraph].toString().replace(/ *\([^)]*\) */g, "").replace(/,/g, ' • '); } else { // console.log('event[this.flowGraph]', event[this.flowGraph], event, this.flowGraph) graphParam = (event[this.flowGraph] ?? "").replace(/ *\([^)]*\) */g, "").replace(/,/g, ' • '); } return graphParam; } renderCalendarAnnotations = (event: any, mmdd: string, j: number, fromDrilldown: boolean) => { var html = ''; console.log('rendering Annotations', event.module, event.completenessstatus) html += '
' // if(event.concise == null && event.approvers != null){ let reporterStr = event.concise == null ? this.getReporterStringFromEvent(event) : ""; let approverStr = event.concise == null ? this.getApproverStringFromEvent(event) : ""; let graphParam = this.getGraphParam(event); // console.log("graphParam", graphParam.split(';')[0]); const configHome = Util.getProjectConfigHome(); const configFlag = configHome.features != null && configHome.features.indexOf("understood") >= 0 html += '
' + graphParam.split(';')[0] + '
' + reporterStr + approverStr + (((event.module == "compliances" || event.module == null) && event.concise == null && ((event.reportformat == null || event.reportformat.length == 0) && (event.customreporting == null) && (event.reportedlocationsflag != true)) && !fromDrilldown) ? ('') : '') + (((event.module == "compliances" || event.module == null) && event.concise == null && configFlag) ? (event.review ? ('') : ('')) : '') + ((event.module == "rcmresource" && event.completenessstatus == "approved") ? '' : '') + '
'; // } return html; } //(firstDay, endDay, 1, lastDay, true, 0, (firstDate.getMonth()), period, firstDate,"From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), showBackgroundButton) renderEvents = (_firstDay: any, _endDay: any, iInit: number, iLast: number, showGraph: boolean, index: number, month: number, period: string, firstDate: any = null, parametersTitle: string, showBackgroundButton: boolean, fromDrilldown: boolean = false) => { var total = 0, notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0, inTime = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0, lateReported = 0, scheduled = 0, partiallyComplied = 0, notComplied = 0, complied = 0, compliedWithGaps = 0, reportedNonCompliance = 0, active = 0, aboutToExpire = 0, expired = 0, terminated = 0; var html = ''; this.selectedItemIds = []; this.selectedItems = []; this.selectedStatus = ""; var csvCols = "", htmlCols = "", htmlSummaryCols = ""; var csvValues = "", htmlValues = "", htmlSummaryValues = ""; var slice = 2; this.eventsInWindow = []; var lastDay = iLast; this.minRiskMitigated = 0; this.minRiskResidual = 0; this.maxRiskMitigated = 0; this.maxRiskResidual = 0; this.finRiskCurrency = ""; this.clearGraphData(); console.log('this.clearSelectedGraphParam(); 1', this.graphFilter); this.clearSelectedGraphParam(); this.clearSelectedLegend(); if (!fromDrilldown) { html += this.renderCalendarGraphs(showGraph, parametersTitle, showBackgroundButton); } html += this.renderCalendarContainerDivStart(index) html += `
Upload External reporting file (.xlsx only)
` html += this.renderCalendarEventSummary(); if (!fromDrilldown) { if (this.selectedFeatures.indexOf('contracts') >= 0) { csvCols += 'Id,ReferenceNo.,Type,Country,Entity,Location,Party1,Party2,Party3,Reporter,Approver,Functionhead,DueDate,Status,ReportParameter' htmlCols += 'IdReference No.TypeCountryEntityLocationParty 1Party 2Party 3DueDateStatusReportParameter' } else if (this.selectedFeatures.indexOf('licenses') >= 0) { csvCols += 'Id,ReferenceNo.,Type,Country,Entity,Location,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter' htmlCols += 'IdReference No.TypeCountryEntityLocationStateJurisdictionCategorySubcategoryStatuteObligationTypeRiskSeverityRiskAreasFrequencySubFrequencyDueDateStatusReportParameter' } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { csvCols += 'Id,Name,Url,Country,Entity,Location,Reporter,Approver,Functionhead,LastCheckedDate,DueDate,Terminated,Status,ReportParameter' htmlCols += 'IdNameUrlCountryEntityLocationLastCheckedDateDueDateTerminatedStatusReportParameter' } else { csvCols += 'Id,Country,Entity,Location,Function,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,Reference,Applicability,ObligationType,ObligationTitle,Obligation,Firstlineofdefence,Secondlineofdefence,Thirdlineofdefence,Internalcontrols,Penalty,Form,AdditionalUrl,Definition,Authority,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter' htmlCols += 'IdCountryStateJurisdictionCategorySubcategoryStatuteReferenceApplicabilityObligationTypeObligationTitleObligationFirstlineofdefenceSecondlineofdefenceThirdlineofdefenceInternalControlsPenaltyFormAdditional URLDefinitionAuthorityRiskSeverityRiskAreasFrequencySubFrequencyDueDateStatusReportParameter' } if (this.selectedFeatures.indexOf('contracts') >= 0) { htmlSummaryCols += 'IdReference No.StatusDocuments' } else if (this.selectedFeatures.indexOf('licenses') >= 0) { htmlSummaryCols += 'IdReference No.StatusDocuments' } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { htmlSummaryCols += 'IdNameStatusUrl' } else { htmlSummaryCols += 'IdObligationTitleStatusDocuments' } } let tempMinRiskMitigatedLocal = 0; let tempMinRiskResidualLocal = 0; let tempMaxRiskMitigatedLocal = 0; let tempMaxRiskResidualLocal = 0; let tempMinRiskMitigatedGlobal = 0; let tempMinRiskResidualGlobal = 0; let tempMaxRiskMitigatedGlobal = 0; let tempMaxRiskResidualGlobal = 0; this.finRiskCurrency = "" let flagGlobal = false; for (var i = iInit; i <= iLast; i++) { let mmdd: string = ""; if (firstDate == null) { mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2); } else { const currDate = new Date(firstDate.getTime()); currDate.setDate(firstDate.getDate() + (i)); mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2); } //console.log('mmdd', mmdd); console.log('mmddevent', mmdd, this.events[mmdd], firstDate); var hide; if (firstDate == null) { hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, null); } else { const currDate = new Date(firstDate.getTime()); currDate.setDate(firstDate.getDate() + (i - 1)); hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, currDate); } if (this.events[mmdd] != null) { html += this.renderCalendarRowDivStart(i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]); for (var j = 0; j < (this.events[mmdd] as Array).length; j++) { total++; this.events[mmdd][j]['mmdd'] = mmdd this.eventsInWindow.push(this.events[mmdd][j]); var partStatus = ""; var lateStatus = ""; var complianceStatus = ""; var bgStatus = "event-status-" // const tempEvents1 = JSON.parse(JSON.stringify(this.events)); // //console.log('eventlog1', tempEvents1['06/30'][7].comments, mmdd, j); partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(this.events[mmdd][j]))); this.events[mmdd][j].completenessstatus = partStatus; lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(this.events[mmdd][j])), partStatus); complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(this.events[mmdd][j])).percentage, JSON.parse(JSON.stringify(this.events[mmdd][j]))); console.log("agreement partStatus", partStatus, lateStatus, complianceStatus); if (this.flowGraph == this.FLOW_GRAPH_TIMELINESS) { bgStatus += lateStatus } else if (this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { bgStatus += complianceStatus } else { bgStatus += partStatus } // const tempEvents2 = JSON.parse(JSON.stringify(this.events)); // //console.log('eventlog2', tempEvents2['06/30'][7].comments, mmdd, j); if (this.finRiskCurrency == "") { this.finRiskCurrency = this.events[mmdd][j]['localcurrency'] ?? "" } if (this.finRiskCurrency != this.events[mmdd][j]['localcurrency'] && this.finRiskCurrency == "") { this.finRiskCurrency = this.events[mmdd][j]['globalcurrency'] ?? "" flagGlobal = true } let minLocal = parseInt(this.events[mmdd][j]['minlocal'] == null || this.events[mmdd][j]['minlocal'] == "" ? "0" : this.events[mmdd][j]['minlocal']) let maxLocal = parseInt(this.events[mmdd][j]['maxlocal'] == null || this.events[mmdd][j]['maxlocal'] == "" ? "0" : this.events[mmdd][j]['maxlocal']) let minGlobal = parseInt(this.events[mmdd][j]['minglobal'] == null || this.events[mmdd][j]['minglobal'] == "" ? "0" : this.events[mmdd][j]['minglobal']) let maxGlobal = parseInt(this.events[mmdd][j]['maxglobal'] == null || this.events[mmdd][j]['maxglobal'] == "" ? "0" : this.events[mmdd][j]['maxglobal']) if (partStatus == "approved") { tempMinRiskMitigatedLocal = tempMinRiskMitigatedLocal + minLocal tempMaxRiskMitigatedLocal = tempMaxRiskMitigatedLocal + maxLocal tempMinRiskMitigatedGlobal = tempMinRiskMitigatedGlobal + minGlobal tempMaxRiskMitigatedGlobal = tempMaxRiskMitigatedGlobal + maxGlobal } else { tempMinRiskResidualLocal = tempMinRiskResidualLocal + minLocal tempMaxRiskResidualLocal = tempMaxRiskResidualLocal + maxLocal tempMinRiskResidualGlobal = tempMinRiskResidualGlobal + minGlobal tempMaxRiskResidualGlobal = tempMaxRiskResidualGlobal + maxGlobal } notStarted = notStarted + (partStatus == "not-started" ? 1 : 0); pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0); rejected = rejected + (partStatus == "rejected" ? 1 : 0); approved = approved + (partStatus == "approved" ? 1 : 0); inTime = inTime + (lateStatus == "in-time" ? 1 : 0); pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0); lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0); lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0); lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0); scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0); partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0); notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0); complied = complied + (complianceStatus == "complied" ? 1 : 0); compliedWithGaps = compliedWithGaps + (complianceStatus == "complied-with-gaps" ? 1 : 0); reportedNonCompliance = reportedNonCompliance + (complianceStatus == "reported-non-compliance" ? 1 : 0); active = active + (complianceStatus == "active" ? 1 : 0); aboutToExpire = aboutToExpire + (complianceStatus == "about-to-expire" ? 1 : 0); expired = expired + (complianceStatus == "expired" ? 1 : 0); terminated = terminated + (complianceStatus == "terminated" ? 1 : 0); this.events[mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus; this.events[mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus; if (this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] != null) { this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE + "obj"] = this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE]; } this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus; this.updateStats(this.events[mmdd][j], partStatus, lateStatus, complianceStatus); if (this.events[mmdd][j]["documents"] != null && !fromDrilldown) { if (this.selectedFeatures.indexOf('contracts') >= 0) { //Id,ReferenceNo.,Type,Country,Entity,Location,Party1,Party2,Party3,Reporter,Approver,Functionhead,DueDate,Status,ReportParameter csvValues += ('"' + (this.events[mmdd][j]["id"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["contracttypename"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["party1"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["party2"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["party3"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",')); csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]) + '"\n')); //Id,RefNo,Type,Country,Entity,Location,Party1,Party2,Party3,DueDate,Status,ReportParameter htmlValues += ('' + this.events[mmdd][j]["id"] + '' + '' + this.events[mmdd][j]["obligationtitle"] + '' + '' + this.events[mmdd][j]["contracttypename"] + '' + '' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + this.events[mmdd][j]["party1"] + '' + '' + this.events[mmdd][j]["party2"] + '' + '' + this.events[mmdd][j]["party3"] + '' + '' + this.events[mmdd][j]["duedate"] + '' + '' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '' + '' + this.getGraphParam(this.events[mmdd][j]) + '' + ''); } else if (this.selectedFeatures.indexOf('licenses') >= 0) { //Id,ReferenceNo.,Type,Country,Entity,Location,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter csvValues += ('"' + (this.events[mmdd][j]["id"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["licensetypename"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.statute?.state ?? "") + '",')); csvValues += ('"' + (this.events[mmdd][j]["jurisdiction"] + '",')); csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.complianceobj?.category ?? "") + '",')); csvValues += ('"' + (this.events[mmdd][j]["subcategory"] + '",')); csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.statute?.name ?? "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtype"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["risk"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["riskarea"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["frequency"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (((this.events?.[mmdd]?.[j]?.complianceobj?.subfrequency ?? "") + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",')); csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]) + '"\n')); //Id,ReferenceNo.,Type,Country,Entity,Location,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter htmlValues += ('' + this.events[mmdd][j]["id"] + '' + '' + this.events[mmdd][j]["obligationtitle"] + '' + '' + this.events[mmdd][j]["licensetypename"] + '' + '' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events?.[mmdd]?.[j]?.statute?.state ?? "") + '' + '' + this.events[mmdd][j]["jurisdiction"] + '' + '' + (this.events?.[mmdd]?.[j]?.complianceobj?.category ?? "") + '' + '' + this.events[mmdd][j]["subcategory"] + '' + '' + (this.events?.[mmdd]?.[j]?.statute?.name ?? "") + '' + '' + this.events[mmdd][j]["obligationtype"] + '' + '' + this.events[mmdd][j]["risk"] + '' + '' + this.events[mmdd][j]["riskarea"] + '' + '' + this.events[mmdd][j]["frequency"] + '' + '' + ((this.events?.[mmdd]?.[j]?.complianceobj?.subfrequency ?? "") + "").replace(/"/g, "") + '' + '' + this.events[mmdd][j]["duedate"] + '' + '' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '' + '' + this.getGraphParam(this.events[mmdd][j]) + '' + ''); } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { //Id,Name,Url,Country,Entity,Location,Reporter,Approver,Functionhead,LastCheckedDate,DueDate,Terminated,Status,ReportParameter csvValues += ('"' + (this.events[mmdd][j]["id"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["url"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (this.events[mmdd][j]["lastcheckeddate"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["terminated"] ? "Yes" : "No").replace(/"/g, "") + '",')); csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",')); csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]) + '"\n')); //Id,Name,Url,Country,Entity,Location,LastCheckedDate,DueDate,Terminated,Status,ReportParameter htmlValues += ('' + this.events[mmdd][j]["id"] + '' + '' + this.events[mmdd][j]["obligationtitle"] + '' + '' + this.events[mmdd][j]["url"] + '' + '' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '' + '' + this.events[mmdd][j]["lastcheckeddate"] + '' + '' + this.events[mmdd][j]["duedate"] + '' + '' + (this.events[mmdd][j]["terminated"] ? "Yes" : "No") + '' + '' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '' + '' + this.getGraphParam(this.events[mmdd][j]) + '' + ''); } else { //Id,Country,Entity,Location,Function,Reporter,Approver,Functionhead,State csvValues += ('"' + (this.events[mmdd][j]["id"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["functions"] ?? [])[0] ?? "").split(';')[0] + "").replace(/\((.*?)\)/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (this.events[mmdd][j]["state"] + '",')); csvValues += ('"' + (this.events[mmdd][j]["jurisdiction"] + '",')); csvValues += ('"' + (this.events[mmdd][j]["category"] + '",')); csvValues += ('"' + (this.events[mmdd][j]["subcategory"] + '",')); csvValues += ('"' + (this.events[mmdd][j]["statute"] + '",')); csvValues += ('"' + ((this.events[mmdd][j]["reference"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["applicability"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtype"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["obligation"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["firstlineofdefence"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["secondlineofdefence"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["thirdlineofdefence"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["internalcontrols"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["penalty"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["form"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["additionalurls"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["definition"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["authority"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["risk"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["riskarea"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["frequency"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["subfrequency"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",')); csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",')); csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]) + '"\n')); // csvValues += (period + ',' // + this.renderStatusString(partStatus, lateStatus, complianceStatus) + ',' // + this.events[mmdd][j]["id"] + ',' // + this.events[mmdd][j]["obligationtitle"] + ',' // + this.events[mmdd][j]["obligation"] + ',' // + this.events[mmdd][j]["duedate"] // + '\n'); htmlValues += ('' + this.events[mmdd][j]["id"] + '' + '' + this.events[mmdd][j]["country"] + '' + '' + this.events[mmdd][j]["state"] + '' + '' + this.events[mmdd][j]["jurisdiction"] + '' + '' + this.events[mmdd][j]["category"] + '' + '' + this.events[mmdd][j]["subcategory"] + '' + '' + this.events[mmdd][j]["statute"] + '' + '' + this.events[mmdd][j]["reference"] + '' + '' + this.events[mmdd][j]["applicability"] + '' + '' + this.events[mmdd][j]["obligationtype"] + '' + '' + this.events[mmdd][j]["obligationtitle"] + '' + '' + this.events[mmdd][j]["obligation"] + '' + '' + this.events[mmdd][j]["firstlineofdefence"] + '' + '' + this.events[mmdd][j]["secondlineofdefence"] + '' + '' + this.events[mmdd][j]["thirdlineofdefence"] + '' + '' + this.events[mmdd][j]["internalcontrols"] + '' + '' + this.events[mmdd][j]["penalty"] + '' + '' + this.events[mmdd][j]["form"] + '' + '' + this.events[mmdd][j]["additionalurls"] + '' + '' + this.events[mmdd][j]["definition"] + '' + '' + this.events[mmdd][j]["authority"] + '' + '' + this.events[mmdd][j]["risk"] + '' + '' + this.events[mmdd][j]["riskarea"] + '' + '' + this.events[mmdd][j]["frequency"] + '' + '' + this.events[mmdd][j]["subfrequency"] + '' + '' + this.events[mmdd][j]["duedate"] + '' + '' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '' + '' + this.getGraphParam(this.events[mmdd][j]) + '' + ''); } if (this.selectedFeatures.indexOf('contracts') >= 0) { htmlSummaryValues += ('' + '' + '' + ''); for (let document of this.events[mmdd][j].contractdocuments ?? []) { htmlSummaryValues += `
` } htmlSummaryValues += '' } else if (this.selectedFeatures.indexOf('licenses') >= 0) { htmlSummaryValues += ('' + '' + '' + ''); for (let document of this.events[mmdd][j].licensedocuments ?? []) { htmlSummaryValues += `
` } htmlSummaryValues += '' } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { htmlSummaryValues += ('' + '' + '' + '') } else { htmlSummaryValues += ('' + '' // + '' + '' + ''); for (let document of this.events[mmdd][j].documents) { htmlSummaryValues += `
` } // htmlSummaryValues += this.renderCalendarAnnotations(this.events[mmdd][j]); htmlSummaryValues += '' } } html += this.renderCalendarRowDivItemDivStart(mmdd, this.events[mmdd][j], j, partStatus, bgStatus, fromDrilldown); // if (this.events[mmdd][j]["countryname"] != null) { if (this.events[mmdd][j]["concise"] == null) { html += this.renderCalendarRowDivItemDivTableHead(this.events[mmdd][j], partStatus); html += this.renderCalendarRowDivItemDivTableBody(this.events[mmdd][j], partStatus, lateStatus, complianceStatus, mmdd, i, j); } html += this.renderCalendarAnnotations(this.events[mmdd][j], mmdd, j, fromDrilldown); html += '
' html += this.renderCalendarRowDivItemDivEnd(); } html += this.renderCalendarRowDivEnd(); } else { const result: any = this.renderCalendarBlankRowDiv(hide, slice, i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]); //console.log('result', result); html += result.html; slice = result.slice; } } html += this.renderCalendarContainerDivEnd(); if (flagGlobal) { this.minRiskMitigated = tempMinRiskMitigatedGlobal this.maxRiskMitigated = tempMaxRiskMitigatedGlobal this.minRiskResidual = tempMinRiskResidualGlobal this.maxRiskResidual = tempMaxRiskResidualGlobal } else { this.minRiskMitigated = tempMinRiskMitigatedLocal this.maxRiskMitigated = tempMaxRiskMitigatedLocal this.minRiskResidual = tempMinRiskResidualLocal this.maxRiskResidual = tempMaxRiskResidualLocal } let showFinRisk = false if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('notices') && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0 && this.finRiskCurrency != "" && (this.minRiskResidual > 0 || this.minRiskMitigated > 0 || this.maxRiskResidual > 0 || this.maxRiskMitigated > 0)) { showFinRisk = true } //console.log('final risk severities', this.riskSeverityData); //this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear(); this.period = period; this.csvDataCompliances = csvCols + "\n" + csvValues; this.htmlDataCompliances = '' + htmlCols + htmlValues + '
'; this.htmlDataSummary = '' + htmlSummaryCols + htmlSummaryValues + '
'; //console.log('renderevents htmlcols', this.htmlDataCompliances); //console.log('progress', this.period, total, notStarted, approved) html = html.replace("DASHBOARD_TOTAL", total + ""); html = html.replace("DASHBOARD_SUSPENSE_CLASS", (this.suspenseCount > 0) ? "" : " hide"); html = html.replace("DASHBOARD_SUSPENSE", this.suspenseCount + ""); html = html.replace("DASHBOARD_NOT_STARTED", notStarted + ""); html = html.replace("DASHBOARD_APPROVED", approved + ""); html = html.replace("DASHBOARD_PENDING_APPROVAL", pendingApproval + ""); html = html.replace("DASHBOARD_REJECTED", rejected + ""); html = html.replace("DASHBOARD_IN_TIME", inTime + ""); html = html.replace("DASHBOARD_PAST_DUE_DATE", pastDueDate + ""); html = html.replace("DASHBOARD_LATE_REPORTED", lateReported + "") html = html.replace("DASHBOARD_LATE_EXECUTED", lateExecuted + ""); html = html.replace("DASHBOARD_LATE_APPROVED", lateApproved + ""); html = html.replace("DASHBOARD_SCHEDULED", scheduled + ""); html = html.replace("DASHBOARD_NOT_COMPLIED", notComplied + ""); html = html.replace("DASHBOARD_PARTIALLY_COMPLIED", partiallyComplied + ""); html = html.replace("DASHBOARD_COMPLIED", complied + ""); html = html.replace("DASHBOARD_COMPLIED_WITH_GAPS", compliedWithGaps + ""); html = html.replace("DASHBOARD_REPORTED_NON_COMPLIANCE", reportedNonCompliance + ""); html = html.replace("DASHBOARD_ACTIVE", active + ""); html = html.replace("DASHBOARD_ABOUT_TO_EXPIRE", aboutToExpire + ""); html = html.replace("DASHBOARD_EXPIRED", expired + ""); html = html.replace("DASHBOARD_TERMINATED", terminated + ""); console.log('financial risk values', this.minRiskResidual, this.maxRiskResidual, this.minRiskMitigated, this.maxRiskMitigated); html = html.replace("FIN_RISK_CURRENCY", this.finRiskCurrency); html = html.replace("FIN_RISK_RESIDUAL_MIN", this.formatIndianNumber(this.minRiskResidual)); html = html.replace("FIN_RISK_RESIDUAL_MAX", this.formatIndianNumber(this.maxRiskResidual)); html = html.replace("FIN_RISK_MITIGATED_MIN", this.formatIndianNumber(this.minRiskMitigated)); html = html.replace("FIN_RISK_MITIGATED_MAX", this.formatIndianNumber(this.maxRiskMitigated)); html = html.replace("gone FIN_RISK_HIDE_CLASS", showFinRisk ? "d-flex" : "gone"); if (this.selectedFeatures.indexOf("contracts") >= 0) { this.csvDataStats = 'Period,Total,Not Started,Approved,Pending Approval,Rejected,Past Due Date,Late Reported,Late Executed,Late Approved,Active,About To Expire,Expired,Terminated\n'; this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + pendingApproval + "," + rejected + "," + pastDueDate + "," + lateReported + "," + lateExecuted + "," + lateApproved + "," + active + "," + aboutToExpire + "," + expired + "," + terminated; } else { this.csvDataStats = 'Period,Total,Not Started,Approved,Pending Approval,Rejected,Past Due Date,Late Reported,Late Executed,Late Approved,Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance\n'; this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + pendingApproval + "," + rejected + "," + pastDueDate + "," + lateReported + "," + lateExecuted + "," + lateApproved + "," + scheduled + "," + notComplied + "," + partiallyComplied + "," + complied + "," + compliedWithGaps + "," + reportedNonCompliance; } this.htmlDataStats = 'Completeness

'; this.htmlDataStats += '
TotalNot StartedApprovedPending ApprovalRejected
' + total + '' + notStarted + '' + approved + '' + pendingApproval + '' + rejected + '
' this.htmlDataStats += '

Timeliness

'; this.htmlDataStats += '
TotalIn TimePast Due DateLate ReportedLate ExecutedLate Approved
' + total + '' + (total - (pastDueDate + lateApproved + lateExecuted)) + '' + pastDueDate + '' + lateReported + '' + lateExecuted + '' + lateApproved + '
' if (this.selectedFeatures.indexOf("contracts") >= 0) { this.htmlDataStats += '

Compliance

'; this.htmlDataStats += '
TotalActiveAbout To ExpireExpiredTerminated
' + total + '' + active + '' + aboutToExpire + '' + expired + '' + terminated + '
' } else { this.htmlDataStats += '

Compliance

'; this.htmlDataStats += '
TotalScheduledNot CompliedPartially CompliedCompliedComplied With GapsReported Non Compliance
' + total + '' + scheduled + '' + notComplied + '' + partiallyComplied + '' + complied + '' + compliedWithGaps + '' + reportedNonCompliance + '
' } return html; } renderStatistics = (_firstDay: any, _endDay: any, iInit: number, iLast: number, showGraph: boolean, index: number, month: number, period: string, firstDate: any = null, parametersTitle: string) => { var total = 0, notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0; let subfiltersTotal: any = {} let subfiltersNotStarted: any = {} let subfiltersPendingApproval: any = {} let subfiltersRejected: any = {} let subfiltersApproved: any = {} let finRiskCurrency = ""; let finRiskMitigatedMin = 0; let finRiskMitigatedMax = 0; let finRiskResidualMin = 0; let finRiskResidualMax = 0; var html = ''; // var lastDay = iLast; // var slice = 2; this.clearGraphData(); console.log('this.clearSelectedGraphParam(); 2'); this.clearSelectedGraphParam(); this.clearSelectedLegend(); html += this.renderCalendarStatisticsGraphs(showGraph, parametersTitle); html += this.renderCalendarContainerDivStart(index) html += this.renderCalendarEventSummaryViewer(); let filtersTableHtml = "" if (Object.keys(this.statisticsFiltersData).length > 0) { filtersTableHtml += this.renderStatisticsFiltersTableStart() } console.log('statistics', firstDate, iInit, iLast) for (var i = iInit; i <= iLast; i++) { let mmdd: string = ""; if (firstDate == null) { mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2); } else { const currDate = new Date(firstDate.getTime()); currDate.setDate(firstDate.getDate() + (i)); mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2); } console.log('mmddevent', mmdd, this.statistics[mmdd], firstDate); // var hide; // if(firstDate == null) { // hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, null); // } else { // const currDate = new Date(firstDate.getTime()); // currDate.setDate(firstDate.getDate() + (i - 1)); // hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, currDate); // } if (this.statistics[mmdd] != null) { // html += this.renderCalendarRowDivStart(i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]); total += this.statistics[mmdd].count; console.log('mmdd', mmdd, this.statistics[mmdd].count, total); notStarted += this.statistics[mmdd]["not-started"] ?? 0; pendingApproval += this.statistics[mmdd]["pending-approval"] ?? 0; rejected += this.statistics[mmdd]["rejected"] ?? 0; approved += this.statistics[mmdd]["approved"] ?? 0; finRiskCurrency = this.statistics[mmdd]['currency'] ?? finRiskCurrency finRiskMitigatedMax = finRiskMitigatedMax + (this.statistics[mmdd]['mitigatedmax'] ?? 0) finRiskMitigatedMin = finRiskMitigatedMin + (this.statistics[mmdd]['mitigatedmin'] ?? 0) finRiskResidualMax = finRiskResidualMax + (this.statistics[mmdd]['residualmax'] ?? 0) finRiskResidualMin = finRiskResidualMin + (this.statistics[mmdd]['residualmin'] ?? 0) for (let subfilter of Object.keys(this.statistics['subfilters'])) { if (subfiltersTotal[subfilter] == null) { subfiltersTotal[subfilter] = 0 } if (subfiltersNotStarted[subfilter] == null) { subfiltersNotStarted[subfilter] = 0 } if (subfiltersPendingApproval[subfilter] == null) { subfiltersPendingApproval[subfilter] = 0 } if (subfiltersRejected[subfilter] == null) { subfiltersRejected[subfilter] = 0 } if (subfiltersApproved[subfilter] == null) { subfiltersApproved[subfilter] = 0 } if (this.statistics['subfilters'][subfilter][mmdd] != null) { subfiltersTotal[subfilter] += (this.statistics['subfilters'][subfilter][mmdd].count) subfiltersNotStarted[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['not-started'] ?? 0) subfiltersPendingApproval[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['pending-approval'] ?? 0) subfiltersRejected[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['rejected'] ?? 0) subfiltersApproved[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['approved'] ?? 0) } } } } if (Object.keys(this.statisticsFiltersData).length > 0) { let filtercriteria = Object.keys(this.statisticsFiltersData)[0] let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[filtercriteria]) finRiskCurrency = ""; finRiskMitigatedMin = 0; finRiskMitigatedMax = 0; finRiskResidualMin = 0; finRiskResidualMax = 0; for (let [filterindex, filterval] of sortedFilters.entries()) { let filtername = filterval.split(';')[0] let filterid = filterval.split(';')[1] let filterTotal = 0, filterNotStarted = 0, filterPendingApproval = 0, filterRejected = 0, filterApproved = 0; let lastActive = ""; let lastAction = ""; let subfiltersFilterTotal: any = {} let subfiltersFilterNotStarted: any = {} let subfiltersFilterPendingApproval: any = {} let subfiltersFilterRejected: any = {} let subfiltersFilterApproved: any = {} for (var i = iInit; i <= iLast; i++) { let mmdd: string = ""; if (firstDate == null) { mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2); } else { const currDate = new Date(firstDate.getTime()); currDate.setDate(firstDate.getDate() + (i)); mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2); } console.log('mmddFilters', mmdd) if (this.statisticsFiltersData[filtercriteria][filterid] != null) { if (this.statisticsFiltersData[filtercriteria][filterid]['lasttime'] != null) { lastAction = this.statisticsFiltersData[filtercriteria][filterid]['lasttime']['lastaction'] ?? "" lastActive = this.statisticsFiltersData[filtercriteria][filterid]['lasttime']['lastactive'] ?? "" } if (this.statisticsFiltersData[filtercriteria][filterid][mmdd] != null) { filterTotal += this.statisticsFiltersData[filtercriteria][filterid][mmdd].count filterNotStarted += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['not-started'] ?? 0 filterPendingApproval += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['pending-approval'] ?? 0 filterRejected += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['rejected'] ?? 0 filterApproved += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['approved'] ?? 0 finRiskCurrency = this.statisticsFiltersData[filtercriteria][filterid][mmdd]['currency'] ?? finRiskCurrency finRiskMitigatedMax = finRiskMitigatedMax + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['mitigatedmax'] ?? 0) finRiskMitigatedMin = finRiskMitigatedMin + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['mitigatedmin'] ?? 0) finRiskResidualMax = finRiskResidualMax + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['residualmax'] ?? 0) finRiskResidualMin = finRiskResidualMin + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['residualmin'] ?? 0) for (let subfilter of Object.keys(this.statisticsFiltersData[filtercriteria][filterid]['subfilters'])) { if (subfiltersFilterTotal[subfilter] == null) { subfiltersFilterTotal[subfilter] = 0 } if (subfiltersFilterNotStarted[subfilter] == null) { subfiltersFilterNotStarted[subfilter] = 0 } if (subfiltersFilterPendingApproval[subfilter] == null) { subfiltersFilterPendingApproval[subfilter] = 0 } if (subfiltersFilterRejected[subfilter] == null) { subfiltersFilterRejected[subfilter] = 0 } if (subfiltersFilterApproved[subfilter] == null) { subfiltersFilterApproved[subfilter] = 0 } if (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd] != null) { subfiltersFilterTotal[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd].count) console.log('subfilterTotal', subfiltersFilterTotal); subfiltersFilterNotStarted[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['not-started'] ?? 0) subfiltersFilterPendingApproval[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['pending-approval'] ?? 0) subfiltersFilterRejected[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['rejected'] ?? 0) subfiltersFilterApproved[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['approved'] ?? 0) } } } } } filtersTableHtml += this.renderStatisticsFiltersTableRow(filterindex, lastAction != "" || lastActive != "", filtercriteria == "location") if (filterindex % 2 == 0) { filtersTableHtml = filtersTableHtml.replace(/TD_BODY_CLASS/g, "td-light"); } else { filtersTableHtml = filtersTableHtml.replace(/TD_BODY_CLASS/g, "td-dark"); } filtersTableHtml = filtersTableHtml.replace("FILTER_CRITERIA_NAME", filtercriteria + ""); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_FILTER_NAME", (filtername + "").replace(/\([^)]*\)/g, "")); let filterTotalHtml = filterTotal + "" let filterNotStartedHtml = filterNotStarted + Util.percentageString(filterNotStarted, filterTotal) let filterPendingApprovalHtml = filterPendingApproval + Util.percentageString(filterPendingApproval, filterTotal) let filterRejectedHtml = filterRejected + Util.percentageString(filterRejected, filterTotal) let filterApprovedHtml = filterApproved + Util.percentageString(filterApproved, filterTotal) for (let subfilter of Object.keys(this.statisticsFiltersData[filtercriteria][filterid]['subfilters'])) { filterTotalHtml += `
${subfilter}: ${subfiltersFilterTotal[subfilter]}${Util.percentageString(subfiltersFilterTotal[subfilter], filterTotal)}` filterNotStartedHtml += `
${subfilter}: ${subfiltersFilterNotStarted[subfilter]}${Util.percentageString(subfiltersFilterNotStarted[subfilter], filterNotStarted)}` filterPendingApprovalHtml += `
${subfilter}: ${subfiltersFilterPendingApproval[subfilter]}${Util.percentageString(subfiltersFilterPendingApproval[subfilter], filterPendingApproval)}` filterRejectedHtml += `
${subfilter}: ${subfiltersFilterRejected[subfilter]}${Util.percentageString(subfiltersFilterRejected[subfilter], filterRejected)}` filterApprovedHtml += `
${subfilter}: ${subfiltersFilterApproved[subfilter]}${Util.percentageString(subfiltersFilterApproved[subfilter], filterApproved)}` } console.log('subfilterstotal', subfiltersFilterTotal) filtersTableHtml = filtersTableHtml.replace("DASHBOARD_TOTAL", filterTotalHtml); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_NOT_STARTED", filterNotStartedHtml); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_APPROVED", filterApprovedHtml); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_PENDING_APPROVAL", filterPendingApprovalHtml); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_REJECTED", filterRejectedHtml); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_LAST_ACTION", lastAction); filtersTableHtml = filtersTableHtml.replace("DASHBOARD_LAST_ACTIVE", lastActive); } filtersTableHtml += this.renderStatisticsFiltersTableEnd() } html += filtersTableHtml html += this.renderCalendarContainerDivEnd(); //console.log('final risk severities', this.riskSeverityData); //this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear(); this.period = period; //console.log('renderevents htmlcols', this.htmlDataCompliances); console.log('progress', this.period, total, notStarted, approved, this.statistics) let totalHtml = "" let notStartedHtml = "" let pendingApprovalHtml = "" let rejectedHtml = "" let approvedHtml = "" for (let subfilter of Object.keys(this.statistics['subfilters'])) { totalHtml += `
${subfilter}: ${subfiltersTotal[subfilter]}${Util.percentageString(subfiltersTotal[subfilter], total)}` notStartedHtml += `
${subfilter}: ${subfiltersNotStarted[subfilter]}${Util.percentageString(subfiltersNotStarted[subfilter], notStarted)}` pendingApprovalHtml += `
${subfilter}: ${subfiltersPendingApproval[subfilter]}${Util.percentageString(subfiltersPendingApproval[subfilter], pendingApproval)}` rejectedHtml += `
${subfilter}: ${subfiltersRejected[subfilter]}${Util.percentageString(subfiltersRejected[subfilter], rejected)}` approvedHtml += `
${subfilter}: ${subfiltersApproved[subfilter]}${Util.percentageString(subfiltersApproved[subfilter], approved)}` } let showFinRisk = false if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('notices') && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0 && finRiskCurrency != "" && (finRiskResidualMin > 0 || finRiskMitigatedMin > 0 || finRiskResidualMax > 0 || finRiskMitigatedMax > 0)) { showFinRisk = true } html = html.replace("DASHBOARD_TOTAL", total + ""); html = html.replace("DASHBOARD_TOTAL_SUBFILTER", totalHtml.replace('
', '')); html = html.replace("DASHBOARD_NOT_STARTED", notStarted + ""); html = html.replace("DASHBOARD_NOT_STARTED_SUBFILTER", notStartedHtml.replace('
', '')); html = html.replace("DASHBOARD_APPROVED", approved + ""); html = html.replace("DASHBOARD_APPROVED_SUBFILTER", approvedHtml.replace('
', '')); html = html.replace("DASHBOARD_PENDING_APPROVAL", pendingApproval + ""); html = html.replace("DASHBOARD_PENDING_APPROVAL_SUBFILTER", pendingApprovalHtml.replace('
', '')); html = html.replace("DASHBOARD_REJECTED", rejected + ""); html = html.replace("DASHBOARD_REJECTED_SUBFILTER", rejectedHtml.replace('
', '')); html = html.replace("FIN_RISK_CURRENCY", finRiskCurrency); html = html.replace("FIN_RISK_RESIDUAL_MIN", this.formatIndianNumber(finRiskResidualMin)); html = html.replace("FIN_RISK_RESIDUAL_MAX", this.formatIndianNumber(finRiskResidualMax)); html = html.replace("FIN_RISK_MITIGATED_MIN", this.formatIndianNumber(finRiskMitigatedMin)); html = html.replace("FIN_RISK_MITIGATED_MAX", this.formatIndianNumber(finRiskMitigatedMax)); html = html.replace("gone FIN_RISK_HIDE_CLASS", showFinRisk ? "d-flex" : "gone"); this.htmlDataStats = 'Completeness

'; this.htmlDataStats += '
TotalNot StartedApprovedPending ApprovalRejected
' + total + totalHtml + '' + notStarted + notStartedHtml + '' + approved + approvedHtml + '' + pendingApproval + pendingApprovalHtml + '' + rejected + rejectedHtml + '
' if (Object.keys(this.statisticsFiltersData).length > 0) { this.htmlDataStats += '

Report

' this.htmlDataStats += filtersTableHtml } return html; } renderReporting = (event: any, mmddyyyy: any) => { let html = ''; let completeness = this.getCompletenessStatus(event); let docs = event['documents'] == null ? [] : event['documents']; let approved = event['approved'] == null ? false : event['approved']; let dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion']; let percentage = event['percentage'] == null ? '100' : event['percentage']; let makercheckers = event['makercheckers'] == null ? [] : event['makercheckers']; let docsOptional = event['docs'] == null ? [] : event['docs']; let uploadGuidance = event['uploadguidance'] ?? 0 this.reportedLocationsVals = (event['reportedlocations'] != null) ? (Util.isJSONParsable(event['reportedlocations']) ? JSON.parse(event['reportedlocations']) : [event['reportedlocations']]) : [''] console.log('reportedLocations found', this.reportedLocationsVals) console.log('rendering reporting', event, percentage, this.reportedLocationsVals) if (this.selectedItemIds.length > 0) { html += `

${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected

` } if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) { if (event.comments.length > 0) { html += '
'; html += '


Approve Compliance

'; html += '
'; html += '
'; html += '
' html += '' html += '' html += '
' if (this.myRole != this.TAB_FUNCTION_HEAD && docs.length > 0 && event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') { html += '
'; html += ''; html += ''; html += '
The analysis is running in the background. You can proceed further.
' html += '
'; } html += '
'; html += ''; html += ('
'); if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') { html += ''; html += '
'; html += '
'; html += '
'; html += ''; html += '
'; html += '
' html += '
'; html += '
'; html += ''; html += ''; html += '
' html += '
'; html += ''; html += ''; html += '
' if (this.reportedLocationsVals.length > 1) { let indexLocation = 1; while (indexLocation < this.reportedLocationsVals.length) { html += '
'; html += '
'; html += ''; html += ''; html += '
' html += '
'; html += ''; html += ''; html += '
' html += '
' indexLocation++ } } html += '
' html += '
' } html += '
' html += '
'; html += '
' html += ' Yes'; html += ' No'; html += '
' if (event['reportformat'] != null && event['reportformat'].length > 0) { html += '
' } else if (event['customreporting'] != null && event['customreporting'].length > 0) { html += '
' } html += '
'; html += '
'; html += '
'; } } if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { html += '
'; html += '


Report Compliance

'; html += '
'; var showSubmissionSection = true; var showGoogleFormLink = false; if (event['form'] != null && event['form'].length > 5) { if (event['form'].indexOf('docs.google.com/forms') >= 0) { showSubmissionSection = false; if (!approved) { showGoogleFormLink = true; } } } if (showGoogleFormLink) { html += ('
'); } if (showSubmissionSection) { html += '
'; html += '
' html += '' html += '' html += '
' html += '
'; html += ''; html += '' if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') { html += '
' for (let reportingSuggestion of this.reportingSuggestions) { html += `
${reportingSuggestion}
` } html += '' for (let reportingSuggestion of this.reportingSuggestionsNotApplicable) { html += `
${reportingSuggestion}
` } html += '
'; html += '
'; html += ''; html += '
'; html += '
'; html += '
'; html += ''; html += ''; html += '
' html += '
'; html += '
'; html += '
'; html += ''; html += ''; html += '
' html += '
'; html += ''; html += ''; html += '
' html += '
' if (this.reportedLocationsVals.length > 1) { let indexLocation = 1; while (indexLocation < this.reportedLocationsVals.length) { html += '
'; html += '
'; html += ''; html += ''; html += '
' html += '
'; html += ''; html += ''; html += '
' html += '
' indexLocation++ } } html += '
' html += '
' html += '
'; html += '
' html += '
For reporting full non-compliance, choose 0%. For reporting compliance with gaps, choose the appropriate % value.

' // if(docsOptional.length === 0) { html += ''; html += ''; if (uploadGuidance == 1) { html += '
help Get Help
' } else if (uploadGuidance != 0) { html += '
' html += '
Upload Guidance
' html += '') + '" minLength="150">'; html += '
' } html += '
Uploading supporting documents is highly recommended by FlaggGRC to ensure effective compliance monitoring.
' html += '
The analysis is running in the background. You can proceed further.
' } // } html += '
'; if (event['reportformat'] != null && event['reportformat'].length > 0) { html += '
' } else if (event['customreporting'] != null && event['customreporting'].length > 0) { html += '
' } html += '
'; if (makercheckers.length > 0) { html += '
check_small
 Auto-approve Enabled
'; if (completeness == "pending-approval" && this.enableDeleteLatestReport) { html += '
'; } } html += '
'; html += '
'; } } if (this.myRole == this.TAB_AUDITOR) { html += '
'; html += '


Audit Compliance

'; html += '
'; html += '
'; html += '
' html += '' html += '' html += '
' html += '
'; html += ''; html += '
'; if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') { html += ''; html += '
'; html += ''; html += '
'; html += '
For reporting full non-compliance, choose 0%. For reporting compliance with gaps, choose the appropriate % value.

' } html += '
' html += '
'; html += '
' html += ' Yes'; html += ' No'; html += '
' html += '
'; html += '
'; if (docs.length > 0) { html += ''; html += ''; html += '
The analysis is running in the background. You can proceed further.
' } html += '
'; html += '
'; } if (this.myRole == this.TAB_VIEWER) { html += '
'; html += '


View Compliance

'; html += '
'; html += '
'; html += '
'; html += '
' html += '
'; html += '
' html += ' Yes'; html += ' No'; html += '
' html += '
'; html += '
'; if (docs.length === 0) { html += ''; html += ''; html += '
The analysis is running in the background. You can proceed further.
' } html += '
'; html += '
'; } return html; } renderListReporting = (listReportingContainer: HTMLDivElement, event: any, mmddyyyy: any, eventsContainer: HTMLDivElement) => { console.log('listreporting event', event, this.graphFilter); let html = '' let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let reportformatName: string = ''; if (event['reportformat'] != null) { reportformatName = (event['reportformat'][0] ?? "").trim().replace('&', '&'); } let docs = event['documents'] == null ? [] : event['documents']; event.approved = event['approved'] == null ? false : event['approved']; event.dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion']; event.makercheckers = event['makercheckers'] == null ? [] : event['makercheckers']; event.docsOptional = event['docs'] == null ? [] : event['docs']; html = this.renderReporting(event, mmddyyyy); console.log('reporting html', html); let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2]; let emailcontent = `
Compliance ID${event.id}
Country${event.countryname.replace(/ *\([^)]*\) */g, "")}
Entity${event.entityname.replace(/ *\([^)]*\) */g, "")}
Location${event.locationname.replace(/ *\([^)]*\) */g, "")}
Statute${(event.statute[0] ?? "")}
Subcategory${event.subcategory}
Reporter${event.reporters[0].split(';')[0]}
Approver${event.approvers[0].split(';')[0]}
Due Date${ddmmyyyy}
`; let listReportingContainers = eventsContainer.querySelectorAll('.list-reporting-container') as NodeListOf for (let tempReportingContainer of listReportingContainers) { tempReportingContainer.style.display = 'none'; tempReportingContainer.innerHTML = ''; } listReportingContainer.style.display = 'flex'; const id = listReportingContainer.id; const idArr = id.split("-") // const i = idArr[3]; const j = idArr[5]; let buttonListReportings = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReporting of buttonListReportings) { if (buttonListReporting.id == 'button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') { console.log('buttonListReporting', buttonListReporting.id, 'button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-'); buttonListReporting.setAttribute('part', 'button-list-reporting-selected') } else { buttonListReporting.setAttribute('part', 'button-list-reporting') } } let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { if (streamEventTitle.id == 'stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + ((event.module ?? false) ? event.module : 'compliance') + '-') { streamEventTitle.setAttribute('part', 'stream-event-title-selected') } else { streamEventTitle.removeAttribute('part') } } listReportingContainer.innerHTML = html; if (this._SfUploader[0] != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.emailcontent = emailcontent; } (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.addEventListener('change', (e) => { let value = (e.target as HTMLInputElement).value; if (this.reportingSuggestionsNotApplicable.indexOf(value) >= 0) { console.log('suggestion matched', value); let uploadOptionalWarning = listReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement; uploadOptionalWarning.classList.remove('hide'); let supportingDocumentsLabel = listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement; supportingDocumentsLabel.innerText = 'Supporting Documents'; } else { let uploadOptionalWarning = listReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement; uploadOptionalWarning.classList.add('hide'); let supportingDocumentsLabel = listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement; supportingDocumentsLabel.innerText = 'Supporting Documents' + (event.docsOptional.length > 0 ? '' : '*'); } }) let deleteButtons = listReportingContainer.querySelectorAll('.button-delete') as NodeListOf for (let deleteButton of deleteButtons) { deleteButton?.addEventListener('click', async () => { await this.fetchDeleteReview(event["id"], mmddyyyy, event.entityid, event.locationid); this.setSuccess('Deleted successfully!') setTimeout(() => { this.clearMessages() }, 3000); //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } }); } listReportingContainer.querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length <= 1) { await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); this.setSuccess('Auto-Approved successfully!') setTimeout(() => { this.clearMessages() }, 3000); } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": "Auto approved", "approved": true, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance" }) } await this.uploadReviewsBulk(bulkBodyReview); } if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } }); listReportingContainer.querySelector('#upload-guidance-button')?.addEventListener('click', async () => { console.log('upload guidance clicked', event); let inputReportingPercentage = (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement)?.value ?? "100"; let selectReportedLocations = (listReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf); let selectReportedLocationValue = "[]"; for (let selectReportedLocation of selectReportedLocations) { selectReportedLocationValue = JSON.stringify([...JSON.parse(selectReportedLocationValue), selectReportedLocation.value]) } let approvercomments = (listReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement)?.value ?? ""; let reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.value ?? ""; let dateOfCompletion; if ((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement) != null) { dateOfCompletion = new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + ""; } else { dateOfCompletion = new Date((listReportingContainer.querySelector('#input-approver-doc') as HTMLInputElement).value).getTime() + ""; } let documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader).selectedValues() if (dateOfCompletion == "NaN") { dateOfCompletion = ""; } console.log('dateOfCompletion', dateOfCompletion) await this.fetchEventDetails(event, mmddyyyy, null, eventsContainer, "", "", true, listReportingContainer, reportercomments, approvercomments, inputReportingPercentage, selectReportedLocationValue, documents, dateOfCompletion); }) if (this.mode == "consumer" || this.mode == "next") { let reportingSuggestionMoreButton = listReportingContainer.querySelector('#reporting-suggestions-more') as HTMLButtonElement; reportingSuggestionMoreButton?.addEventListener('click', (e) => { (e.target as HTMLButtonElement).style.display = 'none'; let reportingSuggestions = listReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf; reportingSuggestions.forEach(suggestion => { suggestion.classList.remove('hide'); }) }) let reportingSuggestionButtons = listReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf; for (let reportingSuggestionButton of reportingSuggestionButtons) { reportingSuggestionButton.addEventListener('click', (e) => { let button = e.currentTarget as HTMLDivElement; (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value = ((listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value + " " + button.innerHTML).trim(); (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).dispatchEvent(new Event('change', { bubbles: true })); }) } let inputReportingPercentage = listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement; let percentage = inputReportingPercentage?.value ?? 0 const entityContainers = listReportingContainer.querySelectorAll('.reporting-entity-container') as NodeListOf; const locationsContainers = listReportingContainer.querySelectorAll('.reporting-location-container') as NodeListOf; const addLocationButtons = listReportingContainer.querySelectorAll('.button-reporter-location-add') as NodeListOf; if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) { entityContainers.forEach(container => container.classList.remove('hide')); locationsContainers.forEach(container => container.classList.remove('hide')); addLocationButtons.forEach(container => container.classList.remove('hide')); } else { entityContainers.forEach(container => container.classList.add('hide')); locationsContainers.forEach(container => container.classList.add('hide')); addLocationButtons.forEach(container => container.classList.add('hide')); } inputReportingPercentage?.addEventListener('change', () => { setTimeout(() => { let percentage = inputReportingPercentage.value console.log('percentage', percentage, inputReportingPercentage, inputReportingPercentage.value, event.reportedlocations); if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) { entityContainers.forEach(container => container.classList.remove('hide')); locationsContainers.forEach(container => container.classList.remove('hide')); addLocationButtons.forEach(container => container.classList.remove('hide')); } else { entityContainers.forEach(container => container.classList.add('hide')); locationsContainers.forEach(container => container.classList.add('hide')); addLocationButtons.forEach(container => container.classList.add('hide')); } if ((percentage != null && parseInt(percentage) == 0) || event.docsOptional.length > 0) { (listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents'; } else { (listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents*'; } if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100 && (event.reportedlocations == "" || event.reportedlocations == "[]")) { event.percentage = percentage event.reportedlocations = JSON.stringify([""]) event.reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; event.dateofcompletion = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); console.log('rendering list reporting', event.percentage, event.reportedlocations) this.renderListReporting(listReportingContainer, event, mmddyyyy, eventsContainer); } }, 200); }) let projectUserMap = Util.getProjectUsermap() addLocationButtons.forEach((addLocationBtn) => { addLocationBtn.addEventListener('click', () => { let iconhtml = addLocationBtn.innerHTML let index = parseInt(addLocationBtn.id.split('-')[4]) console.log('button clicked', iconhtml, addLocationBtn.id); if (iconhtml == "add") { console.log('this.reportedLocationsVals', this.reportedLocationsVals) this.reportedLocationsVals.push(""); } else { this.reportedLocationsVals.splice(index, 1); } event.percentage = inputReportingPercentage.value; event.reportedlocations = JSON.stringify(this.reportedLocationsVals) if (this.reportedLocationsVals.length == 0) { event.percentage = "100"; } console.log('rendering list reporting', event.percentage, event.reportedlocations) event.reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; event.dateofcompletion = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); this.renderListReporting(listReportingContainer, event, mmddyyyy, eventsContainer); }) }) for (let indexRepLoc = 0; indexRepLoc < this.reportedLocationsVals.length; indexRepLoc++) { console.log('AddingEntities', indexRepLoc) let selectReportingEntity = listReportingContainer.querySelector('#input-reporter-entity-' + indexRepLoc) as HTMLSelectElement; let selectReportingLocation = listReportingContainer.querySelector('#input-reporter-location-' + indexRepLoc) as HTMLSelectElement; if (selectReportingEntity != null && selectReportingLocation != null) { selectReportingEntity.innerHTML = ''; let defaultOption = new Option("Select Location", "", true, true) defaultOption.disabled = true selectReportingEntity.add(defaultOption) for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { let entityName = entity.split(';')[0].replace(/ *\([^)]*\) */g, "") let option = new Option(entityName, entity) selectReportingEntity.add(option); } } selectReportingEntity.addEventListener('change', (e: any) => { selectReportingLocation.innerHTML = '' let defaultOption = new Option("Select Location", "", true, true) defaultOption.disabled = true selectReportingLocation.add(defaultOption) for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { if (entity.indexOf(e.target.value) < 0) { continue; } for (let location of Object.keys(projectUserMap[country][entity])) { let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "") let option = new Option(locationName, location) selectReportingLocation.add(option); } } } (listReportingContainer.querySelector('#reporting-location-container-' + indexRepLoc) as HTMLDivElement).classList.remove('hide') selectReportingLocation.value = event.reportedlocations != null ? (Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations) : ""; }) if (selectReportingLocation.innerHTML == '') { let defaultOption = new Option("Select Location", "", true, true) defaultOption.disabled = true selectReportingLocation.add(defaultOption) // for (let country of Object.keys(projectUserMap)) { // if (country == "roles") { // continue; // } // for (let entity of Object.keys(projectUserMap[country])) { // for (let location of Object.keys(projectUserMap[country][entity])) { // let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "") // let option = new Option(locationName, location) // selectReportingLocation.add(option); // break; // } // break; // } // break; // } } selectReportingLocation.addEventListener('change', (e: any) => { if (selectReportingEntity.value == "") { return; } let index = parseInt(e.target.id.split('-')[3]) this.reportedLocationsVals[index] = e.target.value }) if (event.reportedlocations != null && event.reportedlocations.length > 0) { console.log('setting reportedlocations', event.reportedlocations) let tempReportedLocation = Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { let flagSetVal = false; for (let location of Object.keys(projectUserMap[country][entity])) { if (tempReportedLocation.indexOf(location) >= 0) { selectReportingEntity.value = entity; const changeEvent = new Event('change', { bubbles: true }); selectReportingEntity.dispatchEvent(changeEvent) selectReportingLocation.value = location; flagSetVal = true; break; } } if (flagSetVal) { break; } } } } else { selectReportingEntity.value = ""; selectReportingLocation.value = ""; } } } listReportingContainer.querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = (listReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement).value; console.log('comments', comments, JSON.stringify(event.comments)) const approved = (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(event); let newEvent = { ...event }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('selectedevent', JSON.stringify(event)); if (await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) { if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) { this.nextEvents[this.nextTabRole][mmdd][p].approved = approved console.log('selected event', this.nextEvents[this.nextTabRole][mmdd][p]); this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString() if (approved) { this.nextEvents[this.nextTabRole][mmdd][p].dateofcompletion = new Date().getTime() + "" } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = approved console.log('selected event', this.events[mmdd][p]); this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() if (approved) { this.events[mmdd][p].dateofcompletion = new Date().getTime() + "" } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) } } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityid = selectedId.split('-')[7].replace(/_/g, '-'); let locationid = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityid, "locationid": locationid, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityid = selectedId.split('-')[7].replace(/_/g, '-'); let locationid = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityid) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationid && this.events[mmdd][p].entityid == entityid) { this.events[mmdd][p].isbulk = true flagBulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage) // this.renderRoleTabsNext(this.nextPage) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } console.log('events', this.events); this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); } } }); listReportingContainer.querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = (listReportingContainer.querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked; if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() if (approved) { this.events[mmdd][p].dateofcompletion = new Date().getTime() + "" } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) } } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": event.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (event.approved) { if ((listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) { (listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } } else { if ((listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) { (listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; listReportingContainer.querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); const reporterdoc = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); // if(docsOptional.length === 0) { let percentage: string = "100"; if ((listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value } docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } let flag = false; do { if (docs.length > 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments.trim().toLowerCase()) < 0) { for (let doc of docs) { if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) { flag = false } else { flag = true; } } } else { flag = true; } if (flag === false) { await this.sleep(1000); console.log('waiting for docs', docs); docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); } } while (flag === false); //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (this._SfReporting[0] != null) { reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? ""; reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? ""; } console.log('percentage', percentage, (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value); if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('Invalid Percentage!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { if (docs.length == 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments.trim()) < 0) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('No documents uploaded!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('reporterdoc', reporterdoc); if (reporterdoc.length === 0) { buttonClick.innerHTML = "Save" this.setError('Date of completion not selected!'); setTimeout(() => { this.clearMessages(); }, 3000); } else if (parseInt(reporterdoc) > new Date().getTime()) { buttonClick.innerHTML = "Save" this.setError('Date of completion cannot be in future!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('makerscheckers 1', reportercomments); if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; // let reportedlocations = selectReportingLocation?.value ?? ""; let reportedlocations = "[]"; if (parseInt(percentage) !== 100) { let selectReportedLocations = (listReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf); for (let selectReportedLocation of selectReportedLocations) { reportedlocations = JSON.stringify([...JSON.parse(reportedlocations), selectReportedLocation.value]) } } if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(event.entityid, event.locationid, mmddyyyy, event["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, event.module ?? "compliance", percentage, event.makercheckers, reportedlocations)) { if (this.mode != "next") { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].documents = docs this.events[mmdd][p].percentage = percentage this.events[mmdd][p].reportedlocations = reportedlocations this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (event.makercheckers.length > 0) { // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = true // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) console.log('recently reported', this.recentlyReported) } else { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) { this.nextEvents[this.nextTabRole][mmdd][p].documents = docs this.nextEvents[this.nextTabRole][mmdd][p].percentage = percentage this.nextEvents[this.nextTabRole][mmdd][p].reportedlocations = reportedlocations this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString() } } if (event.makercheckers.length > 0) { // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) { this.nextEvents[this.nextTabRole][mmdd][p].approved = true // this.events[mmdd][p].documents = docs this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString() } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) console.log('recently reported', this.recentlyReported) } } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null) // if(parseInt(makercheckersL) > 0) { // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "report", // "eventid": eventId, // "comments": reportercomments, // "dateofcompletion": reporterdoc, // "percentage": percentage, // "entityid": entityId, // "locationid": locationId, // "event": null, // "docs": JSON.stringify(docs), // "approved": true, // "username": this.userName, // "reportformatvalues": reportformatvalues, // "reportformatschema": reportformatschema, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY, // "module": event.module ?? "compliance" // } ) // // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true); // }else{ let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "reportedlocations": reportedlocations, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) // } // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } // await this.uploadReportsBulk(bulkBody); // await this.fetchBulkReportingData(); if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } // if(bulkBodyReview.length > 0){ // await this.uploadReportsReviewsBulk(bulkBodyReview) // } for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { flagBulk = true; this.events[mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } } } } }); } } } if (this._SfUploader[0] != null) { if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" } this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" } }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" } }); //console.log('documentType checking', documentType); if (event.documenttype != null) { if (Array.isArray(event.documenttype)) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype[0] ?? ""; } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype; } } else if (event.documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documentType; } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = ""; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = 0; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = docs.length; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || event.approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: event.entityid, locationId: event.locationid, mmddyyyy: mmddyyyy, complianceId: event['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); console.log('uploader prepopulate', (this._SfUploader[0].querySelector('#uploader') as SfIUploader).prepopulatedInputArr, (this._SfUploader[0].querySelector('#uploader') as SfIUploader).extract) } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (event["approved"] != null) { if (event["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if ((listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) { (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if ((listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) { (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement != null) { (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } if (event['reportformat'] != null && event['reportformat'].length > 0) { this.fetchReportFormat(listReportingContainer, reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? ""); } } attachListReportingListeners = (eventsContainer: HTMLDivElement) => { let buttonListReports = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReport of buttonListReports) { buttonListReport?.addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); // const i = idArr[5]; const j = idArr[5]; let listReportingContainer = eventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement // console.log('mmddyyyy', this.events[mmdd][j], listReportingContainer, '#list-reporting-container-'+mmdd.replace(/\//g,'-')+'-'+j); if (listReportingContainer.style.display == 'none' || listReportingContainer.style.display == '') { this.renderListReporting(listReportingContainer, this.events[mmdd][j], mmdd + '/' + yyyy, eventsContainer) } else { listReportingContainer.innerHTML = ''; listReportingContainer.style.display = 'none'; ev.target.setAttribute('part', 'button-list-reporting') let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { streamEventTitle.removeAttribute('part') } } // console.log('part', ev.target.getAttribute('part')); }) } } attachReviewListeners = (eventsContainer: HTMLDivElement) => { let buttonReviews = eventsContainer.querySelectorAll('.button-icon-review') as NodeListOf for (let buttonReview of buttonReviews) { buttonReview?.addEventListener('click', async (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); // const i = idArr[5]; const j = idArr[5]; console.log('review clicked', mmdd, yyyy, j, this.events[mmdd][j], ev.target.checked); let eventKey = this.events[mmdd][j].entityid + ';' + this.events[mmdd][j].locationid + ';' + this.events[mmdd][j].id; for (var p = 0; p < Object.keys(this.events).length; p++) { let tempMmDd = Object.keys(this.events)[p]; for (var q = 0; q < this.events[tempMmDd].length; q++) { let tempEventKey = this.events[tempMmDd][q].entityid + ';' + this.events[tempMmDd][q].locationid + ';' + this.events[tempMmDd][q].id; if (tempEventKey == eventKey) { this.events[tempMmDd][q].review = ev.target.innerHTML.indexOf('flag_check') < 0 } } } this.markReviewed(eventKey, yyyy, ev.target.innerHTML.indexOf('flag_check') < 0); this.renderAppropriateStream(this.sdate, this.edate, true); }) } } renderStreamEvents = (index: number, month: number, year: number, showGraph: boolean = true, showBackgroundButton: boolean = false) => { //console.log('flowgraph renderStreamEvents', this.flowGraph); const lastDay = this.getLastDayOfMonth(month, year); let firstDay = new Date(year, month, 1); let endDay = new Date(year, month, 1); endDay?.setDate(endDay.getDate() + lastDay + 1); var period = ("0" + (month + 1)).slice(-2) + "/" + ("0" + 1).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (month + 1)).slice(-2) + "/" + ("0" + lastDay).slice(-2) + '/' + firstDay.getFullYear() return this.renderEvents(firstDay, endDay, 1, lastDay, showGraph, index, month, period, null, this.monthNames[month] + " " + year, showBackgroundButton); } renderThisEvents = (index: number, startDate: Date, showGraph: boolean = true, showBackgroundButton: boolean = false) => { var firstDate = new Date(); var count = 7; //console.log('this start date', startDate); if (index === 0) { firstDate = (this.getFirstDateOfWeek(startDate) as Date); //console.log('this first date', firstDate); count = 7; } if (index === 1) { firstDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1); count = this.getLastDayOfMonth(startDate.getMonth(), startDate.getFullYear()); //console.log('last day of month', count); } const lastDay = count; let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); endDay?.setDate(endDay.getDate() + lastDay + 1); var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + 1).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + count).slice(-2) + '/' + endDay.getFullYear() return this.renderEvents(firstDay, endDay, 1, lastDay, showGraph, index, (firstDate.getMonth()), period, null, "This " + (index === 0 ? "Week" : "Month"), showBackgroundButton); } renderRangeEvents = (firstDate: Date, count: number, eventsContainer: HTMLDivElement, showBackgroundButton: boolean = false) => { console.log('render range events called', firstDate, count) var lastDate = new Date(firstDate.getTime()); lastDate.setDate(lastDate.getDate() + count - 1) const lastDay = count; let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); endDay?.setDate(endDay.getDate() + lastDay); console.log('firstday', firstDay, endDay) var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDay.getDate()).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear(); console.log('rangeperiod', period, lastDay); var html = this.renderEvents(firstDay, endDay, 0, lastDay, true, 0, (firstDate.getMonth()), period, firstDate, "From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), showBackgroundButton); eventsContainer.querySelector('.calendar-right-data')!.innerHTML = html; if (eventsContainer.innerHTML.indexOf('button-select-all') < 0) { eventsContainer.insertAdjacentHTML('beforeend', this.renderSelectAllButtons()); } this.renderButtonRefresh(eventsContainer); this.attachTimelineFilterHandlers(eventsContainer); let backgroundProcessButton = eventsContainer.querySelector('#button-background-process') as HTMLButtonElement if (showBackgroundButton) { backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none' console.log('backgroundprocessbutton', backgroundProcessButton.style.display); if (showBackgroundButton) { backgroundProcessButton.addEventListener('click', () => { console.log('bulk-progress clicked') let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement bulkLoader.scrollIntoView(); }) } } const filterButton = eventsContainer.querySelector('#filter-button') as HTMLButtonElement filterButton?.addEventListener('click', () => { const filterList = eventsContainer.querySelector('#filter-list-container') as HTMLDivElement filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none') filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close') const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement filterSubmitButton.addEventListener('click', () => { Util.setFeatures(this.selectedFeatures); this.enableCustom(); this.renderTabs(this.selectedTab); // this.processDateSelection(eventsContainer); if (this.myRole == this.TAB_VIEWER) { this.renderCustomViewer() } else { this.renderCustom(); } }) // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement // selectFeatureAll.addEventListener('click',async(ev: any) => { // let target = ev.target; // if(target.checked){ // for(let feature of this.getFeatures()){ // if(this.selectedFeatures.indexOf(feature) < 0){ // this.selectedFeatures.push(feature); // } // } // }else{ // this.selectedFeatures = [] // } // const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf // for(let selectFeature of selectFeatures){ // let id = selectFeature.id; // let i = id.split('-')[3]; // let selectedFeature = this.getFeatures()[parseInt(i)] // selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0 // } // filterSubmitButton.style.visibility = 'visible' // }) // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement // selectFeatureAllLabel.addEventListener('click',()=>{ // selectFeatureAll.checked = !selectFeatureAll.checked // selectFeatureAll.click(); // }) const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf for (let [i, selectFeature] of selectFeatures.entries()) { selectFeature.addEventListener('click', (ev: any) => { let target = ev.target; let id = target.id; let index = id.split('-')[3]; let selectedFeature = this.getFeatures()[index] if (target.checked) { if (this.selectedFeatures.indexOf(selectedFeature) < 0) { // this.selectedFeatures.push(selectedFeature) this.selectedFeatures = [selectedFeature] } } // else{ // // selectFeatureAll.checked = false; // if(this.selectedFeatures.indexOf(selectedFeature) >= 0){ // this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1); // } // } // filterSubmitButton.style.visibility = 'visible' filterSubmitButton.click(); }) selectFeatureLabels[i].addEventListener('click', () => { selectFeature.checked = !selectFeature.checked selectFeature.click(); }) } }) const radioExpander = eventsContainer.querySelector('#graph-radios-expander') as HTMLButtonElement; radioExpander?.addEventListener('click', (e: any) => { const button = (e.currentTarget as HTMLButtonElement); button.style.display = 'none'; const arrRadios = eventsContainer.querySelectorAll('.chart-radio-item-secondary') as NodeListOf; arrRadios.forEach(div => { div.style.display = 'block'; }); }); if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) { radioExpander?.click(); } const buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement buttonRefresh.addEventListener('click', async () => { this.processDateSelection(eventsContainer) }) const chipSuspense = eventsContainer.querySelector('#chip-suspense') as HTMLDivElement chipSuspense?.addEventListener('click', async () => { this.suspenseFlag = !this.suspenseFlag this.processDateSelection(eventsContainer) }) const externalInput = eventsContainer.querySelector('#external-reporting-file-uploader') as HTMLInputElement externalInput.addEventListener('change', async () => { console.log('trying to upload external file', externalInput.files); if (externalInput.files != null) { let file = externalInput.files[0] if (file != null) { let jsonObj = await Util.parseMISExcel(file); console.log('parsed JSON', jsonObj, this.events) let externalMapping = await this.fetchExternalMapping() console.log('external mapping', externalMapping); let changeCount = 0 let totalCount = 0 for (let dateStr of Object.keys(this.events)) { for (let compliance of this.events[dateStr]) { let complianceId = compliance.id totalCount++; if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { console.log('external compliance found', jsonObj.compliances[externalId]) changeCount++ } } } } this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [ () => { for (let dateStr of Object.keys(this.events)) { for (let [index, compliance] of this.events[dateStr].entries()) { let complianceId = compliance.id if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { if (jsonObj.compliances[externalId].status == "Complied") { this.events[dateStr][index].approved = true; this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() }); } } } } } this.renderAppropriateStream(this.sdate, this.edate, true); this.clearMessages() }, () => { this.clearMessages() } ]) } } }) this.attachListReportingListeners(eventsContainer); this.attachReviewListeners(eventsContainer); const buttonArr = eventsContainer.querySelectorAll('.button-expand') as NodeListOf; for (var i = 0; i < buttonArr.length; i++) { let indexPrevNext = i; buttonArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.selectedItems = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null); let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id; flagPrev = false; } else { prevString = ""; indexPrev-- } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < buttonArr.length - 1) { if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) { nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id; flagNext = false; } else { nextString = ""; indexNext++ } } else { flagNext = false; } } this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, eventsContainer, prevString, nextString); } }) } const titleArr = eventsContainer.querySelectorAll('.button-event-title') as NodeListOf; for (var i = 0; i < titleArr.length; i++) { let indexPrevNext = i; titleArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; const flag = idArr[7]; if (flag != null && flag == "reportedlocations") { return; } var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.selectedItems = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id; let prevIdArr = prevString.split("-") if ((prevIdArr[7] ?? "") == "reportedlocations") { prevString = ""; indexPrev--; } else { flagPrev = false; } } else { prevString = ""; indexPrev--; } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < titleArr.length - 1) { if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) { nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id; console.log('prev nextString', nextString) let nextIdArr = nextString.split("-") console.log('prev nextArr', nextIdArr) if ((nextIdArr[7] ?? "") == "reportedlocations") { nextString = ""; console.log('prev nextString2', nextString) indexNext++; } else { console.log('prev nextString3', nextString) flagNext = false; } } else { indexNext++; } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, eventsContainer, prevString, nextString); } }) } const buttonRenewArr = eventsContainer.querySelectorAll('.button-renew') as NodeListOf; for (var i = 0; i < buttonRenewArr.length; i++) { buttonRenewArr[i].addEventListener('click', async (ev: any) => { const id = ev.target.id; const idArr = id.split("-") console.log('idArr', idArr); const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]); let renewEvent = this.events[mmdd][j]; let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true); console.log('renew clicked', fullEvent, fullEvent.reportformatvalues); this.renewRCMResource(fullEvent, fullEvent.reportformatvalues); }) } const streamEventsContainer = eventsContainer.querySelectorAll('.stream-events-container') as NodeListOf; const buttonSelect = eventsContainer.querySelectorAll('.button-select') as NodeListOf; if (eventsContainer.innerHTML.indexOf('button-select-all') >= 0) { let selectAllArr = this.attachSelectAllListeners(eventsContainer, buttonSelect) const buttonSelectAll = selectAllArr[0] const buttonUnselectAll = selectAllArr[1] for (i = 0; i < buttonSelect.length; i++) { buttonSelect[i].addEventListener('click', (ev: any) => { //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length); const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; // const makercheckers = idArr[5]; const docs = idArr[6]; const module = idArr[14]; if ((ev.target as HTMLInputElement).checked) { this.selectedItemIds.push(id); } else { this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1); let listReportingContainer = eventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement listReportingContainer.style.display = 'none'; listReportingContainer.innerHTML = ''; let buttonListReporting = eventsContainer.querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement buttonListReporting.setAttribute('part', 'button-list-reporting') let streamEventTitle = eventsContainer.querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText streamEventTitle.removeAttribute('part') } if (this.selectedItemIds.length === 0) { for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } else { (buttonSelect[k] as HTMLInputElement).style.display = 'block'; } (streamEventsContainer[k] as HTMLDivElement).style.display = 'block'; } let bulkUploadLables = eventsContainer.querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = '' } buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'none'; } else { if (this.selectedItemIds.length === 1) { const id1 = id; const idArr1 = id1.split("-") const status = idArr1[13].replace(/_/g, '-'); this.selectedStatus = status; } let totalVisibleCount = 0 for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const docs1 = idArr1[6]; const status = idArr1[13].replace(/_/g, '-'); const module1 = idArr1[14] const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } if (docs == docs1 && status == this.selectedStatus && module == module1) { totalVisibleCount++ } else { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; (streamEventsContainer[k] as HTMLDivElement).style.display = 'none'; } } let bulkUploadLables = eventsContainer.querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected` } if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) { buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'flex'; } else { buttonSelectAll.style.display = 'flex'; buttonUnselectAll.style.display = 'none'; } } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + "")); if (this.selectedItemIds.length == 1) { ev.target.scrollIntoView() } }) } } // this.clearGraphData(); // //console.log('rendering range', firstDate, count); // this.selectedItems = []; // var html = ''; // html += '
'; // html += '
'; // html += '
Select Chart
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
' // html += '
' // html += '
'; // html += '
'; // var total = 0, notStarted = 0, approved = 0, inProgress = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0; // html += '
'; // html += '
Total: DASHBOARD_TOTAL
'; // html += '
schedule  Not Started: DASHBOARD_NOT_STARTED
'; // html += '
pending  In Progress: DASHBOARD_IN_PROGRESS
'; // html += '
check_circle  Approved:DASHBOARD_APPROVED
'; // // html += '
navigate_next
'; // html += '
timer  In Time: DASHBOARD_IN_TIME
'; // html += '
running_with_errors  Past Due Date: DASHBOARD_PAST_DUE_DATE
'; // html += '
running_with_errors  Late Approved: DASHBOARD_LATE_APPROVED
'; // html += '
running_with_errors  Late Executed: DASHBOARD_LATE_EXECUTED
'; // html += '
'; // html += '
'; // var lastDate = new Date(firstDate.getTime()); // lastDate.setDate(lastDate.getDate() + count) // this.eventsInWindow = []; // var csvCols = "", htmlCols = ""; // var csvValues = "", htmlValues = ""; // var period = ("0" + (firstDate.getMonth()+1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2) + ' - ' + ("0" + (lastDate.getMonth()+1)).slice(-2) + "/" + ("0" + lastDate.getDate()).slice(-2) // let firstDay: Date | null = null; // let endDay = null; // var slice = 2; // for(var i = 1; i <= count; i++) { // if(i === 1) { // firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); // endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); // } else { // endDay?.setDate(endDay.getDate() + 1); // } // const mmdd = ("0" + (firstDate.getMonth()+1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2); // var hide = true; // //console.log('eventslice', slice); // //console.log('event status', mmdd, this.events[mmdd]); // if(this.events[mmdd] != null) { // hide = false; // } else if(i === 1){ // hide = false; // } else if(i === (count)){ // hide = false; // } else { // const startNextDate = new Date(firstDate.getTime()); // startNextDate.setDate(firstDate.getDate() + 1); // const startPrevDate = new Date(firstDate.getTime()); // startPrevDate.setDate(firstDate.getDate() - 1); // const mmddNext = ("0" + (startNextDate.getMonth()+1)).slice(-2) + "/" + ("0" + (startNextDate.getDate())).slice(-2); // const mmddPrev = ("0" + (startPrevDate.getMonth()+1)).slice(-2) + "/" + ("0" + (startPrevDate.getDate())).slice(-2); // //console.log('hide', i, hide, startNextDate, startPrevDate, mmddNext, mmddPrev); // if((this.events[mmddPrev] != null || this.events[mmddNext] != null)) { // hide = false; // } // } // if(this.events[mmdd] != null) { // html += '
'; // html += '
'+("0" + firstDate.getDate()).slice(-2)+'/'+(firstDate.getMonth()+1)+' |
'; // html += '
' // for(var j = 0; j < (this.events[mmdd] as Array).length; j++) { // total++; // this.events[mmdd][j]['mmdd'] = mmdd // this.eventsInWindow.push(this.events[mmdd][j]); // // this.events[mmdd][j] = this.renderLatestCompliance(("0" + (firstDate.getMonth()+1)).slice(-2), this.events[mmdd][j]); // var partStatus = ""; // var lateStatus = "in-time"; // if(this.events[mmdd][j].approved != null && (this.events[mmdd][j].approved) != null && (this.events[mmdd][j].approved)) { // partStatus = "status-approved"; // if(this.getLateExecuted(mmdd, this.events[mmdd][j])) { // lateStatus = "late-executed" // } else { // if(this.getLateApproved(mmdd, this.events[mmdd][j])) { // lateStatus = "late-approved" // } // } // } else if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) { // partStatus = "status-in-progress"; // if(this.getPastDueDate(mmdd)) { // lateStatus = "past-due-date" // } // } else { // partStatus = "status-not-started"; // if(this.getPastDueDate(mmdd)) { // lateStatus = "past-due-date" // } // } // this.updateRiskAreaStats(this.events[mmdd][j]['riskarea'], partStatus, lateStatus); // this.updateRiskSeverityStats(this.events[mmdd][j]['risk'], partStatus, lateStatus); // this.updateFunctionStats(this.events[mmdd][j]['functions'], partStatus, lateStatus); // this.updateObligationTypeStats(this.events[mmdd][j]['obligationtype'], partStatus, lateStatus); // this.updateJurisdictionStats(this.events[mmdd][j]['jurisdiction'], partStatus, lateStatus) // this.updateFrequencyStats(this.events[mmdd][j]['frequency'], partStatus, lateStatus) // this.updateLocationStats([this.events[mmdd][j]['locationname']], partStatus, lateStatus) // html += '
'; // html += '
'+JSON.stringify(this.events[mmdd][j]['tags'])+'
' // html += '
filtered out
' // html += '
' + ('') + '
'; // html += ''; // html += ''; // html += '' // } // html += ''; // html += ''; // html += '' // html += '' // html += '' // html += '' // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) { // if(this.getEventPreviewFields().includes(Object.keys(this.events[mmdd][j])[k])) { // html += ''; // } // } // //console.log('listing docs',this.events[mmdd][j].documents ) // if(this.events[mmdd][j].documents != null && this.events[mmdd][j].documents != null && (this.events[mmdd][j].documents).length > 0) { // html += ''; // } // if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) { // html += ''; // } else { // if(partStatus != "status-approved") { // notStarted++; // } // } // if(this.events[mmdd][j].lastupdated != null && this.events[mmdd][j].lastupdated != null && (this.events[mmdd][j].lastupdated).length > 0) { // html += ''; // } // if(this.events[mmdd][j].makercheckers != null && (this.events[mmdd][j].makercheckers).length > 0) { // html += '' // } // if(this.events[mmdd][j].docs != null && (this.events[mmdd][j].docs).length > 0) { // html += '' // } // // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) { // // html += ''; // // } // html += ''; // html += ''; // csvValues += (period + ','); // htmlValues += (''); // if(partStatus == "status-approved") { // approved++ // html += ''); // } else if(lateStatus == "late-approved") { // lateApproved++; // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'check_circle' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'running_with_errors' // } // csvValues += 'approved late-approved,'; // htmlValues += (''); // } else { // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'check_circle' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'timer' // } // csvValues += 'approved,'; // htmlValues += (''); // } // html += ''; // } else if(partStatus == "status-in-progress") { // html += ''); // } else { // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'pending' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'timer' // } // csvValues += 'in-progress,'; // htmlValues += (''); // } // html += ''; // } else { // html += ''); // } else { // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'schedule' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'timer' // } // csvValues += 'not started,'; // htmlValues += (''); // } // html += ''; // } // html += ''; // html += ''; // html += ''; // html += ''; // var functions = ''; // for(const element of this.events[mmdd][j]["functions"]) { // functions += (element.split(';')[0].replace(/ *\([^)]*\) */g, "") + ","); // } // functions = functions.replace(/,\s*$/, ""); // html += ''; // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) { // if(this.getEventPreviewFields().includes(Object.keys(this.events[mmdd][j])[k])) { // html += ''; // } // } // csvValues += this.events[mmdd][j]["id"] + ',' + this.events[mmdd][j]["obligationtitle"] + ',' + this.events[mmdd][j]["obligation"] + ',' + this.events[mmdd][j]["duedate"]; // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // htmlValues += (''); // if(this.events[mmdd][j].documents != null && this.events[mmdd][j].documents != null && (this.events[mmdd][j].documents).length > 0) { // html += ''; // } // if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) { // html += ''; // } // if(this.events[mmdd][j].lastupdated != null && this.events[mmdd][j].lastupdated != null && (this.events[mmdd][j].lastupdated).length > 0) { // html += ''; // } // if(this.events[mmdd][j].makercheckers != null && (this.events[mmdd][j].makercheckers).length > 0) { // html += ''; // } // if(this.events[mmdd][j].docs != null && (this.events[mmdd][j].docs).length > 0) { // html += '' // } // csvValues += '\n'; // // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) { // // html += ''; // // } // html += ''; // html += '
'; // html += 'Status' // if(csvCols.indexOf('Status') < 0) { // csvCols += 'Period,Status,Id,ObligationTitle,Obligation,Duedate' // htmlCols += '
IdStatusStatuteReferenceApplicabilityObligationTypeObligationInternalControlsPenaltyRiskSeverityFrequencySubFrequencyDueDateReportParameter
'; // html += ''; // html += 'Location' // html += ''; // html += 'Entity' // html += ''; // html += 'Country' // html += ''; // html += 'Function' // html += ''; // html += Object.keys(this.events[mmdd][j])[k]; // html += ''; // html += 'Docs' // html += ''; // html += 'Comments' // html += ''; // html += 'Updated' // html += ''; // html += '' // html += ''; // html += '' // html += ''; // // html += Object.keys(this.events[mmdd][j])[k]; // // html += '
'+this.events[mmdd][j]["id"]+''; // if(lateStatus == "late-executed") { // lateExecuted++; // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'check_circle'; // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'running_with_errors'; // } // csvValues += 'approved late-executed,'; // htmlValues += ('approved late-executedapproved late-approvedapproved'; // if(lateStatus == "past-due-date") { // pastDueDate++; // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'pending' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'running_with_errors' // } // csvValues += 'in-progress past-due-date,'; // htmlValues += ('in-progress past-due-datein-progress'; // if(lateStatus == "past-due-date") { // pastDueDate++; // if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // html += 'schedule' // } // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) { // html += 'running_with_errors' // } // csvValues += 'not started past-due-date,'; // htmlValues += ('not-started past-due-datenot-started'; // html += '' // html += ''; // if(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].indexOf("[") >= 0) { // html += this.getEventTexts(Object.keys(this.events[mmdd][j])[k], JSON.parse(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]]), this.events[mmdd][j]); // } else { // html += ' '; // } // html += ''+this.events[mmdd][j]["statute"]+''+this.events[mmdd][j]["reference"]+''+this.events[mmdd][j]["applicability"]+''+this.events[mmdd][j]["obligationtype"]+''+this.events[mmdd][j]["obligation"]+''+this.events[mmdd][j]["internalcontrols"]+''+this.events[mmdd][j]["penalty"]+''+this.events[mmdd][j]["risk"]+''+this.events[mmdd][j]["frequency"]+''+this.events[mmdd][j]["subfrequency"]+''+this.events[mmdd][j]["duedate"]+''; // html += 'description' // html += (this.events[mmdd][j].documents).length // html += ''; // html += 'forum' // html += (this.events[mmdd][j].comments).length // html += ''; // html += Util.timeSince(new Date(this.events[mmdd][j].lastupdated).getTime()) // html += ''; // html += 'done_all' // html += ''; // html += 'scan_delete' // html += ''; // // if(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].indexOf("[") >= 0) { // // html += this.getEventTexts(Object.keys(this.events[mmdd][j])[k], JSON.parse(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]]), this.events[mmdd][j]); // // } else { // // html += this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].replace(/"/g, ""); // // } // // html += '
'; // html += '
' // let reporterStr = this.getReporterStringFromEvent(this.events[mmdd][j]); // let approverStr = this.getApproverStringFromEvent(this.events[mmdd][j]); // if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS && this.flowGraph != this.FLOW_GRAPH_TIMELINESS) { // let graphParam = ''; // if(Array.isArray(this.events[mmdd][j][this.flowGraph])) { // graphParam = this.events[mmdd][j][this.flowGraph].toString().replace(/ *\([^)]*\) */g, ""); // } else { // graphParam = this.events[mmdd][j][this.flowGraph].replace(/ *\([^)]*\) */g, ""); // } // html += '
' + graphParam + '
'+reporterStr + approverStr+'
'; // htmlValues += (''+graphParam+''); // } else { // if(this.flowGraph == this.FLOW_GRAPH_COMPLETENESS) { // html += '
' + partStatus.replace('status-', '') + '
'+reporterStr + approverStr+'
'; // htmlValues += (''+partStatus.replace('status-', '')+''); // } // if(this.flowGraph == this.FLOW_GRAPH_TIMELINESS) { // html += '
' + lateStatus + '
'+reporterStr + approverStr+'
'; // htmlValues += (''+lateStatus+''); // } // } // htmlValues += (''); // html += '
'; // } // html += '
'; // html += '
'; // } else { // if(!hide) { // html += '
'; // html += '
'+("0" + firstDate.getDate()).slice(-2)+'/'+(firstDate.getMonth()+1)+'
'; // html += '
'; // slice = 2; // } else { // //console.log('eventslice=person', i, slice, i%slice); // if(i%slice === 0) { // html += '
'; // //html += '
'+("0" + i).slice(-2)+' |
'; // html += '
.
'; // html += '
'; // slice+=3; // } // } // } // firstDate.setDate(firstDate.getDate() + 1); // } // html += '
'; // this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear(); // this.csvDataCompliances = csvCols + "\n" + csvValues; // this.htmlDataCompliances = '' + htmlCols + htmlValues + '
'; // inProgress = total - notStarted - approved; // //console.log('progress', total, notStarted, approved) // html = html.replace("DASHBOARD_TOTAL", total+""); // html = html.replace("DASHBOARD_NOT_STARTED", notStarted+""); // html = html.replace("DASHBOARD_APPROVED", approved+""); // html = html.replace("DASHBOARD_IN_PROGRESS", inProgress+""); // html = html.replace("DASHBOARD_IN_TIME", (total - pastDueDate - lateApproved - lateExecuted)+""); // html = html.replace("DASHBOARD_PAST_DUE_DATE", pastDueDate+""); // html = html.replace("DASHBOARD_LATE_EXECUTED", lateExecuted+""); // html = html.replace("DASHBOARD_LATE_APPROVED", lateApproved+""); // this.csvDataStats = 'Period,Total,Not Started,Approved,In Progress,Past Due Date,Late Executed,Late Approved\n'; // this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + inProgress + "," + pastDueDate + "," + lateExecuted + "," + lateApproved; // this.htmlDataStats = ''; // this.htmlDataStats += '
TotalNot StartedApprovedIn ProgressPast Due DateLate ExecutedLate Approved
'+total+''+notStarted+''+approved+''+inProgress+''+pastDueDate+''+lateExecuted+''+lateApproved+'
'; } renderRangeStatistics = (firstDate: Date, count: number, eventsContainer: HTMLDivElement) => { var lastDate = new Date(firstDate.getTime()); lastDate.setDate(lastDate.getDate() + count - 1) const lastDay = count; let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); endDay?.setDate(endDay.getDate() + lastDay); var period = ("0" + (firstDate.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2) + '/' + firstDate.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear(); console.log('rangeperiod', period, lastDay) var html = this.renderStatistics(firstDay, endDay, 0, lastDay, true, 0, (firstDate.getMonth()), period, firstDate, "From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN')); eventsContainer.querySelector('.calendar-right-data')!.innerHTML = html; this.renderButtonRefresh(eventsContainer); const filterButton = eventsContainer.querySelector('#filter-button') as HTMLButtonElement filterButton?.addEventListener('click', () => { const filterList = eventsContainer.querySelector('#filter-list-container') as HTMLDivElement filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none') filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close') const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement filterSubmitButton.addEventListener('click', () => { Util.setFeatures(this.selectedFeatures); this.renderTabs(this.selectedTab) this.processDateSelectionViewer(eventsContainer); }) const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf for (let [i, selectFeature] of selectFeatures.entries()) { selectFeature.addEventListener('click', (ev: any) => { let target = ev.target; let id = target.id; let index = id.split('-')[3]; let selectedFeature = this.getFeatures()[index] if (target.checked) { if (this.selectedFeatures.indexOf(selectedFeature) < 0) { // this.selectedFeatures.push(selectedFeature) this.selectedFeatures = [selectedFeature] } } filterSubmitButton.click(); }) selectFeatureLabels[i].addEventListener('click', () => { selectFeature.checked = !selectFeature.checked selectFeature.click(); }) } }) const buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement buttonRefresh.addEventListener('click', async () => { this.processDateSelectionViewer(eventsContainer) }) let filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).value if (Object.keys(this.statisticsFiltersData).length > 0 && filtercriteria != "location") { this.renderDrilldownListeners(eventsContainer); } } renderDrilldownListeners = async (eventsContainer: HTMLDivElement) => { await new Promise(resolve => setTimeout(resolve, 1000)); console.log('rendering drilldown listeners', this.statisticsFiltersData, this.statisticsMeta) let rows = eventsContainer.querySelectorAll('.tablerow') as NodeListOf let filtercriteria = Object.keys(this.statisticsFiltersData)[0] console.log('rendering statistics filters for criteria', filtercriteria, this.statisticsMeta[filtercriteria]) let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[filtercriteria]) for (let [rowIndex, row] of rows.entries()) { let filterVal = sortedFilters[rowIndex] let filterValue = filterVal.split(';')[1] let filterName = filterVal.split(';')[0].replace(/\([^)]*\)/g, "") let filterNameDiv = row.querySelector('#filter-' + rowIndex) as HTMLDivElement filterNameDiv.addEventListener('click', () => { console.log('clicked name filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "") }) let notStartedDiv = row.querySelector('#filter-not-started-' + rowIndex) as HTMLDivElement notStartedDiv.addEventListener('click', () => { console.log('clicked not started filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "not-started") }) let pendingApprovalDiv = row.querySelector('#filter-pending-approval-' + rowIndex) as HTMLDivElement pendingApprovalDiv.addEventListener('click', () => { console.log('clicked pending approval filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "pending-approval") }) let rejectedDiv = row.querySelector('#filter-rejected-' + rowIndex) as HTMLDivElement rejectedDiv.addEventListener('click', () => { console.log('clicked rejected filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "rejected") }) let approvedDiv = row.querySelector('#filter-approved-' + rowIndex) as HTMLDivElement approvedDiv.addEventListener('click', () => { console.log('clicked approved filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "approved") }) let totalDiv = row.querySelector('#filter-total-' + rowIndex) as HTMLDivElement totalDiv.addEventListener('click', () => { console.log('clicked total filter', rowIndex) console.log('filter', filtercriteria, filterValue, filterName) this.renderStatisticsDetails(filtercriteria, filterValue, filterName) }) } } renderStatisticsFilters = (eventsContainer: HTMLDivElement) => { let selectFilterCriteria = eventsContainer.querySelector('#select-filter-criteria') as HTMLSelectElement let inputLabelFilter = eventsContainer.querySelector('#input-label-filter') as HTMLLabelElement let selectFilterCriteriaMobile = eventsContainer.querySelector('#select-filter-criteria-mobile') as HTMLSelectElement let inputLabelFilterMobile = eventsContainer.querySelector('#input-label-filter-mobile') as HTMLLabelElement selectFilterCriteria.style.display = 'block' inputLabelFilter.style.display = 'block' selectFilterCriteriaMobile.style.display = 'block' inputLabelFilterMobile.style.display = 'block' selectFilterCriteria.innerHTML = "" selectFilterCriteriaMobile.innerHTML = "" let option = new Option() option.value = ""; option.innerHTML = "all" selectFilterCriteria.add(option) option = new Option() option.value = ""; option.innerHTML = "all" selectFilterCriteriaMobile.add(option) let filterscriteria = "" if (Object.keys(this.statisticsFiltersData ?? {}).length > 0) { filterscriteria = Object.keys(this.statisticsFiltersData)[0] } for (let criteria of Object.keys(this.statisticsMeta)) { if (criteria == "subfilters") { continue; } let option = new Option() option.value = criteria; console.log('statistics filters criteria', criteria, filterscriteria, criteria == filterscriteria) option.selected = (criteria == filterscriteria) if (criteria == "reporter" || criteria == "approver" || criteria == "functionhead") { option.innerHTML = "user:" + criteria } else { option.innerHTML = criteria } selectFilterCriteria.add(option) option = new Option() option.value = criteria; option.selected = (criteria == filterscriteria) if (criteria == "reporter" || criteria == "approver" || criteria == "functionhead") { option.innerHTML = "user:" + criteria } else { option.innerHTML = criteria } selectFilterCriteriaMobile.add(option) } let selectFilterCriteriaNew = Util.clearListeners(selectFilterCriteria) selectFilterCriteriaNew.addEventListener('change', (ev: any) => { let target = ev.target as HTMLSelectElement let inputLabelCriteria = eventsContainer.querySelector('#input-label-criteria') as HTMLLabelElement let selectFilterValues = eventsContainer.querySelector('#select-filter-values') as HTMLSelectElement selectFilterValues.value = "" let inputLabelSubfilters = eventsContainer.querySelector('#input-label-subfilter') as HTMLLabelElement let selectSubfilterCriteria = eventsContainer.querySelector('#select-subfilter-criteria') as HTMLSelectElement selectSubfilterCriteria.value = "" selectSubfilterCriteria.length = 0 selectFilterValues.innerHTML = "" let option = new Option() option.value = ""; option.innerHTML = "All"; selectFilterValues.add(option) if (this.statisticsMeta[target.value] != null) { let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[target.value]) selectFilterValues.style.display = 'block' inputLabelCriteria.style.display = 'block' inputLabelCriteria.innerHTML = target.value for (let filter of sortedFilters) { let option = new Option() option.value = filter.split(';')[1]; option.innerHTML = filter.split(';')[0].replace(/\([^)]*\)/g, "") selectFilterValues.add(option) } let selectFilterValuesNew = Util.clearListeners(selectFilterValues) selectFilterValuesNew.addEventListener('change', () => { console.log('changed') this.processDateSelectionViewer(eventsContainer); }) selectSubfilterCriteria.style.display = 'block' inputLabelSubfilters.style.display = 'block' let sortedSubfilters = Util.alphabeticalSort(Object.keys(this.statisticsMeta.subfilters)) if (sortedSubfilters.length > 1) { let option = new Option() option.value = ""; option.innerHTML = "None"; selectSubfilterCriteria.add(option) } for (let subfilter of sortedSubfilters) { let option = new Option() option.value = subfilter; option.innerHTML = subfilter selectSubfilterCriteria.add(option) } let inputLabelSubfiltersValue = eventsContainer.querySelector('#input-label-subfilter-value') as HTMLLabelElement let selectSubfilterValues = eventsContainer.querySelector('#select-subfilter-values') as HTMLSelectElement inputLabelSubfiltersValue.style.display = 'none' selectSubfilterValues.style.display = 'none' let selectSubfilterCriteriaNew = Util.clearListeners(selectSubfilterCriteria) selectSubfilterCriteriaNew.addEventListener('change', () => { this.processDateSelectionViewer(eventsContainer) }) } else { selectFilterValues.style.display = 'none' inputLabelCriteria.style.display = 'none' selectSubfilterCriteria.style.display = 'none' inputLabelSubfilters.style.display = 'none' } this.processDateSelectionViewer(eventsContainer) }) let selectFilterCriteriaMobileNew = Util.clearListeners(selectFilterCriteriaMobile) selectFilterCriteriaMobileNew.addEventListener('change', (ev: any) => { let target = ev.target as HTMLSelectElement let inputLabelCriteriaMobile = eventsContainer.querySelector('#input-label-criteria-mobile') as HTMLLabelElement let selectFilterValuesMobile = eventsContainer.querySelector('#select-filter-values-mobile') as HTMLSelectElement selectFilterValuesMobile.value = "" this.processDateSelectionViewer(eventsContainer) selectFilterValuesMobile.innerHTML = "" let option = new Option() option.value = ""; option.innerHTML = "All"; selectFilterValuesMobile.add(option) if (this.statisticsMeta[target.value] != null) { let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[target.value]) selectFilterValuesMobile.style.display = 'block' inputLabelCriteriaMobile.style.display = 'block' inputLabelCriteriaMobile.innerHTML = target.value for (let filter of sortedFilters) { let option = new Option() option.value = filter.split(';')[1]; option.innerHTML = filter.split(';')[0].replace(/\([^)]*\)/g, "") selectFilterValuesMobile.add(option) } let selectFilterValuesMobileNew = Util.clearListeners(selectFilterValuesMobile) selectFilterValuesMobileNew.addEventListener('change', () => { console.log('changed') this.processDateSelectionViewer(eventsContainer); }) } else { selectFilterValuesMobile.style.display = 'none' inputLabelCriteriaMobile.style.display = 'none' } }); (selectFilterCriteriaNew as HTMLSelectElement).value = filterscriteria; (selectFilterCriteriaMobileNew as HTMLSelectElement).value = filterscriteria; let selectFilterValues = eventsContainer.querySelector('#select-filter-values') as HTMLSelectElement let inputLabelCriteria = eventsContainer.querySelector('#input-label-criteria') as HTMLLabelElement let selectFilterValuesMobile = eventsContainer.querySelector('#select-filter-values-mobile') as HTMLSelectElement let inputLabelCriteriaMobile = eventsContainer.querySelector('#input-label-criteria-mobile') as HTMLLabelElement if (filterscriteria == "") { selectFilterValues.style.display = 'none' inputLabelCriteria.style.display = 'none' selectFilterValuesMobile.style.display = 'none' inputLabelCriteriaMobile.style.display = 'none' } else { selectFilterValues.style.display = 'block' inputLabelCriteria.style.display = 'block' selectFilterValuesMobile.style.display = 'block' inputLabelCriteriaMobile.style.display = 'block' } } renderSelectAllButtons = () => { let selectAllHtml = '
'; selectAllHtml += ''; selectAllHtml += ''; selectAllHtml += '
'; return selectAllHtml } attachSelectAllListeners = (eventsContainer: HTMLDivElement, buttonSelect: NodeListOf) => { const buttonSelectAll = eventsContainer.querySelector('#button-select-all') as HTMLButtonElement const buttonUnselectAll = eventsContainer.querySelector('#button-unselect-all') as HTMLButtonElement if (this.selectedItemIds.length == 0) { buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'none'; } buttonSelectAll?.addEventListener('click', () => { let count = this.selectedItemIds.length for (let checkSelect of buttonSelect) { console.log('select count', count, parseInt(this.selectallblock)) if (count < parseInt(this.selectallblock) && checkSelect.style.display != 'none' && !(checkSelect as HTMLInputElement).checked) { checkSelect.click(); count++; } if (count >= parseInt(this.selectallblock)) { break; } } setTimeout(() => { console.log('Selected All', this.selectedItemIds); }, 1000) }) buttonUnselectAll?.addEventListener('click', () => { for (let checkSelect of buttonSelect) { if ((checkSelect as HTMLInputElement).checked) { checkSelect.click(); } } }) return [buttonSelectAll, buttonUnselectAll] } renderRegisterEvents = (events: any, meta: string = "", searchCountryIndex: number = -1, searchIndex: number = -1, searchVal: string = "") => { var html = ''; this.registerSelectedIds = [] this.csvDataRegisters = ''; let flagUpdateFilters = Object.keys(this.registerFilters).length == 0; const configHome = Util.getProjectConfigHome(); const showUnderstood = (configHome.features == null || (configHome.features.indexOf('hide-understood') < 0)) && (this.myRole == this.TAB_REPORTER) console.log('showunderstood', configHome.features, showUnderstood); html += '
' html += ''; html += '
' html += '
'; for (var i = 0; i < Object.keys(events).length; i++) { const country = Object.keys(events)[i]; html += (''); } html += '
'; html += '
'; if (this._SfRegisterContainer.querySelector('.calendar-right-data-register') == null) { return; } this._SfRegisterContainer.querySelector('.calendar-right-data-register').innerHTML = html; const divRegisterList = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#register-list'); const arrButtons = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.tab-button-country') as NodeListOf; for (i = 0; i < arrButtons.length; i++) { const button = Util.clearListeners(arrButtons[i]); button.addEventListener('click', (e: any) => { const index = e.currentTarget.id.split('-')[3]; this.selectedCountryTab = index this.selectedRegisterIndex = -1 this.renderRegisterEvents(events); }); } this.tablecols = [] let linesCount = 0; let searchFilterString = "" if (this.selectedCountryTab >= 0) { const index = this.selectedCountryTab; //console.log('indexclicked', index); const objCountry = events[Object.keys(events)[index]]; //console.log('indexclicked', objCountry); var html = ''; this.csvDataRegisters += '"ID",'; linesCount = 0 for (var i = 0; i < Object.keys(objCountry).length; i++) { const statute = Object.keys(objCountry)[i]; // this.csvDataRegisters += ('\n\n"' + statute + '"\n\n'); html += ('

' + statute + '

'); // html += '
'; // html += ''; if (i == this.selectedRegisterIndex && meta == "") { console.log('meta', meta, this.selectedCountryTab); for (var k = 0; k < JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols).length; k++) { if (!this.EXCLUDE_COLS_FROM_REGS.includes(JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k].toLowerCase())) { this.csvDataRegisters += ('"' + JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k] + '",'); console.log('loggin col', JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k]) } } this.csvDataRegisters = this.csvDataRegisters.replace(/,\s*$/, ""); this.csvDataRegisters += ('\n'); } else { continue; } html += '
'; html += '
'; html += '
' html += '
'; html += '
' html += '
' html += '' html += ''; if (showUnderstood) { html += ''; } html += '
'; html += '
'; html += '
'; html += ''; html += '
'; html += '
'; html += '
Test String
' html += '
'; html += '
'; let tableBodyHtml = '' for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) { const complianceId = Object.keys(objCountry[statute])[j]; const compliance = objCountry[statute][complianceId]; console.log('hidecompliances', compliance.hide, complianceId); const understood = objCountry[statute][complianceId]['understood'] ?? -1 const data = JSON.parse(compliance.data); const cols = JSON.parse(compliance.cols); if (!this.tablecols.includes('ID') && !this.EXCLUDE_COLS_FROM_REGS.includes('ID')) { this.tablecols.push('ID') } // for (let col of cols) { for (let registercol of this.COLS_REGS) { if (!this.tablecols.includes(registercol.toLowerCase())) { this.tablecols.push(registercol) if (flagUpdateFilters && this.registerFilters[registercol] == null) { this.registerFilters[registercol] = {} } } } // } if (compliance.hide != null && compliance.hide == true) { continue; } linesCount++ let understoodMessage = 'Not reviewed' let understoodMessagePart = 'mark-understood-message' if (showUnderstood) { switch (understood) { case 0: understoodMessage = "Not Understood"; understoodMessagePart = "mark-understood-not-understood" break; case 1: understoodMessage = "Compliance Understood"; understoodMessagePart = "mark-understood-compliance-understood" break; case 2: understoodMessage = "Applicability Not Clear"; understoodMessagePart = "mark-understood-not-applicable" break; case 3: understoodMessage = "Compliance and applicability Understood"; understoodMessagePart = "mark-understood-compliance-applicability-understood" break; case 4: understoodMessage = "Accepted"; understoodMessagePart = "mark-understood-accepted" break; case 5: understoodMessage = "Not For Me"; understoodMessagePart = "mark-understood-not-accepted" break; default: understoodMessage = "Not reviewed"; understoodMessagePart = "mark-understood-not-reviewed" break; } } this.csvDataRegisters += ('"' + complianceId + '",'); // html += '
'; // html += '
'; tableBodyHtml += ''; if (showUnderstood) { tableBodyHtml += (''); } tableBodyHtml += (''; if (flagUpdateFilters) { if (this.registerFilters["ID"] == null) { this.registerFilters["ID"] = {} } this.registerFilters["ID"][complianceId] = true; } tableBodyHtml += (''); // tableBodyHtml += (''); // let tempCount = 0; for (let registercol of this.COLS_REGS) { if (compliance[registercol] != null) { console.log("Fetching from compliance", registercol) let colVal = compliance[registercol] + "" if (Array.isArray(compliance[registercol])) { colVal = "" for (let registerColVal of compliance[registercol]) { colVal += registerColVal.split(';')[0] if (registerColVal.indexOf(compliance[registercol]) < (compliance[registercol].length - 1)) { colVal += ", " } } } console.log('ColVal', compliance[registercol], colVal) tableBodyHtml += (''); this.csvDataRegisters += ('"' + (colVal + "").replace(/"/g, '') + '",'); // this.csvDataRegisters += ('",'); if (flagUpdateFilters) { this.registerFilters[registercol][colVal.toString().trim()] = true; // if (cols[k] == "thirdlineofdefence") { // console.log('thirdlineofdefence', data[k], this.registerFilters[cols[k]], k + 1, cols[k]) // } } // tempCount++; // } else { // console.log('skipping col', cols[k], this.tablecols.indexOf(cols[k]), k + 1) // } } else if (cols.indexOf(registercol) >= 0) { let k = cols.indexOf(registercol) console.log('fetching from cols', registercol, k, data[k]) // for (var k = 0; k < cols.length; k++) { // if (!this.EXCLUDE_COLS_FROM_REGS.includes(cols[k].toLowerCase()) && this.tablecols.indexOf(cols[k]) == tempCount + 1) { // tableBodyHtml += (''); tableBodyHtml += (''); this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",'); // this.csvDataRegisters += ('",'); if (flagUpdateFilters) { this.registerFilters[cols[k]][data[k].toString().trim()] = true; if (cols[k] == "thirdlineofdefence") { console.log('thirdlineofdefence', data[k], this.registerFilters[cols[k]], k + 1, cols[k]) } } // tempCount++; } else { console.log("column not found", registercol, Object.keys(compliance)) } } if (compliance['entities'] != null && Array.isArray(compliance['entities'])) { let entities = ''; for (let entity of compliance['entities']) { entities += entity.split(';')[0].replace(/\([^)]*\)/g, "") + ',' } entities = entities.slice(0, entities.length - 1) tableBodyHtml += (''); if (!this.tablecols.includes('entities') && !this.EXCLUDE_COLS_FROM_REGS.includes('entities')) { this.tablecols.push('entities') } if (flagUpdateFilters) { if (this.registerFilters["entities"] == null) { this.registerFilters["entities"] = {} } this.registerFilters["entities"][entities] = true; } // this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",'); } if (compliance['locations'] != null && Array.isArray(compliance['locations'])) { let locations = ''; for (let location of compliance['locations']) { locations += location.split(';')[0].replace(/\([^)]*\)/g, "") + ',' } locations = locations.slice(0, locations.length - 1) tableBodyHtml += (''); if (!this.tablecols.includes('locations') && !this.EXCLUDE_COLS_FROM_REGS.includes('locations')) { this.tablecols.push('locations') } if (flagUpdateFilters) { if (this.registerFilters["locations"] == null) { this.registerFilters["locations"] = {} } this.registerFilters["locations"][locations] = true; } // this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",'); } this.csvDataRegisters = this.csvDataRegisters.replace(/,\s*$/, ""); this.csvDataRegisters += ('\n'); console.log('enter'); tableBodyHtml += ''; // html += '
= 0) ? " checked" : '') + '>') if (showUnderstood) { tableBodyHtml += '' + understoodMessage + '' } tableBodyHtml += 'ID
' + cols[k] + '
'; // html += '
'; } html += ''; if (showUnderstood) { html += ' 0 && this.registerSelectedIds.length == objCountry[statute].length) ? " checked" : '') + '>' } html += '' searchFilterString = "" for (let colName of this.tablecols) { let allSelected = true; for (let subfilterObj of Object.keys(this.registerFilters[colName] ?? {})) { if (this.registerFilters[colName][subfilterObj] == false) { allSelected = false; for (let subfilterObjVal of Object.keys(this.registerFilters[colName] ?? {})) { if (this.registerFilters[colName][subfilterObjVal] == true) { if (searchFilterString == "") { searchFilterString += subfilterObjVal } else { searchFilterString += ', ' + subfilterObjVal } } } break; } } html += '
' + colName + '
' html += '
' html += `
` for (let [index, filterKey] of Object.keys(this.registerFilters[colName]).entries()) { // console.log('rendering filter', filterKey); html += `
` } html += '
' } html += ''; html += tableBodyHtml; html += ''; html += '
'; // html += ''; // html += ''; } divRegisterList!.innerHTML = html; console.log('registerFilters', flagUpdateFilters, this.registerFilters, html.indexOf('input-select-filter-0-0')); // console.log('csvdataregisters', this.csvDataRegisters); let buttonExportRegister = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-export') as HTMLButtonElement buttonExportRegister?.addEventListener('click', () => { this.exportRegister(); }) if (this.selectedRegisterIndex >= 0) { const divFilterString = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#filter-string') as HTMLDivElement let filterString = "" if (searchVal != "" || searchFilterString != "") { filterString = linesCount + " result(s) when " if (searchVal != "") { filterString += "searched by \"" + searchVal + "\"" if (searchFilterString != "") { filterString += ", filtered by \"" + searchFilterString + "\"" } } else if (searchFilterString != "") { filterString += "filtered by \"" + searchFilterString + "\"" } } if (filterString != "") { filterString += 'delete' } if (divFilterString != null) { divFilterString.innerHTML = filterString } const filterDeleteButton = divFilterString.querySelector('#filter-delete') as HTMLSpanElement; filterDeleteButton?.addEventListener('click', () => { for (let col of Object.keys(this.registerFilters)) { for (let filterVal of Object.keys(this.registerFilters[col])) { this.registerFilters[col][filterVal] = true; } } this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, ""); }) } const arrButtonCountries = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-icon-country') as NodeListOf; for (i = 0; i < arrButtonCountries.length; i++) { const button = Util.clearListeners(arrButtonCountries[i]); button.addEventListener('click', (e: any) => { const index = e.currentTarget.id.split('-')[3]; const i1 = e.currentTarget.id.split('-')[4]; const j1 = e.currentTarget.id.split('-')[5]; //console.log('country clicked', index, i1, j1); const objCountry = events[Object.keys(events)[index]]; const statute = Object.keys(objCountry)[i1]; const complianceId = Object.keys(objCountry[statute])[j1]; const compliance = objCountry[statute][complianceId]; this.renderEventDetailShort(compliance, Object.keys(events)[index], statute); }); } const buttonAcceptAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-accept-all') as HTMLButtonElement buttonAcceptAll?.addEventListener('click', async () => { console.log('accepting', this.registerSelectedIds); let resultMarkUnderstoodBulk = await this.markUnderstoodBulk(this.registerSelectedIds, this.userProfileId, 4); console.log('markUnderstoodBulk result', resultMarkUnderstoodBulk); let objCountry = events[Object.keys(events)[this.selectedCountryTab]]; const statute = Object.keys(objCountry)[this.selectedRegisterIndex]; console.log('objectCountry', Object.keys(objCountry), this.selectedRegisterIndex, statute, objCountry[statute]); for (let complianceId of Object.keys(objCountry[statute])) { console.log('changing understood', complianceId, this.registerSelectedIds.indexOf(complianceId)); if (this.registerSelectedIds.indexOf(complianceId) >= 0) { objCountry[statute][complianceId].understood = 4 } } events[Object.keys(events)[searchCountryIndex]] = objCountry this.registerEvents = events; this.renderRegisterEvents(this.registerEvents, meta, searchCountryIndex, searchIndex, searchVal); }) const arrInputChecks = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-check') as NodeListOf; for (i = 0; i < arrInputChecks.length; i++) { const checkbox = Util.clearListeners(arrInputChecks[i]); checkbox.addEventListener('change', (e: any) => { const index = e.currentTarget.id.split('-')[2]; const i1 = e.currentTarget.id.split('-')[3]; const j1 = e.currentTarget.id.split('-')[4]; //console.log('country clicked', index, i1, j1); const objCountry = events[Object.keys(events)[index]]; const statute = Object.keys(objCountry)[i1]; const complianceId = Object.keys(objCountry[statute])[j1]; // const compliance = objCountry[statute][complianceId]; let tempArr = this.registerSelectedIds if (tempArr.indexOf(complianceId) >= 0) { tempArr.splice(tempArr.indexOf(complianceId), 1); } if (e.currentTarget.checked && this.registerSelectedIds.indexOf(complianceId) < 0) { tempArr.push(complianceId) } this.registerSelectedIds = tempArr console.log('input clicked', statute, i1, j1, complianceId, this.registerSelectedIds) if (!e.currentTarget.checked) { const inputCheckAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-check-all') as HTMLInputElement inputCheckAll.checked = false; } if (this.registerSelectedIds.length > 0) { buttonAcceptAll.classList.remove('hide') } else { buttonAcceptAll.classList.add('hide') } }); } const inputCheckAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-check-all') as HTMLInputElement inputCheckAll?.addEventListener('change', (e) => { if (e.currentTarget == null) { console.log('returning') return; } let arrInputChecksTemp = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-check') as NodeListOf; console.log('input check length', arrInputChecksTemp.length) for (let inputCheck of arrInputChecksTemp) { console.log('checking all', (e.currentTarget as HTMLInputElement).checked) inputCheck.checked = (e.currentTarget as HTMLInputElement).checked inputCheck.dispatchEvent( new Event("change", { bubbles: true }) ); } // if ((e.currentTarget as HTMLInputElement).checked) { // buttonAcceptAll.classList.remove('hide') // } else { // buttonAcceptAll.classList.add('hide') // } }) const arrRegisterStatutes = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.register-statute') as NodeListOf; for (i = 0; i < arrRegisterStatutes.length; i++) { const button = Util.clearListeners(arrRegisterStatutes[i]); button.addEventListener('click', async (e: any) => { // const button = (e.currentTarget as HTMLDivElement); const index = e.currentTarget.id.split('-')[2]; console.log('index', index); if (this.selectedRegisterIndex == index) { this.selectedRegisterIndex = -1; } else { this.selectedRegisterIndex = index; let selectedCountry = Object.keys(events)[this.selectedCountryTab] let selectedStatute = Object.keys(events[selectedCountry])[index] console.log('registerevents', Object.keys(events[selectedCountry][selectedStatute]).length) if (Object.keys(events[selectedCountry][selectedStatute]).length == 0) { let tempRegisters = await this.fetchRegisters("", "", selectedCountry, selectedStatute); this.registerEvents[selectedCountry][selectedStatute] = tempRegisters[selectedCountry][selectedStatute] } } this.renderRegisterEvents(this.registerEvents); // const divBodys = ((this._SfRegisterContainer.querySelector('.calendar-right-data') as HTMLDivElement).querySelectorAll('.register-body-'+ index) as NodeListOf); // for(let divBody of divBodys){ // if(divBody.classList.contains('hide')) { // divBody.classList.remove('hide') // button.setAttribute('part','register-section-title-selected'); // } else { // divBody.classList.add('hide') // button.setAttribute('part','register-section-title-not-selected'); // } // } }); } const arrInputStatuteSearch = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.stream-search-statute') as NodeListOf; for (i = 0; i < arrInputStatuteSearch.length; i++) { const input = Util.clearListeners(arrInputStatuteSearch[i]); input.addEventListener('change', (e: any) => { const searchedValue = e.currentTarget.value; const countryIndex = e.currentTarget.id.split('-')[3]; const searchIndex = e.currentTarget.id.split('-')[4]; // const objCountry = events[Object.keys(events)[countryIndex]] // const statute = Object.keys(objCountry)[searchIndex]; // for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) { // const complianceId = Object.keys(objCountry[statute])[j]; // const compliance = objCountry[statute][complianceId]; // if (JSON.stringify(compliance).toLowerCase().includes(searchedValue.toLowerCase())) { // events[Object.keys(events)[countryIndex]][statute][complianceId].hide = false; // } else { // events[Object.keys(events)[countryIndex]][statute][complianceId].hide = true; // } // } this.processRegisterFilters(events, meta, countryIndex, searchIndex, searchedValue); // this.renderRegisterEvents(events, meta, countryIndex, searchIndex, searchedValue); }) } const arrButtonStatuteSearch = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-search-statute') as NodeListOf; for (i = 0; i < arrButtonStatuteSearch.length; i++) { const button = Util.clearListeners(arrButtonStatuteSearch[i]); button.addEventListener('click', (e: any) => { const inputId = e.currentTarget.id.replace('button-', 'stream-') const searchedValue = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector(inputId).value; const countryIndex = e.currentTarget.id.split('-')[3]; const searchIndex = e.currentTarget.id.split('-')[4]; this.processRegisterFilters(events, meta, countryIndex, searchIndex, searchedValue); }) } const arrButtonDownloadStatute = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-download-statute') as NodeListOf; for (i = 0; i < arrButtonDownloadStatute.length; i++) { const button = Util.clearListeners(arrButtonDownloadStatute[i]); button.addEventListener('click', (e: any) => { const countryIndex = e.currentTarget.id.split('-')[3]; const searchIndex = e.currentTarget.id.split('-')[4]; const objCountry = events[Object.keys(events)[countryIndex]] const statute = Object.keys(objCountry)[searchIndex]; let csvData = '"ID","Country","Entities","Locations","Statute","Reference","Obligation Title"\n'; for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) { const complianceId = Object.keys(objCountry[statute])[j]; const compliance = objCountry[statute][complianceId]; console.log('hidecompliances', compliance.hide, complianceId); if (compliance.hide != null && compliance.hide == true) { continue; } const data = JSON.parse(compliance.data); const cols = JSON.parse(compliance.cols); csvData += ('"' + complianceId + '",'); csvData += ('"' + Object.keys(events)[countryIndex] + '",'); csvData += ('"' + (compliance['entities'] != null && Array.isArray(compliance['entities']) ? compliance['entities'].map((e: string) => e.split(';')[0].replace(/\([^)]*\)/g, "")).join(',') : '') + '",'); csvData += ('"' + (compliance['locations'] != null && Array.isArray(compliance['locations']) ? compliance['locations'].map((e: string) => e.split(';')[0].replace(/\([^)]*\)/g, "")).join(',') : '') + '",'); csvData += ('"' + statute + '",'); csvData += ('"' + data[cols.indexOf('reference')] + '",'); csvData += ('"' + data[cols.indexOf('obligationtitle')] + '"\n'); } console.log('csvData', csvData); const ts = new Date(); let fileName = 'register_' + statute.replace(/ /g, '_').slice(0, 25) + '_' + ts + '.xlsx' Util.downloadExcelFromCSV(csvData, fileName, "Register Export", this.projectName); }) } const arrFilterButtons = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.filter-button') as NodeListOf; for (i = 0; i < arrFilterButtons.length; i++) { const button = Util.clearListeners(arrFilterButtons[i]); button.addEventListener('click', (e: any) => { const index = e.currentTarget.id.split('-')[2]; let filterListContainer = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#filter-list-container-' + index) as HTMLDivElement; if (filterListContainer != null) { if (filterListContainer.classList.contains('hide')) { filterListContainer.classList.remove('hide'); } else { filterListContainer.classList.add('hide'); } } }) } const arrFilterInputs = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-select-filter') as NodeListOf; for (i = 0; i < arrFilterInputs.length; i++) { const input = Util.clearListeners(arrFilterInputs[i]); input.addEventListener('change', (e: any) => { let checked = e.currentTarget.checked; let selectedColIndex = e.currentTarget.id.split('-')[3]; let selectedFilterIndex = e.currentTarget.id.split('-')[4]; let colName = this.tablecols[selectedColIndex] // for (let [colIndex, colName] of Object.keys(this.registerFilters).entries()) { if (colName != null) { for (let [filterIndex, filterKey] of Object.keys(this.registerFilters[colName]).entries()) { if (filterIndex == parseInt(selectedFilterIndex) || selectedFilterIndex == 'all') { this.registerFilters[colName][filterKey] = checked; console.log('registerFilters entry', this.registerFilters[colName][filterKey], colName, filterKey); } if (selectedFilterIndex == 'all') { ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-' + filterIndex) as HTMLInputElement).checked = checked; } } if (!checked) { ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-all') as HTMLInputElement).checked = checked; } if (selectedFilterIndex == 'all') { for (let [filterIndex, filterKey] of Object.keys(this.registerFilters[colName]).entries()) { ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-' + filterIndex) as HTMLInputElement).checked = checked; console.log('Changing Key', filterKey); } } } // } // this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, searchVal); const buttonSubmitFilters = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-submit-filters-' + selectedColIndex) as HTMLButtonElement if (buttonSubmitFilters != null) { buttonSubmitFilters.style.visibility = 'visible' } console.log('registerFilters applying', colName, selectedFilterIndex, this.tablecols) }) } const arrButtonSubmitFilters = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-submit-filters') as NodeListOf; for (i = 0; i < arrButtonSubmitFilters.length; i++) { const button = Util.clearListeners(arrButtonSubmitFilters[i]) button.addEventListener('click', (e: any) => { console.log('registerFilters applied', e.currentTarget.id) this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, searchVal); }) } const registerStatute = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#register-statute-' + this.selectedRegisterIndex) as HTMLDivElement; if (registerStatute != null) { registerStatute.scrollIntoView(); } } else { const index = 0; this.selectedCountryTab = index this.renderRegisterEvents(events, meta); } } processRegisterFilters = (events: any, meta: string = "", searchCountryIndex: number = -1, searchIndex: number = -1, searchVal: string = "") => { if (this.selectedCountryTab >= 0) { const index = this.selectedCountryTab; //console.log('indexclicked', index); const objCountry = events[Object.keys(events)[index]]; for (var i = 0; i < Object.keys(objCountry).length; i++) { const statute = Object.keys(objCountry)[i]; for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) { let flagFilter = true; const complianceId = Object.keys(objCountry[statute])[j]; events[Object.keys(events)[index]][statute][complianceId].hide = false; if (this.registerFilters['ID'][complianceId] == false) { flagFilter = false; events[Object.keys(events)[index]][statute][complianceId].hide = true; } const compliance = objCountry[statute][complianceId]; const data = JSON.parse(compliance.data); const cols = JSON.parse(compliance.cols); for (var k = 0; k < cols.length; k++) { if (this.registerFilters[cols[k]] != null && this.registerFilters[cols[k]][data[k]] == false) { flagFilter = false events[Object.keys(events)[index]][statute][complianceId].hide = true; } else { console.log('notFound', k, this.registerFilters[cols[k]]) } } if (JSON.stringify(compliance).toLowerCase().includes(searchVal.toLowerCase())) { if (flagFilter) { events[Object.keys(events)[index]][statute][complianceId].hide = false; } } else { events[Object.keys(events)[index]][statute][complianceId].hide = true; } } } } this.renderRegisterEvents(events, meta, searchCountryIndex, searchIndex, searchVal); } checkStartDateEarliness = (value: string) => { var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); var startDateChosen = new Date(value); if (startDateChosen.getTime() > startDateCalendar.getTime()) { return true; } else { return false; } } checkEndDateLateness = (value: string) => { var endDateCalendar = new Date(this.calendarStartMM + '/' + (this.calendarStartDD + 10) + '/' + (parseInt(this.calendarStartYYYY) + 1)); var endDateChosen = new Date(value); //console.log('end date calendar', endDateCalendar); //console.log('end date chosen', endDateChosen); if (endDateChosen.getTime() > endDateCalendar.getTime()) { return false; } else { return true; } } attachHandlers = (eventContainer: HTMLDivElement, valueStart: string, valueEnd: string) => { const radioCompleteness = eventContainer.querySelector('#radio-completeness') as HTMLButtonElement; radioCompleteness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderCompletenessGraph(eventContainer); this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioTimeliness = eventContainer.querySelector('#radio-timeliness') as HTMLButtonElement; radioTimeliness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_TIMELINESS; //console.log('setting flow graph to ', this.flowGraph); this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderTimelinessGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioCompliance = eventContainer.querySelector('#radio-compliance') as HTMLButtonElement; radioCompliance?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLIANCE; //console.log('setting flow graph to ', this.flowGraph); this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderComplianceGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioRisk = eventContainer.querySelector('#radio-risk') as HTMLButtonElement; radioRisk?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKAREAS; // console.log('setting flow graph to ', this.flowGraph); this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderRiskGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioFunction = eventContainer.querySelector('#radio-function') as HTMLButtonElement; radioFunction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FUNCTION; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderFunctionGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioRiskSeverity = eventContainer.querySelector('#radio-riskseverity') as HTMLButtonElement; radioRiskSeverity?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderRiskSeverityGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioObligationType = eventContainer.querySelector('#radio-obligationtype') as HTMLButtonElement; radioObligationType?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderObligationTypeGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioJurisdiction = eventContainer.querySelector('#radio-jurisdiction') as HTMLButtonElement; radioJurisdiction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_JURISDICTION; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderJurisdictionGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioFrequency = eventContainer.querySelector('#radio-frequency') as HTMLButtonElement; radioFrequency?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FREQUENCY; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderFrequencyGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioSubcategory = eventContainer.querySelector('#radio-subcategory') as HTMLButtonElement; radioSubcategory?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderSubcategoryGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); const radioLocation = eventContainer.querySelector('#radio-location') as HTMLButtonElement; radioLocation?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_LOCATION; this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer); this.renderLocationGraph(eventContainer) this.attachHandlers(eventContainer, valueStart, valueEnd); }); // const buttonStatusMore = (this._SfCustomContainer as HTMLDivElement).querySelector('#button-status-more'); // buttonStatusMore?.addEventListener('click', () => { // const divStatusList = (this._SfCustomContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf; // for(var i = 0; i < divStatusList.length; i++) { // divStatusList[i].style.display = 'flex'; // } // (buttonStatusMore as HTMLButtonElement).style.display = 'none'; // }); } processFindSelection = async (eventContainer: HTMLDivElement, searchString: string) => { var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1)); const tsStart = new Date(startDateCalendar); const tsEnd = new Date(endDateCalendar); tsStart.setDate(tsStart.getDate() - 2); tsEnd.setDate(tsEnd.getDate() + 2); //console.log('tsstart', tsStart); //console.log('tsend', tsEnd); // await this.fetchUserCalendar_2(tsStart.getMonth() + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), valueEnd.split('-')[1] + "/" + valueEnd.split('-')[2] + "/" + valueEnd.split('-')[0]); await this.fetchAndYearlyRenderUserCalendar_2((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear(), searchString); this.renderRangeEvents(startDateCalendar, ((endDateCalendar.getTime() + 24 * 60 * 60 * 1000) - startDateCalendar.getTime()) / (1000 * 60 * 60 * 24), (this._SfFindContainer as HTMLDivElement)); this.attachHandlers(eventContainer, this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY, this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1)); if (eventContainer.innerHTML.indexOf('myChart') >= 0) { this.renderCompletenessGraph(eventContainer); } } processDateSelection = async (eventContainer: HTMLDivElement, fetchData: boolean = true, showBackgroundButton: boolean = false) => { // var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); // var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1)); var valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value; if (valueStart == "") { valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value; } var valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value; if (valueEnd == "") { valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value; } if (this.mode == "viewer") { valueStart = this.sdate; valueEnd = this.edate; } //console.log('valuestart', valueStart); //console.log('valueend', valueEnd); if (valueStart != "" && valueEnd != "") { this.initCustomRightCol(); // if(!this.checkStartDateEarliness(valueStart)) { // (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen Start Date cannot be earlier than " + startDateCalendar; // return; // } // if(!this.checkEndDateLateness(valueEnd)) { // (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be later than " + endDateCalendar; // return; // } if (new Date(valueStart).getTime() > new Date(valueEnd).getTime()) { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be earlier than chosen Start Date"; return; } if (!this.isLessThanYearApart(valueEnd, valueStart)) { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen time window cannot be greater than 365 days"; return; } const tsStart = new Date(valueStart); const tsEnd = new Date(valueEnd); console.log('start date', tsStart, 'endDate', tsEnd) // tsStart.setDate(tsStart.getDate() - 2); // tsEnd.setDate(tsEnd.getDate() + 2); if (fetchData) { await this.renderWithFeatures((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear()) // await this.fetchAndYearlyRenderUserCalendar_2((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear()); } this.renderRangeEvents(new Date(valueStart), ((new Date(valueEnd).getTime()) - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), (this._SfCustomContainer as HTMLDivElement), showBackgroundButton); } else if (valueStart != "" && valueEnd == "") { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select End Date"; } else if (valueStart == "" && valueEnd != "") { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date"; } else { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date and End Date"; } this.attachHandlers(eventContainer, valueStart, valueEnd); if (eventContainer.innerHTML.indexOf('myChart') >= 0) { this.renderCompletenessGraph(eventContainer); } } isLessThanYearApart = (date1: string | Date, date2: string | Date) => { let d1: Date = new Date(date1); let d2: Date = new Date(date2); // Ensure d1 is always the earlier date if (d1 > d2) { [d1, d2] = [d2, d1]; } // Check if the dates are exactly one year apart (same month & day) if (d2.getFullYear() - d1.getFullYear() === 1 && d2.getMonth() === d1.getMonth() && d2.getDate() === d1.getDate()) { return false; } // Calculate difference in milliseconds const diffInMs = d2.getTime() - d1.getTime(); // One full year in milliseconds, considering leap years const oneYearInMs = 365.25 * 24 * 60 * 60 * 1000; return diffInMs < oneYearInMs; } processDateSelectionViewer = async (eventContainer: HTMLDivElement) => { // var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); // var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1)); var valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value; if (valueStart == "") { valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value; } var valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value; if (valueEnd == "") { valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value; } //console.log('valuestart', valueStart); //console.log('valueend', valueEnd); let filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).value let filtercriterianame = "" if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).selectedIndex] != null) { filtercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).selectedIndex].innerHTML } if (filtercriteria == "") { filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).value if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).selectedIndex] != null) { filtercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).selectedIndex].innerHTML } } let filtervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).value let filtervaluename = "" if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).selectedIndex] != null) { filtervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).selectedIndex].innerHTML } if (filtervalue == "") { filtervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).value if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).selectedIndex] != null) { filtervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).selectedIndex].innerHTML } } if (filtercriteria == "") { this.htmlStatsFilter = "Filters Selected -> All" } else { if (filtervalue == "") { this.htmlStatsFilter = "Filters Selected -> " + Util.titleCase(filtercriterianame) + " -> All" } else { this.htmlStatsFilter = "Filters Selected -> " + Util.titleCase(filtercriterianame) + " -> " + Util.titleCase(filtervaluename) } } let subfiltervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).value let subfiltervaluename = "" if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).selectedIndex] != null) { subfiltervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).selectedIndex].innerHTML } if (subfiltervalue == "") { subfiltervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).value if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).selectedIndex] != null) { subfiltervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).selectedIndex].innerHTML } } console.log('subfiltervalue, subfiltervaluename', subfiltervalue, subfiltervaluename) let subfiltercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).value let subfiltercriterianame = "" if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).selectedIndex] != null) { subfiltercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).selectedIndex].innerHTML } if (subfiltercriteria == "") { subfiltercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).value if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).selectedIndex] != null) { subfiltercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).selectedIndex].innerHTML } } console.log('subfiltercriteria, subfiltercriterianame', subfiltercriteria, subfiltercriterianame) if (valueStart != "" && valueEnd != "") { this.initCustomRightColViewer(); // if(!this.checkStartDateEarliness(valueStart)) { // (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen Start Date cannot be earlier than " + startDateCalendar; // return; // } // if(!this.checkEndDateLateness(valueEnd)) { // (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be later than " + endDateCalendar; // return; // } if (new Date(valueStart).getTime() > new Date(valueEnd).getTime()) { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be earlier than chosen Start Date"; return; } if (!this.isLessThanYearApart(valueEnd, valueStart)) { console.log('dates entered', valueEnd, valueStart); (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen time window cannot be greater than 365 days"; return; } const tsStart = new Date(valueStart); const tsEnd = new Date(valueEnd); // tsStart.setDate(tsStart.getDate() - 2); // tsEnd.setDate(tsEnd.getDate() + 2); //console.log('tsstart', tsStart); //console.log('tsend', tsEnd); let meta = await this.fetchStatistics((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear(), filtercriteria, filtervalue, subfiltercriteria, subfiltervalue); this.renderRangeStatistics(new Date(valueStart), ((new Date(valueEnd).getTime()) - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), (this._SfCustomContainer as HTMLDivElement)); if (meta != null) this.renderStatisticsFilters((this._SfCustomContainer as HTMLDivElement)) } else if (valueStart != "" && valueEnd == "") { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select End Date"; } else if (valueStart == "" && valueEnd != "") { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date"; } else if (valueStart == "" && valueEnd == "") { (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date and End Date"; } this.attachHandlers(eventContainer, valueStart, valueEnd); if (eventContainer.innerHTML.indexOf('myChart') >= 0) { this.renderCompletenessGraph(eventContainer, -1, 2, ["Completeness", "From " + new Date(valueStart).toLocaleDateString('en-IN') + " To " + new Date(valueEnd).toLocaleDateString('en-IN'), this.htmlStatsFilter]); } } initFindRightCol = () => { var html = ""; html += '
'; html += '
'; html += '

Type something and press enter

'; html += '
'; html += '
'; (this._SfFindContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html } initCustomRightCol = () => { var html = ""; html += '
'; html += '
'; html += '

Please select Start Date and End Date

'; html += '
'; html += '
'; (this._SfCustomContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html } initCustomRightColViewer = () => { var html = ""; html += '
'; html += '
'; html += '

Please select Start Date, End Date and Filter Criteria

'; html += '
'; html += '
'; (this._SfCustomContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html } checkAndShowBulk = () => { const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf; var checked = 0; //console.log('checkAndShowBulk', inputArr.length); for (var i = 0; i < inputArr.length; i++) { //console.log(inputArr[i].checked); if (inputArr[i].checked) { checked++; } } //console.log('checkAndShowBulk', checked); if (checked > 1) { return true; } return false; } calculateAndShowSummary = () => { //console.log('showing summary',this.mappedValuesUsers); const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-users'); var mapped = 0; for (var i = 0; i < Object.keys(this.mappedValuesUsers).length; i++) { if (this.mappedValuesUsers[Object.keys(this.mappedValuesUsers)[i]].length > 0) { mapped++; } } (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-summary')!.innerHTML = 'Completed ' + mapped + ' / ' + inputArr.length; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-graph')!.querySelector('.div-graph-pending')! as HTMLDivElement).style.width = ((inputArr.length - mapped) * 100 / (inputArr.length)) + '%'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-graph')!.querySelector('.div-graph-complete')! as HTMLDivElement).style.width = ((mapped) * 100 / (inputArr.length)) + '%'; //console.log('showing summary', mapped, Object.keys(this.mappedValuesUsers).length); if (mapped == inputArr.length) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.style.visibility = 'visible'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.style.visibility = 'hidden'; } } showAllEvents = () => { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = true; // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = false; // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = false; //this.renderMapping(this.unmappedEvents) this.applyFilter(); this.calculateAndShowSummary(); } showMappedEvents = () => { // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = false; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = true; // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = false; //this.renderMapping(this.unmappedEvents) this.applyFilter("mapped") } showUnmappedEvents = () => { // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = false; // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = false; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = true; //this.renderMapping(this.unmappedEvents) this.applyFilter("unmapped") } updateInAllSelections = (param: string, value: any) => { //console.log('updateinallselections', param, value); const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf; const inputDatesArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-dates') as NodeListOf; const divDatesArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-dates') as NodeListOf; const inputTagsArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-tags') as NodeListOf; const divTagsArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-tags') as NodeListOf; const inputUsersArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-users') as NodeListOf; const divUsersArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-users') as NodeListOf; for (var i = 0; i < inputArr.length; i++) { //console.log('updateinallselections', i); if (inputArr[i].checked) { if (param == "duedate") { inputDatesArr[i].value = value; divDatesArr[i].innerHTML = value; this.mappedValuesDueDates[i] = value; } if (param == "tags") { inputTagsArr[i].preselectedValues = JSON.stringify(value); inputTagsArr[i].populatePreselected(); divTagsArr[i].innerHTML = ''; var html = ''; for (var j = 0; j < value.length; j++) { html += value[j]; if (j < (value.length - 1)) { html += ","; } } divTagsArr[i].innerHTML = ''; this.mappedValuesTags[i] = value; } if (param == "users") { // inputUsersArr[i].value = value; // divUsersArr[i].innerHTML = value; // this.mappedValuesUsers[i] = value; inputUsersArr[i].preselectedValues = JSON.stringify(value); inputUsersArr[i].populatePreselected(); divUsersArr[i].innerHTML = ''; var html = ''; for (var j = 0; j < value.length; j++) { html += value[j]; if (j < (value.length - 1)) { html += ","; } } divUsersArr[i].innerHTML = ''; this.mappedValuesUsers[i] = value; this.updateMappingStatus(value, i); this.calculateAndShowSummary(); } } } } updateMappingStatus = (value: any, clickIndex: number) => { //console.log('clickindex', clickIndex); if (value.length > 0) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + clickIndex) as HTMLDivElement).innerHTML = 'check_circle' } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + clickIndex) as HTMLDivElement).innerHTML = 'pending' } } filterEventsInWindow = (tags: Array, _ctx: any, divContainer: HTMLDivElement | null) => { const arrData = []; //console.log('window', this.eventsInWindow, ctx); if (divContainer != null) this.clearGraph(divContainer, 2); if (divContainer != null) this.clearGraph(divContainer, 3); for (var i = 0; i < tags.length; i++) { var countApproved = 0; var countInProgress = 0; var countNotStarted = 0; for (var j = 0; j < this.eventsInWindow.length; j++) { const event = this.eventsInWindow[j]; for (var l = 0; l < event.tags.length; l++) { if ((event.tags[l] + "").toLowerCase().indexOf((tags[i] + "").toLowerCase().split(';')[1]) >= 0) { //console.log('plot approved', event.approved) //if(event.documents == null || event.documents[event.mmdd + '/' + new Date().getFullYear()] == null || JSON.parse(event.documents[event.mmdd + '/' + new Date().getFullYear()]) == null) { if (event.comments == null || event.comments.length === 0) { countNotStarted++; } else if (event.approved == null) { countInProgress++; } else if (!event.approved) { countInProgress++; } else if (event.approved) { countApproved++; } // if(event.documents == null || event.documents.length === 0) { // countNotStarted++; // } else if (event.approved == null) { // countInProgress++; // } else if(!event.approved) { // countInProgress++; // } else if(event.approved) { // countApproved++; // } } } } const arrItem = [countApproved, countInProgress, countNotStarted]; arrData.push(arrItem) } //console.log(arrData); const dataSetApproved = []; const dataSetInProgress = []; const dataSetNotStarted = []; for (i = 0; i < arrData.length; i++) { dataSetApproved.push(arrData[i][0]); dataSetInProgress.push(arrData[i][1]); dataSetNotStarted.push(arrData[i][2]); } //console.log('plotting dataset', dataSetApproved, dataSetInProgress, dataSetNotStarted); const tagsCompressed = []; for (i = 0; i < tags.length; i++) { tagsCompressed.push(this.truncate(tags[i].split(';')[0], 20, false, false)); } if (divContainer != null) { this.clearGraph(divContainer, 1); this.showGraph(divContainer, 4); } if (this.fill == "solid") { const data = { labels: tagsCompressed, datasets: [ { label: 'Approved', data: dataSetApproved, backgroundColor: '#8cd039' }, { label: 'In Progress', data: dataSetInProgress, backgroundColor: '#FFBA49' }, { label: 'Not Started', data: dataSetNotStarted, backgroundColor: '#A4A9AD' } ] } const ctx4 = divContainer?.querySelector('#myChart4') as ChartItem; (divContainer?.querySelector('#myChart4') as HTMLCanvasElement).classList.remove('gone'); if (this.fill == "solid") { this.renderChart4(ctx4, 'bar', data, "Custom Plot") } else { this.renderChart4(ctx4, 'bar', data, "Custom Plot") } } else { const data = { labels: tagsCompressed, datasets: [ { label: 'Approved', data: dataSetApproved, backgroundColor: Util.createDiagonalPattern3('#8cd039') }, { label: 'In Progress', data: dataSetInProgress, backgroundColor: Util.createDiagonalPattern1('#FFBA49') }, { label: 'Not Started', data: dataSetNotStarted, backgroundColor: Util.createDiagonalPattern2('#A4A9AD') } ] } const ctx4 = divContainer?.querySelector('#myChart4') as ChartItem; (divContainer?.querySelector('#myChart4') as HTMLCanvasElement).classList.remove('gone'); if (this.fill == "solid") { this.renderChart4(ctx4, 'bar', data, "Custom Plot") } else { this.renderChart4(ctx4, 'bar', data, "Custom Plot") } // this.renderChart(ctx, 'bar', data, "Custom Plot") } } sleep = (ms: number) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); } hideTabContainers = async () => { (this._SfOnboardingStatutesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingCompliancesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingCountriesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingEntitiesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingLocationsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingFunctionsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingTagsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingReportersContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingApproversContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingAuditorsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingViewersContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingDocsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingDuedatesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingExtensionsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingActivationsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingInvalidationsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingTriggersContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingInternalControlsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingSignoffContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingCalendarContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingSuspenseContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingGovLocationsContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingGovUsersContainer as HTMLDivElement).style.display = 'none'; (this._SfOnboardingStatutesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingCompliancesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingCountriesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingEntitiesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingLocationsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingFunctionsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingTagsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingReportersContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingApproversContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingAuditorsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingViewersContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingDocsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingDuedatesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingExtensionsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingActivationsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingInvalidationsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingTriggersContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingInternalControlsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingCalendarContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingGovLocationsContainer as HTMLDivElement).innerHTML = ''; (this._SfOnboardingGovUsersContainer as HTMLDivElement).innerHTML = ''; } hideRcmTabContainers = async () => { (this._SfRcmComplianceContainer as HTMLDivElement).style.display = 'none'; (this._SfRcmProjectsContainer as HTMLDivElement).style.display = 'none'; (this._SfRcmDateContainer as HTMLDivElement).style.display = 'none'; (this._SfRcmConfirmContainer as HTMLDivElement).style.display = 'none'; (this._SfRcmJobsContainer as HTMLDivElement).style.display = 'none'; (this._SfRcmComplianceContainer as HTMLDivElement).innerHTML = ''; (this._SfRcmProjectsContainer as HTMLDivElement).innerHTML = ''; (this._SfRcmDateContainer as HTMLDivElement).innerHTML = ''; (this._SfRcmConfirmContainer as HTMLDivElement).innerHTML = ''; (this._SfRcmJobsContainer as HTMLDivElement).innerHTML = ''; } loadRcmNotifications = async () => { const notifs = await this.fetchRcmNotifications(this.projectId); //console.log('notifs', notifs); this.renderRcmNotifications(notifs); } loadRcmCompliances = async () => { this.hideRcmTabContainers(); (this._SfRcmComplianceContainer as HTMLDivElement).style.display = 'flex'; const compliances: Array = []; var nextBackwardTokenOrig = ''; const tempCompliances: Array = []; while (true) { const updatedCompliances = await this.fetchUpdatedCompliances(nextBackwardTokenOrig); //console.log('updatedCompliances', updatedCompliances.data.length); const nextBackwardTokenNew = updatedCompliances.nextBackwardToken; //console.log('comparison', nextBackwardTokenNew, nextBackwardTokenOrig); if (nextBackwardTokenOrig == nextBackwardTokenNew) { //console.log('breaking...'); break; } else { nextBackwardTokenOrig = nextBackwardTokenNew; } for (var i = 0; i < updatedCompliances.data.length; i++) { const event = JSON.parse(updatedCompliances.data[i].message); //console.log(i, 'event op', JSON.parse(event.req.body).id); if (event.op == "update") { if (!tempCompliances.includes(JSON.parse(event.req.body).id)) { compliances.push(JSON.parse(event.req.body)); tempCompliances.push(JSON.parse(event.req.body).id); } } } //console.log('compliances', compliances); } if (compliances.length > 0) { this.renderRcmCompliances(compliances); const arrCompliances = []; for (var i = 0; i < compliances.length; i++) { arrCompliances.push(compliances[i].id); } //console.log('compliances 2', arrCompliances); const lockedCompliances = await this.fetchRcmLockedCompliances(arrCompliances); //console.log('compliances 2 locked', lockedCompliances); this.renderRcmLockedCompliances(lockedCompliances); (this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#cb-completed')?.addEventListener('change', (e: any) => { const cb = (e.currentTarget as HTMLInputElement); if (cb.checked) { this.renderRcmUnlockedCompliances(lockedCompliances); } else { this.renderRcmLockedCompliances(lockedCompliances); } }); const arrButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.buttonselect-icon') as NodeListOf; for (i = 0; i < arrButtons.length; i++) { arrButtons[i].addEventListener('click', (e: any) => { const id = e.currentTarget.id.replace('button-', ''); var index = -1; for (var j = 0; j < compliances.length; j++) { if (compliances[j].id == id) { index = j; } } //console.log(id, index, compliances[index]); this.rcmSelectedCompliance = compliances[index]; ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects') as HTMLButtonElement).click(); }) } const arrLockButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.button-lock-icon') as NodeListOf; for (i = 0; i < arrLockButtons.length; i++) { arrLockButtons[i].addEventListener('click', async (e: any) => { const index = e.currentTarget.id.replace('button-lock-', ''); await this.fetchUpdateRcmLock(index); this.loadRcmCompliances(); }) } } } loadRcmProjects = async () => { //console.log('loadRcmProjects'); this.hideRcmTabContainers(); (this._SfRcmProjectsContainer as HTMLDivElement).style.display = 'flex'; this.renderRcmSelectedComplianceInProject((this._SfRcmProjectsContainer as HTMLDivElement)); var mappedProjects; if (this.rcmSelectedCompliance != null) { mappedProjects = await this.fetchMappedProjects(); //console.log('mappedProjects', mappedProjects.data); } const projects = []; if (mappedProjects != null) { for (var i = 0; i < mappedProjects.data.length; i++) { const projectDetail = await this.fetchDetailProject(mappedProjects.data[i]['projectid']['S']); projects.push(projectDetail.data.value); } } this.rcmSelectedProjects = projects; this.renderRcmProjects((this._SfRcmProjectsContainer as HTMLDivElement), this.rcmSelectedProjects); if (this.rcmSelectedProjects != null && this.rcmSelectedProjects.length > 0) { this.renderRcmProceed((this._SfRcmProjectsContainer as HTMLDivElement), (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-date')); } } loadRcmDate = async () => { //console.log('loadRcmDate'); this.hideRcmTabContainers(); (this._SfRcmDateContainer as HTMLDivElement).style.display = 'flex'; this.renderRcmDate((this._SfRcmDateContainer as HTMLDivElement)); this.renderRcmSelectedComplianceInProject((this._SfRcmDateContainer as HTMLDivElement)); //console.log('projects', this.rcmSelectedProjects); this.renderRcmProjects((this._SfRcmDateContainer as HTMLDivElement), this.rcmSelectedProjects); if (this.rcmSelectedProjects != null && this.rcmSelectedProjects.length > 0) { this.renderRcmProceed((this._SfRcmDateContainer as HTMLDivElement), (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-jobs')); } ((this._SfRcmDateContainer as HTMLDivElement).querySelector('#rcm-date') as HTMLInputElement)?.addEventListener('change', (e: any) => { this.rcmSelectedDate = (e.currentTarget as HTMLInputElement).value; //console.log(this.rcmSelectedDate); }); ((this._SfRcmDateContainer as HTMLDivElement).querySelector('#rcm-message') as HTMLInputElement)?.addEventListener('change', (e: any) => { this.rcmSelectedMessage = (e.currentTarget as HTMLInputElement).value; //console.log(this.rcmSelectedMessage); }); } loadRcmJobs = async () => { //console.log('loadRcmJobs'); this.hideRcmTabContainers(); (this._SfRcmJobsContainer as HTMLDivElement).style.display = 'flex'; if (this.rcmSelectedCompliance != null) { const jobs = await this.fetchRcmJobs(this.rcmSelectedCompliance.id); //console.log('jobs', jobs, this.rcmSelectedDate, this.rcmSelectedMessage); if (this.rcmSelectedDate != null && this.rcmSelectedMessage != null) { this.renderRcmJobs((this._SfRcmJobsContainer as HTMLDivElement)); this.renderRcmSelectedDate((this._SfRcmJobsContainer as HTMLDivElement)); } this.renderRcmSelectedComplianceInProject((this._SfRcmJobsContainer as HTMLDivElement)); this.renderRcmProjects((this._SfRcmJobsContainer as HTMLDivElement), this.rcmSelectedProjects); this.renderRcmSelectedJobs((this._SfRcmJobsContainer as HTMLDivElement), jobs); //console.log('projects', this.rcmSelectedProjects); ((this._SfRcmJobsContainer as HTMLDivElement).querySelector('#button-submit') as HTMLButtonElement)?.addEventListener('click', async () => { //console.log(this.rcmSelectedCompliance); await this.fetchCreateRcmJob(this.rcmSelectedCompliance.id, this.rcmSelectedCompliance, this.rcmSelectedDate, this.rcmSelectedMessage, this.rcmSelectedProjects); this.loadRcmJobs(); }); } else { } } loadOnboardingStatutes = async () => { this.hideTabContainers(); (this._SfOnboardingStatutesContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutes(); //console.log('mappedstatutes', mappedStatutes); this.renderOnboardingStatutes(mappedStatutes); } loadOnboardingCompliances = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingCompliancesContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList(); console.log("mapped statutes", mappedStatutes); // const mappedStatutes = await this.fetchMappedStatutes(); // const mappedCompliances = await this.fetchMappedCompliances(); // this.renderOnboardingCompliances(mappedStatutes, mappedCompliances); this.renderOnboardingStatutesDropdownMapping(this._SfOnboardingCompliancesContainer as HTMLDivElement, mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.renderOnboardingCompliances); } loadOnboardingCountries = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingCountriesContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList(); // const countriesJobs = await this.fetchCountriesJobs(); // const mappedCountries = await this.fetchMappedCountries(); // const mappedCompliances = await this.fetchMappedCompliances(); // const mappedStatutes = await this.fetchMappedStatutes(); // //console.log('countriesJobs', countriesJobs); // console.log('mappedCompliances', mappedCompliances); // console.log('mappedCountries', mappedCountries); // this.renderOnboardingCountries(mappedCountries, mappedCompliances, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingCountriesContainer as HTMLDivElement, 'countries-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, () => { return [] }, this.fetchMappedCountries, this.renderOnboardingCountries); } loadOnboardingEntities = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingEntitiesContainer as HTMLDivElement).style.display = 'flex'; // const entitiesJobs = await this.fetchEntitiesJobs(); const mappedStatutes = await this.fetchMappedStatutesList(); // const mappedEntities = await this.fetchMappedEntities(); // const mappedSerializedCountries = await this.fetchMappedSerializedCountries(); // const arrStatuteEntitiesApplicabilities = await this.loadProposedFromStatutes(1); // // const mappedStatutes = await this.fetchMappedStatutes(); //console.log('mappedSerializedCountries', mappedSerializedCountries); //console.log('mappedEntities', mappedEntities); //console.log('entitiesApplicabilities', arrStatuteEntitiesApplicabilities); // this.renderOnboardingEntities(mappedEntities, mappedSerializedCountries, null, arrStatuteEntitiesApplicabilities); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingEntitiesContainer as HTMLDivElement, 'entities-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedCountries, this.fetchMappedEntities, this.renderOnboardingEntities); } loadOnboardingLocations = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingLocationsContainer as HTMLDivElement).style.display = 'flex'; // const locationsJobs = await this.fetchLocationsJobs(); const mappedStatutes = await this.fetchMappedStatutesList(); // const mappedSerializedEntities = await this.fetchMappedSerializedEntities(); // const mappedLocations = await this.fetchMappedLocations(); //console.log('mappedserializedentities', mappedSerializedEntities); //console.log('mappedlocations', mappedLocations); // this.renderOnboardingLocations(mappedLocations, mappedSerializedEntities, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingLocationsContainer as HTMLDivElement, 'locations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedEntities, this.fetchMappedLocations, this.renderOnboardingLocations); } loadOnboardingFunctions = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingFunctionsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const functionsJobs = await this.fetchFunctionJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedFunctions = await this.fetchMappedFunctions(); //console.log('functionjobs', functionsJobs); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedfunctions', mappedFunctions); // this.renderOnboardingFunctions(mappedFunctions, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingFunctionsContainer as HTMLDivElement, 'functions-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedLocations, this.fetchMappedFunctions, this.renderOnboardingFunctions); } loadOnboardingTags = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingTagsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const tagsJobs = await this.fetchTagsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedTags = await this.fetchMappedTags(); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedtags', mappedTags); // this.renderOnboardingTags(mappedTags, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingTagsContainer as HTMLDivElement, 'tags-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedTags, this.renderOnboardingTags); } loadProposedFromStatutes = async (fieldIndex: number) => { const mappedStatutes = await this.fetchMappedStatutes(); //console.log('mappedstatutes', mappedStatutes); const arrStatuteReporters: any = {} for (var i = 0; i < mappedStatutes.data.mappings.mappings.length; i++) { if (arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname] == null) { arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname] = {} } if (arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] == null) { arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] = {} } arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] = mappedStatutes.data.mappings.mappings[i].extraFields[fieldIndex]; } //console.log('mappedstatutesend', arrStatuteReporters); return arrStatuteReporters; } loadOnboardingReporters = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingReportersContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const reportersJobs = await this.fetchReportersJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedReporters = await this.fetchMappedReporters(); // const arrStatuteReporters = await this.loadProposedFromStatutes(1); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedreporters', mappedReporters); //console.log('arrstatutereporters', arrStatuteReporters); // this.renderOnboardingReporters(mappedReporters, mappedSerializedLocations, null, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingReportersContainer as HTMLDivElement, 'reporters-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedReporters, this.renderOnboardingReporters); } loadOnboardingApprovers = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingApproversContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const approversJobs = await this.fetchApproversJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedApprovers = await this.fetchMappedApprovers(); // const arrStatuteApprovers = await this.loadProposedFromStatutes(2); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedapprovers', mappedApprovers); // this.renderOnboardingApprovers(mappedApprovers, mappedSerializedLocations, null, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingApproversContainer as HTMLDivElement, 'approvers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedApprovers, this.renderOnboardingApprovers); } loadOnboardingFunctionHeads = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const functionHeadsJobs = await this.fetchFunctionHeadsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedFunctionHeads = await this.fetchMappedFunctionHeads(); // const arrStatuteFunctionheads = await this.loadProposedFromStatutes(3); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedfunctionheads', mappedFunctionHeads); // this.renderOnboardingFunctionHeads(mappedFunctionHeads, mappedSerializedLocations, null, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingFunctionHeadsContainer as HTMLDivElement, 'functionheads-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedFunctionHeads, this.renderOnboardingFunctionHeads); } loadOnboardingViewers = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingViewersContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const makerViewersJobs = await this.fetchViewersJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedViewers = await this.fetchMappedViewers(); // const arrStatuteViewers = await this.loadProposedFromStatutes(5); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedViewers', mappedViewers); // this.renderOnboardingViewers(mappedViewers, mappedSerializedLocations, null, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingViewersContainer as HTMLDivElement, 'viewers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedViewers, this.renderOnboardingViewers); } loadOnboardingDocs = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingDocsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const docsJobs = await this.fetchDocsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedDocs = await this.fetchMappedDocs(); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedDocs', mappedDocs); // this.renderOnboardingDocs(mappedDocs, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingDocsContainer as HTMLDivElement, 'docs-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedDocs, this.renderOnboardingDocs); } loadOnboardingMakerCheckers = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const makerCheckersJobs = await this.fetchMakerCheckersJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedMakerCheckers = await this.fetchMappedMakerCheckers(); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedMakerCheckers', mappedMakerCheckers); // this.renderOnboardingMakerCheckers(mappedMakerCheckers, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingMakerCheckersContainer as HTMLDivElement, 'makercheckers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedMakerCheckers, this.renderOnboardingMakerCheckers); } loadOnboardingAuditors = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingAuditorsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const auditorsJobs = await this.fetchAuditorsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedAuditors = await this.fetchMappedAuditors(); // const arrStatuteAuditors = await this.loadProposedFromStatutes(4); //console.log('mappedSerializedFunctionheads', mappedSerializedLocations); //console.log('mappedAuditors', mappedAuditors); // this.renderOnboardingAuditors(mappedAuditors, mappedSerializedLocations, null, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingAuditorsContainer as HTMLDivElement, 'auditors-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedAuditors, this.renderOnboardingAuditors); } loadOnboardingDuedates = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingDuedatesContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const duedatesJobs = await this.fetchDueDatesJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedDuedates = await this.fetchMappedDuedates(); //console.log('mappedSerializedLocations', mappedSerializedLocations); //console.log('mappedduedates', mappedDuedates); // this.renderOnboardingDuedates(mappedDuedates, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingDuedatesContainer as HTMLDivElement, 'duedates-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedDuedates, this.renderOnboardingDuedates); } loadOnboardingActivations = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingActivationsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const activationsJobs = await this.fetchExtensionsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedActivations = await this.fetchMappedActivations(); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedactivations', mappedActivations); // this.renderOnboardingActivations(mappedActivations, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingActivationsContainer as HTMLDivElement, 'activations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedActivations, this.renderOnboardingActivations); } loadOnboardingInvalidations = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingInvalidationsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const invalidationsJobs = await this.fetchExtensionsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedInvalidations = await this.fetchMappedInvalidations(); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedinvalidations', mappedInvalidations); // this.renderOnboardingInvalidations(mappedInvalidations, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingInvalidationsContainer as HTMLDivElement, 'invalidations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedInvalidations, this.renderOnboardingInvalidations); } loadOnboardingAlertSchedules = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const alertschedulesJobs = await this.fetchAlertSchedulesJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedAlertSchedules = await this.fetchMappedAlertSchedules(); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedalertschedules', mappedAlertSchedules); // this.renderOnboardingAlertSchedules(mappedAlertSchedules, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingAlertSchedulesContainer as HTMLDivElement, 'alertschedules-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedAlertSchedules, this.renderOnboardingAlertSchedules); } loadOnboardingExtensions = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingExtensionsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const extensionsJobs = await this.fetchExtensionsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedExtensions = await this.fetchMappedExtensions(); //console.log('mappedserializedlocations', mappedSerializedLocations); //console.log('mappedextensions', mappedExtensions); // this.renderOnboardingExtensions(mappedExtensions, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingExtensionsContainer as HTMLDivElement, 'extensions-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedExtensions, this.renderOnboardingExtensions); } loadOnboardingTriggers = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingTriggersContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const triggersJobs = await this.fetchInternalControlsJobs(); // const mappedSerializedAlertSchedules = await this.fetchMappedSerializedAlertSchedules(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedTriggers = await this.fetchMappedTriggers(); //console.log('mappedSerializedAlertSchedules', mappedSerializedAlertSchedules); //console.log('mappedTriggers', mappedTriggers); // this.renderOnboardingTriggers(mappedTriggers, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingTriggersContainer as HTMLDivElement, 'triggers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedTriggers, this.renderOnboardingTriggers); } loadOnboardingInternalControls = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingInternalControlsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const internalcontrolsJobs = await this.fetchInternalControlsJobs(); // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedInternalControls = await this.fetchMappedInternalControls(); //console.log('mappedSerializedlocations', mappedSerializedLocations); //console.log('mappedinternalcontrols', mappedInternalControls); // this.renderOnboardingInternalControls(mappedInternalControls, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingInternalControlsContainer as HTMLDivElement, 'internalcontrols-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedInternalControls, this.renderOnboardingInternalControls); } loadOnboardingReportedLocations = async (selectedStatutes: any = []) => { this.hideTabContainers(); (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).style.display = 'flex'; const mappedStatutes = await this.fetchMappedStatutesList() // const mappedSerializedLocations = await this.fetchMappedSerializedLocations(); // const mappedReportedLocations = await this.fetchMappedReportedLocations(); //console.log('mappedSerializedlocations', mappedSerializedLocations); //console.log('mappedReportedLocations', mappedReportedLocations); // this.renderOnboardingReportedLocations(mappedReportedLocations, mappedSerializedLocations, null); this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingReportedLocationsContainer as HTMLDivElement, 'reportedlocations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedReportedLocations, this.renderOnboardingReportedLocations); } loadOnboardingSignoff = async () => { this.hideTabContainers(); (this._SfOnboardingSignoffContainer as HTMLDivElement).style.display = 'flex'; const signoff = await this.fetchGetSignOff(); this.renderOnboardingSignoff(signoff); //console.log(signoff); } loadOnboardingCalendar = async () => { this.hideTabContainers(); (this._SfOnboardingCalendarContainer as HTMLDivElement).style.display = 'flex'; const calendarJobs = await this.fetchCalendarJobs(); this.renderOnboardingCalendar(calendarJobs); } loadOnboardingSuspense = async (year: string = this.getCurrentYearGeneric()) => { this.hideTabContainers(); (this._SfOnboardingSuspenseContainer as HTMLDivElement).style.display = 'flex'; const mappedSerializedLocations = await this.fetchMappedSerializedFunctions(); const suspenseList = await this.fetchSuspenseList(year); console.log('suspenseList', suspenseList); this.renderOnboardingSuspense(mappedSerializedLocations, suspenseList, year); } loadOnboardingMappedGovLocations = async () => { this.hideTabContainers(); (this._SfOnboardingGovLocationsContainer as HTMLDivElement).style.display = 'flex'; let sourceLocationsArr = await this.fetchLocaltions() let tempArr = [] for (let location of sourceLocationsArr) { let cols = JSON.parse(location.fields.cols[0]) let data = JSON.parse(location.fields.data[0]) let tempObj = { id: location.id, name: data[cols.indexOf("name")] } tempArr.push(tempObj) } sourceLocationsArr = tempArr console.log('locations', sourceLocationsArr) let mappedModules = await this.fetchMappedGovLocationsList(); this.renderOnboardingGovLocations(sourceLocationsArr, mappedModules); } loadOnboardingMappedGovUsers = async () => { this.hideTabContainers(); (this._SfOnboardingGovUsersContainer as HTMLDivElement).style.display = 'flex'; let sourceLocationsArr = await this.fetchLocaltions() let mappedModules = await this.fetchMappedGovLocationsList(); let tempArr = [] for (let location of sourceLocationsArr) { let cols = JSON.parse(location.fields.cols[0]) let data = JSON.parse(location.fields.data[0]) if (mappedModules[location.id] != null) { for (let mappedModule of mappedModules[location.id]) { let tempObj = { id: location.id, name: data[cols.indexOf("name")], moduleid: mappedModule.id, modulename: mappedModule.name } tempArr.push(tempObj) } } } sourceLocationsArr = tempArr console.log('users', sourceLocationsArr) let mappedUsers = await this.fetchMappedGovUsersList(); this.renderOnboardingGovUsers(sourceLocationsArr, mappedUsers); } calculateStartAndEndDateOfPast = (index: number = 0) => { //console.log('calculating start and end of past'); let block = 10; if (index === 0) { block = 10; } else { block = 30; } let nowMonth = new Date().getMonth() + 1; let nowYear = parseInt(this.getCurrentYear(nowMonth + "")); let nowDate = new Date(nowYear, new Date().getMonth(), new Date().getDate()) let currDay = nowDate; for (var i = 0; i < block; i++) { currDay.setDate(currDay.getDate() - 1); } const startDate = ("0" + (currDay.getMonth() + 1)).slice(-2) + "/" + ("0" + (currDay.getDate() + 1)).slice(-2) + "/" + currDay.getFullYear(); // currDay = new Date(); currDay = nowDate; for (var i = 0; i < block; i++) { currDay.setDate(currDay.getDate() + 1); } const endDate = ("0" + (currDay.getMonth() + 1)).slice(-2) + "/" + ("0" + (currDay.getDate() + 1)).slice(-2) + "/" + currDay.getFullYear(); return { startDate: startDate, endDate: endDate } } calculateStartAndEndDateOfThis = (index: number = 0) => { //console.log('calculating start and end of this'); let block = 10; var firstDate = new Date(); firstDate = new Date(parseInt(this.getCurrentYear((firstDate.getMonth() + 1) + "")), firstDate.getMonth(), firstDate.getDate()) if (index === 0) { let nowMonth = new Date().getMonth() + 1; let nowYear = parseInt(this.getCurrentYear(nowMonth + "")); let nowDate = new Date(nowYear, new Date().getMonth(), new Date().getDate()) firstDate = (this.getFirstDateOfWeek(nowDate) as Date); //console.log('this first date', firstDate); block = 10; } if (index === 1) { let nowMonth = new Date().getMonth() + 1; let nowYear = parseInt(this.getCurrentYear(nowMonth + "")); firstDate = new Date(nowYear, new Date().getMonth(), 1); //console.log('this first date', firstDate); block = 35; } let sDate = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate()); let eDate = new Date(sDate.getFullYear(), sDate.getMonth(), sDate.getDate()); for (var i = 0; i < block; i++) { eDate.setDate(eDate.getDate() + 1); } return { startDate: (sDate.getMonth() + 1) + '/' + sDate.getDate() + '/' + sDate.getFullYear(), endDate: (eDate.getMonth() + 1) + '/' + eDate.getDate() + '/' + eDate.getFullYear() } } calculateStartAndEndDateOfUpcoming = (index: number = 0): any => { //console.log('calculating start and end of upcoming'); let nowMonth = new Date().getMonth() + 1; let nowYear = parseInt(this.getCurrentYear(nowMonth + "")); let currDate = new Date(); let sDate = new Date(nowYear, currDate.getMonth(), currDate.getDate()); sDate.setDate(sDate.getDate() - 1); let block = 10; if (index === 0) { block = 8; } else if (index === 1) { block = 32; } else { block = 92; } let eDate = new Date(sDate.getFullYear(), sDate.getMonth(), sDate.getDate()); for (var i = 0; i < block; i++) { eDate.setDate(eDate.getDate() + 1); } return { startDate: (sDate.getMonth() + 1) + '/' + sDate.getDate() + '/' + sDate.getFullYear(), endDate: (eDate.getMonth() + 1) + '/' + eDate.getDate() + '/' + eDate.getFullYear() } } calculateMonthFromIndex = (index: number = 0) => { let month = parseInt(this.calendarStartMM); for (var j = 0; j < 12; j++) { if (j == index) { return month } else { if (month === 12) { month = 1; } else { month++; } } } return 0; } calculateStartAndEndDateOfStream = (index: number = 0) => { let month = parseInt(this.calendarStartMM); //console.log('calculateStartAndEndDateOfStream', index, month); for (var j = 0; j < 12; j++) { if (j === index) { let currentMonth = month; let nowMonth = new Date().getMonth() + 1; //let nowYear = new Date().getFullYear(); let nowYear = parseInt(this.getCurrentYear(nowMonth + "")); let lastMonth = -1; let nextMonth = -1; console.log('calculating startAndEndOfStream', index, nowMonth, currentMonth) let lastMonthsYear = -1; let nextMonthsYear = -1; if (currentMonth === 1) { // Mar lastMonth = 12; nextMonth = 2; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear + 1; } } if (currentMonth === 2) { // Mar lastMonth = 1; nextMonth = 3; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } else { lastMonthsYear = nowYear + 1; nextMonthsYear = nowYear + 1; } } if (currentMonth === 3) { // Mar lastMonth = 2; nextMonth = 4; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } else { lastMonthsYear = nowYear + 1; nextMonthsYear = nowYear + 1; } } if (currentMonth === 4) { // Mar lastMonth = 3; nextMonth = 5; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 5) { // Mar lastMonth = 4; nextMonth = 6; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 6) { // Mar lastMonth = 5; nextMonth = 7; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 7) { // Mar lastMonth = 6; nextMonth = 8; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 8) { // Mar lastMonth = 7; nextMonth = 9; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 9) { // Mar lastMonth = 8; nextMonth = 10; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 10) { // Mar lastMonth = 9; nextMonth = 11; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 11) { // Mar lastMonth = 10; nextMonth = 12; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear - 1; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear; } } if (currentMonth === 12) { // Mar lastMonth = 11; nextMonth = 1; if (nowMonth < parseInt(this.calendarStartMM)) { lastMonthsYear = nowYear - 1; nextMonthsYear = nowYear; } else { lastMonthsYear = nowYear; nextMonthsYear = nowYear + 1; } } // //console.log('calculateStartAndEndDateOfStream', currentMonth, index); // if(currentMonth <= 11 && currentMonth >= 2) { // lastMonth = parseInt(((currentMonth - 1) + "").slice(-2)); // nextMonth = parseInt(((currentMonth + 1) + "").slice(-2)); // } else if(currentMonth === 12) { // lastMonth = 11; // nextMonth = 1; // } else if(currentMonth === 1) { // lastMonth = 12; // nextMonth = 2; // } // //console.log('last month', lastMonth); // //console.log('next month', nextMonth, this.calendarStartMM); // // let lastMonthsYear = -1; // // let nextMonthsYear = -1; // if((lastMonth) >= parseInt(this.calendarStartMM)) { // lastMonthsYear = parseInt(this.calendarStartYYYY); // } else { // if(j === 0) { // lastMonthsYear = parseInt(this.calendarStartYYYY); // } else { // lastMonthsYear = parseInt(this.calendarStartYYYY) + 1; // } // } // if((nextMonth) >= parseInt(this.calendarStartMM)) { // nextMonthsYear = parseInt(this.calendarStartYYYY); // } else { // nextMonthsYear = parseInt(this.calendarStartYYYY) + 1; // } let startDate = ("0" + lastMonth).slice(-2) + "/25/" + lastMonthsYear; let endDate = ("0" + nextMonth).slice(-2) + "/01/" + nextMonthsYear; return { startDate: startDate, endDate: endDate }; } else { if (month === 12) { month = 1; } else { month++; } } } return null; } renderAdhocConfirmed = async (adhocQuestions: any, render: boolean) => { for (var i = 0; i < Object.keys(adhocQuestions).length; i++) { const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement; console.log(radioYes.checked); if (render) { if (!radioYes.checked) { const divQuestion = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-question-' + i) as HTMLDivElement); if (divQuestion != null) { console.log('divQuestion', divQuestion, render, divQuestion.classList); if (!divQuestion.classList.contains('hide')) { divQuestion.classList.add('hide'); } } } } else { if (!radioYes.checked) { const divQuestion = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-question-' + i) as HTMLDivElement); if (divQuestion != null) { console.log('divQuestion', divQuestion, render, divQuestion.classList); if (divQuestion.classList.contains('hide')) { divQuestion.classList.remove('hide'); } } } } } } renderAdhoc = async (flagFetch: boolean = true, searchString: string = '', adhocQuestionsFetched: any = {}) => { var html = ''; html += '
'; html += 'Loading ...'; html += '
'; (this._SfAdhocContainer as HTMLDivElement).innerHTML = html; const adhocQuestions: any = adhocQuestionsFetched; if (flagFetch) { const resultAdhoc = await this.fetchAdhoc(); console.log('resultAdhoc', resultAdhoc); if (resultAdhoc.data?.events?.['00/00'] != null) { for (var i = 0; i < resultAdhoc.data.events["00/00"].length; i++) { if (resultAdhoc.data.events["00/00"][i]['adhocquestion'] != null && resultAdhoc.data.events["00/00"][i]['adhocquestion'].length > 0) { if (adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()] == null) { adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()] = []; } adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()].push(resultAdhoc.data.events["00/00"][i]); } } } else { await this.uploadAdHocCheckTime(false); } console.log('adHocQuestions', adhocQuestions); } // console.log('adhocQuestions', adhocQuestions); html = ''; html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; const arrAllTriggerIds: any = {}; for (i = 0; i < Object.keys(adhocQuestions).length; i++) { // const firstCompliance = adhocQuestions[Object.keys(adhocQuestions)[i]][0]; // console.log('triggers', i, '=' + firstCompliance.triggers + '='); // const firstComplianceTriggers = firstCompliance.triggers == null ? [] : firstCompliance.triggers == "" ? [] : JSON.parse(firstCompliance.triggers); const flagHide = !flagFetch && searchString.trim() !== '' && Object.keys(adhocQuestions)[i].toLowerCase().indexOf(searchString.trim().toLowerCase()) === -1; // console.log('Filter', flagHide, searchString, Object.keys(adhocQuestions)[i].toLowerCase().indexOf(searchString.toLowerCase())); html += '
'; html += '

' + Object.keys(adhocQuestions)[i] + '

'; html += '
'; html += '
' html += ''; html += ''; html += ''; html += '' for (var j = 0; j < adhocQuestions[Object.keys(adhocQuestions)[i]].length; j++) { const compliance = adhocQuestions[Object.keys(adhocQuestions)[i]][j]; html += ''; html += (''); html += '' } html += '
ComplianceIdLocationObligation TitleObligation
' html += '
' html += '
'; html += '  '; html += '
'; html += '
' html += ('
'); html += ('
'); html += '
' html += ('
'); html += ('
'); if (this.locationId != "") { html += (''); } else if (this.entityId != "") { html += (''); } else if (this.countryId != "") { html += (''); } html += '
'; let arrTriggerIds: Array = []; let arrTriggerRemarks: Array = []; let arrTriggerStatutes: any = {}; let arrTriggers: any = {}; for (var j = 0; j < adhocQuestions[Object.keys(adhocQuestions)[i]].length; j++) { const compliance = adhocQuestions[Object.keys(adhocQuestions)[i]][j]; const locationname = compliance.locationname; const statutename = compliance.statute[0]; const complianceTriggers = compliance.triggers == null ? [] : compliance.triggers == "" ? [] : JSON.parse(compliance.triggers); console.log('complianceTriggers', complianceTriggers, statutename); for (var k = 0; k < complianceTriggers.length; k++) { const triggerDate = complianceTriggers[k].triggerDate; const occurrenceDate = complianceTriggers[k].occurrenceDate; const complianceId = complianceTriggers[k].complianceId; const triggerId = complianceTriggers[k].triggerId; const remarks = complianceTriggers[k].remarks; const triggerdd = triggerDate.split('/')[0]; const triggermm = triggerDate.split('/')[1]; const triggeryyyy = triggerDate.split('/')[2]; const tsTrigger = (new Date(triggeryyyy, parseInt(triggermm) - 1, triggerdd) + "").split(" "); const dateTrigger = (tsTrigger[0] + " " + tsTrigger[1] + " " + tsTrigger[2] + " " + tsTrigger[3]); const occurrencedd = occurrenceDate.split('/')[0]; const occurrencemm = occurrenceDate.split('/')[1]; const occurrenceyyyy = occurrenceDate.split('/')[2]; const tsOccurrence = (new Date(occurrenceyyyy, parseInt(occurrencemm) - 1, occurrencedd) + "").split(" "); const dateOccurrence = (tsOccurrence[0] + " " + tsOccurrence[1] + " " + tsOccurrence[2] + " " + tsOccurrence[3]); console.log('triggerId', triggerId); if (!arrTriggerIds.includes(triggerId)) { arrTriggerIds.push(triggerId); arrTriggerRemarks.push(remarks) } if (arrTriggers[triggerId] == null) { arrTriggers[triggerId] = {}; } if (arrTriggerStatutes[triggerId] == null) { arrTriggerStatutes[triggerId] = []; } if (arrTriggerStatutes[triggerId].indexOf(statutename.trim()) === -1) { arrTriggerStatutes[triggerId].push(statutename.trim()); } if (arrTriggers[triggerId][dateTrigger] == null) { arrTriggers[triggerId][dateTrigger] = {}; } if (arrTriggers[triggerId][dateTrigger][locationname] == null) { arrTriggers[triggerId][dateTrigger][locationname] = {}; } if (arrTriggers[triggerId][dateTrigger][locationname][complianceId] == null) { arrTriggers[triggerId][dateTrigger][locationname][complianceId] = dateOccurrence; } } } arrAllTriggerIds[i] = arrTriggerIds; if (arrTriggerIds.length > 0) { html += '
'; html += ('
'); html += '
'; } html += '
'; for (var j = 0; j < arrTriggerIds.length; j++) { html += '
' html += '' + (j + 1) + ''; html += '
'; html += '
' html += '
' html += '
Trigger Id:
     '; html += '
' for (var k = 0; k < Object.keys(arrTriggers[arrTriggerIds[j]]).length; k++) { const dateTrigger = Object.keys(arrTriggers[arrTriggerIds[j]])[k]; for (var l = 0; l < Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger]).length; l++) { const locationTrigger = Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger])[l]; for (var m = 0; m < Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger]).length; m++) { const complianceTrigger = Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger])[m]; const dateOccurrence = arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger][complianceTrigger]; html += '
'; html += '
Occurred on  ' + dateOccurrence + ',  Triggered on  ' + dateTrigger + '  at  ' + locationTrigger.replace(/ *\([^)]*\) */g, "").trim() + '  for Compliance Id  
'; html += '
'; } } } } html += '
'; html += '
'; } html += '
'; if (this.flagAdhoc) { html += '
' html += 'Please review the questions. Click yes to trigger associated ad hoc compliances wherever applicable. Click the finished button after you have completed the review.' html += '' html += '
' // html += ''; } else { html += ''; } html += '' html += '' html += '
'; if (Object.keys(adhocQuestions).length === 0) { html = '
No records found
'; } (this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-list')!.innerHTML = html; let triggerDeleteStartButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-start') as NodeListOf); for (let triggerDeleteStartButton of triggerDeleteStartButtons) { triggerDeleteStartButton.addEventListener('click', (e: any) => { const _id = e.currentTarget.id; const triggerid = _id.split('-')[3]; ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-start-' + triggerid) as HTMLButtonElement).classList.add('hide'); ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-cancel-' + triggerid) as HTMLButtonElement).classList.remove('hide'); ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-confirm-' + triggerid) as HTMLButtonElement).classList.remove('hide'); }) } let triggerDeleteCancelButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-cancel') as NodeListOf); for (let triggerDeleteCancelButton of triggerDeleteCancelButtons) { triggerDeleteCancelButton.addEventListener('click', (e: any) => { const _id = e.currentTarget.id; const triggerid = _id.split('-')[3]; ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-start-' + triggerid) as HTMLButtonElement).classList.remove('hide'); ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-cancel-' + triggerid) as HTMLButtonElement).classList.add('hide'); ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-confirm-' + triggerid) as HTMLButtonElement).classList.add('hide'); }) } let triggerDeleteConfirmButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-confirm') as NodeListOf); for (let triggerDeleteConfirmButton of triggerDeleteConfirmButtons) { triggerDeleteConfirmButton.addEventListener('click', async (e: any) => { const _id = e.currentTarget.id; const triggerid = _id.split('-')[3]; const statutes = e.currentTarget.getAttribute('statutes') console.log('statutes', statutes) const untrigger = { projectid: this.projectId, triggerid: triggerid, statutes: statutes.split(';') } console.log('untrigger', untrigger); await this.uploadUnTriggerEvent(untrigger) // this.renderAdhoc(); }) } for (i = 0; i < Object.keys(adhocQuestions).length; i++) { const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement; radioYes.addEventListener('click', (e: any) => { const id = e.currentTarget.id.split('-')[2]; const chooseDate = (this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-' + id) as HTMLDivElement; console.log(chooseDate); chooseDate.classList.remove('hide'); }) const radioNo = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-no-' + i) as HTMLInputElement; radioNo.addEventListener('click', (e: any) => { const id = e.currentTarget.id.split('-')[2]; const chooseDate = (this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-' + id) as HTMLDivElement; console.log(chooseDate); chooseDate.classList.add('hide'); }) } for (i = 0; i < Object.keys(adhocQuestions).length; i++) { const complianceCount = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-count-' + i) as HTMLDivElement; complianceCount.addEventListener('click', (e: any) => { const index = e.currentTarget.id.split('-')[2]; console.log(index); const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-list-body-' + index) as HTMLDivElement; if (body.classList.contains('hide')) { body.classList.remove('hide'); e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-selected') } else { body.classList.add('hide'); e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-not-selected') } }); } for (i = 0; i < Object.keys(adhocQuestions).length; i++) { const previousTriggerCount = (this._SfAdhocContainer as HTMLDivElement).querySelector('#previous-triggers-' + i) as HTMLDivElement; if (previousTriggerCount != null) { previousTriggerCount.addEventListener('click', (e: any) => { const index = e.currentTarget.id.split('-')[2]; console.log(index); const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#previous-triggers-body-' + index) as HTMLDivElement; if (body.classList.contains('hide')) { body.classList.remove('hide'); e.currentTarget.setAttribute('part', 'adhoc-previous-triggers-count-selected') } else { body.classList.add('hide'); e.currentTarget.setAttribute('part', 'adhoc-previous-triggers-count-not-selected') } }); } // complianceCount.addEventListener('click', (e:any) => { // const index = e.currentTarget.id.split('-')[2]; // console.log(index); // const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-list-body-'+index) as HTMLDivElement; // if(body.classList.contains('hide')) { // body.classList.remove('hide'); // e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-selected') // } else { // body.classList.add('hide'); // e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-not-selected') // } // }); } const onSearch = Util.debounce((query: string) => { this.renderAdhoc(false, query, adhocQuestions); }, 200); let adHocQuestionsSearch = (this._SfAdhocContainer as HTMLDivElement).querySelector('#ad-hoc-search') as HTMLInputElement; if (adHocQuestionsSearch != null) { adHocQuestionsSearch.addEventListener('keyup', async (ev: any) => { //console.log('ev', ev.key); if (ev.key == "Enter") { const searchString = ev.currentTarget.value; console.log('input event', searchString) onSearch(searchString); } }); } const submitButtonCancel = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit-cancel') as HTMLButtonElement; if (submitButtonCancel != null) { submitButtonCancel.addEventListener('click', () => { if (submitButtonConfirm != null && !submitButtonConfirm.classList.contains('hide')) { submitButtonConfirm.classList.add('hide'); } if (submitButtonCancel != null && !submitButtonCancel.classList.contains('hide')) { submitButtonCancel.classList.add('hide'); } if (submitButton != null && submitButton.classList.contains('hide')) { submitButton.classList.remove('hide'); } this.renderAdhocConfirmed(adhocQuestions, false); }) } const submitButtonConfirm = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit-confirm') as HTMLButtonElement; if (submitButtonConfirm != null) { submitButtonConfirm.addEventListener('click', async () => { let triggeredCompliances: any = []; var submitFlag = true; for (i = 0; i < Object.keys(adhocQuestions).length; i++) { const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement; console.log(radioYes.checked); if (radioYes.checked) { const compliances = adhocQuestions[Object.keys(adhocQuestions)[i]]; // const chooseDate = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-'+i) as HTMLDivElement) const chooseDateInput = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#date-of-occurrence-' + i) as HTMLInputElement); const remarksInput = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#remarks-' + i) as HTMLTextAreaElement); const dateOfTrigger = (new Date().getDate() + "").slice(-2) + "/" + ((new Date().getMonth() + 1) + "").slice(-2) + "/" + (new Date().getFullYear() + ""); const dateOfOccurrence = chooseDateInput.value; const remarks = remarksInput.value; if (dateOfOccurrence == "") { chooseDateInput.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important'); submitFlag = false; } // if (remarks == "") { // remarksInput.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important'); // submitFlag = false; // } if (submitFlag) { triggeredCompliances.push({ compliances: compliances, dateOfOccurrence: dateOfOccurrence, dateOfTrigger: dateOfTrigger, locationId: this.locationId, entityId: this.entityId, countryId: this.countryId, tagId: this.tagId, remarks: remarks, }); chooseDateInput.setAttribute('style', 'border:'); } else { break; } } } console.log('triggeredCompliances', triggeredCompliances); if (submitFlag) { await this.uploadTriggerEvent(triggeredCompliances); this.renderAdhoc(); } }); } const submitButton = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit') as HTMLButtonElement; if (submitButton != null) { submitButton.addEventListener('click', async () => { if (submitButtonConfirm != null && submitButtonConfirm.classList.contains('hide')) { submitButtonConfirm.classList.remove('hide'); } if (submitButtonCancel != null && submitButtonCancel.classList.contains('hide')) { submitButtonCancel.classList.remove('hide'); } if (submitButton != null && !submitButton.classList.contains('hide')) { submitButton.classList.add('hide'); } this.renderAdhocConfirmed(adhocQuestions, true); }); } const markReviewedButton = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-mark-reviewed') as HTMLButtonElement; if (markReviewedButton != null) { markReviewedButton.addEventListener('click', async () => { await this.uploadAdHocCheckTime() }) } } renderRegister = async () => { var html = ''; html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '
' html += '' html += '
'; console.log('showRegisterExport', this.showRegisterExport); // if (this.showRegisterExport && this.showRegisterExport == "true") { // html += '
'; // html += '

' // html += ''; // html += '
'; // html += ''; // html += '
'; // } html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; (this._SfRegisterContainer as HTMLDivElement).innerHTML = html; this.selectedCountryIndex = 0; this.selectedRegisterIndex = -1; this.registerEvents = await this.fetchRegisters("", "yes"); this.renderRegisterEvents(this.registerEvents, "yes"); (this._SfRegisterContainer as HTMLDivElement).querySelector('#stream-search')?.addEventListener('keyup', async (ev: any) => { //console.log('ev', ev.key); if (ev.key == "Enter") { const searchString = ((this._SfRegisterContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.registerEvents = await this.fetchRegisters(searchString); this.renderRegisterEvents(this.registerEvents); } }); (this._SfRegisterContainer as HTMLDivElement).querySelector('#button-download')?.addEventListener('click', async () => { let tempEvents = await this.fetchRegisters("", "all", "", "") this.renderRegisterEvents(tempEvents, "all"); const ts = new Date(); console.log(this.csvDataRegisters); const blob = new Blob([this.csvDataRegisters], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + ts + '.csv'); a.click() }); } renderFind = () => { //console.log('renderingFind'); this.clearGraphData(); console.log('this.clearSelectedGraphParam(); 3'); this.clearSelectedGraphParam(); this.clearSelectedLegend(); var html = ''; html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; (this._SfFindContainer as HTMLDivElement).innerHTML = html; this.initFindRightCol(); (this._SfFindContainer as HTMLDivElement).querySelector('#stream-search')?.addEventListener('keyup', (ev: any) => { //console.log('key', ev.key); if (ev.key == "Enter") { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } }); } renderCustom = () => { this.clearGraphData(); console.log('this.clearSelectedGraphParam(); 4'); this.clearSelectedGraphParam(); this.clearSelectedLegend(); var html = ''; html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '
'; html += '
{ //console.log('start-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date')?.addEventListener('change', (_ev: any) => { //console.log('end-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile')?.addEventListener('change', (_ev: any) => { //console.log('start-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile')?.addEventListener('change', (_ev: any) => { //console.log('end-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date-mobile')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year-mobile')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; let year = parseInt(this.calendarStartYYYY); let month = parseInt(this.calendarStartMM) - 1; if (month === 0) { month = 12; year -= 1; } // Pad month const monthStr = month < 10 ? '0' + month : '' + month; // Determine last day of month (safe) const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month` const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay; const finalDate = `${year + 1}-${monthStr}-${dayStr}`; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; let year = parseInt(this.calendarStartYYYY); let month = parseInt(this.calendarStartMM) - 1; if (month === 0) { month = 12; year -= 1; } // Pad month const monthStr = month < 10 ? '0' + month : '' + month; // Determine last day of month (safe) const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month` const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay; const finalDate = `${year + 1}-${monthStr}-${dayStr}`; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter-mobile')?.addEventListener('click', () => { const mmCurrent = ((new Date().getMonth() + 1)); let startDate: string = ""; let endDate: string = ""; if (mmCurrent >= 4 && mmCurrent <= 6) { startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; } else if (mmCurrent >= 6 && mmCurrent <= 9) { startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; } else if (mmCurrent >= 9 && mmCurrent <= 12) { startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; } else { startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01"; } ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter')?.addEventListener('click', () => { const mmCurrent = ((new Date().getMonth() + 1)); let startDate: string = ""; let endDate: string = ""; if (mmCurrent >= 4 && mmCurrent <= 6) { startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; } else if (mmCurrent >= 6 && mmCurrent <= 9) { startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; } else if (mmCurrent >= 9 && mmCurrent <= 12) { startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; } else { startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01"; } ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate; this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); }); if (this.selectedFeatures.indexOf('contracts') >= 0 && this.mode != "viewer") { ((this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year') as HTMLButtonElement).click(); } // for(var i = 0; i < 3; i++) { // (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', (ev: any)=> { // const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]); // //console.log('clicked ', target); // this.renderPast(target); // }) // } } renderCustomViewer = () => { this.clearGraphData(); this.clearSelectedGraphParam(); this.clearSelectedLegend(); var html = ''; html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '
' html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; console.log('html', html); (this._SfCustomContainer as HTMLDivElement).innerHTML = html; this.initCustomRightColViewer(); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date')?.addEventListener('change', (_ev: any) => { //console.log('start-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date')?.addEventListener('change', (_ev: any) => { //console.log('end-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile')?.addEventListener('change', (_ev: any) => { //console.log('start-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile')?.addEventListener('change', (_ev: any) => { //console.log('end-date', ev); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2); ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2); this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date-mobile')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year-mobile')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; let year = parseInt(this.calendarStartYYYY); let month = parseInt(this.calendarStartMM) - 1; if (month === 0) { month = 12; year -= 1; } // Pad month const monthStr = month < 10 ? '0' + month : '' + month; // Determine last day of month (safe) const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month` const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay; const finalDate = `${year + 1}-${monthStr}-${dayStr}`; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year')?.addEventListener('click', () => { ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD; let year = parseInt(this.calendarStartYYYY); let month = parseInt(this.calendarStartMM) - 1; if (month === 0) { month = 12; year -= 1; } // Pad month const monthStr = month < 10 ? '0' + month : '' + month; // Determine last day of month (safe) const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month` const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay; const finalDate = `${year + 1}-${monthStr}-${dayStr}`; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter-mobile')?.addEventListener('click', () => { const mmCurrent = ((new Date().getMonth() + 1)); let startDate: string = ""; let endDate: string = ""; if (mmCurrent >= 4 && mmCurrent <= 6) { startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; } else if (mmCurrent >= 6 && mmCurrent <= 9) { startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; } else if (mmCurrent >= 9 && mmCurrent <= 12) { startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; } else { startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01"; } ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter')?.addEventListener('click', () => { const mmCurrent = ((new Date().getMonth() + 1)); let startDate: string = ""; let endDate: string = ""; if (mmCurrent >= 4 && mmCurrent <= 6) { startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; } else if (mmCurrent >= 6 && mmCurrent <= 9) { startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01"; endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; } else if (mmCurrent >= 9 && mmCurrent <= 12) { startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; } else { startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01"; endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01"; } ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate; ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate; this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement)); }); let selectFilterCriteria = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement selectFilterCriteria.style.display = 'none' let selectFilterValues = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement selectFilterValues.style.display = 'none' let inputLabelFilter = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-filter') as HTMLLabelElement inputLabelFilter.style.display = 'none'; let selectSubfilterCriteria = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement selectSubfilterCriteria.style.display = 'none' let selectSubfilterValues = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement selectSubfilterValues.style.display = 'none' let inputLabelSubfilter = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-subfilter') as HTMLLabelElement inputLabelSubfilter.style.display = 'none'; let selectFilterCriteriaMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement selectFilterCriteriaMobile.style.display = 'none' let selectFilterValuesMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement selectFilterValuesMobile.style.display = 'none' let inputLabelFilterMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-filter-mobile') as HTMLLabelElement inputLabelFilterMobile.style.display = 'none'; let selectSubfilterCriteriaMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement selectSubfilterCriteriaMobile.style.display = 'none' let selectSubfilterValuesMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement selectSubfilterValuesMobile.style.display = 'none' let inputLabelSubfilterMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-subfilter-mobile') as HTMLLabelElement inputLabelSubfilterMobile.style.display = 'none'; ((this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date') as HTMLButtonElement).click(); } renderThis = (index: number = 1, showGraph: boolean = true, showBackgroundButton: boolean) => { // this.clearGraphData(); // this.clearSelectedGraphParam(); // this.clearSelectedLegend(); this.streamIndex = index; var html = ''; html += '
'; var part = ""; if (index === 0) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
Current Week
'; part = ""; if (index === 1) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
Current Month
'; html += '
'; html += '
'; html += '
'; var part = ""; if (index === 0) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
Week
'; part = ""; if (index === 1) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
Month
'; html += '
'; html += '
'; // var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); var startDate = new Date(); html += this.renderThisEvents(index, startDate, showGraph, showBackgroundButton); startDate.setDate(startDate.getDate() + 1); html += '
'; html += this.renderSelectAllButtons(); html += '
'; (this._SfThisContainer as HTMLDivElement).innerHTML = html; this.renderButtonRefresh((this._SfThisContainer as HTMLDivElement)); let backgroundProcessButton = (this._SfThisContainer as HTMLDivElement).querySelector('#button-background-process') as HTMLButtonElement if (backgroundProcessButton != null) { backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none' console.log('backgroundprocessbutton', backgroundProcessButton.style.display); if (showBackgroundButton) { backgroundProcessButton.addEventListener('click', () => { console.log('bulk-progress clicked') let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement bulkLoader.scrollIntoView(); }) } } const filterButton = (this._SfThisContainer as HTMLDivElement).querySelector('#filter-button') as HTMLButtonElement filterButton?.addEventListener('click', () => { const filterList = (this._SfThisContainer as HTMLDivElement).querySelector('#filter-list-container') as HTMLDivElement filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none') filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close') const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement filterSubmitButton.addEventListener('click', async () => { Util.setFeatures(this.selectedFeatures); const dateResult = this.calculateStartAndEndDateOfStream(index); console.log('dateresult', dateResult, index); console.log('selectedfeatures', this.selectedFeatures); this.currentColumnIndex = index + ""; if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate); } this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(index, showGraph, showBackgroundButton); }) // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement // selectFeatureAll.addEventListener('click',async(ev: any) => { // let target = ev.target; // if(target.checked){ // for(let feature of this.getFeatures()){ // if(this.selectedFeatures.indexOf(feature) < 0){ // this.selectedFeatures.push(feature); // } // } // }else{ // this.selectedFeatures = [] // } // const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf // for(let selectFeature of selectFeatures){ // let id = selectFeature.id; // let i = id.split('-')[3]; // let selectedFeature = this.getFeatures()[parseInt(i)] // selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0 // } // filterSubmitButton.style.visibility = 'visible' // }) // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement // selectFeatureAllLabel.addEventListener('click',()=>{ // selectFeatureAll.checked = !selectFeatureAll.checked // selectFeatureAll.click(); // }) const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf for (let [i, selectFeature] of selectFeatures.entries()) { selectFeature.addEventListener('click', async (ev: any) => { let target = ev.target; let id = target.id; let i = id.split('-')[3]; let selectedFeature = this.getFeatures()[i] if (target.checked) { if (this.selectedFeatures.indexOf(selectedFeature) < 0) { // this.selectedFeatures.push(selectedFeature) this.selectedFeatures = [selectedFeature] } } // else{ // // selectFeatureAll.checked = false; // if(this.selectedFeatures.indexOf(selectedFeature) >= 0){ // this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1); // } // } // filterSubmitButton.style.visibility = 'visible' filterSubmitButton.click(); }) selectFeatureLabels[i].addEventListener('click', () => { selectFeature.checked = !selectFeature.checked selectFeature.click(); }) } }) const radioExpander = (this._SfThisContainer as HTMLDivElement).querySelector('#graph-radios-expander') as HTMLButtonElement; radioExpander?.addEventListener('click', (e: any) => { const button = (e.currentTarget as HTMLButtonElement); button.style.display = 'none'; const arrRadios = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.chart-radio-item-secondary') as NodeListOf; arrRadios.forEach(div => { div.style.display = 'block'; }); }); if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) { radioExpander?.click(); } const radioCompleteness = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-completeness') as HTMLButtonElement; radioCompleteness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderThis(index, showGraph, showBackgroundButton); this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement)); }); const radioTimeliness = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-timeliness') as HTMLButtonElement; radioTimeliness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_TIMELINESS; this.renderThis(index, showGraph, showBackgroundButton); this.renderTimelinessGraph((this._SfThisContainer as HTMLDivElement)) }); const radioCompliance = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement; radioCompliance?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLIANCE; this.renderThis(index, showGraph, showBackgroundButton); this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement)) }); // const radioCompliance = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement; // radioCompliance?.addEventListener('click', () => { // this.flowGraph = this.FLOW_GRAPH_COMPLIANCE; // this.renderStream(index); // this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement)) // }); const radioRisk = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-risk') as HTMLButtonElement; radioRisk?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKAREAS; this.renderThis(index, showGraph, showBackgroundButton); this.renderRiskGraph((this._SfThisContainer as HTMLDivElement)) }); const radioFunction = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-function') as HTMLButtonElement; radioFunction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FUNCTION; this.renderThis(index, showGraph, showBackgroundButton); this.renderFunctionGraph((this._SfThisContainer as HTMLDivElement)) }); const radioRiskSeverity = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-riskseverity') as HTMLButtonElement; radioRiskSeverity?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY; this.renderThis(index, showGraph, showBackgroundButton); this.renderRiskSeverityGraph((this._SfThisContainer as HTMLDivElement)) }); const radioObligationType = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-obligationtype') as HTMLButtonElement; radioObligationType?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE; this.renderThis(index, showGraph, showBackgroundButton); this.renderObligationTypeGraph((this._SfThisContainer as HTMLDivElement)) }); const radioJurisdiction = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-jurisdiction') as HTMLButtonElement; radioJurisdiction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_JURISDICTION; this.renderThis(index, showGraph, showBackgroundButton); this.renderJurisdictionGraph((this._SfThisContainer as HTMLDivElement)) }); const radioFrequency = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-frequency') as HTMLButtonElement; radioFrequency?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FREQUENCY; this.renderThis(index, showGraph, showBackgroundButton); this.renderFrequencyGraph((this._SfThisContainer as HTMLDivElement)) }); const radioSubcategory = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-subcategory') as HTMLButtonElement; radioSubcategory?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY; this.renderThis(index, showGraph, showBackgroundButton); this.renderSubcategoryGraph((this._SfThisContainer as HTMLDivElement)) }); const radioLocation = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-location') as HTMLButtonElement; radioLocation?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_LOCATION; this.renderThis(index, showGraph, showBackgroundButton); this.renderLocationGraph((this._SfThisContainer as HTMLDivElement)) }); // const buttonStatusMore = (this._SfThisContainer as HTMLDivElement).querySelector('#button-status-more'); // buttonStatusMore?.addEventListener('click', () => { // const divStatusList = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf; // for(var i = 0; i < divStatusList.length; i++) { // divStatusList[i].style.display = 'flex'; // } // (buttonStatusMore as HTMLButtonElement).style.display = 'none'; // }); for (var i = 0; i < 3; i++) { (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', async (ev: any) => { const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]); //console.log('clicked ', target); const dateResult = this.calculateStartAndEndDateOfThis(target); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.currentColumnIndex = target + ""; await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); this.renderThis(target, showGraph, showBackgroundButton); }); (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + i + '-mobile')?.addEventListener('click', async (ev: any) => { const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]); //console.log('clicked ', target); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.currentColumnIndex = target + ""; const dateResult = this.calculateStartAndEndDateOfThis(target); await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); this.renderThis(target, showGraph, showBackgroundButton); }) } const buttonRefresh = (this._SfThisContainer as HTMLDivElement).querySelector('#button-refresh') as HTMLButtonElement buttonRefresh.addEventListener('click', async () => { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.currentColumnIndex = index + ""; const dateResult = this.calculateStartAndEndDateOfThis(index); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); await this.renderWithFeatures(dateResult.startDate, dateResult.endDate); this.renderThis(index, showGraph, showBackgroundButton); }) const chipSuspense = (this._SfThisContainer as HTMLDivElement).querySelector('#chip-suspense') as HTMLDivElement chipSuspense?.addEventListener('click', async () => { this.suspenseFlag = !this.suspenseFlag this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.currentColumnIndex = index + ""; const dateResult = this.calculateStartAndEndDateOfThis(index); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); await this.renderWithFeatures(dateResult.startDate, dateResult.endDate); this.renderThis(index, showGraph, showBackgroundButton); }) const externalInput = (this._SfThisContainer as HTMLDivElement).querySelector('#external-reporting-file-uploader') as HTMLInputElement externalInput.addEventListener('change', async () => { console.log('trying to upload external file', externalInput.files); if (externalInput.files != null) { let file = externalInput.files[0] if (file != null) { let jsonObj = await Util.parseMISExcel(file); console.log('parsed JSON', jsonObj, this.events) let externalMapping = await this.fetchExternalMapping() console.log('external mapping', externalMapping); let changeCount = 0 let totalCount = 0 for (let dateStr of Object.keys(this.events)) { for (let compliance of this.events[dateStr]) { let complianceId = compliance.id totalCount++; if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { console.log('external compliance found', jsonObj.compliances[externalId]) changeCount++ } } } } this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [ () => { for (let dateStr of Object.keys(this.events)) { for (let [index, compliance] of this.events[dateStr].entries()) { let complianceId = compliance.id if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { if (jsonObj.compliances[externalId].status == "Complied") { this.events[dateStr][index].approved = true; this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() }); } } } } } this.renderAppropriateStream(this.sdate, this.edate, true); this.clearMessages() }, () => { this.clearMessages() } ]) } } }) this.attachListReportingListeners(this._SfThisContainer as HTMLDivElement); this.attachReviewListeners(this._SfThisContainer as HTMLDivElement); const buttonArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf; for (i = 0; i < buttonArr.length; i++) { let indexPrevNext = i; buttonArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id; flagPrev = false; } else { prevString = ""; indexPrev-- } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < buttonArr.length - 1) { if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) { nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id; flagNext = false; } else { nextString = ""; indexNext++ } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfThisContainer as HTMLDivElement, prevString, nextString); } }) } const titleArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf; for (var i = 0; i < titleArr.length; i++) { let indexPrevNext = i; titleArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; const flag = idArr[7]; if (flag != null && flag == "reportedlocations") { return; } var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.selectedItems = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id; let prevIdArr = prevString.split("-") if ((prevIdArr[7] ?? "") == "reportedlocations") { prevString = ""; indexPrev--; } else { flagPrev = false; } } else { prevString = ""; indexPrev--; } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < titleArr.length - 1) { if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) { nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id; let nextIdArr = nextString.split("-") if ((nextIdArr[7] ?? "") == "reportedlocations") { nextString = ""; indexNext++; } else { flagNext = false; } } else { indexNext++; } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfThisContainer as HTMLDivElement), prevString, nextString); } }) } const buttonRenewArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf; for (var i = 0; i < buttonRenewArr.length; i++) { buttonRenewArr[i].addEventListener('click', async (ev: any) => { const id = ev.target.id; const idArr = id.split("-") console.log('idArr', idArr); const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]); let renewEvent = this.events[mmdd][j]; let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true); console.log('renew clicked', fullEvent, fullEvent.reportformatvalues); this.renewRCMResource(fullEvent, fullEvent.reportformatvalues); }) } const streamEventsContainer = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.stream-events-container') as NodeListOf; const buttonSelect = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf; let selectAllArr = this.attachSelectAllListeners((this._SfThisContainer as HTMLDivElement), buttonSelect) const buttonSelectAll = selectAllArr[0] const buttonUnselectAll = selectAllArr[1] for (i = 0; i < buttonSelect.length; i++) { buttonSelect[i].addEventListener('click', (ev: any) => { //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length); const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; // const makercheckers = idArr[5]; const docs = idArr[6]; const module = idArr[14]; if ((ev.target as HTMLInputElement).checked) { this.selectedItemIds.push(id); } else { this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1); let listReportingContainer = (this._SfThisContainer as HTMLDivElement).querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement listReportingContainer.style.display = 'none'; listReportingContainer.innerHTML = ''; let buttonListReporting = (this._SfThisContainer as HTMLDivElement).querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement buttonListReporting.setAttribute('part', 'button-list-reporting') let streamEventTitle = (this._SfThisContainer as HTMLDivElement).querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText streamEventTitle.removeAttribute('part') } if (this.selectedItemIds.length === 0) { for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select1', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } else { (buttonSelect[k] as HTMLInputElement).style.display = 'block'; } (streamEventsContainer[k] as HTMLDivElement).style.display = 'block'; } let bulkUploadLables = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected` } buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'none'; } else { if (this.selectedItemIds.length === 1) { const id1 = id; const idArr1 = id1.split("-") const status = idArr1[13].replace(/_/g, '-'); this.selectedStatus = status; } let totalVisibleCount = 0 for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const docs1 = idArr1[6]; const status = idArr1[13].replace(/_/g, '-'); const module1 = idArr1[14] const isbulk = idArr1[15] == "bulk" if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } if (docs == docs1 && status == this.selectedStatus && module == module1) { totalVisibleCount++ } else { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; (streamEventsContainer[k] as HTMLDivElement).style.display = 'none'; } } if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) { buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'flex'; } else { buttonSelectAll.style.display = 'flex'; buttonUnselectAll.style.display = 'none'; } let bulkUploadLables = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected` } } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + "")); if (this.selectedItemIds.length == 1) { ev.target.scrollIntoView() } }) } if (showGraph) { switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph((this._SfThisContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph((this._SfThisContainer as HTMLDivElement)); break; default: this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement)); break; } } } renderButtonRefresh = (eventsContainer: HTMLDivElement) => { document.addEventListener('scroll', () => { // console.log('scroll',window.scrollY) let buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement if (buttonRefresh != null) { if (window.scrollY > 720) { if (buttonRefresh.style.display == "flex") { } else { buttonRefresh.style.display = 'flex' } } else { if (buttonRefresh.style.display == "none") { } else { buttonRefresh.style.display = 'none' } } } }) } renderStream = (index: number = 0, showGraph: boolean = true, showBackgroundButton: boolean) => { //console.log('flowgraph renderStream', this.flowGraph); this.streamIndex = index; // this.clearGraphData(); // this.clearSelectedGraphParam(); // this.clearSelectedLegend(); var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); var html = ''; html += '
'; for (var i = 0; i < 12; i++) { var part = ""; if (i === index) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
' + this.monthNames[startDate.getMonth()] + ' ' + startDate.getFullYear() % 100 + '
'; startDate.setMonth(startDate.getMonth() + 1); } html += '
'; html += '
'; html += '
'; var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); for (i = 0; i < 12; i++) { var part = ""; if (i === index) { part = "stream-month-selected"; } else { part = "stream-month-not-selected"; } html += '
' + this.monthNames[startDate.getMonth()] + '  ' + startDate.getFullYear() + '
'; startDate.setMonth(startDate.getMonth() + 1); } html += '
'; html += '
'; startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); for (i = 0; i < 12; i++) { if (i === index) { //console.log(i, index) html += this.renderStreamEvents(i, startDate.getMonth(), startDate.getFullYear(), showGraph, showBackgroundButton) } startDate.setMonth(startDate.getMonth() + 1); } html += '
'; html += this.renderSelectAllButtons(); html += '
'; (this._SfStreamContainer as HTMLDivElement).innerHTML = html; this.renderButtonRefresh((this._SfStreamContainer as HTMLDivElement)); this.attachTimelineFilterHandlers((this._SfStreamContainer as HTMLDivElement)); const filterButton = (this._SfStreamContainer as HTMLDivElement).querySelector('#filter-button') as HTMLButtonElement filterButton?.addEventListener('click', () => { const filterList = (this._SfStreamContainer as HTMLDivElement).querySelector('#filter-list-container') as HTMLDivElement filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none') filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close') const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement filterSubmitButton.addEventListener('click', async () => { Util.setFeatures(this.selectedFeatures); const dateResult = this.calculateStartAndEndDateOfStream(index); const monthResult = this.calculateMonthFromIndex(index); console.log('monthResult', monthResult); console.log('dateresult', dateResult, index); console.log('selectedfeatures', this.selectedFeatures); this.currentColumnIndex = index + ""; if (this.selectedFeatures.indexOf('contracts') >= 0) { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.enableCustom(); this.renderTabs(this.TAB_CUSTOM); console.log('stats clicked'); if (this.myRole == this.TAB_VIEWER) { this.renderCustomViewer() } else { this.renderCustom(); } } else { if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "no", ("0" + monthResult).slice(-2)); } this.renderTabs(this.TAB_STREAM); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(index, showGraph, showBackgroundButton); } }) // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement // selectFeatureAll?.addEventListener('click',async(ev: any) => { // let target = ev.target; // if(target.checked){ // for(let feature of this.getFeatures()){ // if(this.selectedFeatures.indexOf(feature) < 0){ // this.selectedFeatures.push(feature); // } // } // }else{ // this.selectedFeatures = [] // } // const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf // for(let selectFeature of selectFeatures){ // let id = selectFeature.id; // let i = id.split('-')[3]; // let selectedFeature = this.getFeatures()[parseInt(i)] // selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0 // } // filterSubmitButton.style.visibility = 'visible' // }) // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement // selectFeatureAllLabel?.addEventListener('click',()=>{ // selectFeatureAll.checked = !selectFeatureAll.checked; // selectFeatureAll.click(); // }) const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf for (let [i, selectFeature] of selectFeatures.entries()) { selectFeature.addEventListener('click', async (ev: any) => { let target = ev.target; let id = target.id; let i = id.split('-')[3]; let selectedFeature = this.getFeatures()[i] if (target.checked) { if (this.selectedFeatures.indexOf(selectedFeature) < 0) { // this.selectedFeatures.push(selectedFeature) this.selectedFeatures = [selectedFeature] } } // else{ // // selectFeatureAll.checked = false; // if(this.selectedFeatures.indexOf(selectedFeature) >= 0){ // this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1); // } // } // filterSubmitButton.style.visibility = 'visible' filterSubmitButton.click(); }) selectFeatureLabels[i].addEventListener('click', () => { selectFeature.checked = !selectFeature.checked selectFeature.click() }) } }) const radioExpander = (this._SfStreamContainer as HTMLDivElement).querySelector('#graph-radios-expander') as HTMLButtonElement; radioExpander?.addEventListener('click', (e: any) => { const button = (e.currentTarget as HTMLButtonElement); button.style.display = 'none'; const arrRadios = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.chart-radio-item-secondary') as NodeListOf; arrRadios.forEach(div => { div.style.display = 'block'; }); }); if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) { radioExpander?.click(); } const radioCompleteness = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-completeness') as HTMLButtonElement; radioCompleteness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(index, showGraph, showBackgroundButton); this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement)); }); const radioTimeliness = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-timeliness') as HTMLButtonElement; radioTimeliness?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_TIMELINESS; this.renderStream(index, showGraph, showBackgroundButton); this.renderTimelinessGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioCompliance = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement; radioCompliance?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_COMPLIANCE; this.renderStream(index, showGraph, showBackgroundButton); this.renderComplianceGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioRisk = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-risk') as HTMLButtonElement; radioRisk?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKAREAS; this.renderStream(index, showGraph, showBackgroundButton); this.renderRiskGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioRiskSeverity = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-riskseverity') as HTMLButtonElement; radioRiskSeverity?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY; this.renderStream(index, showGraph, showBackgroundButton); this.renderRiskSeverityGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioFunction = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-function') as HTMLButtonElement; radioFunction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FUNCTION; this.renderStream(index, showGraph, showBackgroundButton); this.renderFunctionGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioObligationType = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-obligationtype') as HTMLButtonElement; radioObligationType?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE; this.renderStream(index, showGraph, showBackgroundButton); this.renderObligationTypeGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioJurisdiction = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-jurisdiction') as HTMLButtonElement; radioJurisdiction?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_JURISDICTION; this.renderStream(index, showGraph, showBackgroundButton); this.renderJurisdictionGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioFrequency = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-frequency') as HTMLButtonElement; radioFrequency?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_FREQUENCY; this.renderStream(index, showGraph, showBackgroundButton); this.renderFrequencyGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioSubcategory = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-subcategory') as HTMLButtonElement; radioSubcategory?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY; this.renderStream(index, showGraph, showBackgroundButton); this.renderSubcategoryGraph((this._SfStreamContainer as HTMLDivElement)) }); const radioLocation = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-location') as HTMLButtonElement; radioLocation?.addEventListener('click', () => { this.flowGraph = this.FLOW_GRAPH_LOCATION; this.renderStream(index, showGraph, showBackgroundButton); this.renderLocationGraph((this._SfStreamContainer as HTMLDivElement)) }); let backgroundProcessButton = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-background-process') as HTMLButtonElement if (showBackgroundButton) { backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none' console.log('backgroundprocessbutton', backgroundProcessButton.style.display); if (showBackgroundButton) { backgroundProcessButton.addEventListener('click', () => { console.log('bulk-progress clicked') let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement bulkLoader.scrollIntoView(); }) } } // const buttonStatusMore = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-status-more'); // buttonStatusMore?.addEventListener('click', () => { // const divStatusList = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf; // for(var i = 0; i < divStatusList.length; i++) { // divStatusList[i].style.display = 'flex'; // } // (buttonStatusMore as HTMLButtonElement).style.display = 'none'; // }); for (var i = 0; i < 12; i++) { (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', async (ev: any) => { const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]); const dateResult = this.calculateStartAndEndDateOfStream(target); const monthResult = this.calculateMonthFromIndex(target); // console.log('monthResult', monthResult); //console.log('dateresult', dateResult); this.currentColumnIndex = target + ""; if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2)); } this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(target, showGraph, showBackgroundButton); }); (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + i + '-mobile')?.addEventListener('click', async (ev: any) => { const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]); const dateResult = this.calculateStartAndEndDateOfStream(target); const monthResult = this.calculateMonthFromIndex(target); if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2)); } this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.currentColumnIndex = target + ""; this.renderStream(target, showGraph, showBackgroundButton); }) } const buttonRefresh = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-refresh') as HTMLButtonElement buttonRefresh?.addEventListener('click', async () => { const dateResult = this.calculateStartAndEndDateOfStream(index); const monthResult = this.calculateMonthFromIndex(index); console.log('monthResult', monthResult); console.log('dateresult', dateResult); this.currentColumnIndex = index + ""; if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2)); } this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(index, showGraph, showBackgroundButton); }) const chipSuspense = (this._SfStreamContainer as HTMLDivElement).querySelector('#chip-suspense') as HTMLDivElement chipSuspense?.addEventListener('click', async () => { this.suspenseFlag = !this.suspenseFlag const dateResult = this.calculateStartAndEndDateOfStream(index); const monthResult = this.calculateMonthFromIndex(index); console.log('monthResult', monthResult); console.log('dateresult', dateResult); this.currentColumnIndex = index + ""; if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2)); } this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.renderStream(index, showGraph, showBackgroundButton); }) const externalInput = (this._SfStreamContainer as HTMLDivElement).querySelector('#external-reporting-file-uploader') as HTMLInputElement externalInput.addEventListener('change', async () => { console.log('trying to upload external file', externalInput.files); if (externalInput.files != null) { let file = externalInput.files[0] if (file != null) { let jsonObj = await Util.parseMISExcel(file); console.log('parsed JSON', jsonObj, this.events) let externalMapping = await this.fetchExternalMapping() console.log('external mapping', externalMapping); let changeCount = 0 let totalCount = 0 for (let dateStr of Object.keys(this.events)) { for (let compliance of this.events[dateStr]) { let complianceId = compliance.id totalCount++; if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { console.log('external compliance found', jsonObj.compliances[externalId]) changeCount++ } } } } this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [ () => { for (let dateStr of Object.keys(this.events)) { for (let [index, compliance] of this.events[dateStr].entries()) { let complianceId = compliance.id if (externalMapping.data != null && externalMapping.data[complianceId] != null) { let externalId = externalMapping.data[complianceId] if (jsonObj.compliances[externalId] != null) { if (jsonObj.compliances[externalId].status == "Complied") { this.events[dateStr][index].approved = true; this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() }); } } } } } this.renderAppropriateStream(this.sdate, this.edate, true); this.clearMessages() }, () => { this.clearMessages() } ]) } } }) this.attachListReportingListeners(this._SfStreamContainer as HTMLDivElement); this.attachReviewListeners(this._SfStreamContainer as HTMLDivElement); const buttonArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf; for (i = 0; i < buttonArr.length; i++) { let indexPrevNext = i; buttonArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { console.log('selectedItems', this.selectedItemIds[k], idArr[3] + '-' + idArr[4] + '-' + idArr[5], this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5])); if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; //console.log('commentsinlist', (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement, this.events[mmdd][j].comments, mmdd, j); let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id; flagPrev = false; } else { prevString = ""; indexPrev-- } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < buttonArr.length - 1) { if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) { nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id; flagNext = false; } else { nextString = ""; indexNext++ } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement); // console.log('errorFetchEvent', mmdd, j, buttonArr[i].outerHTML, idArr); console.log('previous event clicked', buttonArr[indexPrevNext - 1], prevString, indexPrevNext); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfStreamContainer as HTMLDivElement, prevString, nextString); } }) } const titleArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf; for (var i = 0; i < titleArr.length; i++) { let indexPrevNext = i; titleArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; const flag = idArr[7]; if (flag != null && flag == "reportedlocations") { return; } var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.selectedItems = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id; let prevIdArr = prevString.split("-") if ((prevIdArr[7] ?? "") == "reportedlocations") { prevString = ""; indexPrev--; } else { flagPrev = false; } } else { prevString = ""; indexPrev--; } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < titleArr.length - 1) { if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) { nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id; let nextIdArr = nextString.split("-") if ((nextIdArr[7] ?? "") == "reportedlocations") { nextString = ""; indexNext++; } else { flagNext = false; } } else { indexNext++; } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfStreamContainer as HTMLDivElement), prevString, nextString); } }) } const buttonRenewArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf; for (var i = 0; i < buttonRenewArr.length; i++) { buttonRenewArr[i].addEventListener('click', async (ev: any) => { const id = ev.target.id; const idArr = id.split("-") console.log('idArr', idArr); const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]); let renewEvent = this.events[mmdd][j]; let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true); console.log('renew clicked', fullEvent, fullEvent.reportformatvalues); this.renewRCMResource(fullEvent, fullEvent.reportformatvalues); }) } const streamEventsContainer = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.stream-events-container') as NodeListOf; const buttonSelect = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf; let selectAllArr = this.attachSelectAllListeners((this._SfStreamContainer as HTMLDivElement), buttonSelect) const buttonSelectAll = selectAllArr[0] const buttonUnselectAll = selectAllArr[1] for (i = 0; i < buttonSelect.length; i++) { buttonSelect[i].addEventListener('click', (ev: any) => { //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length); const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; // const makercheckers = idArr[5]; const docs = idArr[6]; const module = idArr[14]; if ((ev.target as HTMLInputElement).checked) { this.selectedItemIds.push(id); } else { this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1); let listReportingContainer = (this._SfStreamContainer as HTMLDivElement).querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement listReportingContainer.style.display = 'none'; listReportingContainer.innerHTML = ''; let buttonListReporting = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement buttonListReporting.setAttribute('part', 'button-list-reporting') let streamEventTitle = (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText streamEventTitle.removeAttribute('part') } if (this.selectedItemIds.length === 0) { for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select2', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } else { (buttonSelect[k] as HTMLInputElement).style.display = 'block'; } (streamEventsContainer[k] as HTMLDivElement).style.display = 'block'; } let bulkUploadLables = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = `` } buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'none'; } else { if (this.selectedItemIds.length === 1) { const id1 = id; const idArr1 = id1.split("-") const status = idArr1[13].replace(/_/g, '-'); this.selectedStatus = status; } let totalVisibleCount = 0 for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const docs1 = idArr1[6]; const status = idArr1[13].replace(/_/g, '-'); const module1 = idArr1[14] const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } if (docs == docs1 && status == this.selectedStatus && module == module1) { totalVisibleCount++ } else { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; (streamEventsContainer[k] as HTMLDivElement).style.display = 'none'; } } let bulkUploadLables = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf for (let bulkUploadLable of bulkUploadLables) { bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected` } if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) { buttonSelectAll.style.display = 'none'; buttonUnselectAll.style.display = 'flex'; } else { buttonSelectAll.style.display = 'flex'; buttonUnselectAll.style.display = 'none'; } } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + "")); if (this.selectedItemIds.length == 1) { ev.target.scrollIntoView() } }) } if (showGraph) { console.log('showing graph', showGraph, this.flowGraph) switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph((this._SfStreamContainer as HTMLDivElement)); break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph((this._SfStreamContainer as HTMLDivElement)); break; default: this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement)); break; } } } attachTimelineFilterHandlers = (divContainer: HTMLDivElement) => { const divs = divContainer.querySelectorAll('.chip') as NodeListOf; divs.forEach(div => { div.addEventListener('click', () => { // const spans = div.querySelectorAll('span') as NodeListOf; // if(spans[2].innerHTML == "0") { // this.setError('No items present for the selected filter!') // setTimeout(() => { // this.clearMessages(); // }, 2000); // } else { // this.clickOnPie(false, parseInt(div.id.split('-')[2])) // this.chart.update(); // } }) }); } getFinancialYear = (mmddyyyy: string): string => { const date = new Date(mmddyyyy); const year = date.getFullYear(); const month = date.getMonth() + 1; // getMonth() is 0-indexed let finYear: number; if (month >= 4) { // April to December → Financial year starts in this year finYear = year; } else { // January to March → Financial year started in previous year finYear = year - 1; } return `${finYear}`; } getYearFromMonthBetween = (startDateStr: string, endDateStr: string, monthStr: string): string => { const startDate = new Date(startDateStr); const endDate = new Date(endDateStr); const month = parseInt(monthStr, 10); // Ensure month is a number console.log('getting date', startDate, endDate, month); if (isNaN(month) || month < 1 || month > 12) { return this.calendarStartYYYY } let current = new Date(startDate.getFullYear(), startDate.getMonth(), 1); while (current <= endDate) { if (current.getMonth() + 1 === month) { // getMonth() is 0-indexed return current.getFullYear() + ""; } // Move to next month current.setMonth(current.getMonth() + 1); } // If no matching month found in the range return this.calendarStartYYYY; } getCurrentYearGeneric = () => { if (new Date().getMonth() >= 3) { return new Date().getFullYear() + "" } return (new Date().getFullYear() - 1) + "" } getCurrentYear = (mm: string) => { // var currMonth = new Date().getMonth() + 1; // // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // // yyyy = new Date().getFullYear() + ""; // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() - 1) + ""; // // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() + 1) + ""; // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // // yyyy = (new Date().getFullYear() + 1) + ""; // // } // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) { // yyyy = parseInt(this.calendarStartYYYY) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) - 1) + ""; // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) { // yyyy = (parseInt(this.calendarStartYYYY) + 1) + ""; // } // if(parseInt(mm) >= 4){ // return new Date().getFullYear() + "" // }else{ // return (new Date().getFullYear() + 1) + "" // } var yyyy = this.getYearFromMonthAndCalendarStart(mm); return yyyy; } clearButtonSelection = () => { const buttonSelect = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf; for (var i = 0; i < buttonSelect.length; i++) { (buttonSelect[i] as HTMLInputElement).checked = false; } } clearGraphData = () => { this.chart = null; this.chart2 = null; this.chart3 = null; this.chart4 = null; this.riskAreasData = null; this.riskAreasPartStatusData = null; this.riskAreasLateStatusData = null; this.riskAreasComplianceStatusData = null; this.riskSeverityData = null; this.riskSeverityLateStatusData = null; this.riskSeverityPartStatusData = null; this.riskSeverityComplianceStatusData = null; this.functionData = null; this.functionLateStatusData = null; this.functionPartStatusData = null; this.functionComplianceStatusData = null; this.locationData = null; this.locationLateStatusData = null; this.locationPartStatusData = null; this.locationComplianceStatusData = null; this.obligationTypeData = null; this.obligationTypeLateStatusData = null; this.obligationTypePartStatusData = null; this.obligationTypeComplianceStatusData = null; this.jurisdictionData = null; this.jurisdictionPartStatusData = null; this.jurisdictionLateStatusData = null; this.jurisdictionComplianceStatusData = null; this.subcategoryData = null; this.subcategoryLateStatusData = null; this.subcategoryPartStatusData = null; this.subcategoryComplianceStatusData = null; this.frequencyData = null; this.frequencyLateStatusData = null; this.frequencyPartStatusData = null; this.frequencyComplianceStatusData = null; } showGraph = (divContainer: HTMLDivElement, index: number) => { if (index == 1) { (divContainer.querySelector('#myChart') as HTMLCanvasElement).parentElement!.style.display = 'block'; } if (index == 4) { (divContainer.querySelector('#myChart4') as HTMLCanvasElement).parentElement!.style.display = 'block'; } if (index == 2) { (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.display = 'block'; // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).classList.add('gone'); // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.height = '0px'; // if(this.chart2 != null) { // (this.chart2 as Chart).destroy(); // } // this.chart2 = null; } if (index == 3) { (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.display = 'block'; // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).classList.add('gone'); // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.height = '0px'; // if(this.chart3 != null) { // (this.chart3 as Chart).destroy(); // } // this.chart3 = null; } } clearGraph = (divContainer: HTMLDivElement, index: number) => { if (index == 1) { (divContainer.querySelector('#myChart') as HTMLCanvasElement).parentElement!.style.display = 'none'; } if (index == 4) { (divContainer.querySelector('#myChart4') as HTMLCanvasElement).parentElement!.style.display = 'none'; } if (index == 2) { (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.display = 'none'; // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).classList.add('gone'); // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.height = '0px'; // if(this.chart2 != null) { // (this.chart2 as Chart).destroy(); // } // this.chart2 = null; } if (index == 3) { (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.display = 'none'; // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).classList.add('gone'); // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.height = '0px'; // if(this.chart3 != null) { // (this.chart3 as Chart).destroy(); // } // this.chart3 = null; } } renderCompletenessCsvForGraph = (dataBar: any, parameter: string) => { this.csvCompletenessStats = parameter + ",Not Started,In Progress,Complete,Rejected\n"; for (var i = 0; i < dataBar['labels'].length; i++) { this.csvCompletenessStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : ""); } console.log('rendering csv completeness', dataBar, this.csvCompletenessStats); } renderTimelinessCsvForGraph = (dataBar: any, parameter: string) => { //console.log('dataBar', dataBar); this.csvTimelinessStats = parameter + ",In Time,Past Due Date,Late Approved,Late Executed,Late Reported\n"; for (var i = 0; i < dataBar['labels'].length; i++) { this.csvTimelinessStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + "\",\"" + dataBar['datasets'][4]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : ""); } //console.log('rendering csv csvTimelinessStats', this.csvTimelinessStats); } renderComplianceCsvForGraph = (dataBar: any, parameter: string) => { this.csvComplianceStats = parameter + ",Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance\n"; for (var i = 0; i < dataBar['labels'].length; i++) { this.csvComplianceStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][4]['data'][i] + "\",\"" + dataBar['datasets'][5]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : ""); } //console.log('rendering csv csvComplianceStats', this.csvComplianceStats); } renderCompletenessGraph = (divContainer: HTMLDivElement, selectedTab: number = -1, selectedSummary: number = -1, title: string | string[] = "Completeness") => { this.clearSelectedGraphParam(); // this.clearSelectedLegend(); this.csvGraphStats = ""; this.csvCompletenessStats = ""; this.csvTimelinessStats = ""; this.csvComplianceStats = ""; if ((divContainer.querySelector('#graph-approved') as HTMLSpanElement) == null) return; var dataApproved = (divContainer.querySelector('#graph-approved') as HTMLSpanElement).innerHTML; var dataNotStarted = (divContainer.querySelector('#graph-not-started') as HTMLSpanElement).innerHTML; var dataPendingApproval = (divContainer.querySelector('#graph-pending-approval') as HTMLSpanElement).innerHTML; var dataRejected = (divContainer.querySelector('#graph-rejected') as HTMLSpanElement).innerHTML; const ctx = divContainer.querySelector('#myChart') as ChartItem; this.showGraph(divContainer, 1); this.clearGraph(divContainer, 2); this.clearGraph(divContainer, 3); this.clearGraph(divContainer, 4); if (this.fill == "pattern") { const data = { labels: ['Approved', 'Not Started', 'Pending Approval', 'Rejected'], datasets: [{ label: 'Compliances', data: [dataApproved, dataNotStarted, dataPendingApproval, dataRejected], borderWidth: 1, backgroundColor: [ Util.createDiagonalPattern3(this.COLOR_APPROVED), Util.createDiagonalPattern2(this.COLOR_NOT_STARTED), Util.createDiagonalPattern1(this.COLOR_PENDING_APPROVAL), Util.createDiagonalPattern1(this.COLOR_REJECTED) ] }] } this.renderChartSettings(divContainer, selectedTab, selectedSummary, ctx); this.renderChart(ctx, 'doughnut', data, title, false) } const data = { labels: ['Approved', 'Not Started', 'Pending Approval', 'Rejected'], datasets: [{ label: 'Compliances', data: [dataApproved, dataNotStarted, dataPendingApproval, dataRejected], borderWidth: 1, backgroundColor: [ this.COLOR_APPROVED, this.COLOR_NOT_STARTED, this.COLOR_PENDING_APPROVAL, this.COLOR_REJECTED ] }] } this.csvGraphStats += 'Completeness,Approved,Not Started,Pending Approval,Rejected,Total\n'; this.csvGraphStats += 'Total,' + dataApproved + ',' + dataNotStarted + ',' + dataPendingApproval + ',' + dataRejected + ',' + (parseInt(dataApproved) + parseInt(dataNotStarted) + parseInt(dataPendingApproval) + parseInt(dataRejected)) + '\n'; const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf; for (var i = 0; i < itemsTimeliness.length; i++) { itemsTimeliness[i].style.display = 'none'; } const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf; for (var i = 0; i < itemsCompleteness.length; i++) { itemsCompleteness[i].style.display = 'flex'; } const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf; for (var i = 0; i < itemsCompliance.length; i++) { itemsCompliance[i].style.display = 'none'; } let flagFilterFound = false; for (let label of data.labels) { if (label.toLowerCase().replace(/ /g, "-").replace('status-', '') === this.graphFilter) { flagFilterFound = true; break; } } if (!flagFilterFound) { this.graphFilter = "" } this.renderChartSettings(divContainer, selectedTab, selectedSummary, ctx); this.renderChart(ctx, 'doughnut', data, title, false) } renderComplianceGraph = (divContainer: HTMLDivElement) => { //console.log('Rendering compliance graph...'); this.clearSelectedGraphParam(); // this.clearSelectedLegend(); this.csvGraphStats = ""; this.csvCompletenessStats = ""; this.csvTimelinessStats = ""; this.csvComplianceStats = ""; console.log('contracts') let data: any = null; let ctx: any = null; if (this.selectedFeatures.indexOf('contracts') >= 0) { var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML; var dataActive = (divContainer.querySelector('#graph-active') as HTMLSpanElement).innerHTML; var dataAboutToExpire = (divContainer.querySelector('#graph-about-to-expire') as HTMLSpanElement).innerHTML; var dataExpired = (divContainer.querySelector('#graph-expired') as HTMLSpanElement).innerHTML; var dataTerminated = (divContainer.querySelector('#graph-terminated') as HTMLSpanElement).innerHTML; ctx = divContainer.querySelector('#myChart') as ChartItem; this.showGraph(divContainer, 1); this.clearGraph(divContainer, 2); this.clearGraph(divContainer, 3); this.clearGraph(divContainer, 4); data = { labels: ['Active', 'About To Expire', 'Expired', 'Terminated'], datasets: [{ label: 'Compliances', data: [dataActive, dataAboutToExpire, dataExpired, dataTerminated], borderWidth: 1, backgroundColor: [ this.COLOR_SCHEDULED, this.COLOR_PARTIALLY_COMPLIED, this.COLOR_NOT_COMPLIED, // this.COLOR_COMPLIED, // this.COLOR_COMPLIED_WITH_EXCEPTION, this.COLOR_REPORTED_NON_COMPLIANCE ] }] } this.csvGraphStats += 'Compliance,Active,About To Expire,Expired,Terminated,Total\n'; this.csvGraphStats += 'Count,' + parseInt(dataActive) + ',' + parseInt(dataAboutToExpire) + ',' + parseInt(dataExpired) + ',' + parseInt(dataTerminated) + ',' + parseInt(dataTotal) + '\n'; } else { var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML; var dataNotComplied = (divContainer.querySelector('#graph-not-complied') as HTMLSpanElement).innerHTML; var dataScheduled = (divContainer.querySelector('#graph-scheduled') as HTMLSpanElement).innerHTML; var dataPartiallyComplied = (divContainer.querySelector('#graph-partially-complied') as HTMLSpanElement).innerHTML; var dataComplied = (divContainer.querySelector('#graph-complied') as HTMLSpanElement).innerHTML; var dataCompliedWithGaps = (divContainer.querySelector('#graph-complied-with-gaps') as HTMLSpanElement).innerHTML; var dataReportedNonComplaince = (divContainer.querySelector('#graph-reported-non-compliance') as HTMLSpanElement).innerHTML; ctx = divContainer.querySelector('#myChart') as ChartItem; this.showGraph(divContainer, 1); this.clearGraph(divContainer, 2); this.clearGraph(divContainer, 3); this.clearGraph(divContainer, 4); data = { labels: ['Scheduled', 'Not Complied', 'Partially Complied', 'Complied', 'Complied With Gaps', 'Reported Non Compliance'], datasets: [{ label: 'Compliances', data: [dataScheduled, dataNotComplied, dataPartiallyComplied, dataComplied, dataCompliedWithGaps, dataReportedNonComplaince], borderWidth: 1, backgroundColor: [ this.COLOR_SCHEDULED, this.COLOR_NOT_COMPLIED, this.COLOR_PARTIALLY_COMPLIED, this.COLOR_COMPLIED, this.COLOR_COMPLIED_WITH_EXCEPTION, this.COLOR_REPORTED_NON_COMPLIANCE ] }] } this.csvGraphStats += 'Compliance,Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance,Total\n'; this.csvGraphStats += 'Count,' + parseInt(dataScheduled) + ',' + parseInt(dataNotComplied) + ',' + parseInt(dataPartiallyComplied) + ',' + parseInt(dataCompliedWithGaps) + ',' + parseInt(dataComplied) + ',' + parseInt(dataReportedNonComplaince) + ',' + parseInt(dataTotal) + '\n'; } //console.log('rendering timeliness graph', this.csvGraphStats); const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf; for (var i = 0; i < itemsTimeliness.length; i++) { itemsTimeliness[i].style.display = 'none'; } const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf; for (var i = 0; i < itemsCompleteness.length; i++) { itemsCompleteness[i].style.display = 'none'; } const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf; for (var i = 0; i < itemsCompliance.length; i++) { itemsCompliance[i].style.display = 'flex'; } let flagFilterFound = false; for (let label of data.labels) { console.log('finding flag', this.graphFilter, label.toLowerCase()); if (label.toLowerCase() === this.graphFilter) { flagFilterFound = true; break; } } if (!flagFilterFound) { console.log('resetting flagFilter', this.graphFilter); this.graphFilter = "" } this.renderChartSettings(divContainer, -1, -1, ctx); this.renderChart(ctx, 'doughnut', data, "Compliance", false) } renderTimelinessGraph = (divContainer: HTMLDivElement) => { this.clearSelectedGraphParam(); // this.clearSelectedLegend(); this.csvGraphStats = ""; this.csvCompletenessStats = ""; this.csvTimelinessStats = ""; this.csvComplianceStats = ""; var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML; var dataPastDueDate = (divContainer.querySelector('#graph-past-due-date') as HTMLSpanElement).innerHTML; var dataLateApproved = (divContainer.querySelector('#graph-late-approved') as HTMLSpanElement).innerHTML; var dataLateExecuted = (divContainer.querySelector('#graph-late-executed') as HTMLSpanElement).innerHTML; var dataLateReported = (divContainer.querySelector('#graph-late-reported') as HTMLSpanElement).innerHTML; const ctx = divContainer.querySelector('#myChart') as ChartItem; this.showGraph(divContainer, 1); this.clearGraph(divContainer, 2); this.clearGraph(divContainer, 3); this.clearGraph(divContainer, 4); const data = { labels: ['In Time', 'Past Due Date', 'Late Approved', 'Late Executed', 'Late Reported'], datasets: [{ label: 'Compliances', data: [(parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted) + parseInt(dataLateReported))) + "", dataPastDueDate, dataLateApproved, dataLateExecuted, dataLateReported], borderWidth: 1, backgroundColor: [ this.COLOR_NOT_STARTED, this.COLOR_PAST_DUE_DATE, this.COLOR_LATE_APPROVED, this.COLOR_LATE_EXECUTED, this.COLOR_LATE_REPORTED ] }] } this.csvGraphStats += 'Completeness,In Time,Past Due Date,Late Approved,Late Executed,Late Reported,Total\n'; this.csvGraphStats += 'Count,' + (parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted))) + ',' + (parseInt(dataPastDueDate) + ',' + parseInt(dataLateApproved) + ',' + parseInt(dataLateExecuted) + ',' + parseInt(dataLateReported) + ',' + (parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted) + parseInt(dataLateReported)))) + '\n'; //console.log('rendering timeliness graph', this.csvGraphStats); const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf; for (var i = 0; i < itemsTimeliness.length; i++) { itemsTimeliness[i].style.display = 'flex'; } const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf; for (var i = 0; i < itemsCompleteness.length; i++) { itemsCompleteness[i].style.display = 'none'; } const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf; for (var i = 0; i < itemsCompliance.length; i++) { itemsCompliance[i].style.display = 'none'; } let flagFilterFound = false; for (let label of data.labels) { if (label.toLowerCase().replace(/ /g, "-").replace('status-', '') === this.graphFilter) { flagFilterFound = true; break; } } if (!flagFilterFound) { this.graphFilter = "" } this.renderChartSettings(divContainer, -1, -1, ctx); this.renderChart(ctx, 'doughnut', data, "Timeliness", false) } renderRiskSeverityGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { //console.log('Rendering risk severity', this.riskSeverityComplianceStatusData); this.renderGraph(divContainer, this.riskSeverityData, this.riskSeverityPartStatusData, this.riskSeverityLateStatusData, this.riskSeverityComplianceStatusData, 'RiskSeverity', flagBarChart, flagInModal); } renderObligationTypeGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.obligationTypeData, this.obligationTypePartStatusData, this.obligationTypeLateStatusData, this.obligationTypeComplianceStatusData, 'ObligationType', flagBarChart, flagInModal); } renderFunctionGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.functionData, this.functionPartStatusData, this.functionLateStatusData, this.functionComplianceStatusData, 'Function', flagBarChart, flagInModal); } renderLocationGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.locationData, this.locationPartStatusData, this.locationLateStatusData, this.locationComplianceStatusData, 'Location', flagBarChart, flagInModal); } renderJurisdictionGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.jurisdictionData, this.jurisdictionPartStatusData, this.jurisdictionLateStatusData, this.jurisdictionComplianceStatusData, 'Jurisdiction', flagBarChart, flagInModal); } renderSubcategoryGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.subcategoryData, this.subcategoryPartStatusData, this.subcategoryLateStatusData, this.subcategoryComplianceStatusData, 'SubCategory', flagBarChart, flagInModal); } renderFrequencyGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.frequencyData, this.frequencyPartStatusData, this.frequencyLateStatusData, this.frequencyComplianceStatusData, 'Frequency', flagBarChart, flagInModal); } renderRiskGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => { this.renderGraph(divContainer, this.riskAreasData, this.riskAreasPartStatusData, this.riskAreasLateStatusData, this.riskAreasComplianceStatusData, 'RiskAreas', flagBarChart, flagInModal); } populateGraphDataBarPart = (partData: any) => { const dataBar: any = {}; dataBar['labels'] = []; for (var i = 0; i < Object.keys(partData).length; i++) { dataBar['labels'].push(this.formatLabel(Object.keys(partData)[i], 15)); } dataBar['datasets'] = []; dataBar['datasets'].push({}); dataBar['datasets'].push({}); dataBar['datasets'].push({}); dataBar['datasets'].push({}); dataBar['datasets'][0]['label'] = 'Approved'; dataBar['datasets'][0]['data'] = []; for (i = 0; i < Object.keys(partData).length; i++) { dataBar['datasets'][0]['data'].push(partData[Object.keys(partData)[i]]['approved']); } dataBar['datasets'][0]['backgroundColor'] = this.COLOR_APPROVED; dataBar['datasets'][1]['label'] = 'Pending Approval'; dataBar['datasets'][1]['data'] = []; for (i = 0; i < Object.keys(partData).length; i++) { dataBar['datasets'][1]['data'].push(partData[Object.keys(partData)[i]]['pending-approval']); } dataBar['datasets'][1]['backgroundColor'] = this.COLOR_PENDING_APPROVAL; dataBar['datasets'][2]['label'] = 'Rejected'; dataBar['datasets'][2]['data'] = []; for (i = 0; i < Object.keys(partData).length; i++) { dataBar['datasets'][2]['data'].push(partData[Object.keys(partData)[i]]['rejected']); } dataBar['datasets'][2]['backgroundColor'] = this.COLOR_REJECTED; dataBar['datasets'][3]['label'] = 'Not Started'; dataBar['datasets'][3]['data'] = []; for (i = 0; i < Object.keys(partData).length; i++) { dataBar['datasets'][3]['data'].push(partData[Object.keys(partData)[i]]['not-started']); } dataBar['datasets'][3]['backgroundColor'] = this.COLOR_NOT_STARTED; return dataBar; } populateGraphDataBarLate = (lateData: any) => { const dataBar2: any = {}; dataBar2['labels'] = []; for (var i = 0; i < Object.keys(lateData).length; i++) { dataBar2['labels'].push(this.formatLabel(Object.keys(lateData)[i], 15)); } dataBar2['datasets'] = []; dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'][0]['label'] = 'In Time'; dataBar2['datasets'][0]['data'] = []; for (i = 0; i < Object.keys(lateData).length; i++) { dataBar2['datasets'][0]['data'].push(lateData[Object.keys(lateData)[i]]['in-time']); } dataBar2['datasets'][0]['backgroundColor'] = '#888888'; dataBar2['datasets'][1]['label'] = 'Past Due Date'; dataBar2['datasets'][1]['data'] = []; for (i = 0; i < Object.keys(lateData).length; i++) { dataBar2['datasets'][1]['data'].push(lateData[Object.keys(lateData)[i]]['past-due-date']); } dataBar2['datasets'][1]['backgroundColor'] = this.COLOR_PAST_DUE_DATE; dataBar2['datasets'][2]['label'] = 'Late Executed'; dataBar2['datasets'][2]['data'] = []; for (i = 0; i < Object.keys(lateData).length; i++) { dataBar2['datasets'][2]['data'].push(lateData[Object.keys(lateData)[i]]['late-executed']); } dataBar2['datasets'][2]['backgroundColor'] = this.COLOR_LATE_EXECUTED; dataBar2['datasets'][3]['label'] = 'Late Approved'; dataBar2['datasets'][3]['data'] = []; for (i = 0; i < Object.keys(lateData).length; i++) { dataBar2['datasets'][3]['data'].push(lateData[Object.keys(lateData)[i]]['late-approved']); } dataBar2['datasets'][3]['backgroundColor'] = this.COLOR_LATE_APPROVED; dataBar2['datasets'][4]['label'] = 'Late Reported'; dataBar2['datasets'][4]['data'] = []; for (i = 0; i < Object.keys(lateData).length; i++) { dataBar2['datasets'][4]['data'].push(lateData[Object.keys(lateData)[i]]['late-reported']); } dataBar2['datasets'][4]['backgroundColor'] = this.COLOR_LATE_REPORTED; return dataBar2; } populateGraphDataBarCompliance = (complianceData: any) => { const dataBar2: any = {}; dataBar2['labels'] = []; for (var i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['labels'].push(this.formatLabel(Object.keys(complianceData)[i], 15)); } dataBar2['datasets'] = []; dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'].push({}); dataBar2['datasets'][0]['label'] = 'Scheduled'; dataBar2['datasets'][0]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][0]['data'].push(complianceData[Object.keys(complianceData)[i]]['scheduled']); } dataBar2['datasets'][0]['backgroundColor'] = this.COLOR_SCHEDULED; dataBar2['datasets'][1]['label'] = 'Not Complied'; dataBar2['datasets'][1]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][1]['data'].push(complianceData[Object.keys(complianceData)[i]]['not-complied']); } dataBar2['datasets'][1]['backgroundColor'] = this.COLOR_NOT_COMPLIED; dataBar2['datasets'][2]['label'] = 'Partially Complied'; dataBar2['datasets'][2]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][2]['data'].push(complianceData[Object.keys(complianceData)[i]]['partially-complied']); } dataBar2['datasets'][2]['backgroundColor'] = this.COLOR_PARTIALLY_COMPLIED; dataBar2['datasets'][3]['label'] = 'Complied'; dataBar2['datasets'][3]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][3]['data'].push(complianceData[Object.keys(complianceData)[i]]['complied']); } dataBar2['datasets'][3]['backgroundColor'] = this.COLOR_COMPLIED; dataBar2['datasets'][4]['label'] = 'Complied With Gaps'; dataBar2['datasets'][4]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][4]['data'].push(complianceData[Object.keys(complianceData)[i]]['complied-with-gaps']); } dataBar2['datasets'][4]['backgroundColor'] = this.COLOR_COMPLIED_WITH_EXCEPTION; dataBar2['datasets'][5]['label'] = 'Reported Non Compliance'; dataBar2['datasets'][5]['data'] = []; for (i = 0; i < Object.keys(complianceData).length; i++) { dataBar2['datasets'][5]['data'].push(complianceData[Object.keys(complianceData)[i]]['reported-non-compliance']); } dataBar2['datasets'][5]['backgroundColor'] = this.COLOR_REPORTED_NON_COMPLIANCE; return dataBar2; } populateGraphDataPie = (pieData: any) => { const data: any = {}; data['labels'] = []; data['datasets'] = []; data['datasets'].push({}); data['datasets'][0]['data'] = []; data['datasets'][0]['backgroundColor'] = []; data['datasets'][0]['borderWidth'] = 1; for (var i = 0; i < Object.keys(pieData).length; i++) { data['labels'].push(Object.keys(pieData)[i]); } for (var i = 0; i < Object.keys(pieData).length; i++) { data['datasets'][0]['data'].push(pieData[Object.keys(pieData)[i]]); data['datasets'][0]['backgroundColor'].push(Util.getRandomColor(i)); } return data; } renderPieCsv = (pieData: any, csv: string, param: string) => { csv += '"' + param + '",' for (var i = 0; i < Object.keys(pieData).length; i++) { csv += '"' + (Object.keys(pieData)[i]) + '"' if (i < (Object.keys(pieData).length - 1)) { csv += ',' } } csv += '\n' csv += '"Count",' for (var i = 0; i < Object.keys(pieData).length; i++) { csv += '"' + (pieData[Object.keys(pieData)[i]]) + '"' if (i < (Object.keys(pieData).length - 1)) { csv += ',' } } csv += '\n' return csv; } renderGraph = (divContainer: HTMLDivElement, pieData: any, partData: any, lateData: any, complianceData: any, param: string, flagBarChart: boolean, flagInModal: boolean) => { console.log('rendering graph chart2', pieData, partData); this.clearSelectedGraphParam(); // this.clearSelectedLegend(); this.csvGraphStats = ""; this.csvCompletenessStats = ""; this.csvTimelinessStats = ""; this.csvComplianceStats = ""; if (pieData == null) return; // this.clearGraph(divContainer, 4); const data: any = this.populateGraphDataPie(pieData); this.csvGraphStats = this.renderPieCsv(pieData, this.csvGraphStats, param); const ctx = divContainer.querySelector('#myChart') as ChartItem; this.renderChartSettings(divContainer, -1, -1, ctx); if (flagBarChart) { this.renderChart(ctx, 'bar', data, param + " Distribution", true, flagInModal) } else { this.renderChart(ctx, 'pie', data, param + " Distribution", true, flagInModal) } // 2 const dataBar: any = this.populateGraphDataBarPart(partData); const ctx2 = divContainer.querySelector('#myChart2') as ChartItem; this.showGraph(divContainer, 2); this.renderChart2(ctx2, 'bar', dataBar, param + " vs Completeness") this.renderCompletenessCsvForGraph(dataBar, param + " Completeness Breakdown") // 3 const dataBar2: any = this.populateGraphDataBarLate(lateData); const ctx3 = divContainer.querySelector('#myChart3') as ChartItem; this.showGraph(divContainer, 3); this.renderChart3(ctx3, 'bar', dataBar2, param + " vs Timeliness") this.renderTimelinessCsvForGraph(dataBar2, param + " Timeliness Breakdown") // 4 //console.log('rendering compliance matrix', complianceData); const dataBar3: any = this.populateGraphDataBarCompliance(complianceData); console.log('rendering compliance matrix', dataBar3); const ctx4 = divContainer.querySelector('#myChart4') as ChartItem; this.showGraph(divContainer, 4); this.renderChart4(ctx4, 'bar', dataBar3, param + " vs Compliance") this.renderComplianceCsvForGraph(dataBar3, param + " Compliance Breakdown") const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf; for (var i = 0; i < itemsTimeliness.length; i++) { itemsTimeliness[i].style.display = 'flex'; } const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf; for (var i = 0; i < itemsCompleteness.length; i++) { itemsCompleteness[i].style.display = 'flex'; } const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf; for (var i = 0; i < itemsCompliance.length; i++) { itemsCompliance[i].style.display = 'flex'; } let flagFilterFound = false; for (let label of data.labels) { if (label.toLowerCase() === this.graphFilter) { flagFilterFound = true; break; } } if (!flagFilterFound) { this.graphFilter = "" } } renderStatisticsDetails = async (filter: string, filterid: string, filtervalue: string, filterstatus: string = "") => { let userid = this.userProfileId // let username = this.userName; let filterString = `countryid="${this.countryId}" locationid="${this.locationId}" entityid="${this.entityId}" tagid="${this.tagId}" selectedcriteria="${this.selectedCriteria}"`; console.log('FilterString', filterString) let rolestr = "viewer" ; if (filter == "reporter" || filter == "approver" || filter == "functionhead") { userid = filterid; // username = filtervalue; rolestr = filter await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, userid, rolestr, this.entityId, this.countryId, this.locationId, this.tagId, this.functionId); filterString = `${filter} - ${filtervalue}`; } else if (filter == "function") { await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, this.userProfileId, rolestr, this.entityId, "", "", filterid, this.functionId); // filterString = `tagid="${filterid}" selectedcriteria="Tag - ${filtervalue}"`; filterString = `Function - ${filtervalue}`; } else if (filter == "location") { await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, this.userProfileId, rolestr, this.entityId, "", filterid, this.tagId, this.functionId); // filterString = `locationid="${filterid}" selectedcriteria="Location - ${filtervalue}"`; filterString = `Location - ${filtervalue}`; } var html = `

Statistics Details: ${filterString}

`; html += `
`; (this._SfDetailListContainer as HTMLDivElement).style.display = 'block'; (this._SfDetailListContainer as HTMLDivElement).innerHTML = html; const lastDay = ((new Date(this.edate).getTime()) - new Date(this.sdate).getTime()) / (1000 * 60 * 60 * 24) let firstDay = new Date((new Date(this.sdate)).getFullYear(), (new Date(this.sdate)).getMonth(), (new Date(this.sdate)).getDate()); let endDay = new Date((new Date(this.sdate)).getFullYear(), (new Date(this.sdate)).getMonth(), (new Date(this.sdate)).getDate()); endDay?.setDate(endDay.getDate() + lastDay); console.log('firstday', firstDay, endDay) var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDay.getDate()).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear(); console.log('rangeperiod', period, lastDay); var htmlEvents = this.renderEvents(firstDay, endDay, 0, lastDay, false, 0, ((new Date(this.sdate)).getMonth()), period, (new Date(this.sdate)), "From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), false, true); ((this._SfDetailListContainer as HTMLDivElement).querySelector('#list-container') as HTMLDivElement).innerHTML = htmlEvents; let divContainer = ((this._SfDetailListContainer as HTMLDivElement).querySelector('#list-container') as HTMLDivElement) const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf; for (var i = 0; i < itemsTimeliness.length; i++) { itemsTimeliness[i].style.display = 'none'; } const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf; for (var i = 0; i < itemsCompliance.length; i++) { itemsCompliance[i].style.display = 'none'; } if (filterstatus != "") { this.processGraphFilter(filterstatus, divContainer); } (this._SfDetailListContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailListContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailListContainer as HTMLDivElement).style.display = 'none'; }); const buttonArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf; for (i = 0; i < buttonArr.length; i++) { let indexPrevNext = i; buttonArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { console.log('selectedItems', this.selectedItemIds[k], idArr[3] + '-' + idArr[4] + '-' + idArr[5], this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5])); if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; //console.log('commentsinlist', (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement, this.events[mmdd][j].comments, mmdd, j); let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id; flagPrev = false; } else { prevString = ""; indexPrev-- } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < buttonArr.length - 1) { if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) { nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id; flagNext = false; } else { nextString = ""; indexNext++ } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement); // console.log('errorFetchEvent', mmdd, j, buttonArr[i].outerHTML, idArr); console.log('previous event clicked', buttonArr[indexPrevNext - 1], prevString, indexPrevNext); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfStreamContainer as HTMLDivElement, prevString, nextString, false, null, null, null, null, null, null, null, true); } }) } const titleArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf; for (var i = 0; i < titleArr.length; i++) { let indexPrevNext = i; titleArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; const module = idArr[6]; const flag = idArr[7]; if (flag != null && flag == "reportedlocations") { return; } var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]); if (module === "notice") { this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "contract") { this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "license") { this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else if (module === "rcmresource") { this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy) } else { let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.selectedItems = []; this.clearButtonSelection(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block' let prevString = ""; let flagPrev = true; let indexPrev = indexPrevNext while (flagPrev) { if (indexPrev > 0) { if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) { prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id; let prevIdArr = prevString.split("-") if ((prevIdArr[7] ?? "") == "reportedlocations") { prevString = ""; indexPrev--; } else { flagPrev = false; } } else { prevString = ""; indexPrev--; } } else { flagPrev = false; } } let nextString = ""; let flagNext = true; let indexNext = indexPrevNext while (flagNext) { if (indexNext < titleArr.length - 1) { if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) { nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id; let nextIdArr = nextString.split("-") if ((nextIdArr[7] ?? "") == "reportedlocations") { nextString = ""; indexNext++; } else { flagNext = false; } } else { indexNext++; } } else { flagNext = false; } } // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null); this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfStreamContainer as HTMLDivElement), prevString, nextString, false, null, null, null, null, null, null, null, true); } }) } const buttonRenewArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf; for (var i = 0; i < buttonRenewArr.length; i++) { buttonRenewArr[i].addEventListener('click', async (ev: any) => { const id = ev.target.id; const idArr = id.split("-") console.log('idArr', idArr); const mmdd = idArr[2] + "/" + idArr[3]; const j = idArr[4]; const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]); let renewEvent = this.events[mmdd][j]; let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true); console.log('renew clicked', fullEvent, fullEvent.reportformatvalues); this.renewRCMResource(fullEvent, fullEvent.reportformatvalues); }) } } renderEventDetailShort = (compliance: any, selectedCountry: string, selectedStatute: string) => { var html = `

Compliance Details

`; let shortId: string = ""; console.log('shoiwing compliance', compliance); const data = JSON.parse(compliance.data); console.log('compliance data', data) const cols = JSON.parse(compliance.cols); const configHome = Util.getProjectConfigHome(); const showUnderstood = (configHome.features == null || (configHome.features.indexOf('hide-understood') < 0)) && (this.myRole == this.TAB_REPORTER) html += '
' html += data[cols.indexOf('obligationtitle')].replace(/\\n|\r?\n/g, ' ') html += '
' html += '
' const understood = compliance.understood ?? -1; html += '
' html += '
Review this compliance
' if (showUnderstood) { html += `



` } html += '
' html += '' // html += '
' // html += '
' html += (''); html += (''); html += (''); html += '
'; html += '
'; html += '
' html += '
Your obligation is:
' html += '
' + data[cols.indexOf('obligation')].replace(/\\n|\r?\n/g, '
') + '
' html += '
' html += '
' html += '
This is applicable to:
' html += '
' + data[cols.indexOf('applicability')] + '
' html += '
This is mapped to Entities:
' let entities = [] for (let entity of compliance.entities ?? []) { entities.push(entity.split(';')[0].replace(/\([^)]*\)/g, "")) } html += '
' + entities.join(', ') + '
' html += '
This is mapped to Locations:
' let locations = [] for (let location of compliance.locations ?? []) { locations.push(location.split(';')[0].replace(/\([^)]*\)/g, "")) } html += '
' + locations.join(', ') + '
' html += '
' html += '
' html += '
'; html += '
'; html += '
'; //console.log('cols', cols, cols.length); for (var k = 0; k < cols.length; k++) { if (!this.EXCLUDE_COLS_FROM_REGS.includes(cols[k].toLowerCase())) { if (cols[k].toLowerCase() == "attachment") { console.log('attachments', data[k]); if (typeof data[k] === "string") { let attachmentArr = JSON.parse(data[k].toString()); if (attachmentArr.length > 0) { html += '
'; html += '
' + cols[k] + '
' for (let attachment of attachmentArr) { html += `` } html += '
'; } } else { html += '
'; html += '
' + cols[k] + '
' for (let attachmentStr of data[k]) { let attachment: any = {}; if (typeof attachmentStr === "object") { attachment = attachmentStr; } else { attachment = JSON.parse(attachmentStr.toString()); } html += `` } html += '
'; } // html += '
'; } else { html += '
'; html += '
' + cols[k] + '
' html += ''; html += '
'; } } if (cols[k].toLowerCase() == "shortid") { shortId = (data[k]); if(Util.isJSONParsable(shortId)){ shortId = JSON.parse(shortId)[0] } } } console.log('shortid', shortId); html += '
'; // html += '
' // html += '
' // html += '' // html += '
' // html += '
' // html += (''); // html += (''); // html += (''); // html += '
' // html += '
' html += '
'; html += '
'; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); let radios = ((this._SfDetailContainer as HTMLDivElement).querySelectorAll("input[type=radio]") as NodeListOf) for (let radio of radios) { if (understood >= 2 && parseInt(radio.value) == 1) { radio.checked = true; } else if (understood >= 4 && parseInt(radio.value) == 3) { radio.checked = true; } else if (understood === parseInt(radio.value)) { radio.checked = true; } radio.addEventListener('change', async () => { let understood = parseInt(radio.value) ?? -1; let radioContainerDiv1 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-1') as HTMLDivElement if (understood >= 1) { if (radioContainerDiv1 != null) { radioContainerDiv1.classList.remove('hide') } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-2') as HTMLInputElement).checked && understood < 3) { understood = 2 } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-3') as HTMLInputElement).checked && understood < 3) { understood = 3 } } else { if (radioContainerDiv1 != null) { radioContainerDiv1.classList.add('hide') } } let radioContainerDiv2 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-2') as HTMLDivElement if (understood >= 3) { if (radioContainerDiv2 != null) { radioContainerDiv2.classList.remove('hide') } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-4') as HTMLInputElement).checked) { understood = 4 } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-5') as HTMLInputElement).checked) { understood = 5 } } else { if (radioContainerDiv2 != null) { radioContainerDiv2.classList.add('hide') } } if (understood != 1 && understood != 3) { let resultMarkUnderstood = await this.markUnderstood(compliance.id, this.userProfileId, understood); console.log('mark understood result', resultMarkUnderstood, selectedCountry, selectedStatute, this.registerEvents) if (resultMarkUnderstood.result) { this.registerEvents[selectedCountry][selectedStatute][compliance.id].understood = understood; this.renderRegisterEvents(this.registerEvents); } } // const buttonSaveUnderstood = (this._SfDetailContainer as HTMLDivElement).querySelector('#button-save-understood') as HTMLButtonElement // if (buttonSaveUnderstood != null) { // console.log('understood', understood) // if (understood != 1 && understood != 3) { // buttonSaveUnderstood.classList.remove('hide') // } else { // buttonSaveUnderstood.classList.add('hide') // } // } }) }; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-save-understood')?.addEventListener('click', async () => { let understood = -1; if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-0') as HTMLInputElement).checked) { understood = 0 } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-1') as HTMLInputElement).checked) { understood = 1 } let radioContainerDiv1 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-1') as HTMLDivElement if (!radioContainerDiv1.classList.contains('hide')) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-2') as HTMLInputElement).checked) { understood = 2 } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-3') as HTMLInputElement).checked) { understood = 3 } } let radioContainerDiv2 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-2') as HTMLDivElement if (!radioContainerDiv2.classList.contains('hide')) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-4') as HTMLInputElement).checked) { understood = 4 } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-5') as HTMLInputElement).checked) { understood = 5 } } console.log('understood save', understood); let resultMarkUnderstood = await this.markUnderstood(compliance.id, this.userProfileId, understood); console.log('mark understood result', resultMarkUnderstood, selectedCountry, selectedStatute, this.registerEvents) if (resultMarkUnderstood.result) { this.registerEvents[selectedCountry][selectedStatute][compliance.id].understood = understood, this.renderRegisterEvents(this.registerEvents); const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement); buttonClose.click() } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback')?.addEventListener('click', () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); console.log(buttonConfirm.classList); if (feedbackMessage.classList.contains('hide')) { feedbackMessage.classList.remove('hide'); } if (buttonConfirm.classList.contains('hide')) { buttonConfirm.classList.remove('hide'); } if (buttonCancel.classList.contains('hide')) { buttonCancel.classList.remove('hide'); } if (!buttonFeedback.classList.contains('hide')) { buttonFeedback.classList.add('hide'); } // const body = { // projectid: this.projectId, // complianceid: compliance.id // } // console.log(body); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel')?.addEventListener('click', () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); console.log(buttonConfirm.classList); if (!feedbackMessage.classList.contains('hide')) { feedbackMessage.classList.add('hide'); } if (!buttonConfirm.classList.contains('hide')) { buttonConfirm.classList.add('hide'); } if (!buttonCancel.classList.contains('hide')) { buttonCancel.classList.add('hide'); } if (buttonFeedback.classList.contains('hide')) { buttonFeedback.classList.remove('hide'); } }); // ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement).addEventListener('change', (e) => { // }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm')?.addEventListener('click', async () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement); if (feedbackMessage.value.length === 0) { feedbackMessage.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important'); } else { feedbackMessage.setAttribute('style', 'border:'); const cols = JSON.parse(compliance.cols) as Array; const data = JSON.parse(compliance.data) console.log(compliance, cols, data); this.uploadTriggerMyEvent( compliance.id + " - " + shortId, feedbackMessage.value, compliance.countries.join(",").replace(/ *\([^)]*\) */g, ""), compliance.entities.join(',').replace(/ *\([^)]*\) */g, ""), compliance.locations.join(',').replace(/ *\([^)]*\) */g, ""), data[cols.indexOf('statute')][0], data[cols.indexOf('subcategory')][0], { obligationtitle: data[cols.indexOf('obligationtitle')], obligation: data[cols.indexOf('obligation')], reference: data[cols.indexOf('reference')] } ); buttonCancel.click(); buttonClose.click(); } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message')?.addEventListener('keyup', (e: any) => { let feedbackMessage = e.currentTarget as HTMLInputElement if (feedbackMessage != null && feedbackMessage.value != null && feedbackMessage.value.length !== 0 && ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement).disabled = false } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement).disabled = true } if (e.code == "Enter") { const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); buttonConfirm.click(); } }) } fetchNoticeDetails = async (listEvent: any) => { console.log('listEvent', listEvent, listEvent.id) let url = "https://" + this.apiIdNotices + "/details"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "noticeid": listEvent.id }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose notice details', jsonRespose); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderNoticeDetails = async (listEvent: any, mmddyyyy: string) => { let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let entityId = listEvent.entityid; let locationId = listEvent.locationid; let comments = listEvent['comments']; let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']); let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved']; let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers']; let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; let html: string = ''; let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0]; html += `

Notice Details

` html += `
` html += ''; if (this.mode != "viewer") { html += '
' html += this.renderReporting(listEvent, mmddyyyy); html += "
" } html += '
'; html += '


Comments

'; html += '
'; html += '
'; html += '
'; for (var i = 0; i < comments.length; i++) { html += '
'; html += '
' + (comments[i].username != null ? comments[i].username : '') + '' + comments[i].author + '' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '
' : '') + '
'; const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim(); try { const jsonComments = JSON.parse(onlyCommentText); if (Util.isInteger(jsonComments)) { html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } else { //console.log('json comments', jsonComments); var htmlTable = ''; for (var j = 0; j < Object.keys(jsonComments).length; j++) { htmlTable += '
'; htmlTable += ('
' + Object.keys(jsonComments)[j] + '
'); htmlTable += (''); htmlTable += '
'; } html += '
' + htmlTable + '' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } } catch (e: any) { //console.log('json comments exception', comments[i]); html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } html += '
'; } if (comments.length === 0) { html += '
No comments yet!
'; } html += '
'; html += '
'; (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting sfireporting.selectedItem = listEvent; sfireporting.loadMode(); sfireporting.addEventListener('valueChanged', () => { sfireporting.classList.remove('hide'); ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-notices') as HTMLDivElement).classList.add('hide'); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => { // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId); // this.setSuccess('Deleted successfully!') // setTimeout(() => { // this.clearMessages() // }, 3000); // //console.log('deleted', resultDelete); // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } // } console.log('delete review clicked') var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length === 0) { // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], "Auto approved", true); // this.setSuccess('Auto-Approved successfully!') // setTimeout(() => { // this.clearMessages() // }, 3000); console.log('audto approve single') } else { // let bulkBodyReview = [] // for(var k = 0; k < this.selectedItemIds.length; k++) { // const selectedId = this.selectedItemIds[k]; // //console.log('selectedid', selectedId); // entityId = selectedId.split('-')[7].replace(/_/g, '-'); // locationId = selectedId.split('-')[8].replace(/_/g, '-'); // const eventId = selectedId.split('-')[9].replace(/_/g, '-'); // mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; // //console.log(entityId, locationId, eventId, mmddyyyy); // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "review", // "eventid": eventId, // "comments": "Auto approved", // "approved": true, // "entityid": entityId, // "locationid": locationId, // "username": this.userName, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY // }) // } // await this.uploadReviewsBulk(bulkBodyReview); console.log('auto approve bulk') } //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); if (this.mode == "consumer" || this.mode == "next") { (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved) let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('mmddyyyy', mmddyyyy) if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) console.log('review single') } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('review bulk') } if (this.mode == "next") { // this.fetchNext(this.nextPage) this.renderRoleTabsNext(this.nextPage) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } console.log('uploadaudit single') } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": listEvent.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('uploadAudit bulk') } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (approved) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); const reporterdoc = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); let percentage: string = "100"; if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value } // if(docsOptional.length === 0) { docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } let flag = false; do { if (docs.length > 0 && docsOptional != null && docsOptional.length === 0 && parseInt(percentage) > 0) { for (let doc of docs) { if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) { flag = false } else { flag = true; } } } else { flag = true; } if (flag === false) { await this.sleep(1000); console.log('waiting for docs', docs); docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); } } while (flag === false); //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (this._SfReporting[0] != null) { reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? ""; reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? ""; } if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('Invalid Percentage!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { if (docs.length === 0 && docsOptional.length === 0) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('No documents uploaded!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('reporterdoc', reporterdoc); if (reporterdoc.length === 0) { buttonClick.innerHTML = "Save" this.setError('Date of completion not selected!'); setTimeout(() => { this.clearMessages(); }, 3000); } else if (parseInt(reporterdoc) > new Date().getTime()) { buttonClick.innerHTML = "Save" this.setError('Date of completion cannot be in future!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('makerscheckers 1', reportercomments); if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) { console.log('this.events', this.events); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } console.log('uploadReport single') if (makercheckers.length > 0) { // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = true // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } console.log('upload report auto approve single') } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null) // if(parseInt(makercheckersL) > 0) { // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "report", // "eventid": eventId, // "comments": reportercomments, // "dateofcompletion": reporterdoc, // "percentage": percentage, // "entityid": entityId, // "locationid": locationId, // "event": null, // "docs": JSON.stringify(docs), // "approved": true, // "username": this.userName, // "reportformatvalues": reportformatvalues, // "reportformatschema": reportformatschema, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY, // "module": listEvent.module ?? "compliance" // } ) // // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true); // }else{ let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) // } // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } // await this.uploadReportsBulk(bulkBody); // await this.fetchBulkReportingData(); if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } // if(bulkBodyReview.length > 0){ // await this.uploadReportsReviewsBulk(bulkBodyReview) // } await this.fetchBulkReportingData(); console.log('uploadReport bulk') for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } } } } }); } } } if (this._SfUploader[0] != null) { (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" }); //console.log('documentType checking', documentType); if (documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: listEvent.entityid, locationId: listEvent.locationid, mmddyyyy: mmddyyyy, complianceId: listEvent['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (listEvent["approved"] != null) { if (listEvent["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } } fetchContractDetails = async (listEvent: any, mmddyyyy: string) => { let entityId = listEvent.entityid; let locationId = listEvent.locationid; let url = "https://" + this.apiIdAgreements + "/getallobjectdetails"; //console.log('fetch calendar url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement details', jsonRespose); this.renderContractDetails(jsonRespose.object, mmddyyyy) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renewContract = async (listEvent: any, reportformatvalues: any) => { let url = "https://" + this.apiIdAgreements + "/reopen"; console.log('renewing', reportformatvalues) //console.log('fetch calendar url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) }; // console.log('reopen body', url, urlBody) const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement reopen', jsonRespose); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderContractDetails = async (listEvent: any, mmddyyyy: string) => { // await this.fetchAgreementDetails(listEvent, mmddyyyy); // return; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let entityId = listEvent.entityid; let locationId = listEvent.locationid; let comments = listEvent['comments']; let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']); let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved']; let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers']; // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; let html: string = ''; let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0]; html += `

Agreement Details

` html += `
` html += ''; if (this.mode != "viewer") { html += '
' html += this.renderReporting(listEvent, mmddyyyy); html += "
" } html += '
'; html += '


Comments

'; html += '
'; html += '
'; html += '
'; for (var i = 0; i < comments.length; i++) { html += '
'; html += '
' + (comments[i].username != null ? comments[i].username : '') + '' + comments[i].author + '' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '
' : '') + '
'; const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim(); try { const jsonComments = JSON.parse(onlyCommentText); if (Util.isInteger(jsonComments)) { html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } else { //console.log('json comments', jsonComments); var htmlTable = ''; for (var j = 0; j < Object.keys(jsonComments).length; j++) { htmlTable += '
'; htmlTable += ('
' + Object.keys(jsonComments)[j] + '
'); htmlTable += (''); htmlTable += '
'; } html += '
' + htmlTable + '' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } } catch (e: any) { //console.log('json comments exception', comments[i]); html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } html += '
'; } if (comments.length === 0) { html += '
No comments yet!
'; } html += '
'; html += '
'; console.log('selected event', JSON.stringify(listEvent)); (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; let usermap = Util.getUsermap(); let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting sfireporting.usermap = JSON.stringify(usermap); sfireporting.selectedItem = listEvent; sfireporting.editdisable = "true" setTimeout(() => { console.log('sfireporting', sfireporting._SfReportingContainer); sfireporting.loadMode(); }, 500); sfireporting.addEventListener('valueChanged', () => { sfireporting.classList.remove('hide'); ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide'); }); let reportingSchemaJson = ""; let reportingSchemaValues = "" if (listEvent.reportformatschema != null) { reportingSchemaJson = listEvent.reportformatschema reportingSchemaValues = listEvent.reportformatvalues } else if (listEvent.customreporting != null) { reportingSchemaJson = listEvent.customreporting } if (listEvent.customreporting != null || listEvent.reportformatschema != null) { let reportingHtml = '' let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf; for (let [indexContainer, reportFormatContainer] of Array.from(reportFormatContainers).entries()) { if (reportFormatContainer != null) { reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer.toString()); } } } let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf for (let reportingReporting of reportingReportings) { if (reportingSchemaJson != "" && reportingReporting != null) { reportingReporting.configjson = reportingSchemaJson; if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view" reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true" reportingReporting.flow = "reporting" setTimeout(() => { reportingReporting.loadMode(); console.log('list-customreporting', reportingSchemaJson); console.log('list-customreporting1', reportingSchemaValues); console.log('list-customreporting2', reportingReporting.mode); }, 500) } } (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => { // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId); // this.setSuccess('Deleted successfully!') // setTimeout(() => { // this.clearMessages() // }, 3000); // //console.log('deleted', resultDelete); // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } // } console.log('delete review clicked') var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length === 0) { console.log('audto approve single') } else { console.log('auto approve bulk') } //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); if (this.mode == "consumer" || this.mode == "next") { (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } let reportformatvalues = "" let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting console.log('renew reporting', reportingReporting) if (reportingReporting != null) { reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? ""; } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved) let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('mmddyyyy', mmddyyyy) if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { if (approved) { await this.renewContract(listEvent, reportformatvalues); } else { console.log('renew reporting', reportformatvalues) } for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) console.log('review single') } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('review bulk') } if (this.mode == "next") { // this.fetchNext(this.nextPage) this.renderRoleTabsNext(this.nextPage) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } console.log('uploadaudit single') } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": listEvent.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('uploadAudit bulk') } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (approved) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; const reporterdoc = new Date().getTime() + ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); // if(docsOptional.length === 0) { // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (listEvent.customreporting != null) { let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting if (reportingReporting == null) { reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting } console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues())) reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? ""; reportformatschema = reportingReporting!.configjson ?? ""; } let percentage: string = "100"; if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value } // if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) { // //console.log('reporter comments 3', reportercomments); // buttonClick.innerHTML = "Save" // this.setError('Invalid Percentage!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { // if (docs.length === 0 && docsOptional.length === 0) { // //console.log('reporter comments 3', reportercomments); // buttonClick.innerHTML = "Save" // this.setError('No documents uploaded!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { // //console.log('reporterdoc', reporterdoc); // if (reporterdoc.length === 0) { // buttonClick.innerHTML = "Save" // this.setError('Date of completion not selected!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else if (parseInt(reporterdoc) > new Date().getTime()) { // buttonClick.innerHTML = "Save" // this.setError('Date of completion cannot be in future!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { //console.log('makerscheckers 1', reportercomments); if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) { console.log('this.events', this.events); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } console.log('uploadReport single') if (makercheckers.length > 0) { // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = true this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } await this.renewContract(listEvent, reportformatvalues); console.log('upload report auto approve single') } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null) // if(parseInt(makercheckersL) > 0) { // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "report", // "eventid": eventId, // "comments": reportercomments, // "dateofcompletion": reporterdoc, // "percentage": percentage, // "entityid": entityId, // "locationid": locationId, // "event": null, // "docs": JSON.stringify(docs), // "approved": true, // "username": this.userName, // "reportformatvalues": reportformatvalues, // "reportformatschema": reportformatschema, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY, // "module": listEvent.module ?? "compliance" // } ) // // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true); // }else{ let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) // } // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } // await this.uploadReportsBulk(bulkBody); // await this.fetchBulkReportingData(); if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } // if(bulkBodyReview.length > 0){ // await this.uploadReportsReviewsBulk(bulkBodyReview) // } await this.fetchBulkReportingData(); console.log('uploadReport bulk') for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } // } // } // } }); } } } if (this._SfUploader[0] != null) { (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" }); //console.log('documentType checking', documentType); if (documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: listEvent.entityid, locationId: listEvent.locationid, mmddyyyy: mmddyyyy, complianceId: listEvent['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (listEvent["approved"] != null) { if (listEvent["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } } fetchLicenseDetails = async (listEvent: any, mmddyyyy: string) => { let entityId = listEvent.entityid; let locationId = listEvent.locationid; let url = "https://" + this.apiIdLicenses + "/getallobjectdetails"; console.log('fetch license details url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy }; console.log('fetch license details urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement details', jsonRespose); this.renderLicenseDetails(jsonRespose.object, mmddyyyy) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renewLicense = async (listEvent: any, reportformatvalues: any) => { let url = "https://" + this.apiIdLicenses + "/reopen"; console.log('renewing', reportformatvalues) //console.log('fetch calendar url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) }; // console.log('reopen body', url, urlBody) const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement reopen', jsonRespose); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderLicenseDetails = async (listEvent: any, mmddyyyy: string) => { // await this.fetchAgreementDetails(listEvent, mmddyyyy); // return; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let entityId = listEvent.entityid; let locationId = listEvent.locationid; let comments = listEvent['comments']; let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']); let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved']; let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers']; // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; let html: string = ''; let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0]; html += `

License Details

` html += `
` html += ''; if (this.mode != "viewer") { html += '
' html += this.renderReporting(listEvent, mmddyyyy); html += "
" } html += '
'; html += '


Comments

'; html += '
'; html += '
'; html += '
'; for (var i = 0; i < comments.length; i++) { html += '
'; html += '
' + (comments[i].username != null ? comments[i].username : '') + '' + comments[i].author + '' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '
' : '') + '
'; const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim(); try { const jsonComments = JSON.parse(onlyCommentText); if (Util.isInteger(jsonComments)) { html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } else { //console.log('json comments', jsonComments); var htmlTable = ''; for (var j = 0; j < Object.keys(jsonComments).length; j++) { htmlTable += '
'; htmlTable += ('
' + Object.keys(jsonComments)[j] + '
'); htmlTable += (''); htmlTable += '
'; } html += '
' + htmlTable + '' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } } catch (e: any) { //console.log('json comments exception', comments[i]); html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } html += '
'; } if (comments.length === 0) { html += '
No comments yet!
'; } html += '
'; html += '
'; console.log('selected event', JSON.stringify(listEvent)); (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; let usermap = Util.getUsermap(); let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting sfireporting.usermap = JSON.stringify(usermap); sfireporting.selectedItem = listEvent; sfireporting.editdisable = "true" setTimeout(() => { console.log('sfireporting', sfireporting._SfReportingContainer); console.log('sfireporting', sfireporting.selectedItem); sfireporting.loadMode(); }, 500); sfireporting.addEventListener('valueChanged', () => { sfireporting.classList.remove('hide'); ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide'); }); let reportingSchemaJson = ""; let reportingSchemaValues = "" if (listEvent.reportformatschema != null) { reportingSchemaJson = listEvent.reportformatschema reportingSchemaValues = listEvent.reportformatvalues } else if (listEvent.customreporting != null) { reportingSchemaJson = listEvent.customreporting } if (listEvent.customreporting != null || listEvent.reportformatschema != null) { let reportingHtml = '' let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf; for (let [indexContainer, reportFormatContainer] of reportFormatContainers.entries()) { if (reportFormatContainer != null) { reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer + ''); } } } let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf for (let reportingReporting of reportingReportings) { if (reportingSchemaJson != "" && reportingReporting != null) { reportingReporting.configjson = reportingSchemaJson; if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view" reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true" reportingReporting.flow = "reporting" setTimeout(() => { reportingReporting.loadMode(); console.log('list-customreporting', reportingSchemaJson); console.log('list-customreporting1', reportingSchemaValues); console.log('list-customreporting2', reportingReporting.mode); }, 500) } } (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => { // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId); // this.setSuccess('Deleted successfully!') // setTimeout(() => { // this.clearMessages() // }, 3000); // //console.log('deleted', resultDelete); // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } // } console.log('delete review clicked') var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length === 0) { console.log('audto approve single') } else { console.log('auto approve bulk') } //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); if (this.mode == "consumer" || this.mode == "next") { (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } let reportformatvalues = "" let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting console.log('renew reporting', reportingReporting) if (reportingReporting != null) { reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? ""; } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved) let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('mmddyyyy', mmddyyyy) if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { if (approved) { await this.renewLicense(listEvent, reportformatvalues); } else { console.log('renew reporting', reportformatvalues) } for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) console.log('review single') } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('review bulk') } if (this.mode == "next") { // this.fetchNext(this.nextPage) this.renderRoleTabsNext(this.nextPage) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } console.log('uploadaudit single') } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": listEvent.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('uploadAudit bulk') } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (approved) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; const reporterdoc = new Date().getTime() + ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); // if(docsOptional.length === 0) { // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (listEvent.customreporting != null) { let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting if (reportingReporting == null) { reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting } console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues())) reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? ""; reportformatschema = reportingReporting!.configjson ?? ""; } let percentage: string = "100"; if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value } // if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) { // //console.log('reporter comments 3', reportercomments); // buttonClick.innerHTML = "Save" // this.setError('Invalid Percentage!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { // if (docs.length === 0 && docsOptional.length === 0) { // //console.log('reporter comments 3', reportercomments); // buttonClick.innerHTML = "Save" // this.setError('No documents uploaded!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { // //console.log('reporterdoc', reporterdoc); // if (reporterdoc.length === 0) { // buttonClick.innerHTML = "Save" // this.setError('Date of completion not selected!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else if (parseInt(reporterdoc) > new Date().getTime()) { // buttonClick.innerHTML = "Save" // this.setError('Date of completion cannot be in future!'); // setTimeout(() => { // this.clearMessages(); // }, 3000); // } else { //console.log('makerscheckers 1', reportercomments); if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) { console.log('this.events', this.events); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } console.log('uploadReport single') if (makercheckers.length > 0) { // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = true this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } await this.renewLicense(listEvent, reportformatvalues); console.log('upload report auto approve single') } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null) // if(parseInt(makercheckersL) > 0) { // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "report", // "eventid": eventId, // "comments": reportercomments, // "dateofcompletion": reporterdoc, // "percentage": percentage, // "entityid": entityId, // "locationid": locationId, // "event": null, // "docs": JSON.stringify(docs), // "approved": true, // "username": this.userName, // "reportformatvalues": reportformatvalues, // "reportformatschema": reportformatschema, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY, // "module": listEvent.module ?? "compliance" // } ) // // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true); // }else{ let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) // } // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } // await this.uploadReportsBulk(bulkBody); // await this.fetchBulkReportingData(); if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } // if(bulkBodyReview.length > 0){ // await this.uploadReportsReviewsBulk(bulkBodyReview) // } await this.fetchBulkReportingData(); console.log('uploadReport bulk') for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } // } // } // } }); } } } if (this._SfUploader[0] != null) { (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" }); //console.log('documentType checking', documentType); if (documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: listEvent.entityid, locationId: listEvent.locationid, mmddyyyy: mmddyyyy, complianceId: listEvent['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (listEvent["approved"] != null) { if (listEvent["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } } fetchRCMResourceDetails = async (listEvent: any, mmddyyyy: string, flagReturn: boolean = false) => { let entityId = listEvent.entityid; let locationId = listEvent.locationid; let url = "https://" + this.apiIdRCMResources + "/getallobjectdetails"; console.log('fetch rcm resource details url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy }; console.log('fetch rcm resource details urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement details', jsonRespose); if (flagReturn) { return jsonRespose.object; } else { this.renderRCMResourceDetails(jsonRespose.object, mmddyyyy) } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renewRCMResource = async (listEvent: any, reportformatvalues: any) => { let url = "https://" + this.apiIdRCMResources + "/reopen1"; console.log('renewing', reportformatvalues) //console.log('fetch calendar url', url); let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) }; console.log('reopen body', url, urlBody) const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Renewing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose agreement reopen', jsonRespose); this.setSuccess("Renewal successful"); setTimeout(() => { this.clearMessages() }, 3000) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderRCMResourceDetails = async (listEvent: any, mmddyyyy: string) => { // await this.fetchAgreementDetails(listEvent, mmddyyyy); // return; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let entityId = listEvent.entityid; let locationId = listEvent.locationid; let comments = listEvent['comments']; let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']); let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved']; let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers']; // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; let html: string = ''; let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0]; html += `

RCM Resource Details

` html += `
` html += ''; if (this.mode != "viewer") { html += '
' html += this.renderReporting(listEvent, mmddyyyy); html += "
" } html += '
'; html += '


Comments

'; html += '
'; html += '
'; html += '
'; for (var i = 0; i < comments.length; i++) { html += '
'; html += '
' + (comments[i].username != null ? comments[i].username : '') + '' + comments[i].author + '' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '
' : '') + '
'; const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim(); try { const jsonComments = JSON.parse(onlyCommentText); if (Util.isInteger(jsonComments)) { html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } else { //console.log('json comments', jsonComments); var htmlTable = ''; for (var j = 0; j < Object.keys(jsonComments).length; j++) { htmlTable += '
'; htmlTable += ('
' + Object.keys(jsonComments)[j] + '
'); htmlTable += (''); htmlTable += '
'; } html += '
' + htmlTable + '' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } } catch (e: any) { //console.log('json comments exception', comments[i]); html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } html += '
'; } if (comments.length === 0) { html += '
No comments yet!
'; } html += '
'; html += '
'; console.log('selected event', JSON.stringify(listEvent)); (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; let usermap = Util.getUsermap(); let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting sfireporting.usermap = JSON.stringify(usermap); sfireporting.selectedItem = listEvent; sfireporting.editdisable = "true" setTimeout(() => { console.log('sfireporting', sfireporting._SfReportingContainer); console.log('sfireporting', sfireporting.selectedItem); sfireporting.loadMode(); }, 500); sfireporting.addEventListener('valueChanged', () => { sfireporting.classList.remove('hide'); ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide'); }); let reportingSchemaJson = ""; let reportingSchemaValues = "" if (listEvent.reportformatschema != null && listEvent.reportformatschema != "") { reportingSchemaJson = listEvent.reportformatschema reportingSchemaValues = listEvent.reportformatvalues } else if (listEvent.customreporting != null) { reportingSchemaJson = listEvent.customreporting } // console.log('reporting schema', reportingSchemaJson) if (listEvent.customreporting != null || listEvent.reportformatschema != null) { let reportingHtml = '' let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf; for (let [indexContainer, reportFormatContainer] of reportFormatContainers.entries()) { if (reportFormatContainer != null) { reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer.toString()); } } } let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf for (let reportingReporting of reportingReportings) { if (reportingSchemaJson != "" && reportingReporting != null) { reportingReporting.configjson = reportingSchemaJson; if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues // reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view" // reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true" reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view" reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true" reportingReporting.flow = "reporting" setTimeout(() => { reportingReporting.loadMode(); console.log('list-customreporting', reportingSchemaJson); console.log('list-customreporting1', reportingSchemaValues); console.log('list-customreporting2', reportingReporting.mode); console.log('list-customreporting3', this.myRole); }, 500) } } (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => { // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId); // this.setSuccess('Deleted successfully!') // setTimeout(() => { // this.clearMessages() // }, 3000); // //console.log('deleted', resultDelete); // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } // } console.log('delete review clicked') var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length === 0) { console.log('audto approve single') } else { console.log('auto approve bulk') } //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); }); if (this.mode == "consumer" || this.mode == "next") { (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } let reportformatvalues: any = {} // let reportformatvaluesStr: string = "" let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting console.log('renew reporting', reportingReporting) if (reportingReporting != null) { reportformatvalues = reportingReporting!.selectedValues() // reportformatvaluesStr = JSON.stringify(reportingReporting!.selectedValues()) } let comparedObj = Util.compareObjects(reportformatvalues, JSON.parse(listEvent.reportformatvalues)) console.log('reportformatvalues', reportformatvalues, JSON.parse(listEvent.reportformatvalues), comparedObj) if (Object.keys(comparedObj).length > 0) { await this.sendSuggestions(listEvent.id, comparedObj); } // return; var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved) let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('mmddyyyy', mmddyyyy) if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { if (approved) { // await this.renewRCMResource(listEvent, reportformatvaluesStr); } else { console.log('renew reporting', reportformatvalues) } for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].terminated = (reportformatvalues.terminated) ?? false this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) console.log('review single') } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('review bulk') } if (this.mode == "next") { // this.fetchNext(this.nextPage) this.renderRoleTabsNext(this.nextPage) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(listEvent); let newEvent = { ...listEvent }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } console.log('uploadaudit single') } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": listEvent.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } console.log('uploadAudit bulk') } var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (approved) { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; const reporterdoc = new Date().getTime() + ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); // if(docsOptional.length === 0) { // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (listEvent.customreporting != null) { let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting if (reportingReporting == null) { reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting } console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues())) reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? ""; reportformatschema = reportingReporting!.configjson ?? ""; } let percentage: string = "100"; if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value } if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent); let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) { console.log('this.events', this.events); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } console.log('uploadReport single') if (makercheckers.length > 0) { // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].approved = true this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } // await this.renewRCMResource(listEvent, reportformatvalues); console.log('upload report auto approve single') } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(listEvent) } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; entityId = selectedId.split('-')[7].replace(/_/g, '-'); locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null) // if(parseInt(makercheckersL) > 0) { // bulkBodyReview.push({ // "mmddyyyy": mmddyyyy, // "projectid": this.projectId, // "type": "report", // "eventid": eventId, // "comments": reportercomments, // "dateofcompletion": reporterdoc, // "percentage": percentage, // "entityid": entityId, // "locationid": locationId, // "event": null, // "docs": JSON.stringify(docs), // "approved": true, // "username": this.userName, // "reportformatvalues": reportformatvalues, // "reportformatschema": reportformatschema, // "userid": this.userProfileId, // "userrole": this.myRole, // "year": this.calendarStartYYYY, // "module": listEvent.module ?? "compliance" // } ) // // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true); // }else{ let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": listEvent.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) // } // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } // await this.uploadReportsBulk(bulkBody); // await this.fetchBulkReportingData(); if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } // if(bulkBodyReview.length > 0){ // await this.uploadReportsReviewsBulk(bulkBodyReview) // } await this.fetchBulkReportingData(); console.log('uploadReport bulk') for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } if (this.mode == "next") { this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } // } // } // } }); } } } if (this._SfUploader[0] != null) { (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" }); //console.log('documentType checking', documentType); if (documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: listEvent.entityid, locationId: listEvent.locationid, mmddyyyy: mmddyyyy, complianceId: listEvent['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (listEvent["approved"] != null) { if (listEvent["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) { ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } } fetchEventDetails = async (listEvent: any, mmddyyyy: any, currentColumnButton: HTMLButtonElement | null, eventsContainer: HTMLDivElement, previousId: string = "", nextId: string = "", flagUploadGuidance: boolean = false, listEventContainer: HTMLDivElement | null = null, reportercomments: string | null = null, approvercomments: string | null = null, inputReportingPercentage: string | null = null, selectReportedLocation: string | null = null, documents: any | null = null, dateOfCompletion: string | null = null, fromDrilldown: boolean = false) => { console.log('listEvent', listEvent, listEvent.id) let url = "https://" + this.apiId + "/getalleventdetails"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "eventid": listEvent.id, "entityid": listEvent.entityid, "locationid": listEvent.locationid, "mmddyyyy": mmddyyyy, "year": this.getFinancialYear(mmddyyyy) }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); if (flagUploadGuidance) { if (listEventContainer != null) { let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.events[mmdd] != null) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == listEvent.locationid && this.events[mmdd][p].entityid == listEvent.entityid) { this.events[mmdd][p].uploadguidance = jsonRespose.data.uploadguidance } } } let data = jsonRespose.data; if (reportercomments != null) { data.reportercomments = reportercomments; } else if (approvercomments != null) { data.approvercomments = approvercomments; } if (inputReportingPercentage != null) { data.percentage = inputReportingPercentage; } console.log('dateOfCompletion', dateOfCompletion, dateOfCompletion == null, dateOfCompletion == ""); data.dateofcompletion = dateOfCompletion; data.reportedlocations = selectReportedLocation; data.documents = documents; this.renderListReporting(listEventContainer, data, mmddyyyy, eventsContainer) } } else { this.renderEventDetail(jsonRespose.data, mmddyyyy, currentColumnButton, eventsContainer, previousId, nextId, fromDrilldown); } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderEventDetail = (event: any, mmddyyyy: any, currentColumnButton: HTMLButtonElement | null, eventsContainer: HTMLDivElement, previousId: string, nextId: string, fromDrilldown: boolean) => { console.log('event details', event, mmddyyyy, currentColumnButton == null ? "null currentColumnButton" : currentColumnButton.id); console.log('previousid', previousId, 'nextid', nextId); console.log('confighome', Util.getProjectConfigHome()) let comments, docs, approved /*,dateOfCompletion, makercheckers: Array, docsOptional: boolean | any, documentType: string | any*/; let entityId: string = ""; let locationId: string = ""; let statuteName: string = ""; let reportformatName: string = ""; // let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] entityId = event.entityid; locationId = event.locationid; // let completeness = this.getCompletenessStatus(event); comments = event['comments'] == null ? [] : (event['comments']); docs = event['documents'] == null ? [] : event['documents'] == null ? [] : (event['documents']); approved = event['approved'] == null ? false : event['approved'] == null ? false : event['approved']; // dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion'] == null ? '' : event['dateofcompletion']; // makercheckers = event['makercheckers'] == null ? [] : event['makercheckers'] == null ? [] : event['makercheckers']; // docsOptional = event['docs'] == null ? [] : event['docs'] == null ? [] : event['docs']; // documentType = event['documenttype'] == null ? null : event['documenttype'][0] == null ? null : event['documenttype'][0].split(" ")[0]; statuteName = event['statute'][0].trim(); if (event['reportformat'] != null) { reportformatName = (event['reportformat'][0] ?? "").trim().replace('&', '&'); } console.log('event detail', event, statuteName); //console.log('event detail comments', comments); //console.log('event dateofcompletion', dateOfCompletion); //console.log('event detail documenttype', documentType); const basicFields = ['id', 'shortid', 'entityname', 'locationname', 'functions']; const statuteFields = ['jurisdiction', 'country', 'state', 'category', 'subcategory', 'statute']; const complianceFields = ['specificity', 'reference', 'obligation', 'penalty', 'authority', 'frequency', 'subfrequency', 'obligationtype', 'duedate', 'applicability', 'form', 'additionalurls', 'adhocquestion', 'adhocquestionschedule', 'adhocinstances', 'uploadguidance', 'attachment']; const grcFields = ['internalcontrols', 'firstlineofdefence', 'secondlineofdefence', 'thirdlineofdefence', 'risk', 'riskarea']; let listReportingContainers = eventsContainer.querySelectorAll('.list-reporting-container') as NodeListOf for (let tempReportingContainer of listReportingContainers) { tempReportingContainer.style.display = 'none'; tempReportingContainer.innerHTML = ''; } let buttonListReportings = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReporting of buttonListReportings) { buttonListReporting.setAttribute('part', 'button-list-reporting') } let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { streamEventTitle.removeAttribute('part') } var html = `
${(previousId != "" || nextId != "") ? `
` : ` `}

Compliance Details

`; // if (previousId != "" || nextId != "") { // html += ` //
// // //
// ` // } if (this.selectedItemIds.length > 1) { html += `

${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected

`; } html += '
'; html += '
'; html += ('

' + event['obligationtitle'].replace(/\\n|\r?\n/g, '') + '

'); let obligationArr = event['obligation'].split('More information:'); console.log('detailsObligation', obligationArr[0], obligationArr[0].replace(/\\n|\r?\n/g, '
')) html += ('

' + obligationArr[0].replace(/\\n|\r?\n/g, '
') + '

'); if (obligationArr.length > 1) { let tempObligationArr = obligationArr.slice(1); console.log('tempObligationArr', tempObligationArr); html += ('
' + ('') + '" minLength="80">') + '
'); } html += ('
' + ('') + '" minLength="80">') + '
'); html += '
'; html += '
'; html += '
'; html += '
'; html += '

Basic Information

' html += '

-

' html += '
'; html += '
'; for (var i = 0; i < basicFields.length; i++) { if (!this.getEventPreviewFields().includes(basicFields[i])) { if (!this.getEventHideFields().includes(basicFields[i])) { console.log('basicFields', event[basicFields[i]] + ""); if ((event[basicFields[i]] + "").indexOf("[") >= 0) { html += '
'; html += '
' + basicFields[i] + '
' html += this.getEventTexts(basicFields[i], JSON.parse(event[basicFields[i]]), event).replace(/ *\([^)]*\) */g, "").trim(); html += '
'; } else { html += '
'; html += '
' + basicFields[i] + '
' html += ''; html += '
'; } } } } if (this.mode == "consumer") { if (approved) { html += '
'; html += '
Approved
' html += 'check_circle' html += '
'; } } if (docs != null) { html += '
'; html += '
Documents
' html += 'description' html += docs.length html += '
'; } if (comments != null) { html += '
'; html += '
Comments
' html += 'forum' html += comments.length html += '
'; } html += '
'; html += '
Reporters
' html += this.getReporterDetailStringFromEvent(event); html += '
'; html += '
'; html += '
Approvers
' html += this.getApproverDetailStringFromEvent(event); html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '

Statute Information

' html += '

-

' html += '
'; html += '
'; for (var i = 0; i < statuteFields.length; i++) { if (!this.getEventPreviewFields().includes(statuteFields[i])) { if (event[statuteFields[i]] != null && event[statuteFields[i]] != "") { if (!this.getEventHideFields().includes(statuteFields[i])) { html += '
'; html += '
' + statuteFields[i] + '
' if ((event[statuteFields[i]] + "").indexOf("[") >= 0 && Util.isJSONParsable((event[statuteFields[i]] + ""))) { html += this.getEventTexts(statuteFields[i], JSON.parse(event[statuteFields[i]]), event); } else { html += ''; } html += '
'; } } } } html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '

Compliance Information

' html += '

-

' html += '
'; html += '
'; for (var i = 0; i < complianceFields.length; i++) { //console.log(complianceFields[i]); //console.log(event[complianceFields[i]]); if (!this.getEventPreviewFields().includes(complianceFields[i])) { if (!this.getEventHideFields().includes(complianceFields[i])) { if (event[complianceFields[i]] != null && event[complianceFields[i]] != "") { if (event[complianceFields[i]].indexOf('http://') >= 0) { let res = event[complianceFields[i]].split(" ").find((word: any) => word.startsWith("http")); html += '
'; html += '
' + complianceFields[i] + '
' if ((event[complianceFields[i]] + "").indexOf("[") >= 0) { html += this.getEventTexts(complianceFields[i], JSON.parse(event[complianceFields[i]]), event) + " Open"; } else { html += '') + '" minLength="80">' + " Open"; } html += '
'; } else if (complianceFields[i] == 'attachment') { if (event[complianceFields[i]] != null && event[complianceFields[i]].length > 0) { console.log('attachments str', event[complianceFields[i]]); html += '
'; html += '
' + complianceFields[i] + '
' if (typeof event[complianceFields[i]] === "string") { let attachmentArr = JSON.parse(event[complianceFields[i]].toString()); if (attachmentArr.length > 0) { for (let attachment of attachmentArr) { html += `` } } } else { for (let attachmentStr of event[complianceFields[i]]) { let attachment: any = {}; if (typeof attachmentStr === "object") { attachment = attachmentStr; } else { attachment = JSON.parse(attachmentStr.toString()); } // html += `` html += `` } } html += '
'; } } else { html += '
'; html += '
' + complianceFields[i] + '
' if ((event[complianceFields[i]] + "").indexOf("[") >= 0) { html += this.getEventTexts(complianceFields[i], JSON.parse(event[complianceFields[i]]), event); } else { html += '') + '" minLength="80">'; } html += '
'; } } } } } html += '
'; html += '
'; html += '
'; html += '
'; html += '

GRC Information

' html += '

-

' html += '
'; html += '
'; for (var i = 0; i < grcFields.length; i++) { //console.log(grcFields[i]); if (!this.getEventPreviewFields().includes(grcFields[i])) { if (event[grcFields[i]] != null && event[grcFields[i]] != "") { if (!this.getEventHideFields().includes(grcFields[i])) { html += '
'; html += '
' + grcFields[i] + '
' if (grcFields[i].toLowerCase() == "riskarea") { const arrValues = event[grcFields[i]]; for (var k = 0; k < arrValues.length; k++) { html += '
' + arrValues[k] + '
'; } } else { if ((event[grcFields[i]] + "").indexOf("[") >= 0) { html += this.getEventTexts(grcFields[i], JSON.parse(event[grcFields[i]]), event); } else { //console.log('grcfield', event[grcFields[i]]); html += '') + '" minLength="80">'; } } html += '
'; } } } } html += '
'; html += '
'; html += '' html += '
'; html += '
'; html += '

Feedback

' html += '

+

' html += '
'; html += '
'; html += '
' html += '
' html += '
Do you wish to send us feedback about this compliance? Any doubts? Need guidance or more clarity? Drop us a feedback and we will revert soon.
' html += '
' html += '
' html += '' html += '
' if (this.myRole == this.TAB_FUNCTION_HEAD || this.myRole == this.TAB_VIEWER) { html += '
' html += '' html += '' html += '
' } html += '
' html += (''); html += (''); html += (''); html += '
' html += '
' html += '
'; html += '
'; html += '
'; if (this.mode == "consumer" || this.mode == "next" || this.mode == "viewer") { if (this.mode != "viewer" && !fromDrilldown) { html += '
' html += this.renderReporting(event, mmddyyyy); html += "
" } html += '
'; html += '


Comments

'; html += '
'; html += '
'; html += '
'; for (var i = 0; i < comments.length; i++) { html += '
'; html += '
' + (comments[i].username != null ? comments[i].username : '') + '' + comments[i].author + '' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '
' : '') + '
'; const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim(); try { const jsonComments = JSON.parse(onlyCommentText); if (Util.isInteger(jsonComments)) { html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } else { //console.log('json comments', jsonComments); var htmlTable = ''; for (var j = 0; j < Object.keys(jsonComments).length; j++) { htmlTable += '
'; htmlTable += ('
' + Object.keys(jsonComments)[j] + '
'); htmlTable += (''); htmlTable += '
'; } html += '
' + htmlTable + '' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } } catch (e: any) { //console.log('json comments exception', comments[i]); html += '
' + comments[i].comment + '
' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '
'; } html += '
'; } if (comments.length === 0) { html += '
No comments yet!
'; } html += '
'; html += '
'; if (event.reportevent != null) { html += '
'; html += '


Reported Event Details

'; html += '
'; html += '
'; html += '
'; console.log("reportevent", JSON.parse(event.reportevent)); const jsonReportEvent = JSON.parse(event.reportevent); html += ''; html += ''; for (i = 0; i < Object.keys(jsonReportEvent).length; i++) { if (!this.EXCLUDE_COLS_FROM_REGS.includes(Object.keys(jsonReportEvent)[i].toLowerCase())) { html += ''; } } html += ''; html += '
'; html += ('' + Object.keys(jsonReportEvent)[i] + ''); html += ('' + ''); html += '
'; html += '
'; html += '
'; } } (this._SfDetailContainer as HTMLDivElement).innerHTML = html; (this._SfDetailContainer as HTMLDivElement).style.display = 'block'; if (this.mode != "viewer" && (this._SfUploader[0]) != null) { let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2]; let emailcontent = `
Compliance ID${event.id}
Country${event.countryname.replace(/ *\([^)]*\) */g, "")}
Entity${event.entityname.replace(/ *\([^)]*\) */g, "")}
Location${event.locationname.replace(/ *\([^)]*\) */g, "")}
Statute${event.statute[0] ?? ""}
Subcategory${event.subcategory}
Reporter${event.reporters[0].split(';')[0]}
Approver${event.approvers[0].split(';')[0]}
Due Date${ddmmyyyy}
`; (this._SfUploader[0].querySelector('#uploader') as SfIUploader).emailcontent = emailcontent; } (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-previous')?.addEventListener('click', () => { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((eventsContainer as HTMLDivElement).querySelector('#' + previousId) as HTMLElement)?.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-next')?.addEventListener('click', () => { var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ((eventsContainer as HTMLDivElement).querySelector('#' + nextId) as HTMLElement)?.dispatchEvent(clickEvent); }); (this._SfDetailContainer as HTMLDivElement).querySelector('.head-basic')?.addEventListener('click', () => { //console.log('head basic clicked', ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display); if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display == '') { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display = 'none'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-basic') as HTMLDivElement).innerHTML = '+'; } else { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display = 'flex'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-basic') as HTMLDivElement).innerHTML = '-'; } }); (this._SfDetailContainer as HTMLDivElement).querySelector('.head-statute')?.addEventListener('click', () => { //console.log('head statute clicked', ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display); if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display == '') { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display = 'none'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-statute') as HTMLDivElement).innerHTML = '+'; } else { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display = 'flex'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-statute') as HTMLDivElement).innerHTML = '-'; } }); (this._SfDetailContainer as HTMLDivElement).querySelector('.head-compliance')?.addEventListener('click', () => { if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display == '') { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display = 'none'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-compliance') as HTMLDivElement).innerHTML = '+'; } else { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display = 'flex'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-compliance') as HTMLDivElement).innerHTML = '-'; } }); (this._SfDetailContainer as HTMLDivElement).querySelector('.head-grc')?.addEventListener('click', () => { if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display == '') { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display = 'none'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-grc') as HTMLDivElement).innerHTML = '+'; } else { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display = 'flex'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-grc') as HTMLDivElement).innerHTML = '-'; } }); (this._SfDetailContainer as HTMLDivElement).querySelector('.head-feedback')?.addEventListener('click', () => { if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display == 'flex') { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display = 'none'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-feedback') as HTMLDivElement).innerHTML = '+'; } else { ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display = 'flex'; ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-feedback') as HTMLDivElement).innerHTML = '-'; } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfDetailContainer as HTMLDivElement).innerHTML = ''; (this._SfDetailContainer as HTMLDivElement).style.display = 'none'; }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback')?.addEventListener('click', () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement); const feedbackSuspenseLabel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense-label') as HTMLLabelElement); const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); console.log(buttonConfirm.classList); if (feedbackMessage.classList.contains('hide')) { feedbackMessage.classList.remove('hide'); } if (feedbackSuspense != null) { if (feedbackSuspense.classList.contains('hide')) { feedbackSuspense.classList.remove('hide'); } } if (feedbackSuspenseLabel != null) { if (feedbackSuspenseLabel.classList.contains('hide')) { feedbackSuspenseLabel.classList.remove('hide'); } } if (buttonConfirm.classList.contains('hide')) { buttonConfirm.classList.remove('hide'); } if (buttonCancel.classList.contains('hide')) { buttonCancel.classList.remove('hide'); } if (!buttonFeedback.classList.contains('hide')) { buttonFeedback.classList.add('hide'); } // const body = { // projectid: this.projectId, // complianceid: compliance.id // } // console.log(body); }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel')?.addEventListener('click', () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement); const feedbackSuspenseLabel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense-label') as HTMLLabelElement); const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); console.log(buttonConfirm.classList); if (!feedbackMessage.classList.contains('hide')) { feedbackMessage.classList.add('hide'); } if (feedbackSuspense != null) { if (feedbackSuspense.classList.contains('hide')) { feedbackSuspense.classList.remove('hide'); } } if (feedbackSuspenseLabel != null) { if (feedbackSuspenseLabel.classList.contains('hide')) { feedbackSuspenseLabel.classList.remove('hide'); } } if (!buttonConfirm.classList.contains('hide')) { buttonConfirm.classList.add('hide'); } if (!buttonCancel.classList.contains('hide')) { buttonCancel.classList.add('hide'); } if (buttonFeedback.classList.contains('hide')) { buttonFeedback.classList.remove('hide'); } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm')?.addEventListener('click', async () => { const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement); const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement); const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement); const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement); console.log('sending feedback', event); if (feedbackMessage.value.length === 0) { feedbackMessage.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important'); } else { feedbackMessage.setAttribute('style', 'border:'); let feedbackSuspenseVal = false if (feedbackSuspense != null && feedbackSuspense.checked) { feedbackSuspenseVal = true } let shortid = event.shortid if(Util.isJSONParsable(event.shortid)){ shortid = JSON.parse(event.shortid)[0] } this.uploadTriggerMyEvent( event.id + " - " + shortid, feedbackMessage.value, (event.country[0] ?? "").replace(/ *\([^)]*\) */g, ""), (event.entityname ?? "").replace(/ *\([^)]*\) */g, ""), (event.locationname ?? "").replace(/ *\([^)]*\) */g, ""), event.statute[0], event.subcategory[0], { addtosuspense: feedbackSuspenseVal, mmddyyyy: mmddyyyy, eventid: event.id, entityid: entityId, locationid: locationId, reporters: event.reporters, approvers: event.approvers, functionheads: event.functionheads, obligationtitle: event.obligationtitle, obligation: event.obligation, reference: event.reference, } ); buttonCancel.click(); buttonClose.click(); } }); (this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message')?.addEventListener('keyup', (e: any) => { if (e.code == "Enter") { const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement); buttonConfirm.click(); } }) if (this.mode == "consumer" || this.mode == "next") { let eventDetailReportingContainer = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-view-container') as HTMLDivElement if (eventDetailReportingContainer != null) { this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, (this._SfDetailContainer as HTMLDivElement)) } } this.fetchStatuteDefinitionDetails(statuteName); console.log('customreporting', event['customreporting']) if (event['customreporting'] != null) { let reportingContainer = (this._SfDetailContainer as HTMLDivElement) if (reportingContainer.querySelector('#report-format-container') != null) { reportingContainer.querySelector('#report-format-container')!.innerHTML = ``; console.log('innerhtml', reportingContainer.querySelector('#report-format-container')!.innerHTML); (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).name = event.obligationtitle; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).mode = "edit"; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).flow = "reporting"; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).configjson = event['customreporting']; // if(reportformatvalues != ""){ // (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).prepopulateValJson = reportformatvalues // } (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).loadMode(); } } else if (event['reportformat'] != null && event['reportformat'].length > 0) { this.fetchReportFormat((this._SfDetailContainer as HTMLDivElement), reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? ""); } } renderEventDetailReporting = (eventDetailReportingContainer: HTMLDivElement, event: any, mmddyyyy: any, eventDetailContainer: HTMLDivElement) => { console.log('detailreporting event', event, this.graphFilter); let html = '' let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] let reportformatName: string = ''; if (event['reportformat'] != null) { reportformatName = (event['reportformat'][0] ?? "").trim().replace('&', '&'); } let docs = event['documents'] == null ? [] : event['documents']; event.approved = event['approved'] == null ? false : event['approved']; event.dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion']; event.makercheckers = event['makercheckers'] == null ? [] : event['makercheckers']; event.docsOptional = event['docs'] == null ? [] : event['docs']; html = this.renderReporting(event, mmddyyyy); console.log('reporting html', html); let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2]; let emailcontent = `
Compliance ID${event.id}
Country${event.countryname.replace(/ *\([^)]*\) */g, "")}
Entity${event.entityname.replace(/ *\([^)]*\) */g, "")}
Location${event.locationname.replace(/ *\([^)]*\) */g, "")}
Statute${(event.statute[0] ?? "")}
Subcategory${event.subcategory}
Reporter${event.reporters[0].split(';')[0]}
Approver${event.approvers[0].split(';')[0]}
Due Date${ddmmyyyy}
`; eventDetailReportingContainer.innerHTML = html; if (this._SfUploader[0] != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.emailcontent = emailcontent; } const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement); (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.addEventListener('change', (e) => { let value = (e.target as HTMLInputElement).value; if (this.reportingSuggestionsNotApplicable.indexOf(value) >= 0) { console.log('suggestion matched', value); let uploadOptionalWarning = eventDetailReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement; uploadOptionalWarning.classList.remove('hide'); let supportingDocumentsLabel = eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement; supportingDocumentsLabel.innerText = 'Supporting Documents'; } else { let uploadOptionalWarning = eventDetailReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement; uploadOptionalWarning.classList.add('hide'); let supportingDocumentsLabel = eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement; supportingDocumentsLabel.innerText = 'Supporting Documents' + (event.docsOptional.length > 0 ? '' : '*'); } }) let deleteButtons = eventDetailContainer.querySelectorAll('.button-delete') as NodeListOf for (let deleteButton of deleteButtons) { deleteButton?.addEventListener('click', async () => { await this.fetchDeleteReview(event["id"], mmddyyyy, event.entityid, event.locationid); this.setSuccess('Deleted successfully!') setTimeout(() => { this.clearMessages() }, 3000); //console.log('deleted', resultDelete); if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } }); } eventDetailReportingContainer.querySelector('#button-auto-approve')?.addEventListener('click', async () => { if (this.selectedItemIds.length <= 1) { await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); this.setSuccess('Auto-Approved successfully!') setTimeout(() => { this.clearMessages() }, 3000); } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": "Auto approved", "approved": true, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance" }) } await this.uploadReviewsBulk(bulkBodyReview); } if (this.getCurrentTab() == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); } else { // if(currentColumnButton != null) { // currentColumnButton.click(); // } } }); eventDetailReportingContainer.querySelector('#upload-guidance-button')?.addEventListener('click', async () => { console.log('upload guidance clicked', event); let inputReportingPercentage = (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement)?.value ?? "100"; let selectReportedLocations = (eventDetailReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf); let selectReportedLocationValue = "[]"; for (let selectReportedLocation of selectReportedLocations) { selectReportedLocationValue = JSON.stringify([...JSON.parse(selectReportedLocationValue), selectReportedLocation.value]) } let approvercomments = (eventDetailReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement)?.value ?? ""; let reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.value ?? ""; let dateOfCompletion; if ((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement) != null) { dateOfCompletion = new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + ""; } else { dateOfCompletion = new Date((eventDetailReportingContainer.querySelector('#input-approver-doc') as HTMLInputElement).value).getTime() + ""; } let documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader).selectedValues() if (dateOfCompletion == "NaN") { dateOfCompletion = ""; } console.log('dateOfCompletion', dateOfCompletion) await this.fetchEventDetails(event, mmddyyyy, null, eventDetailContainer, "", "", true, eventDetailReportingContainer, reportercomments, approvercomments, inputReportingPercentage, selectReportedLocationValue, documents, dateOfCompletion); }) if (this.mode == "consumer" || this.mode == "next") { let inputReportingPercentage = eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement; let percentage = inputReportingPercentage.value const entityContainers = eventDetailReportingContainer.querySelectorAll('.reporting-entity-container') as NodeListOf; const locationsContainers = eventDetailReportingContainer.querySelectorAll('.reporting-location-container') as NodeListOf; const addLocationButtons = eventDetailReportingContainer.querySelectorAll('.button-reporter-location-add') as NodeListOf; if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) { entityContainers.forEach(container => container.classList.remove('hide')); locationsContainers.forEach(container => container.classList.remove('hide')); addLocationButtons.forEach(container => container.classList.remove('hide')); } else { entityContainers.forEach(container => container.classList.add('hide')); locationsContainers.forEach(container => container.classList.add('hide')); addLocationButtons.forEach(container => container.classList.add('hide')); } inputReportingPercentage?.addEventListener('change', () => { setTimeout(() => { let percentage = inputReportingPercentage.value console.log('percentage', percentage, inputReportingPercentage, inputReportingPercentage.value, event.reportedlocations); if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) { entityContainers.forEach(container => container.classList.remove('hide')); locationsContainers.forEach(container => container.classList.remove('hide')); addLocationButtons.forEach(container => container.classList.remove('hide')); } else { entityContainers.forEach(container => container.classList.add('hide')); locationsContainers.forEach(container => container.classList.add('hide')); addLocationButtons.forEach(container => container.classList.add('hide')); } if ((percentage != null && parseInt(percentage) == 0) || event.docsOptional.length > 0) { (eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents'; } else { (eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents*'; } if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100 && (event.reportedlocations == "" || event.reportedlocations == "[]")) { event.percentage = percentage event.reportedlocations = JSON.stringify([""]) event.reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; event.dateofcompletion = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); console.log('rendering list reporting', event.percentage, event.reportedlocations) this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, eventDetailContainer); } }, 200); }) let projectUserMap = Util.getProjectUsermap() addLocationButtons.forEach((addLocationBtn) => { addLocationBtn.addEventListener('click', () => { let iconhtml = addLocationBtn.innerHTML let index = parseInt(addLocationBtn.id.split('-')[4]) console.log('button clicked', iconhtml, addLocationBtn.id); if (iconhtml == "add") { console.log('this.reportedLocationsVals', this.reportedLocationsVals) this.reportedLocationsVals.push(""); } else { this.reportedLocationsVals.splice(index, 1); } event.percentage = inputReportingPercentage.value; event.reportedlocations = JSON.stringify(this.reportedLocationsVals) if (this.reportedLocationsVals.length == 0) { event.percentage = "100"; } console.log('rendering list reporting', this.reportedLocationsVals, event.percentage, event.reportedlocations) event.reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; event.dateofcompletion = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, eventDetailContainer); }) }) for (let indexRepLoc = 0; indexRepLoc < this.reportedLocationsVals.length; indexRepLoc++) { console.log('AddingEntities', indexRepLoc) let selectReportingEntity = eventDetailReportingContainer.querySelector('#input-reporter-entity-' + indexRepLoc) as HTMLSelectElement; let selectReportingLocation = eventDetailReportingContainer.querySelector('#input-reporter-location-' + indexRepLoc) as HTMLSelectElement; selectReportingEntity.innerHTML = ''; let defaultOption = new Option("Select Entity", "", true, true) defaultOption.disabled = true selectReportingEntity.add(defaultOption) for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { let entityName = entity.split(';')[0].replace(/ *\([^)]*\) */g, "") let option = new Option(entityName, entity) selectReportingEntity.add(option); } } selectReportingEntity.addEventListener('change', (e: any) => { selectReportingLocation.innerHTML = '' let defaultOption = new Option("Select Location", "", true, true) defaultOption.disabled = true selectReportingLocation.add(defaultOption) for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { if (entity.indexOf(e.target.value) < 0) { continue; } for (let location of Object.keys(projectUserMap[country][entity])) { let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "") let option = new Option(locationName, location) selectReportingLocation.add(option); } } } (eventDetailReportingContainer.querySelector('#reporting-location-container-' + indexRepLoc) as HTMLDivElement).classList.remove('hide') selectReportingLocation.value = event.reportedlocations != null ? (Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations) : ""; }) if (selectReportingLocation.innerHTML == '') { let defaultOption = new Option("Select Location", "", true, true) defaultOption.disabled = true selectReportingLocation.add(defaultOption) // for (let country of Object.keys(projectUserMap)) { // if (country == "roles") { // continue; // } // for (let entity of Object.keys(projectUserMap[country])) { // for (let location of Object.keys(projectUserMap[country][entity])) { // let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "") // let option = new Option(locationName, location) // selectReportingLocation.add(option); // break; // } // break; // } // break; // } } selectReportingLocation.addEventListener('change', (e: any) => { if (selectReportingEntity.value == "") { return; } let index = parseInt(e.target.id.split('-')[3]) this.reportedLocationsVals[index] = e.target.value }) if (event.reportedlocations != null && event.reportedlocations.length > indexRepLoc) { console.log('setting reportedlocations', event.reportedlocations) let tempReportedLocation = Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations for (let country of Object.keys(projectUserMap)) { if (country == "roles") { continue; } for (let entity of Object.keys(projectUserMap[country])) { let flagSetVal = false; for (let location of Object.keys(projectUserMap[country][entity])) { if (tempReportedLocation.indexOf(location) >= 0) { selectReportingEntity.value = entity; const changeEvent = new Event('change', { bubbles: true }); selectReportingEntity.dispatchEvent(changeEvent) selectReportingLocation.value = location; flagSetVal = true; break; } } if (flagSetVal) { break; } } } } else { selectReportingEntity.value = ""; selectReportingLocation.value = ""; } } eventDetailReportingContainer.querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = (eventDetailReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement).value; console.log('comments', comments, JSON.stringify(event.comments)) const approved = (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked; let currStatus = this.getCompletenessStatus(event); let newEvent = { ...event }; newEvent.comments = comments; newEvent.approved = approved; let newStatus = this.getCompletenessStatus(newEvent); if (currStatus == newStatus) { buttonClick.innerHTML = "Save" this.setError(approved ? 'Already Approved!' : 'Already Rejected!'); setTimeout(() => { this.clearMessages(); }, 3000); return; } let flagBulk = false; if (this.selectedItemIds.length <= 1) { console.log('selectedevent', JSON.stringify(event)); if (await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) { if (this.mode != "next") { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = approved console.log('selected event', this.events[mmdd][p]); this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() if (approved) { this.events[mmdd][p].dateofcompletion = new Date().getTime() + "" } } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) } } else { let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityid = selectedId.split('-')[7].replace(/_/g, '-'); let locationid = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBodyReview.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityid, "locationid": locationid, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance" }) // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved) // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait..."); // await this.sleep(2000); // this.clearMessages(); } await this.uploadReviewsBulk(bulkBodyReview); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityid = selectedId.split('-')[7].replace(/_/g, '-'); let locationid = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityid) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationid && this.events[mmdd][p].entityid == entityid) { this.events[mmdd][p].isbulk = true flagBulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage) // this.renderRoleTabsNext(this.nextPage) buttonClose?.dispatchEvent(new Event('click')) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } console.log('events', this.events); buttonClose?.dispatchEvent(new Event('click')) this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); } } }); eventDetailReportingContainer.querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const comments = (eventDetailReportingContainer.querySelector('#input-auditor-comments') as HTMLInputElement).value; const approved = (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked; if (comments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; if (this.selectedItemIds.length <= 1) { if (await this.uploadAudit(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = approved this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() if (approved) { this.events[mmdd][p].dateofcompletion = new Date().getTime() + "" } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) } } else { let bulkBodyAudit = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); bulkBodyAudit.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventId, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "username": this.userName, "userid": this.userProfileId, "userrole": this.myRole, "year": this.calendarStartYYYY, "module": event.module ?? "compliance" }) // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved); } await this.uploadAuditsBulk(bulkBodyAudit); for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { this.events[mmdd][p].isbulk = true flagBulk = true; if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) buttonClose?.dispatchEvent(new Event('click')) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } buttonClose?.dispatchEvent(new Event('click')) this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk); // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } }); if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) { if (event.approved) { if ((eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) { (eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden'; } if ((eventDetailReportingContainer.querySelector('#reporting-suggestions-container') as HTMLElement) != null) { (eventDetailReportingContainer.querySelector('#reporting-suggestions-container') as HTMLElement).style.visibility = 'hidden'; } } else { let reportingSuggestionMoreButton = eventDetailReportingContainer.querySelector('#reporting-suggestions-more') as HTMLButtonElement; reportingSuggestionMoreButton?.addEventListener('click', (e) => { (e.target as HTMLButtonElement).style.display = 'none'; let reportingSuggestions = eventDetailReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf; reportingSuggestions.forEach(suggestion => { suggestion.classList.remove('hide'); }) }) let reportingSuggestionButtons = eventDetailReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf; for (let reportingSuggestionButton of reportingSuggestionButtons) { reportingSuggestionButton.addEventListener('click', (e) => { let button = e.currentTarget as HTMLDivElement; (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value = ((eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value + " " + button.innerHTML).trim(); (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).dispatchEvent(new Event('change', { bubbles: true })); }) } if ((eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) { (eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible'; eventDetailReportingContainer.querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => { let buttonClick = ev.target as HTMLButtonElement buttonClick.innerHTML = "Saving..." const reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value; //console.log('reporter comments 1', reportercomments); const reporterdoc = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : ""; let docs: any[] = []; //console.log('reporter comments 2', reportercomments); // if(docsOptional.length === 0) { let percentage: string = "100"; if ((eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement) != null) { percentage = (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value } docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); // } let flag = false; do { if (docs.length > 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments) > -1) { for (let doc of docs) { if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) { flag = false } else { flag = true; } } } else { flag = true; } if (flag === false) { await this.sleep(1000); console.log('waiting for docs', docs); docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues(); } } while (flag === false); //console.log('docs', docs); let reportformatvalues: string = ""; let reportformatschema: string = ""; if (this._SfReporting[0] != null) { reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? ""; reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? ""; } console.log('percentage', percentage, (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value); if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('Invalid Percentage!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { if (docs.length == 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments) < 0) { //console.log('reporter comments 3', reportercomments); buttonClick.innerHTML = "Save" this.setError('No documents uploaded!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('reporterdoc', reporterdoc); if (reporterdoc.length === 0) { buttonClick.innerHTML = "Save" this.setError('Date of completion not selected!'); setTimeout(() => { this.clearMessages(); }, 3000); } else if (parseInt(reporterdoc) > new Date().getTime()) { buttonClick.innerHTML = "Save" this.setError('Date of completion cannot be in future!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { //console.log('makerscheckers 1', reportercomments); if (reportercomments.trim().length === 0) { buttonClick.innerHTML = "Save" this.setError('Comments cannot be blank!'); setTimeout(() => { this.clearMessages(); }, 3000); } else { let flagBulk = false; // let reportedlocations = selectReportingLocation?.value ?? ""; let reportedlocations = "[]"; if (parseInt(percentage) !== 100) { let selectReportedLocations = (eventDetailReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf); for (let selectReportedLocation of selectReportedLocations) { reportedlocations = JSON.stringify([...JSON.parse(reportedlocations), selectReportedLocation.value]) } } if (this.selectedItemIds.length <= 1) { if (await this.uploadReport(event.entityid, event.locationid, mmddyyyy, event["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, event.module ?? "compliance", percentage, event.makercheckers, reportedlocations)) { if (this.mode != "next") { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].documents = docs this.events[mmdd][p].percentage = percentage this.events[mmdd][p].reportedlocations = reportedlocations this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } if (event.makercheckers.length > 0) { // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) { this.events[mmdd][p].approved = true // this.events[mmdd][p].documents = docs this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.events[mmdd][p].lastupdated = new Date().toString() } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) console.log('recently reported', this.recentlyReported) } else { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) { this.nextEvents[this.nextTabRole][mmdd][p].documents = docs this.nextEvents[this.nextTabRole][mmdd][p].percentage = percentage this.nextEvents[this.nextTabRole][mmdd][p].reportedlocations = reportedlocations this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() }) this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString() } } if (event.makercheckers.length > 0) { // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance"); for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) { this.nextEvents[this.nextTabRole][mmdd][p].approved = true // this.events[mmdd][p].documents = docs this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() }) this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString() } } } if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(event) console.log('recently reported', this.recentlyReported) } } } else { let bulkBody = [] let bulkBodyReview = [] for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); const makercheckersL = selectedId.split('-')[5]; let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; //console.log(entityId, locationId, eventId, mmddyyyy); let yearStr = this.getFinancialYear(mmddyyyy) bulkBody.push({ "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventId, "comments": reportercomments, "dateofcompletion": reporterdoc, "percentage": percentage, "reportedlocations": reportedlocations, "entityid": entityId, "locationid": locationId, "event": null, "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": event.module ?? "compliance", "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null }) } if (bulkBody.length > 0) { await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0); } for (var k = 0; k < this.selectedItemIds.length; k++) { const selectedId = this.selectedItemIds[k]; //console.log('selectedid', selectedId); let entityId = selectedId.split('-')[7].replace(/_/g, '-'); let locationId = selectedId.split('-')[8].replace(/_/g, '-'); const eventId = selectedId.split('-')[9].replace(/_/g, '-'); mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12]; let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) { if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) { flagBulk = true; this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p]) } } } else { for (var p = 0; p < this.events[mmdd].length; p++) { if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) { flagBulk = true; this.events[mmdd][p].isbulk = true if (this.recentlyReported[mmdd] == null) { this.recentlyReported[mmdd] = [] } this.recentlyReported[mmdd].push(this.events[mmdd][p]) } } } } } if (this.mode == "next") { // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus) buttonClose?.dispatchEvent(new Event('click')) this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { // if(this.getCurrentTab() == this.TAB_CUSTOM) { // this.processDateSelection((this._SfCustomContainer as HTMLDivElement)); // } else if (this.getCurrentTab() == this.TAB_FIND) { const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value; this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString); } else { if (this.selectedItemIds.length > 0) { await this.fetchBulkReportingData(); } buttonClose.dispatchEvent(new Event('click')) this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk) // if(currentColumnButton != null) { // currentColumnButton.click(); // } } } } } } } }); } } } if (this._SfUploader[0] != null) { if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" } this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => { console.log('uploader analysisInProgress', _ev); if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block" } }); this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => { console.log('uploader analysisInProgress', _ev); if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) { (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none" } }); console.log('documentType checking', event.documenttype); if (event.documenttype != null) { if (Array.isArray(event.documenttype)) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype[0] ?? ""; } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype; } } else if (event.documentType != null) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documentType; } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = ""; } (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]); console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader)); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = 0; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); if (docs.length > 0) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = docs.length; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } if (this.myRole == this.TAB_APPROVER || event.approved) { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } else { (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); } const dataPassthrough = { projectId: this.projectId, countryId: this.countryId, entityId: event.entityid, locationId: event.locationid, mmddyyyy: mmddyyyy, complianceId: event['id'], path: "uploadextract" }; const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com"; const callbackUrlPath = "test/uploadextract"; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough); (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath; (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode(); console.log('uploader prepopulate', (this._SfUploader[0].querySelector('#uploader') as SfIUploader).prepopulatedInputArr, (this._SfUploader[0].querySelector('#uploader') as SfIUploader).extract) } //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) { //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER); if (event["approved"] != null) { if (event["approved"] === true) { //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER); if ((eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) { (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = true; } if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = false; } } else { if ((eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) { (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false; } if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement)!.checked = true; } } } else { if (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement != null) { (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = false; } if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) { (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = true; } } } } if (event['reportformat'] != null && event['reportformat'].length > 0) { this.fetchReportFormat(eventDetailReportingContainer, reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? ""); } } renderCalendar = () => { //console.log('redering calendar', this.events); var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); var html = ''; for (var i = 0; i < 12; i++) { const monthStatus = this.getMonthStatus(startDate.getMonth(), startDate.getFullYear()); console.log('monthstatus', monthStatus, startDate); const partApproved = this.COLOR_APPROVED + ' 0%, ' + this.COLOR_APPROVED + ' ' + parseInt(monthStatus['percApproved'] + '') + '%'; const partPendingApproval = this.COLOR_PENDING_APPROVAL + ' ' + parseInt(monthStatus['percApproved'] + '') + '%, ' + this.COLOR_PENDING_APPROVAL + ' ' + (monthStatus['percApproved'] + (monthStatus['percPendingApproval']) + '') + '%'; const partRejected = this.COLOR_REJECTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + '') + '%, ' + this.COLOR_REJECTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + monthStatus['percRejected'] + '') + '%'; const partNotStarted = this.COLOR_NOT_STARTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + monthStatus['percRejected'] + '') + '%, ' + this.COLOR_NOT_STARTED + ' ' + 100 + '%'; html += '
'; html += '
'; html += '
' + this.monthNames[startDate.getMonth()] + '  ' + startDate.getFullYear() + '
'; html += '' html += '
'; html += this.insertDayNames(); html += this.insertDates(startDate.getMonth(), startDate.getFullYear()); html += '
'; startDate.setMonth(startDate.getMonth() + 1); } (this._SfCalendarContainer as HTMLDivElement).innerHTML = html; for (var i = 0; i < 12; i++) { (this._SfCalendarContainer as HTMLDivElement).querySelector('#calendar-button-' + i)?.addEventListener('click', (ev: any) => { const id = (ev.target as HTMLButtonElement).id.split("-")[2]; //console.log('render stream', id); this.enableStream(); this.renderTabs(this.TAB_STREAM); this.renderStream(parseInt(id), false, false); }) } } matchesOnBoardingFilter = (country: string, state: string, subcategory: string, statute: string) => { // console.log('matchingonboarding','country=' + country, 'state=' + state, 'subcategory=' + subcategory, '-' + statute + '-'); let matchesCountry = false; for (var i = 0; i < this.getfilterOnboarding().length; i++) { matchesCountry = false; if (country.toLowerCase().trim().indexOf(this.getfilterOnboarding()[i].country.trim().toLowerCase()) >= 0) { matchesCountry = true; let matchesState = false; let matchesSubcategory = false; //console.log('matchingonboarding', matchesCountry, statute); for (var j = 0; j < this.getfilterOnboarding()[i].states.length; j++) { //if(state.toLowerCase().indexOf(this.getfilterOnboarding()[i].states[j].toLowerCase()) >= 0) { if (this.getfilterOnboarding()[i].states[j].toLowerCase().indexOf(state.toLowerCase()) >= 0) { matchesState = true; break; } } //console.log('matchingonboarding', matchesState, statute); for (var j = 0; j < this.getfilterOnboarding()[i].subcategories.length; j++) { if (subcategory.toLowerCase().trim().indexOf(this.getfilterOnboarding()[i].subcategories[j].toLowerCase().trim()) >= 0) { matchesSubcategory = true; } } //console.log('matchingonboarding', matchesSubcategory, statute); let isNotExcludedStatute = true; if (this.getfilterOnboarding()[i].excludestatutes != null) { if (this.getfilterOnboarding()[i].excludestatutes.includes(statute.trim())) { isNotExcludedStatute = false; } } let isIncludedStatute = false; if (this.getfilterOnboarding()[i].includestatutes != null) { if (this.getfilterOnboarding()[i].includestatutes.includes(statute.trim())) { isIncludedStatute = true; } } if (statute == "Gujarat Goods and Services Tax Act, 2017 + Gujarat Goods and Services Tax Rules, 2017") { console.log('isIncludedStatute', isIncludedStatute); } //console.log('matchingonboarding', isIncludedStatute, this.getfilterOnboarding()[i].includestatutes, '='+statute); if (matchesCountry && matchesState && matchesSubcategory && isNotExcludedStatute) { //console.log('matchingonboarding return true'); return true; } if (matchesCountry && isIncludedStatute) { //console.log('matchingonboarding return true'); return true; } } } //console.log('matchingonboarding return true'); return false; } applyAndReloadTagging = (e: any, colName: string, taggingArray: any, sourceArray: any, divElement: any) => { const selectedIndex = e.currentTarget.id.split('-')[1]; // taggingArray.data.mappings.mappings = []; const tempArray = []; console.log('selectedindexchecking 1', this.selectedCbs) for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) { console.log('selectedindexchecking', selectedIndex, count, this.selectedCbs.includes(selectedIndex + ""), this.selectedCbs.includes(count + "")); //taggingArray.data.mappings.mappings[count] = sourceArray.data.mappings.mappings[count]; //taggingArray.data.mappings.mappings.push(sourceArray.data.mappings.mappings[count]); tempArray.push(sourceArray.data.mappings.mappings[count]); // //console.log('selectedindexchecking', this.selectedCbs, count, this.selectedCbs.includes(selectedIndex), this.selectedCbs.includes(count)); if (this.selectedCbs.includes(selectedIndex + '') && this.selectedCbs.includes(count + '')) { if (((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues != null) { if (tempArray[count] == null) tempArray[count] = {}; tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues(); // //console.log('selectedindexchecking A'); // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {}; // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues(); } else { //console.log('selectedindexchecking B'); if (tempArray[count] == null) tempArray[count] = {}; tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value; // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {}; // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value; } } else { if (((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues != null) { if (tempArray[count] == null) tempArray[count] = {}; tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues(); } else { //console.log('selectedindexchecking D'); if (tempArray[count] == null) tempArray[count] = {}; tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value; // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {}; // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value; } } } taggingArray.data.mappings.mappings = tempArray; //console.log('selectedindexchecking', colName, taggingArray); } applyAndReloadTaggingNew = (e: any, colName: string, taggingArray: any, sourceArray: any, divElement: any) => { const selectedIndex = e.currentTarget.id.split('-')[1]; const tempArray = taggingArray.data.mappings.mappings; console.log('sourceArray apply', sourceArray, taggingArray); console.log('selectedindexchecking 1', this.selectedCbs) for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) { console.log('selectedindexchecking', selectedIndex, count, this.selectedCbs.includes(selectedIndex + ""), this.selectedCbs.includes(count + "")); // tempArray.push(taggingArray.data.mappings.mappings[count]); if (this.selectedCbs.includes(selectedIndex + '') && this.selectedCbs.includes(count + '')) { let selectedValues; // if(!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof HTMLInputElement)){ // selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues() // }else if(((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement) != null){ // selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value // } if (!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof HTMLInputElement) && ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues() != null) { if (tempArray[count] == null) tempArray[count] = {}; if (colName == "countries" || colName == "entities" || colName == "locations") { selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues() if (selectedValues == null || selectedValues.length == 0) { // tempArray[count] = {}; tempArray[count][colName] = "" if (colName == "countries") { tempArray[count]["countryname"] = "" tempArray[count]["countryid"] = "" } if (colName == "entities") { tempArray[count]["entityname"] = "" tempArray[count]["entityid"] = "" } if (colName == "locations") { tempArray[count]["locationname"] = "" tempArray[count]["locationid"] = "" } console.log('deleting1', tempArray, JSON.stringify(selectedValues)) } else { tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues(); if (colName == "countries") { tempArray[count]["countryname"] = selectedValues[0].split(';')[0] tempArray[count]["countryid"] = selectedValues[0].split(';')[1] } if (colName == "entities") { tempArray[count]["entityname"] = selectedValues[0].split(';')[0] tempArray[count]["entityid"] = selectedValues[0].split(';')[1] } if (colName == "locations") { tempArray[count]["locationname"] = selectedValues[0].split(';')[0] tempArray[count]["locationid"] = selectedValues[0].split(';')[1] } } } else { tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues(); } } else { if (tempArray[count] == null) tempArray[count] = {}; tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value; } } else { if (!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof HTMLInputElement) && ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues() != null) { if (tempArray[count] == null) tempArray[count] = {}; if (colName == "countries" || colName == "entities" || colName == "locations") { let selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues() if (selectedValues == null || selectedValues.length == 0) { // tempArray[count] = {}; tempArray[count][colName] = "" if (colName == "countries") { tempArray[count]["countryname"] = "" tempArray[count]["countryid"] = "" } if (colName == "entities") { tempArray[count]["entityname"] = "" tempArray[count]["entityid"] = "" } if (colName == "locations") { tempArray[count]["locationname"] = "" tempArray[count]["locationid"] = "" } console.log('deleting1', tempArray) } else { tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues(); if (colName == "countries") { tempArray[count]["countryname"] = selectedValues[0].split(';')[0] tempArray[count]["countryid"] = selectedValues[0].split(';')[1] } if (colName == "entities") { tempArray[count]["entityname"] = selectedValues[0].split(';')[0] tempArray[count]["entityid"] = selectedValues[0].split(';')[1] } if (colName == "locations") { tempArray[count]["locationname"] = selectedValues[0].split(';')[0] tempArray[count]["locationid"] = selectedValues[0].split(';')[1] } } } else { tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues(); } } else { //console.log('selectedindexchecking D'); if (tempArray[count] == null) tempArray[count] = {}; if (colName == "countries" || colName == "entities" || colName == "locations") { // tempArray[count] = {}; tempArray[count][colName] = "" if (colName == "countries") { tempArray[count]["countryname"] = "" tempArray[count]["countryid"] = "" } if (colName == "entities") { tempArray[count]["entityname"] = "" tempArray[count]["entityid"] = "" } if (colName == "locations") { tempArray[count]["locationname"] = "" tempArray[count]["locationid"] = "" } console.log('deleting2', tempArray); } else { tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value; } } } } taggingArray.data.mappings.mappings = tempArray; console.log('selectedindexchecking', colName, taggingArray); } getDataValue = (jsonData: any, id: string) => { let ret: any = null; //console.log('pushing up again..', id, jsonData); for (var i = 0; i < jsonData.length; i++) { if (jsonData[i].id == id) { return jsonData[i].data.data; } } return ret; } getColsValue = (jsonData: any, id: string) => { let ret: any = null; for (var i = 0; i < jsonData.length; i++) { if (jsonData[i].id == id) { return jsonData[i].data.cols; } } return ret; } saveMapping = async (divElement: any, uploadBlock: number, jsonData: any, extraFields: any, searchString: string, uploadFunction: any, refreshFunction: any, saveInBackground: boolean = false, mappedStatutes: Array) => { const process = async () => { const tableRowArr = (divElement as HTMLDivElement).querySelectorAll('.tablerow') as NodeListOf; const checkboxArr = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf; const statuteArr = (divElement as HTMLDivElement).querySelectorAll('.statute') as NodeListOf; //console.log(tableRowArr); //console.log(checkboxArr); //console.log(statuteArr); for (var i = 0; i < statuteArr.length; i++) { //console.log((statuteArr[i] as SfIElasticText).text); } let updatedRows = []; let jsonArr = []; if (uploadBlock < 0) { if (mappedStatutes.length == 0) { for (var i = 0; i < checkboxArr.length; i++) { //console.log('tablerow', (tableRowArr[i] as HTMLTableRowElement)); if (checkboxArr[i].checked !== true) { continue; } if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') { } else { updatedRows.push((statuteArr[i] as SfIElasticText).text); } let cols = JSON.parse(this.getColsValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]); let data = JSON.parse(this.getDataValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]); var dataToBePushed: any = { id: (statuteArr[i] as SfIElasticText).text, name: data[cols.indexOf('name')], countryname: data[cols.indexOf('country')][0] }; /* var dataToBePushed = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] }; for (var j = 0; j < extraFields.length; j++) { const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf; const value = inputArr[k].getValues(); dataToBePushed.extraFields.push(value); if (j === 0) { const fields = inputArr[i].getFields(); dataToBePushed.updatedFields.push(...fields); } } */ jsonArr.push(dataToBePushed) } console.log('jsonArr', jsonArr); //console.log('updatedRows', updatedRows); // const batchNum = new Date().getTime(); // await uploadFunction({ "searchstring": searchString, "mappings": jsonArr, "batch": batchNum, "updatedrows": updatedRows }); await uploadFunction({ "searchstring": searchString, "mappings": jsonArr }); } else { for (var i = 0; i < checkboxArr.length; i++) { //console.log('tablerow', (tableRowArr[i] as HTMLTableRowElement)); if (checkboxArr[i].checked !== true) { continue; } if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') { } else { updatedRows.push((statuteArr[i] as SfIElasticText).text); } let cols = JSON.parse(this.getColsValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]); let data = JSON.parse(this.getDataValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]); var dataToBePushed: any = { id: (statuteArr[i] as SfIElasticText).text, data: [JSON.stringify(data)], cols: [JSON.stringify(cols)] }; /* var dataToBePushed = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] }; for (var j = 0; j < extraFields.length; j++) { const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf; const value = inputArr[k].getValues(); dataToBePushed.extraFields.push(value); if (j === 0) { const fields = inputArr[i].getFields(); dataToBePushed.updatedFields.push(...fields); } } */ jsonArr.push(dataToBePushed) } let jsonObj: { [key: string]: { [key: string]: any } } = {}; for (let statuteObj of mappedStatutes) { let statuteid = statuteObj.id; if (jsonObj[statuteid] == null) { jsonObj[statuteid] = {}; } for (let mappingObj of jsonArr) { console.log('mappingObj', mappingObj.data, statuteid); if (mappingObj.data[0].indexOf(statuteid) >= 0) { jsonObj[statuteid][mappingObj.id] = mappingObj; } } } await uploadFunction(jsonObj, mappedStatutes); } } else { const batchNum = new Date().getTime(); for (var i = 0; i < checkboxArr.length; i += uploadBlock) { if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') { } else { updatedRows.push((statuteArr[i] as SfIElasticText).text); } jsonArr = []; for (var k = i; k < (i + uploadBlock) && k < checkboxArr.length; k++) { if ((statuteArr[k] as SfIElasticText) != null) { var dataToBePushed: any = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] }; for (var j = 0; j < extraFields.length; j++) { const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf; const value = inputArr[k].getValues(); dataToBePushed.extraFields.push(value); if (j === 0) { const fields = inputArr[i].getFields(); dataToBePushed.updatedFields.push(...fields); } } jsonArr.push(dataToBePushed) } } //console.log('jsonArr', i, jsonArr); //console.log('updatedRows', updatedRows); await uploadFunction({ "searchstring": searchString, "mappings": jsonArr, "percentage": parseInt(((k * 100) / checkboxArr.length) + ""), "batch": batchNum, "updatedrows": updatedRows }); // await this.sleepFunction(2000); } } if (!saveInBackground) { await this.renderOnboardingTabs(); refreshFunction(mappedStatutes); } } if (this.disablesave == "yes") { return; } if (saveInBackground) { if (this.AUTOSAVE_FLAG) { this.AUTOSAVE_FLAG = false; setTimeout(async () => { await process(); this.AUTOSAVE_FLAG = true; this.setSuccess('Autosaved'); setTimeout(() => { this.clearMessages(); }, 1000); }, 5000); } } else { process(); } } saveTagging = async (mapping: any, selectedStatutes: any, uploadFunction: any, refreshFunction: any, saveInBackground: boolean, colName: string) => { let refreshTabs = this.renderOnboardingTabs; async function process() { console.log('Saving...', JSON.stringify(mapping)); let statuteids = [] let statutewiseMapping: any = {} for (let statutesObj of selectedStatutes) { statuteids.push(statutesObj.id); statutewiseMapping[statutesObj.id] = {}; for (let mapObj of mapping.mappings) { if (mapObj.statuteid == statutesObj.id) { let pushObj = mapObj; delete pushObj.statuteid let compoundid = mapObj.id // if (colName == "countries" || colName == "entities" || colName == "locations") { switch (colName) { case "countries": compoundid = mapObj.countryid + ';' + mapObj.id break; case "entities": compoundid = mapObj.entityid + ';' + mapObj.id; break; case "locations": compoundid = mapObj.locationid + ';' + mapObj.id; break; default: compoundid = mapObj.entityid + ';' + mapObj.locationid + ';' + mapObj.id break; } // if(statutesObj.id == "7a9c19d6-fffd-48ef-b1c5-beabcefc00cb"){ // console.log('compoundid', compoundid) // } // } if (compoundid.split(';')[0].length == 0) { continue; } if (statutewiseMapping[statutesObj.id][compoundid] != null) { let pushObjOld = statutewiseMapping[statutesObj.id][compoundid]; pushObj[colName] = [...(pushObjOld[colName] ?? []), ...(mapObj[colName] ?? [])] } else { statutewiseMapping[statutesObj.id][compoundid] = pushObj; } } } } console.log('Uploading ...', JSON.stringify(statutewiseMapping)); await uploadFunction(statutewiseMapping, statuteids); if (!saveInBackground) { await refreshTabs(); refreshFunction(selectedStatutes); } } if (this.disablesave == "yes") { return; } if (saveInBackground) { if (this.AUTOSAVE_FLAG) { this.AUTOSAVE_FLAG = false; setTimeout(async () => { await process(); this.AUTOSAVE_FLAG = true; this.setSuccess('Autosaved'); setTimeout(() => { this.clearMessages(); }, 1000); }, 10000); } } else { process(); } } renderTaggingTable = (divElement: any, sourceArray: any, taggingArray: any, sourceCols: any, uploadFunction: any, refreshFunction: any, colName: any, uniqCols: Array, apiIdDropdown: string, dropdownSearchPhrase: any, mandatoryFields: any, jobs: any, anotherProjection: any, extraFields: Array, _arrFeedbackReference: any, proposedUsersLabel: string, subfilter: string) => { // source array is the serialized field mappedcompliances // tagging array is the tagged array mappedcountries //console.log('divelement', divElement); //console.log('sourcearray', sourceArray); console.log('taggingarray', taggingArray); //console.log('uniqcols', uniqCols); //console.log('subfiltervalue', subfilter); //console.log('arrFeedbackReference', arrFeedbackReference); this.selectedCbs = []; if (taggingArray.length === 0 || sourceArray.length === 0) return; const foundArr = []; if (taggingArray.data.mappings != null && taggingArray.data.mappings.mappings != null) { for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) { var found = false; for (var j = 0; j < sourceArray.data.mappings.mappings.length; j++) { var equal = true; for (var k = 0; k < uniqCols.length; k++) { if (sourceArray.data.mappings.mappings[j] != null && taggingArray.data.mappings.mappings[i] != null) { if (sourceArray.data.mappings.mappings[j][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) { equal = false; // if(taggingArray.data.mappings.mappings.length > 0){ // console.log('taggingarray col not found', uniqCols[k], taggingArray.data.mappings.mappings[i]) // } } } } if (equal) { found = true; } } if (found) { foundArr.push(taggingArray.data.mappings.mappings[i]); } else { console.log('taggingarray not found', taggingArray.data.mappings.mappings[i], i, sourceArray.data.mappings.mappings[i]) } } } console.log('taggingarray2', taggingArray.data.mappings.mappings.length + ""); if (taggingArray.data.mappings == null) { taggingArray.data.mappings = {}; } taggingArray.data.mappings.mappings = foundArr; let mandatoryPresent = true; for (i = 0; i < (mandatoryFields as Array).length; i++) { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { if (taggingArray.data.mappings.mappings[j][mandatoryFields[i]] == null) { mandatoryPresent = false; } } } var tagged = 0; var changed = 0 console.log('taggingarray3', taggingArray.data.mappings.mappings.length + ""); for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { if (taggingArray.data.mappings.mappings[j] != null) { if (taggingArray.data.mappings.mappings[j][colName] != null && taggingArray.data.mappings.mappings[j][colName].length > 0) { tagged++; } if (this.changedOnboardingItemIds.length > 0) { let changedId = "" for (let [k, col] of uniqCols.entries()) { changedId += taggingArray.data.mappings.mappings[j][col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { changed++; } } } } // let colCountry = -1; // let colState = -1; // let colSubcategory = -1; // let colStatute = -1; const unfilteredDict: any[] = []; var html = ''; var showTable = true; html += '
'; // if(jobs && jobs.data) { // html += (jobs.data.status == "0" ? "
schedule  Job initizalied
" : jobs.data.status == "1" ? "
pending  Job in-progress  "+parseInt(jobs.data.progress)+"% complete
" : "
check_circle  Job complete
" ); // if(jobs.data.status == "0" || jobs.data.status == "1") { // showTable = false; // } // } var status = ''; if (tagged < sourceArray.data.mappings.mappings.length) { status = 'pending'; } else { status = 'check_circle'; } var mandatoryStatus = ''; if (!mandatoryPresent) { mandatoryStatus = 'error  Mandatory fields are not present'; } else { mandatoryStatus = 'check_circle  Mandatory fields are present'; } if (showTable) { html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '

' + status + '  Mapped ' + tagged + ' out of ' + sourceArray.data.mappings.mappings.length + '

'); } else { html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '

' + status + '  Mapped ' + tagged + ' out of ' + sourceArray.data.mappings.mappings.length + '

') } if (changed > 0) { html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '

pending  ' + changed + ' Items changed

') } html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '

' + mandatoryStatus + '

') html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '

') html += '
'; // html += ''; html += '
'; html += '
' // html += '
' html += '
' html += '' // console.log('jobs', jobs); html += ((jobs == null || jobs.data == null) ? '' : ((jobs.data.status == "1" || jobs.data.status == "0") ? '' : (this.disablesave == "yes" ? '' : ''))); html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '

' html += '
' html += '
'; html += '
'; var subfiltered = 0; if (showTable) { // for(var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) { // if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "country") { // //console.log('colstate-setting country', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j); // colCountry = j; // } // if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "state") { // //console.log('colstate-setting state', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j); // colState = j; // } // if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "subcategory") { // //console.log('colstate-setting subcategory', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j); // colSubcategory = j; // } // if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "statute") { // //console.log('colstate-setting statute', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j); // colStatute = j; // } // } html += ''; html += ''; html += '' for (var i = 0; i < extraFields.length; i++) { html += '' } html += '' // if(arrFeedbackReference != null) { // html += '' // } for (i = 0; i < uniqCols.length; i++) { html += '' } for (i = 0; i < sourceCols.length; i++) { html += '' } // for(i = 0; i < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; i++) { // html += '' // } html += ''; html += ''; // console.log('changedIds', this.changedOnboardingItemIds); for (i = 0; i < sourceArray.data.mappings.mappings.length; i++) { var showSearch = false; if (subfilter == "") { //console.log('showsearch true 1'); showSearch = true; } // check showSearch in extra fields // if(!showSearch) { // for(var j = 0; j < extraFields.length; j++) { // var k = 0; // for(k = 0; k < taggingArray.data.mappings.mappings.length; k++) { // if(taggingArray.data.mappings.mappings[k].id == sourceArray.data.mappings.mappings[i].id) { // break; // } // } // if(k < taggingArray.data.mappings.mappings.length) { // try { // if(taggingArray.data.mappings.mappings[k].extraFields != null && taggingArray.data.mappings.mappings[k].extraFields[j] != null && taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { // //console.log('showsearch true 2', taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase(), subfilter); // showSearch = true; // subfiltered++; // break; // } // } catch (_e: any) { // } // try { // if(taggingArray.data.mappings.mappings[k].extraFields != null && taggingArray.data.mappings.mappings[k].extraFields[j] != null && JSON.stringify(taggingArray.data.mappings.mappings[k].extraFields[j]).toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { // //console.log('showsearch true 2', taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase(), subfilter); // showSearch = true; // subfiltered++; // break; // } // } catch (_e: any) { // } // } // } // } // if(!showSearch) { // // check showSearch in uniq cols // for(var l = 0; l < uniqCols.length; l++) { // if(sourceArray.data.mappings.mappings[i][uniqCols[l]].replace(/ *\([^)]*\) */g, "").toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { // //console.log('showsearch true 3'); // showSearch = true; // subfiltered++; // break; // } // } // } // if(!showSearch) { // // check showSearch in source cols // for(l = 0; l < sourceCols.length; l++) { // for(var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) { // if(sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) { // if(sourceArray.data.mappings.mappings[i].data != null) { // if(Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) { // for(var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) { // if(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j][k].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { // //console.log('showsearch true 4'); // showSearch = true; // subfiltered++; // break; // } // } // } else { // if(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { // //console.log('showsearch true 5'); // showSearch = true; // subfiltered++; // break; // } // } // } // } // } // } // } var classBg = ""; if (i % 2 === 0) { if (this.changedOnboardingItemIds.length > 0) { let changedId = "" for (let [k, col] of uniqCols.entries()) { // console.log('taggingarray rendered', i, col) changedId += taggingArray.data.mappings.mappings[i][col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-light-selected'; } else { classBg = 'td-light'; } } else { classBg = 'td-light'; } } else { if (this.changedOnboardingItemIds.length > 0) { let changedId = "" for (let [k, col] of uniqCols.entries()) { if (taggingArray.data.mappings.mappings[i] == null) { console.log('id not found', i, taggingArray.data.mappings.mappings.length, sourceArray.data.mappings.mappings.length) } changedId += taggingArray.data.mappings.mappings[i][col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-dark-selected'; } else { classBg = 'td-dark'; } } else { classBg = 'td-dark'; } } html += ''; html += ''; for (var j = 0; j < extraFields.length; j++) { var k = 0; for (k = 0; k < taggingArray.data.mappings.mappings.length; k++) { // if (taggingArray.data.mappings.mappings[k].id == sourceArray.data.mappings.mappings[i].id) { // if (taggingArray.data.mappings.mappings[k].id == "62330e24-298d-4ef2-9449-c0e400e37cac") { // console.log('found', taggingArray.data.mappings.mappings[k]); // //console.log('before before filtermatch',sourceCols[l],JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j], colCountry, (sourceArray.data.mappings.mappings[i]), (sourceArray.data.mappings.mappings[i].data), colState); // //console.log('before filtermatch', colCountry, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry], colState, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory]); // } // break; // } } if (i < taggingArray.data.mappings.mappings.length) { html += ''; } else { html += ''; } } html += '' // if(arrFeedbackReference != null) { // html += '' // } for (var l = 0; l < uniqCols.length; l++) { // console.log('uniqcolval', uniqCols[l], sourceArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i][uniqCols[l]]); html += '' } for (l = 0; l < sourceCols.length; l++) { for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) { if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) { if (sourceArray.data.mappings.mappings[i].data != null) { html += ''; } } } } html += ''; //console.log('i=', i); } html += ''; html += '
' html += '
'; html += '
' html += extraFields[i]; html += '' html += colName; html += '' // html += proposedUsersLabel; // html += '' html += uniqCols[i]; html += '' html += sourceCols[i]; html += '' // html += JSON.parse(sourceArray.data.mappings.mappings[0].cols)[i]; // html += '
'; html += '
' // html += ''; html += ''; html += '
'; html += '
'; html += '
'; html += ''; html += '
'; html += '
' html += '
'; if (apiIdDropdown.length > 0) { if (anotherProjection != null) { html += ''; } else { html += ''; } } else { if (colName.toLowerCase() == "internalcontrols") { html += ''; } else { html += ''; } } html += '
'; html += '
' // html += '
'; // if(arrFeedbackReference[JSON.parse(sourceArray.data.mappings.mappings[i].data)[1][0].trim()][JSON.parse(sourceArray.data.mappings.mappings[i].data)[6][0].trim().replace(/&/g, "&")] == null) { // this.setError(JSON.parse(sourceArray.data.mappings.mappings[i].data)[1][0].trim() + ':' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[6][0].trim().replace(/&/g, "&") + ' - is not mapped correctly'); // setTimeout(() => { // this.clearMessages(); // }, 20000); // } else { // html += ''; // } // html += '
'; // html += '
' html += '
'; html += ''; html += '
'; html += '
'; html += '
'; // if(sourceArray.data.mappings.mappings[i].id == "62330e24-298d-4ef2-9449-c0e400e37cac") { // console.log('found', sourceArray.data.mappings.mappings[i]); // //console.log('before before filtermatch',sourceCols[l],JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j], colCountry, (sourceArray.data.mappings.mappings[i]), (sourceArray.data.mappings.mappings[i].data), colState); // //console.log('before filtermatch', colCountry, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry], colState, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory]); // } //const filterMatch = this.matchesOnBoardingFilter(JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry][0], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState].length > 0 ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState][0] : "", JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory].length > 0 ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory][0] : "", Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute]) ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute][0] : JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute]); const filterMatch = false; //console.log('after filtermatch', filterMatch); if (filterMatch) { if (!unfilteredDict.includes(i)) { unfilteredDict.push(i); } } //console.log('isArray', sourceCols[l], Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])); if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) { for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) { html += (''); } } else { html += ('') } html += '
'; html += '
'; } divElement.innerHTML = html; if (unfilteredDict.length > 0) { var html = ''; html += '
Items In Your Category (' + unfilteredDict.length + ")
"; html += this.getFilterOnboardingString(); ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html; } else { ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none'; } if (subfiltered > 0) { ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '

Filtered Results (' + subfiltered + ')

'; } if (this.getfilterOnboarding().length > 0) { for (var i = 0; i < sourceArray.data.mappings.mappings.length; i++) { if (!unfilteredDict.includes(i)) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i); if (tableRow != null) { (tableRow as HTMLTableRowElement).style.display = 'none'; } } } } // const inputFilter = (divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement; // inputFilter.addEventListener('keyup', (e: any) => { // if(e.key == 'Enter') { // //console.log('filtering...', inputFilter.value); // if(this._SfLoader != null) { // this._SfLoader.innerHTML = '
'; // this._SfLoader.innerHTML += ('
'); // } // setTimeout(() => { // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, inputFilter.value); // // this._SfLoader.innerHTML = ''; // }, 1000); // } // }); (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf; //console.log('cb-length', arrCheckBoxes.length); for (var i = 0; i < arrCheckBoxes.length; i++) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement; //console.log('tablerow', i, tableRow); if (tableRow != null) { if (tableRow.style.display != 'none') { //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement)); (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked; if (e.currentTarget.checked) { if (!this.selectedCbs.includes(i + '')) { this.selectedCbs.push(i + ''); } } else { this.selectedCbs = []; } } } } //console.log('checkedarr', this.selectedCbs); }); for (var j = 0; j < extraFields.length; j++) { const inputArrJ = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf; for (var k = 0; k < inputArrJ.length; k++) { inputArrJ[k].addEventListener('keyup', (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; if (e.key == "Enter") { this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement); const activeIndex = e.target.id.split('-')[2]; for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) { taggingArray.data.mappings.mappings[count].extraFields = []; if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } else { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } } this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) } // this.saveTagging(taggingArray.data.mappings, uploadFunction, refreshFunction, true); }); inputArrJ[k].addEventListener('focusout', (e: any) => { this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement); const activeIndex = e.target.id.split('-')[2]; for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) { taggingArray.data.mappings.mappings[count].extraFields = []; if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } else { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } } this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) }); } } const multiArr = (divElement as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf; for (var i = 0; i < multiArr.length; i++) { if (apiIdDropdown.length > 0) { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; for (var k = 0; k < uniqCols.length; k++) { if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) { if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) { equal = false; } } } // if(taggingArray.data.mappings.mappings[j].id == "62330e24-298d-4ef2-9449-c0e400e37cac" && equal) { // if (taggingArray.data.mappings.mappings[j].id == "62330e24-298d-4ef2-9449-c0e400e37cac") { // // console.log('rendertagging', taggingArray.data.mappings.mappings[j], sourceArray.data.mappings.mappings[i]); // console.log('rendertagging', taggingArray.data.mappings.mappings[j]); // } if (equal) { (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(taggingArray.data.mappings.mappings[j][colName]); if (taggingArray.data.mappings.mappings[j][colName] != null && taggingArray.data.mappings.mappings[j][colName].length > 0) { ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped"); } } } // for(var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { // var equal = true; // for(var k = 0; k < uniqCols.length; k++) { // if(sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) { // if(sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) { // equal = false; // } // } // } // if(taggingArray.data.mappings.mappings[i].id == "fdea6e4a-9d47-4042-916f-724c51f465c1") { // //console.log('rendertagging', taggingArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i]); // } // if(equal) { // (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(taggingArray.data.mappings.mappings[j][colName]); // if(taggingArray.data.mappings.mappings[j][colName].length > 0) { // ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped"); // } // } // } //console.log('preselect', multiArr[i]); multiArr[i].addEventListener('valueChanged', async (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement); // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter); }); } else { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; for (var k = 0; k < uniqCols.length; k++) { if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) { if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) { equal = false; } } } if (taggingArray.data.mappings.mappings[j].id == "89cbfcab-b1a9-4a33-a59b-da3c1210dfd2" && taggingArray.data.mappings.mappings[j].locationid == "a5fd6c0c-7743-4fd2-b8d9-1d5e53fbaefa" && equal) { // console.log('rendertagging', taggingArray.data.mappings.mappings[j], sourceArray.data.mappings.mappings[i]); console.log('rendertagging', i, j, taggingArray.data.mappings.mappings[j], equal); } if (equal) { if (taggingArray.data.mappings.mappings[j] != null) { (multiArr[i] as HTMLInputElement).value = taggingArray.data.mappings.mappings[j][colName]; } } } multiArr[i].addEventListener('keyup', async (e: any) => { if (e.key == "Enter") { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement); // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter) } }); multiArr[i].addEventListener('focusout', async (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement); // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter) }); } } const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; buttonApply.addEventListener('click', () => { // console.log('applied'); // this.applyAndReloadTagging(e,colName, taggingArray, sourceArray, divElement); this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) }) const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'flex'; const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'flex'; const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'flex'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'flex'; const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'flex'; const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'flex'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'flex'; const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups); buttonDownloadBackupsNew.addEventListener('click', async () => { const result = await this.fetchGetStoredMapping(colName); for (var i = 0; i < result.data.length; i++) { const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + colName + '_' + i + '.json'); a.click() } (buttonToggleMoreBack as HTMLButtonElement).click(); if (result.data.length === 0) { this.setError("No backups found!") setTimeout(() => { this.clearMessages(); }, 3000); } }); const buttonExportMappingNew = Util.clearListeners(buttonExportMapping); buttonExportMappingNew.addEventListener('click', async () => { let valueStr: string[] = []; for (var i = 0; i < multiArr.length; i++) { if (apiIdDropdown.length > 0) { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; for (var k = 0; k < uniqCols.length; k++) { if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) { if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) { equal = false; } } } if (equal) { valueStr.push(JSON.stringify(taggingArray.data.mappings.mappings[j][colName])); } } } else { if (taggingArray.data.mappings.mappings[i] != null) { valueStr.push(taggingArray.data.mappings.mappings[i][colName]); } else { valueStr.push(''); } } } //console.log('valueStr', valueStr); const valuesHTML = JSON.stringify(valueStr); const outerHTML = '

This extract is generated on ' + new Date() + '

' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '

' + ((divElement as HTMLDivElement).querySelector('#mapped-stats-title') as HTMLHeadingElement).outerHTML + '

' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML; let tableHTML = this.TAGGING_HTML.replace(/TABLE_DATA/g, outerHTML); tableHTML = tableHTML.replace(/TABLE_VALUES/g, valuesHTML); const blob = new Blob([tableHTML], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html'); a.click() }); const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV); buttonExportMappingCSVNew?.addEventListener('click', async () => { let csvArray = JSON.parse(JSON.stringify(taggingArray.data.mappings.mappings)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj if (obj['cols'] != null && obj['data'] != null) { let dataArr = JSON.parse(obj['data']) let colsArr = JSON.parse(obj['cols']) for (let [j, colKey] of colsArr.entries()) { tempCsvObj['cols_' + colKey] = dataArr[j] } } csvArray[i] = tempCsvObj } console.log('csv array', csvArray) let csvData = Util.convertToCSV(csvArray); // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings); console.log('csvData', csvData); const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.csv'); a.click() }) const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal); buttonLoadLocalNew?.addEventListener('click', async () => { console.log('load-local'); ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); }); const fileInput = (divElement as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement; fileInput.value = ''; const fileInputNew = Util.clearListeners(fileInput); fileInputNew.addEventListener('change', (e: any) => { var fr = new FileReader(); fr.onload = () => { this.renderTaggingTable(divElement, sourceArray, JSON.parse(fr.result + ""), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter); }; var frCsv = new FileReader(); frCsv.onload = () => { console.log('taggingarray onload called'); console.log('csv result', frCsv.result); const tempArr = Util.parseCsv(frCsv.result + ""); console.log('csv data', tempArr) let changeCount = 0; for (let [i, obj] of tempArr.entries()) { let tempObj = taggingArray.data.mappings.mappings[i] delete tempObj['delta']; delete tempObj['lastupdated']; if (tempObj["id"].indexOf("6fb88c28-d572-4b55-b16c-957a519733b9") >= 0 || tempObj["id"].indexOf("90dbfbcc-a009-4778-b28e-a463867ceea9") >= 0 || tempObj["id"].indexOf("62330e24-298d-4ef2-9449-c0e400e37cac") >= 0 || tempObj["id"].indexOf("b9370711-024a-498a-8ce2-21c549824600") >= 0) { console.log('changed onboarding item', tempObj, obj, JSON.stringify(tempObj) !== JSON.stringify(obj)) } let tempNewObj = obj delete tempNewObj['delta']; delete tempNewObj['lastupdated']; if (JSON.stringify(tempObj) !== JSON.stringify(tempNewObj)) { // console.log('item changed', taggingArray.data.mappings.mappings[i], obj) let changedId = "" for (let [k, col] of uniqCols.entries()) { changedId += tempObj[col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } // this.changedOnboardingItemIds.push(taggingArray.data.mappings.mappings[i].id + ";" + taggingArray.data.mappings.mappings[i].entityid + ";" + taggingArray.data.mappings.mappings[i].locationid) this.changedOnboardingItemIds.push(changedId) // if(changedId.indexOf("6fb88c28-d572-4b55-b16c-957a519733b9") >= 0){ // console.log('changed onboarding item', tempObj, obj) // } changeCount++ } } this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [ () => { this.clearMessages(); this.changedOnboardingItemIds = []; (buttonToggleMoreBack as HTMLButtonElement).click(); }, () => { this.clearMessages(); let tempObj: any = {} tempObj["data"] = {} // let mappingsObj:any = {} // mappingsObj.mappings = tempArr // console.log('csv mappingsobj', mappingsObj) tempObj["data"]["mappings"] = {} tempObj["data"]["mappings"]["mappings"] = tempArr // for(let tempItem of tempArr){ // tempObj["data"]["mappings"]["mappings"].push(tempItem) // } // tempObj.data.mappings.mappings.push("pqrs") let tempObjStr = JSON.stringify(tempObj) // console.log('csv taggingarray tempobj', tempObj, tempObjStr, tempObj.data.mappings.mappings[0]) console.log('csv taggingarray cols', uniqCols, JSON.parse(tempObjStr)["data"]["mappings"]["mappings"].length, Object.keys(tempObj.data.mappings.mappings[0])) this.renderTaggingTable(divElement, sourceArray, JSON.parse(tempObjStr), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter); } ]) // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}} // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}} } if (e.target.files[0].name.toLowerCase().indexOf(colName.toLowerCase()) >= 0) { let ext = e.target.files[0].name.split('.')[e.target.files[0].name.split('.').length - 1] if (ext.toLowerCase() == "csv") { frCsv.readAsText(e.target.files[0]); } else { fr.readAsText(e.target.files[0]); } } }) const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal); buttonSaveLocalNew?.addEventListener('click', async () => { console.log('save-local'); const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().toLocaleString() + '.txt'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'none'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'none'; const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'none'; const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'none'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'none'; }); // const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; // buttonLoadLocal?.addEventListener('click', async () => { // console.log('load-local'); // ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); // }); // const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; // buttonSaveLocal?.addEventListener('click', async () => { // console.log('save-local'); // const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' }); // const url = window.URL.createObjectURL(blob) // const a = document.createElement('a') // a.setAttribute('href', url) // a.setAttribute('download', 'mapping_'+colName+'_'+new Date().toLocaleString()+'.txt'); // a.click() // }); const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave?.addEventListener('click', async () => { await this.saveTagging(taggingArray.data.mappings, [], uploadFunction, refreshFunction, false, colName); }); const buttonCancel = (divElement as HTMLDivElement).querySelector('.button-cancel') as HTMLButtonElement; buttonCancel?.addEventListener('click', async () => { //console.log('cancel clicked'); await this.fetchCancelOnboardingJob(colName); refreshFunction(); }); const cbArr = (divElement as HTMLDivElement).querySelectorAll('.cb-select') as NodeListOf; for (i = 0; i < cbArr.length; i++) { cbArr[i].addEventListener('change', (ev: any) => { const cbSelectId = ev.currentTarget.id; const cbSelectIndex = cbSelectId.split('-')[1]; if (!this.selectedCbs.includes(cbSelectIndex)) { this.selectedCbs.push(cbSelectIndex); } else { this.selectedCbs.splice(this.selectedCbs.indexOf(cbSelectIndex), 1); } //console.log(this.selectedCbs); }) } // const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field') as NodeListOf; // var totalFields = 0; // var filledFields = 0; // for(var i = 0; i < arrExtraFields.length; i++) { // const extraField = arrExtraFields[i] as HTMLInputElement; // if(extraField.parentElement?.parentElement?.style.display != "none") { // if(extraField.value != "") { // filledFields++; // } // totalFields++; // } // } if ((divElement as HTMLDivElement).querySelector("#span-extra-filled") != null) { //(divElement as HTMLDivElement).querySelector("#span-extra-filled")!.innerHTML = "Fields: " + filledFields + "/" + totalFields + " completed"; //console.log('Total fields = ' + totalFields + ', filled fields = ' + filledFields); } this.changedOnboardingItemIds = [] } renderTaggingTableNew = (divElement: any, selectedStatutes: any, sourceObject: any, sourceMapping: any, taggingObject: any, sourceCols: any, uploadFunction: any, refreshFunction: any, colName: any, uniqCols: Array, apiIdDropdown: string, dropdownSearchPhrase: any, mandatoryFields: any, compareFields: Array, anotherProjection: any, extraFields: Array, _arrFeedbackReference: any, proposedUsersLabel: string, subfilter: string) => { console.log('sourceObj', sourceObject) console.log('taggingObj', taggingObject) let sourceArray: any = { data: { mappings: { mappings: sourceObject.data.mappings } } }; let taggingArray: any = { data: { mappings: { mappings: taggingObject.data.mappings } } }; if (taggingObject.data.mappings.mappings != null) { taggingArray = taggingObject; } console.log('divelement', divElement); console.log('sourcearray', sourceArray); console.log('sourceMappingStr', JSON.stringify(sourceMapping)); console.log('sourceMapping', sourceMapping); console.log('taggingarray', JSON.stringify(taggingArray)); console.log('tagged length', taggingArray.data.mappings.mappings.length) console.log('selectedStatutes', selectedStatutes); this.selectedCbs = []; if (sourceMapping.data == null) { console.log('sourcemapping data null'); sourceMapping = { data: { mappings: Object.values(sourceArray.data.mappings.mappings) } } } for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) { if (taggingArray.data.mappings.mappings[i].id != null && sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[i].id] == null) { console.log('tagged splicing', taggingArray.data.mappings.mappings[i].id) taggingArray.data.mappings.mappings.splice(i, 1) } else { let flagFoundSource = false for (var j = 0; j < sourceMapping.data.mappings.length; j++) { if (sourceMapping.data.mappings[j].id == taggingArray.data.mappings.mappings[i].id) { flagFoundSource = true; break; } } if (taggingArray.data.mappings.mappings[i].id == "3cadde91-4ef5-4adf-baee-fd088a3297da") { console.log('tagged for splicing', flagFoundSource) } if (!flagFoundSource) { console.log('tagged splicing1', taggingArray.data.mappings.mappings[i].id) taggingArray.data.mappings.mappings.splice(i, 1) } } } let mandatoryPresent = true; console.log('mandatoryFields', mandatoryFields); for (i = 0; i < (mandatoryFields as Array).length; i++) { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { if (taggingArray.data.mappings.mappings[j][mandatoryFields[i]] == null) { console.log('mandatory not found', mandatoryFields[i]) mandatoryPresent = false; } } } var taggedIds = [] for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { if (taggingArray.data.mappings.mappings[j] != null) { if (sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[j].id] != null) { if (taggedIds.indexOf(taggingArray.data.mappings.mappings[j].id) < 0) { taggedIds.push(taggingArray.data.mappings.mappings[j].id) } } else { console.log('tagged id not found', taggingArray.data.mappings.mappings[j]) } } } let countPush = 0; let countFound = 0 let tempMappings = taggingArray.data.mappings.mappings for (let sourceObj of (sourceMapping.data?.mappings ?? [])) { let flagMatch = false; if (sourceArray.data.mappings.mappings[sourceObj.id] == null) { console.log('tagging id not found', sourceObj.id) continue; } for (let taggingObj of taggingArray.data.mappings.mappings) { if (sourceObj.id == taggingObj.id) { let flagMatchObj = true; for (let objKey of compareFields) { if (sourceObj[objKey] !== taggingObj[objKey] && taggingObj[objKey] != null && taggingObj[objKey] != "" && sourceObj[objKey] != null && sourceObj[objKey] != "") { console.log('Flag Mismatch', objKey, sourceObj[objKey], taggingObj[objKey]) flagMatchObj = false; break; } } if (flagMatchObj == true) { flagMatch = true; countFound++; break; } } } if (flagMatch == false) { let objToPush: any = sourceObj for (let mandatoryField of mandatoryFields) { objToPush[mandatoryField] = "" } tempMappings.push(objToPush); countPush++; } } taggingArray.data.mappings.mappings = tempMappings; console.log('found tagging items', countFound) console.log('pushed tagging items', countPush) tempMappings = [] for (let taggingObj of taggingArray.data.mappings.mappings) { if (sourceArray.data.mappings.mappings[taggingObj.id] != null) { tempMappings.push(taggingObj) } } taggingArray.data.mappings.mappings = tempMappings if (colName == "countries" || colName == "entities" || colName == "locations") { let tempMappingObj: any = {} for (let mappingItem of taggingArray.data.mappings.mappings) { let compositeKey = mappingItem.id for (let compareField of compareFields) { compositeKey += ";" + mappingItem[compareField] } if (tempMappingObj[compositeKey] == null) { tempMappingObj[compositeKey] = mappingItem } let tempMap = tempMappingObj[compositeKey][colName] ?? [] let mapStr = "" let flagBlank = false; for (let mandatoryField of mandatoryFields) { if (mappingItem[mandatoryField] == null || mappingItem[mandatoryField] == "") { flagBlank = true; break; } mapStr += mappingItem[mandatoryField] + ";" } if (flagBlank) { continue; } tempMap.push(mapStr.slice(0, -1)) tempMappingObj[compositeKey][colName] = tempMap } taggingArray.data.mappings.mappings = Object.values(tempMappingObj) } var tagged = 0; var changed = 0; var total = 0; var untagged = 0; let countFlagNull = 0 tempMappings = [] for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { if (taggingArray.data.mappings.mappings[j] != null) { let flagFound = false; for (let sourceObj of sourceMapping.data.mappings) { if (sourceObj.id == taggingArray.data.mappings.mappings[j].id) { let flagEqual = true; for (let col of compareFields) { if (sourceObj[col] != taggingArray.data.mappings.mappings[j][col] && taggingArray.data.mappings.mappings[j][col] != null) { flagEqual = false; break; } } if (flagEqual) { flagFound = true; break; } } } if (flagFound) { let tagStr = "" for (let col of compareFields) { tagStr += `${taggingArray.data.mappings.mappings[j][col]};` } tagStr.slice(0, -1) tempMappings.push(taggingArray.data.mappings.mappings[j]) total++; if (this.changedOnboardingItemIds.length > 0) { let changedId = tagStr if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { changed++; } } if (taggingArray.data.mappings.mappings[j][colName] == null || taggingArray.data.mappings.mappings[j][colName] == "" || taggingArray.data.mappings.mappings[j][colName].length == 0) { if (colName == "countries" || colName == "entities" || colName == "locations") { let flagNull = false; for (let mandatoryfield of mandatoryFields) { if (taggingArray.data.mappings.mappings[j][mandatoryfield] == null || taggingArray.data.mappings.mappings[j][mandatoryfield] == "") { flagNull = true; break; } } if (flagNull) { countFlagNull++; console.log('flag null', taggingArray.data.mappings.mappings[j], countFlagNull) continue } } else { countFlagNull++; console.log('flag null 1', taggingArray.data.mappings.mappings[j], countFlagNull) continue; } } tagged++; } else { untagged++; console.log('tagged not found', taggingArray.data.mappings.mappings[j].id, sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[j].id]) } // } } } taggingArray.data.mappings.mappings = tempMappings console.log('taggingarray3', JSON.stringify(taggingArray.data.mappings.mappings)); let tempObj: any = {} let countDuplicate = 0 for (let taggingObj of taggingArray.data.mappings.mappings) { if (tempObj[taggingObj.id] == null) { tempObj[taggingObj.id] = true } else { countDuplicate++; console.log('duplicate taggingObject', taggingObj.id, countDuplicate); } } console.log('tagged', tagged, 'total', total, 'untagged', untagged, 'length', taggingArray.data.mappings.mappings.length); const unfilteredDict: any[] = []; if (divElement == null) { return; } var html = ''; var showTable = true; html += '
'; var status = ''; if (tagged < total) { status = 'pending'; } else { status = 'check_circle'; } var mandatoryStatus = ''; if (!mandatoryPresent) { mandatoryStatus = 'error  Mandatory fields are not present'; } else { mandatoryStatus = 'check_circle  Mandatory fields are present'; } if (showTable) { html += ('

' + status + '  Mapped ' + tagged + ' out of ' + total + '

'); } else { html += ('

' + status + '  Mapped ' + tagged + ' out of ' + total + '

') } if (changed > 0) { html += ('

pending  ' + changed + ' Items changed

') } html += ('

' + mandatoryStatus + '

') html += ('

') html += '
'; html += '
'; html += '
' html += '
' html += '' // console.log('jobs', jobs); html += (''); html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '

' html += '
' html += '
'; html += '
'; var subfiltered = 0; if (showTable) { html += ''; html += ''; html += '' for (var i = 0; i < extraFields.length; i++) { html += '' } html += '' for (i = 0; i < uniqCols.length; i++) { html += '' } for (i = 0; i < sourceCols.length; i++) { html += '' } html += ''; html += ''; // console.log('changedIds', this.changedOnboardingItemIds); for (i = 0; i < taggingArray.data.mappings.mappings.length; i++) { let complianceid = taggingArray.data.mappings.mappings[i].id console.log('compliance id', complianceid); var showSearch = false; if (subfilter == "") { //console.log('showsearch true 1'); showSearch = true; } var classBg = ""; if (i % 2 === 0) { if (this.changedOnboardingItemIds.length > 0) { let changedId = "" for (let [k, col] of uniqCols.entries()) { // console.log('taggingarray rendered', i, col) changedId += taggingArray.data.mappings.mappings[i][col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-light-selected'; } else { classBg = 'td-light'; } } else { classBg = 'td-light'; } } else { if (this.changedOnboardingItemIds.length > 0) { let changedId = "" for (let [k, col] of uniqCols.entries()) { if (taggingArray.data.mappings.mappings[i] == null) { // console.log('id not found', i, taggingArray.data.mappings.mappings.length, sourceArray.data.mappings.mappings.length) } changedId += taggingArray.data.mappings.mappings[i][col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-dark-selected'; } else { classBg = 'td-dark'; } } else { classBg = 'td-dark'; } } html += ''; html += ''; for (var j = 0; j < extraFields.length; j++) { if (i < taggingArray.data.mappings.mappings.length) { html += ''; } else { html += ''; } } html += '' for (var l = 0; l < uniqCols.length; l++) { html += '' } for (l = 0; l < sourceCols.length; l++) { for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[complianceid].cols).length; j++) { if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[complianceid].cols)[j]) { if (sourceArray.data.mappings.mappings[complianceid].data != null) { html += ''; } } } } html += ''; //console.log('i=', i); } html += ''; html += '
' html += '
'; html += '
' html += extraFields[i]; html += '' html += colName; html += '' html += uniqCols[i]; html += '' html += sourceCols[i]; html += '
'; html += '
' html += ''; html += '
'; html += '
'; html += '
'; html += ''; html += '
'; html += '
' html += '
'; if (apiIdDropdown.length > 0) { if (anotherProjection != null) { html += ''; } else { html += ''; } } else { if (colName.toLowerCase() == "internalcontrols") { html += ''; } else { html += ''; } } html += '
'; html += '
' html += '
'; html += ''; html += '
'; html += '
'; html += '
'; if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j])) { for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j].length; k++) { html += (''); } } else { if (typeof JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j] == "string" && Util.isJSONParsable(JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j])) { html += ('') } else { html += ('') } } html += '
'; html += '
'; } if (divElement == null) { return; } divElement.innerHTML = html; if (unfilteredDict.length > 0) { var html = ''; html += '
Items In Your Category (' + unfilteredDict.length + ")
"; html += this.getFilterOnboardingString(); ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html; } else { ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none'; } if (subfiltered > 0) { ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '

Filtered Results (' + subfiltered + ')

'; } if (this.getfilterOnboarding().length > 0) { for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) { if (!unfilteredDict.includes(i)) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i); if (tableRow != null) { (tableRow as HTMLTableRowElement).style.display = 'none'; } } } } (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf; //console.log('cb-length', arrCheckBoxes.length); for (var i = 0; i < arrCheckBoxes.length; i++) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement; //console.log('tablerow', i, tableRow); if (tableRow != null) { if (tableRow.style.display != 'none') { //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement)); (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked; if (e.currentTarget.checked) { if (!this.selectedCbs.includes(i + '')) { this.selectedCbs.push(i + ''); } } else { this.selectedCbs = []; } } } } //console.log('checkedarr', this.selectedCbs); }); for (var j = 0; j < extraFields.length; j++) { const inputArrJ = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf; for (var k = 0; k < inputArrJ.length; k++) { inputArrJ[k].addEventListener('keyup', (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; if (e.key == "Enter") { this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement); const activeIndex = e.target.id.split('-')[2]; for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) { taggingArray.data.mappings.mappings[count].extraFields = []; if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } else { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } } this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) } // this.saveTagging(taggingArray.data.mappings, uploadFunction, refreshFunction, true); }); inputArrJ[k].addEventListener('focusout', (e: any) => { this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement); const activeIndex = e.target.id.split('-')[2]; for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) { taggingArray.data.mappings.mappings[count].extraFields = []; if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } else { for (var l = 0; l < extraFields.length; l++) { const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement); taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value) } } } this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) }); } } const multiArr = (divElement as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf; for (var i = 0; i < multiArr.length; i++) { if (apiIdDropdown.length > 0) { // for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; let complianceid = taggingArray.data.mappings.mappings[i].id for (var k = 0; k < uniqCols.length; k++) { if (uniqCols[k] != "id") { continue; } if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[i] != null) { if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) { equal = false; } } } if (equal) { let preselctedVals = [] if ((colName == "countries" || colName == "entities" || colName == "locations") && (taggingArray.data.mappings.mappings[i][colName] == null || taggingArray.data.mappings.mappings[i][colName].length == 0)) { let preselctedValsStr = "" for (let mandatoryfield of mandatoryFields) { if (taggingArray.data.mappings.mappings[i][mandatoryfield] == null || taggingArray.data.mappings.mappings[i][mandatoryfield] == "") { preselctedValsStr = "" } else { preselctedValsStr += `${taggingArray.data.mappings.mappings[i][mandatoryfield]};` } } preselctedValsStr = preselctedValsStr.slice(0, -1); if (preselctedValsStr.indexOf(';') >= 0) { preselctedVals.push(preselctedValsStr) } taggingArray.data.mappings.mappings[i][colName] = preselctedVals; } else { preselctedVals = taggingArray.data.mappings.mappings[i][colName]; } (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(preselctedVals); if (preselctedVals.length > 0) { ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped"); } } // } multiArr[i].addEventListener('valueChanged', async (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement); }); } else { // for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; let complianceid = taggingArray.data.mappings.mappings[i].id for (var k = 0; k < uniqCols.length; k++) { if (uniqCols[k] != "id") { continue; } if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[i] != null) { if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) { equal = false; } } } console.log('Array JSON parsable', taggingArray.data.mappings.mappings[i][colName], equal); if (equal) { if (taggingArray.data.mappings.mappings[i] != null) { // if (Util.isJSONParsable(taggingArray.data.mappings.mappings[i][colName])) { // (multiArr[i] as HTMLInputElement).value = JSON.parse(taggingArray.data.mappings.mappings[i][colName])[0]; // } else { (multiArr[i] as HTMLInputElement).value = taggingArray.data.mappings.mappings[i][colName] ?? ""; // } } } // } multiArr[i].addEventListener('keyup', async (e: any) => { if (e.key == "Enter") { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement); } }); multiArr[i].addEventListener('focusout', async (e: any) => { ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement); }); } } const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; buttonApply.addEventListener('click', () => { // console.log('applied'); // this.applyAndReloadTagging(e,colName, taggingArray, sourceArray, divElement); this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter) }) const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'flex'; const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'flex'; const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'flex'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'flex'; const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'flex'; const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'flex'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'flex'; const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups); buttonDownloadBackupsNew.addEventListener('click', async () => { const result = await this.fetchGetStoredMapping(colName); for (var i = 0; i < result.data.length; i++) { const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + colName + '_' + i + '.json'); a.click() } (buttonToggleMoreBack as HTMLButtonElement).click(); if (result.data.length === 0) { this.setError("No backups found!") setTimeout(() => { this.clearMessages(); }, 3000); } }); const buttonExportMappingNew = Util.clearListeners(buttonExportMapping); buttonExportMappingNew.addEventListener('click', async () => { let valueStr: string[] = []; for (var i = 0; i < multiArr.length; i++) { if (apiIdDropdown.length > 0) { for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) { var equal = true; let complianceid = taggingArray.data.mappings.mappings[j].id for (var k = 0; k < uniqCols.length; k++) { if (uniqCols[k] != "id") { continue; } if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[j] != null) { if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) { equal = false; } } } if (equal) { valueStr.push(JSON.stringify(taggingArray.data.mappings.mappings[j][colName])); } } } else { if (taggingArray.data.mappings.mappings[i] != null) { valueStr.push(taggingArray.data.mappings.mappings[i][colName]); } else { valueStr.push(''); } } } //console.log('valueStr', valueStr); const valuesHTML = JSON.stringify(valueStr); const outerHTML = '

This extract is generated on ' + new Date() + '

' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '

' + ((divElement as HTMLDivElement).querySelector('#mapped-stats-title') as HTMLHeadingElement).outerHTML + '

' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML; let tableHTML = this.TAGGING_HTML.replace(/TABLE_DATA/g, outerHTML); tableHTML = tableHTML.replace(/TABLE_VALUES/g, valuesHTML); const blob = new Blob([tableHTML], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html'); a.click() }); const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV); buttonExportMappingCSVNew?.addEventListener('click', async () => { let csvArray = JSON.parse(JSON.stringify(taggingArray.data.mappings.mappings)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj // if(tempCsvObj[colName] == null){ // let tempStr = "" // for(let mandatoryfield of mandatoryFields){ // tempStr += `${tempCsvObj[mandatoryfield]};` // } // tempStr = tempStr.slice(0, -1); // tempCsvObj[colName] = [tempStr] // } let tempId = obj.id; let tempCompliance = sourceArray.data.mappings.mappings[tempId] if (tempCompliance['cols'] != null && tempCompliance['data'] != null) { let dataArr = JSON.parse(tempCompliance['data']) let colsArr = JSON.parse(tempCompliance['cols']) for (let [j, colKey] of colsArr.entries()) { tempCsvObj['cols_' + colKey] = dataArr[j] } } csvArray[i] = tempCsvObj } console.log('csv array', csvArray) let csvData = Util.convertToCSV(csvArray); // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings); console.log('csvData', csvData); const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.csv'); a.click() }) const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal); buttonLoadLocalNew?.addEventListener('click', async () => { console.log('load-local'); ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); }); const fileInput = (divElement as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement; fileInput.value = ''; const fileInputNew = Util.clearListeners(fileInput); fileInputNew.addEventListener('change', (e: any) => { var fr = new FileReader(); fr.onload = () => { this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, JSON.parse(fr.result + ""), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter); }; var frCsv = new FileReader(); frCsv.onload = () => { console.log('taggingarray onload called'); console.log('csv result', frCsv.result); const tempArr = Util.parseCsv(frCsv.result + ""); console.log('csv data', tempArr) let changeCount = 0; for (let [i, obj] of taggingArray.data.mappings.mappings.entries()) { let tempObj = tempArr[i] ?? {} for (let key of Object.keys(tempObj)) { if (key.indexOf('cols_') >= 0) { delete tempObj[key] } } delete tempObj['delta']; delete tempObj['lastupdated']; let tempNewObj = obj for (let key of Object.keys(tempNewObj)) { if (key.indexOf('cols_') >= 0) { delete tempNewObj[key] } } delete tempNewObj['delta']; delete tempNewObj['lastupdated']; // if(tempNewObj[colName] == null){ // delete tempObj[colName]; // } console.log('comparing objects', tempObj, tempNewObj); if (JSON.stringify(tempObj) !== JSON.stringify(tempNewObj)) { // console.log('item changed', taggingArray.data.mappings.mappings[i], obj) let changedId = "" for (let [k, col] of uniqCols.entries()) { // if (col != "id") { continue; } changedId += tempObj[col]; if (k < (uniqCols.length - 1)) { changedId += ";" } } this.changedOnboardingItemIds.push(changedId) changeCount++ } } this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [ () => { this.clearMessages(); this.changedOnboardingItemIds = []; (buttonToggleMoreBack as HTMLButtonElement).click(); }, () => { this.clearMessages(); let tempObj: any = {} tempObj["data"] = {} tempObj["data"]["mappings"] = {} tempObj["data"]["mappings"]["mappings"] = tempArr let tempObjStr = JSON.stringify(tempObj) console.log('csv taggingarray cols', uniqCols, JSON.parse(tempObjStr)["data"]["mappings"]["mappings"].length, Object.keys(tempObj.data.mappings.mappings[0]), sourceMapping) this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, JSON.parse(tempObjStr), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter); } ]) } if (e.target.files[0].name.toLowerCase().indexOf(colName.toLowerCase()) >= 0) { let ext = e.target.files[0].name.split('.')[e.target.files[0].name.split('.').length - 1] if (ext.toLowerCase() == "csv") { frCsv.readAsText(e.target.files[0]); } else { fr.readAsText(e.target.files[0]); } } }) const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal); buttonSaveLocalNew?.addEventListener('click', async () => { console.log('save-local'); const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().toLocaleString() + '.txt'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'none'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'none'; const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'none'; const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'none'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'none'; }); const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave?.addEventListener('click', async () => { await this.saveTagging(taggingArray.data.mappings, selectedStatutes, uploadFunction, refreshFunction, false, colName); }); const buttonCancel = (divElement as HTMLDivElement).querySelector('.button-cancel') as HTMLButtonElement; buttonCancel?.addEventListener('click', async () => { //console.log('cancel clicked'); await this.fetchCancelOnboardingJob(colName); refreshFunction(); }); const cbArr = (divElement as HTMLDivElement).querySelectorAll('.cb-select') as NodeListOf; for (i = 0; i < cbArr.length; i++) { cbArr[i].addEventListener('change', (ev: any) => { const cbSelectId = ev.currentTarget.id; const cbSelectIndex = cbSelectId.split('-')[1]; if (!this.selectedCbs.includes(cbSelectIndex)) { this.selectedCbs.push(cbSelectIndex); } else { this.selectedCbs.splice(this.selectedCbs.indexOf(cbSelectIndex), 1); } //console.log(this.selectedCbs); }) } this.changedOnboardingItemIds = [] } renderMappingTable = (divElement: any, jsonData: Array, cursor: Array, fetchFunction: any, searchString: string, mappedArray: any, found: number, uploadFunction: any, refreshFunction: any, extraFields: Array, uploadBlock: number, extraFieldPosition: number, colName: string, subfilter: string, statuteColName: string, extraHintsArr: Array, mappedStatutes: Array = []) => { console.log('cols1', jsonData); // console.log('cols', jsonData[0].data.cols); //console.log('divelement', divElement); //console.log('jsonData', jsonData); //console.log('cursor', cursor); //console.log('fetch', fetchFunction); //console.log('searchstring', searchString); //console.log('subfiltervalue', subfilter); const arrCompliancesFrequencies: any = {}; if (jsonData.length === 0) return; this.selectedCbs = []; let colCountry = -1; let colState = -1; let colSubcategory = -1; let colStatute = -1; const unfilteredDict: any[] = []; var html = ''; let mappedTotal = 0 for (var i = 0; i < jsonData.length; i++) { if (jsonData[i].mapped) { mappedTotal++ } } html += '
'; html += '

Total Items (' + found + ') · Mapped (' + mappedTotal + ')

'; html += '
'; html += '
'; html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '
Row Details
'; html += ''; html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; // html += ''; html += '
'; html += '
' html += '
' html += '
'; html += (this.disablesave == "yes" ? '' : ''); html += '
'; html += '
'; html += ''; html += ''; html += '' html += '' if (extraFieldPosition === 0) { for (var i = 0; i < extraFields.length; i++) { html += '' } } // if (colName.toLowerCase() == "compliances") { // html += '' // } html += '' // for(var j = 0; j < JSON.parse(jsonData[0].data.cols).length; j++) { // if(jsonData[0].cols.includes(JSON.parse(jsonData[0].data.cols)[j])) { // html += '' // } // } for (var j = 0; j < jsonData[0].cols.length; j++) { console.log('jsoncols', JSON.parse(jsonData[0].data.cols), jsonData[0].cols.length, j) html += '' } if (extraFieldPosition === 1) { for (var i = 0; i < extraFields.length; i++) { html += '' } } html += '' //console.log('colstate', JSON.parse(jsonData[0].data.cols)); for (var i = 0; i < JSON.parse(jsonData[0].data.cols).length; i++) { if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "country") { console.log('colstate country', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i); colCountry = i; } if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "state") { //console.log('colstate state', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i); colState = i; } if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "subcategory") { //console.log('colstate subcategory', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i); colSubcategory = i; } if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == statuteColName) { //console.log('colstate statute', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i); colStatute = i; } } //var countExtra0 = 0; var countextra = []; var subfiltered = 0; html += '' var mappedCount = 0; for (let level = 0; level < 2; level++) { for (var i = 0; i < jsonData.length; i++) { // console.log('subfilter value before', subfiltered); console.log('rendering', i, jsonData[i]) let tempColCountry = -1; let tempColState = -1; let tempColStatute = -1; let tempColSubcategory = -1; if (JSON.parse(jsonData[0].data.cols)[0] == ('lastModifiedBy')) { if (JSON.parse(jsonData[i].data.cols)[0] != ('lastModifiedBy')) { tempColCountry = colCountry - 2; tempColState = colState - 2; tempColStatute = colStatute - 2; tempColSubcategory = colSubcategory - 2; } else { tempColCountry = colCountry; tempColState = colState; tempColStatute = colStatute; tempColSubcategory = colSubcategory; } } else { if (JSON.parse(jsonData[i].data.cols)[0] == ('lastModifiedBy')) { tempColCountry = colCountry + 2; tempColState = colState + 2; tempColStatute = colStatute + 2; tempColSubcategory = colSubcategory + 2; } else { tempColCountry = colCountry; tempColState = colState; tempColStatute = colStatute; tempColSubcategory = colSubcategory; } } if ((JSON.parse(jsonData[i].data.data)[tempColCountry] ?? "").length === 0 && level === 1) { html += ''; html += ''; html += ''; for (var j = 0; j < extraFields.length; j++) { html += ''; if (j === 0) { //countExtra0++; countextra.push(i); } } // if (colName.toLowerCase() == "compliances") { // html += ''; // } html += ''; html += ''; continue; } var showSearch = false; if (subfilter == "") { showSearch = true; } else { for (var j = 0; j < extraFields.length; j++) { try { if (jsonData[i].extraFields != null && jsonData[i].extraFields[j] != null && jsonData[i].extraFields[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { showSearch = true; subfiltered++; break; } } catch (e) { } try { if (jsonData[i].extraFields != null && jsonData[i].extraFields[j] != null && JSON.stringify(jsonData[i].extraFields[j]).toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { showSearch = true; subfiltered++; break; } } catch (e) { } } if (!showSearch) { for (var j = 0; j < JSON.parse(jsonData[i].data.cols).length; j++) { if (jsonData[i].cols.includes(JSON.parse(jsonData[i].data.cols)[j])) { if (Array.isArray(JSON.parse(jsonData[i].data.data)[j])) { var tempCount = subfiltered; for (var k = 0; k < JSON.parse(jsonData[i].data.data)[j].length; k++) { if (JSON.parse(jsonData[i].data.data)[j][k].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { showSearch = true; //console.log('subfilter value inside 1', subfiltered); subfiltered++; break; } } if (subfiltered > tempCount) break; } else { if (JSON.parse(jsonData[i].data.data)[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) { showSearch = true; //console.log('subfilter value inside 2', subfiltered); subfiltered++; break; } } } } } } //console.log('subfilter value', subfiltered); var classBg = ""; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } var mapped = ""; if (jsonData[i].mapped) { mapped = "checked"; this.selectedCbs.push(i); } if ((level == 0 && jsonData[i].mapped) || (level == 1 && !jsonData[i].mapped)) { if ((level == 0 && jsonData[i].mapped)) { mappedCount++; } if (arrCompliancesFrequencies[jsonData[i].id] == null) { arrCompliancesFrequencies[jsonData[i].id] = 0; } else { arrCompliancesFrequencies[jsonData[i].id]++; } html += ''; html += ''; html += ''; } /* for(var j = 0; j < extraFields.length; j++) { html += ''; if(j === 0) { countExtra0++; } } */ } // if (colName.toLowerCase() == "compliances") { // var userHtml = ''; // userHtml = this.getPreviousExtraFields(i, jsonData[i].previousExtraFields, locationsForThisItem, showSearch) // html += ''; // } html += ''; //let data = JSON.parse(jsonData[i].fields.data); for (var j = 0; j < JSON.parse(jsonData[i].data.cols).length; j++) { if (jsonData[i].cols.includes(JSON.parse(jsonData[i].data.cols)[j])) { // html += ''; } } for (var k = 0; k < jsonData[i].cols.length; k++) { if (JSON.parse(jsonData[i].data.cols).includes(jsonData[i].cols[k])) { } else { html += ''; } } // else { // var foundCol = false; // for(var k = 0; k < jsonData[i].cols.length; k++) { // console.log('founcol compare', jsonData[i].cols[k], JSON.parse(jsonData[i].data.cols)[j]); // if(jsonData[i].cols[k] == JSON.parse(jsonData[i].data.cols)[j]) { // if(JSON.parse(jsonData[i].data.cols).includes(jsonData[i].cols[k])) { // foundCol = true; // } // } // console.log('founcol compare', foundCol); // } // if(!foundCol) { // html += ''; // } // } if (extraFieldPosition === 1) { for (var j = 0; j < extraFields.length; j++) { html += ''; } } html += ''; } } } html += '' html += '
' // html += 'Select'; html += '
'; html += '
' html += '
View
'; html += '
' html += extraFields[i]; html += '' // html += 'Proposed Users'; // html += '' html += 'Id'; html += '' // html += JSON.parse(jsonData[0].data.cols)[j] // html += '' // html += jsonData[0].cols[j] html += '' html += extraFields[i]; html += '
'; html += '
'; html += '
'; html += '
'; let locationsForThisItem: any = []; if ((JSON.parse(jsonData[i].data.data)[tempColState] ?? "").length > 0) { locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState][0], JSON.parse(jsonData[i].data.data)[tempColStatute]); } else { console.log(JSON.parse(jsonData[i].data.data)[colStatute], colStatute, statuteColName); locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColStatute]); } if (extraFieldPosition === 0) { for (var j = 0; j < extraFields.length; j++) { html += '
'; const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : ""); let strValuesForThisItem: string = ""; strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); html += '
'; // html += '
'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'
'; // html += '
'; html += '
'; let locationsForThisItem: any = ''; if(JSON.parse(jsonData[i].data.data)[colState].length > 0) { locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[colCountry][0], JSON.parse(jsonData[i].data.data)[colState][0], JSON.parse(jsonData[i].data.data)[colStatute][0]); } else { locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[colCountry][0], JSON.parse(jsonData[i].data.data)[colStatute][0]); } const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g,'"'); const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : ""); let strValuesForThisItem: string = ""; strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g,'"'); // try { // JSON.parse(valuesForThisItem); // strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g,'"'); // //console.log('locationsForThisItem 1', JSON.stringify(locationsForThisItem), strValuesForThisItem); // } catch (e: any) { // strValuesForThisItem = ""; // } //console.log('locationsForThisItem', JSON.stringify(locationsForThisItem)); html += '
'; // html += '
'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'
'; // html += '
'; html += '
'; // html += userHtml // html += ''; html += '
'; html += '
'; html += ''; html += '
' html += '
'; let filterMatch: any = null; filterMatch = this.matchesOnBoardingFilter(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState].length > 0 ? JSON.parse(jsonData[i].data.data)[tempColState][0] : "", JSON.parse(jsonData[i].data.data)[tempColSubcategory].length > 0 ? JSON.parse(jsonData[i].data.data)[tempColSubcategory][0] : "", Array.isArray(JSON.parse(jsonData[i].data.data)[tempColStatute]) ? JSON.parse(jsonData[i].data.data)[tempColStatute][0] : JSON.parse(jsonData[i].data.data)[tempColStatute]); if (jsonData[i].id == "f724e2b9-451a-49ec-85ba-2b099f433c73") { console.log('filtermatch', filterMatch); } if (filterMatch) { if (!unfilteredDict.includes(i)) { unfilteredDict.push(i); } } // if(JSON.parse(jsonData[i].data.cols)[j] == "statute") { // html += 'filter_list'; // } html += ('
' + JSON.parse(jsonData[i].data.cols)[j] + '
'); if (Array.isArray(JSON.parse(jsonData[i].data.data)[j])) { for (var k = 0; k < JSON.parse(jsonData[i].data.data)[j].length; k++) { html += (''); //console.log('Considering', JSON.parse(jsonData[i].data.cols)[j], jsonData[i].cols, j, JSON.parse(jsonData[i].data.data)[j], ''); } } else { html += ('') //console.log('Considering', JSON.parse(jsonData[i].data.cols)[j], jsonData[i].cols, j, JSON.parse(jsonData[i].data.data)[j], ''); } html += '
'; html += '
'; html += '
'; let locationsForThisItem: any = []; if (JSON.parse(jsonData[i].data.data)[tempColState].length > 0) { locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState][0], JSON.parse(jsonData[i].data.data)[tempColStatute]); } else { //console.log(JSON.parse(jsonData[i].data.data)[colStatute]); locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColStatute]); } const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : ""); let strValuesForThisItem: string = ""; strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); html += '
'; // html += '
'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'
'; // html += '
'; html += '
'; //console.log('countextra', countExtra0, countextra); console.log('arrCompliancesFrequencies', arrCompliancesFrequencies); divElement.innerHTML = html; // if (unfilteredDict.length > 0) { // var html = ''; // html += '
Items In Your Category (' + unfilteredDict.length + ")
"; // html += this.getFilterOnboardingString(); // ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html; // } else { // ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none'; // } if (subfiltered > 0) { ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '
Filtered Results (' + subfiltered + ')
'; } if (this.getfilterOnboarding().length > 0) { for (var i = 0; i < jsonData.length; i++) { if (!unfilteredDict.includes(i)) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i); if (tableRow != null) { (tableRow as HTMLTableRowElement).style.display = 'none'; } } } } // Scroll arrow handlers // const scrollLeft = (divElement as HTMLDivElement).querySelector('#scroll-overlay-left') as HTMLButtonElement; // scrollLeft.addEventListener('click', () => { // //console.log('left'); // (this._SfOnboardingStatutesListContainer as HTMLDivElement).scrollLeft -= 150; // }); // const scrollRight = (divElement as HTMLDivElement).querySelector('#scroll-overlay-right') as HTMLButtonElement; // scrollRight.addEventListener('click', () => { // //console.log('right'); // //var scrollLeft = ((divElement as HTMLDivElement).querySelector('#statutes-list-container') as HTMLDivElement).scrollLeft; // //((divElement as HTMLDivElement).querySelector('#statutes-list-container') as HTMLDivElement).scrollLeft += 100; // (this._SfOnboardingStatutesListContainer as HTMLDivElement).scrollLeft += 150; // }); // Extra field handlers for (var i = 0; i < extraFields.length; i++) { const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + i) as NodeListOf; // console.log('i='+i, arrExtraFields.length) for (var j = 0; j < arrExtraFields.length; j++) { // console.log('j='+j, jsonData[j], arrExtraFields.length) // const extraField = (divElement as HTMLDivElement).querySelector('#extra-field-' + jsonData[j].id + '-' + i); // extraField?.addEventListener('focusout', () => { // ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; // }); // extraField?.addEventListener('keyup', async (_e:any) => { // if(extraFieldPosition === 1) { // await this.saveMapping (divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, true) // } // }); } } // // Filter field handlers // const inputFilter = (divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement; // inputFilter.addEventListener('keyup', (e: any) => { // if (e.key == 'Enter') { // //console.log(inputFilter.value); // if (this._SfLoader != null) { // this._SfLoader.innerHTML = '
'; // this._SfLoader.innerHTML += ('
'); // } // setTimeout(() => { // this.renderMappingTable(divElement, jsonData, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, inputFilter.value, statuteColName, extraHintsArr) // this._SfLoader.innerHTML = ''; // }, 1000); // } // }); // More button handlers const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'flex'; const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups); buttonDownloadBackupsNew.addEventListener('click', async () => { const result = await this.fetchGetStoredMapping(colName); for (var i = 0; i < result.data.length; i++) { const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + colName + '_' + i + '.json'); a.click() } (buttonToggleMoreBack as HTMLButtonElement).click(); if (result.data.length === 0) { this.setError("No backups found!") setTimeout(() => { this.clearMessages(); }, 3000); } }); const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'flex'; //console.log('buttonExportMapping', buttonExportMapping); const buttonExportMappingNew = Util.clearListeners(buttonExportMapping); buttonExportMappingNew.addEventListener('click', async () => { // const outerHTML = '

This extract is generated on ' + new Date() + '

' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '

     Mapped compliances

     Un-mapped compliances

' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML; const outerHTML = '

This extract is generated on ' + new Date() + '


     Mapped compliances

     Un-mapped compliances

' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML; const tableHTML = this.MAPPING_HTML.replace(/TABLE_DATA/g, outerHTML); const blob = new Blob([tableHTML], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; }); // Statute filters const arrFilterPlain = (divElement as HTMLDivElement).querySelectorAll('.plain-filter-icon') as NodeListOf; for (var i = 0; i < arrFilterPlain.length; i++) { arrFilterPlain[i].addEventListener('click', (e: any) => { const value = ((e.currentTarget as HTMLSpanElement).nextSibling as SfIElasticText).text; ((divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement).value = value; const event = new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', which: 13, keyCode: 13, }); ((divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement).dispatchEvent(event); //console.log('filter click'); }) } // Expand handlers const arrExpands = (divElement as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf; for (var i = 0; i < arrExpands.length; i++) { arrExpands[i].addEventListener('click', (e: any) => { (divElement as HTMLDivElement).querySelector('#detail-overlay')?.classList.remove('hide'); const id = e.currentTarget.id; const index = id.split("-")[2]; //console.log(id, index); var html = ''; html += '
'; for (var j = 0; j < JSON.parse(jsonData[0].data.cols).length; j++) { html += '
'; html += ('
' + JSON.parse(jsonData[0].data.cols)[j] + '
'); if (JSON.parse(jsonData[0].data.cols)[j] == "state") { //console.log('state value', JSON.parse(jsonData[index].data.data)[j]); } if (Array.isArray(JSON.parse(jsonData[index].data.data)[j])) { html += '
'; if (JSON.parse(jsonData[index].data.data)[j].length === 0) { html += ('-
'); } else { for (var k = 0; k < JSON.parse(jsonData[index].data.data)[j].length; k++) { var val = JSON.parse(jsonData[index].data.data)[j][k]; if (val == '') { val = '-'; } html += (''); } } html += '
'; } else { var val = JSON.parse(jsonData[index].data.data)[j]; if (val == '') { val = '-'; } html += ('
' + '' + '

') } html += '
'; } html += '
'; (divElement as HTMLDivElement).querySelector('#detail-overlay-list')!.innerHTML = html; }) } // Detail close ((divElement as HTMLDivElement).querySelector('.detail-close') as HTMLButtonElement).addEventListener('click', (_e: any) => { (divElement as HTMLDivElement).querySelector('#detail-overlay')?.classList.add('hide'); }); // Checkbox handlers const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf; for (var i = 0; i < arrCheckBoxes.length; i++) { arrCheckBoxes[i].addEventListener('change', async (_e: any) => { //console.log(e.currentTarget, (e.currentTarget as HTMLInputElement).checked); ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; if (extraFieldPosition === 1) { await this.saveMapping(divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, true, mappedStatutes) } }); } (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => { //console.log('cb-length', arrCheckBoxes.length); for (var i = 0; i < arrCheckBoxes.length; i++) { const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement; //console.log('tablerow', i, tableRow); if (tableRow != null) { if (tableRow.style.display != 'none') { //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement)); (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked; } } } ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false; }); // Next, previous, save handlers (this._SfButtonNext as HTMLButtonElement)?.addEventListener('click', async () => { const resultFunction = await fetchFunction(searchString, cursor[cursor.length - 1].next); //console.log(resultFunction); if (resultFunction != null) { const jsonData1 = []; for (var i = 0; i < resultFunction.values.length; i++) { var mapped = false; for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) { if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) { if (mappedArray.data.mappings.mappings[j].selected) { mapped = true; } } } for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) { if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) { if (mappedArray.data.mappings.mappings[j].selected) { mapped = true; } } } jsonData1.push({ id: resultFunction.values[i].id, mapped: mapped, data: resultFunction.values[i].fields, cols: jsonData[0].cols }) } cursor.push({ prev: cursor[cursor.length - 1].next, next: resultFunction.cursor }) this.renderMappingTable(divElement, jsonData1, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, subfilter, statuteColName, extraHintsArr) } }); (this._SfButtonPrev as HTMLButtonElement)?.addEventListener('click', async () => { cursor.pop(); const resultFunction = await fetchFunction(searchString, cursor[cursor.length - 1].prev); //console.log(resultFunction); if (resultFunction != null) { const jsonData1 = []; for (var i = 0; i < resultFunction.values.length; i++) { var mapped = false; for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) { if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) { if (mappedArray.data.mappings.mappings[j].selected) { mapped = true; } } } jsonData1.push({ id: resultFunction.values[i].id, mapped: mapped, data: resultFunction.values[i].fields, cols: jsonData[0].cols }) } //console.log('clicked', jsonData1); this.renderMappingTable(divElement, jsonData1, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, subfilter, statuteColName, extraHintsArr) } }); (this._SfButtonSave as HTMLButtonElement)?.addEventListener('click', async () => { await this.saveMapping(divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, false, mappedStatutes) }); // const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field') as NodeListOf; // var totalFields = 0; // var filledFields = 0; // for(var i = 0; i < arrExtraFields.length; i++) { // const extraField = arrExtraFields[i] as SfIMultitextarea; // if(extraField.parentElement?.parentElement?.parentElement?.style.display != "none" && (extraField.parentElement?.parentElement?.parentElement?.firstChild?.firstChild?.firstChild as HTMLInputElement).checked) { // if(extraField.getFilled()) { // filledFields++; // } // totalFields++; // } // } // (divElement as HTMLDivElement).querySelector("#span-extra-filled")!.innerHTML = "Fields: " + filledFields + "/" + totalFields + " completed"; //console.log('Total fields = ' + totalFields + ', filled fields = ' + filledFields); console.log('totalmapped', mappedCount, this.selectedCbs.length, this.selectedCbs); } getPreviousExtraFields = (i: number, previousExtraFields: any, locationsForThisItem: any, showSearch: boolean) => { var userHtml = ''; if (previousExtraFields != null && previousExtraFields.length === 9 && Object.keys(previousExtraFields[0]).length > 0) { userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += ''; userHtml += '
'; userHtml += 'Reporter'; userHtml += ''; userHtml += 'Approver'; userHtml += ''; userHtml += 'Functionhead'; userHtml += ''; userHtml += 'Auditor'; userHtml += ''; userHtml += 'Viewer'; userHtml += '
'; let strLocationsForThisItem: string = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); let valuesForThisItem: any = (previousExtraFields != null ? (previousExtraFields[3] != null ? previousExtraFields[3] : "") : ""); let strValuesForThisItem: string = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); userHtml += '
'; userHtml += '
'; strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[4] != null ? previousExtraFields[4] : "") : ""); strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); userHtml += '
'; userHtml += '
'; strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[5] != null ? previousExtraFields[5] : "") : ""); strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); userHtml += '
'; userHtml += '
'; strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[6] != null ? previousExtraFields[6] : "") : ""); strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); userHtml += '
'; userHtml += '
'; strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '"'); valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[7] != null ? previousExtraFields[7] : "") : ""); strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '"'); userHtml += '
'; userHtml += '
'; userHtml += ''; } return userHtml; } refreshCalendar = async () => { //console.log('tabs',this.myOnboardingTab,this.TAB_CALENDAR); if (this.myOnboardingTab == this.TAB_CALENDAR) { const calendarJobs = await this.fetchCalendarJobs(); if (calendarJobs.data.status == "0" || calendarJobs.data.status == "1") { setTimeout(async () => { await this.loadOnboardingCalendar(); this.refreshCalendar(); }, 10000); } } } renderNewOnboarding = () => { var html = ''; html += '
'; html += '
'; html += '
Client Sign Off

'; html += '
'; html += '

' html += '
'; html += '

' html += '
' html += '
'; html += '
'; html += '
'; (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = html; } renderOnboardingSignoff = (signoff: any) => { var html = ''; // if(signoff.result == null) { this.renderNewOnboarding(); // } else { html += '
'; html += '
'; html += '
New Sign Off

'; html += '
'; html += '

' html += '
'; html += '

' html += '
' html += '
'; html += '
'; html += '
'; html += '
'; html += '
Sign Offs
'; html += (this.disablesignoff == "yes" ? "" : ''); html += '
'; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; const jsonData = JSON.parse(signoff.result.data.S); for (var i = 0; i < jsonData.length; i++) { var classBg = ""; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; html += ''; html += ''; html += ''; html += ''; //console.log(jsonData[i]); } html += '
'; html += 'Name'; html += ''; html += 'Remarks'; html += ''; html += 'Signature'; html += ''; html += 'Timestamp'; html += '
'; html += jsonData[i].username != null ? jsonData[i].username : ""; html += ''; html += jsonData[i].signofftext; html += ''; html += jsonData[i].signature; html += ''; html += new Date(parseInt(jsonData[i].timestamp)); html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; // } (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = html; (this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('.submit-signoff')?.addEventListener('click', async (_e: any) => { const signofftext = ((this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('#rcm-signoff') as HTMLInputElement).value; const signoffsignature = ((this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('#rcm-signature') as HTMLInputElement).value; await this.fetchUpdateSignOff(signofftext, signoffsignature); this.loadOnboardingSignoff(); }) } getAllPastFiscals = (startDate: Date) => { let retArr = [] let date = new Date() while (date.getTime() > startDate.getTime()) { if (date.getMonth() < 3) { retArr.push(date.getFullYear() - 1) } else { retArr.push(date.getFullYear()) } date.setFullYear(date.getFullYear() - 1) } return retArr; } renderOnboardingGovUsers = (sourceLocationsArray: any, mappedModuleUsers: any, changedIndices: number[] = []) => { console.log('sourceLocationsArray', sourceLocationsArray); console.log('modulesMapping', mappedModuleUsers); if (changedIndices.length == 0) { this.changedOnboardingItemIds = [] } else { for (let changedIndex of changedIndices) { let changedId = sourceLocationsArray[changedIndex].id if (this.changedOnboardingItemIds.indexOf(changedId) < 0) { this.changedOnboardingItemIds.push(changedId) } } } let sourceCols = ["id", "name", "modulename"] let uniqCols = ["users"] var html: string = ''; html += '
'; html += '
'; let tagged = 0 var changed = 0 for (let item of sourceLocationsArray) { let locationModuleKey = item.id + ";" + item.moduleid console.log('locationKey', locationModuleKey, item) if (mappedModuleUsers[locationModuleKey] != null && mappedModuleUsers[locationModuleKey].users != null && mappedModuleUsers[locationModuleKey].users.length > 0) { tagged++; } if (this.changedOnboardingItemIds.indexOf(locationModuleKey) >= 0) { changed++; } } var status = ''; if (tagged < sourceLocationsArray.length) { status = 'pending'; } else { status = 'check_circle'; } html += (`

${status}   ${tagged} Locations mapped out of ${sourceLocationsArray.length}

`); if (changed > 0) { html += ('

pending  ' + changed + ' Items changed

') } html += ('

') html += '
'; // html += ''; html += '
'; html += '
' // html += '
' html += '
' html += '' // console.log('jobs', jobs); html += (''); html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += `
` html += ''; html += ''; html += '' for (let i = 0; i < sourceCols.length; i++) { html += '' } for (let i = 0; i < uniqCols.length; i++) { html += '' } html += ''; html += ''; for (let i = 0; i < sourceLocationsArray.length; i++) { var classBg = ""; let item = sourceLocationsArray[i] let locationModuleKey = item.id + ";" + item.moduleid if (i % 2 === 0) { if (this.changedOnboardingItemIds.length > 0) { let changedId = locationModuleKey if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-light-selected'; } else { classBg = 'td-light'; } } else { classBg = 'td-light'; } } else { if (this.changedOnboardingItemIds.length > 0) { let changedId = locationModuleKey if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-dark-selected'; } else { classBg = 'td-dark'; } } else { classBg = 'td-dark'; } } html += ''; // html += ''; html += '' for (var l = 0; l < sourceCols.length; l++) { html += ''; } // let users = mappedModuleUsers[locationModuleKey] ?? [] // let moduleNames = modules.map((m: any) => { // return m.locationname; // }) html += '' html += ''; //console.log('i=', i); } html += ''; html += '
' html += '
'; html += '
' html += sourceCols[i]; html += '' html += uniqCols[i]; html += '
' html += '
'; html += ''; html += '
'; html += '
'; html += '
'; html += ('' html += '
'; html += '
' html += '' html += ''; html += '
'; // html += '
'; html += '
'; (this._SfOnboardingGovUsersContainer as HTMLDivElement).innerHTML = html; const selectAllCheckbox = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#select-all') as HTMLInputElement selectAllCheckbox.addEventListener('change', (e) => { let selCheckbox = e.target as HTMLInputElement let inputCheckboxes = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf console.log('input checkboxes found', inputCheckboxes.length, selCheckbox.checked) for (let inputCheckbox of inputCheckboxes) { inputCheckbox.checked = selCheckbox.checked; } }) let usersInputs = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf; for (let usersInput of usersInputs) { let index = parseInt(usersInput.id.split('-')[1]); let locationModuleKey = sourceLocationsArray[index].id + ";" + sourceLocationsArray[index].moduleid let preselctedVals = mappedModuleUsers[locationModuleKey]?.users ?? [] usersInput.preselectedValues = JSON.stringify(preselctedVals); usersInput.loadMode(); usersInput.addEventListener('valueChanged', (e: any) => { let input = e.currentTarget as SfIForm; let index = parseInt(input.id.split('-')[1]); console.log('edit button clicked', index) let tempModulesUsers = mappedModuleUsers let locationModuleKey = sourceLocationsArray[index].id + ";" + sourceLocationsArray[index].moduleid tempModulesUsers[locationModuleKey] = { moduleid: sourceLocationsArray[index].moduleid, modulename: sourceLocationsArray[index].modulename, users: input.selectedValues() } let indices = [index] let inputCheckboxes = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf for (let inputCheckbox of inputCheckboxes) { let inputId = inputCheckbox.id ?? "" let inputIndex = inputId.split('locations-')[1] if (inputCheckbox.checked && inputIndex != null && sourceLocationsArray[parseInt(inputIndex)] != null) { let locationModuleKey = sourceLocationsArray[parseInt(inputIndex)].id + ";" + sourceLocationsArray[parseInt(inputIndex)].moduleid tempModulesUsers[locationModuleKey] = { moduleid: sourceLocationsArray[parseInt(inputIndex)].moduleid, modulename: sourceLocationsArray[parseInt(inputIndex)].modulename, users: input.selectedValues() } indices.push(parseInt(inputIndex)) } } console.log('changed indices', indices, tempModulesUsers) this.renderOnboardingGovUsers(sourceLocationsArray, tempModulesUsers, indices) }) } const buttonApply = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; buttonApply.addEventListener('click', () => { this.renderOnboardingGovUsers(sourceLocationsArray, mappedModuleUsers) }) const buttonSave = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.addEventListener('click', async () => { console.log('saving gov location', mappedModuleUsers); let response = await this.uploadMappedGovUsers(mappedModuleUsers) console.log('gov users save response', response); this.loadOnboardingMappedGovUsers() }) const buttonToggleMoreBack = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonExportMappingCSV = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'flex'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'flex'; const buttonLoadLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'flex'; const buttonSaveLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'flex'; const buttonSave = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.style.display = 'flex'; const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV); buttonExportMappingCSVNew?.addEventListener('click', async () => { let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj let locationModuleKey = tempCsvObj.id + ";" + tempCsvObj.moduleid; tempCsvObj.users = mappedModuleUsers[locationModuleKey] ?? []; csvArray[i] = tempCsvObj } console.log('csv array', csvArray) let csvData = Util.convertToCSV(csvArray); // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings); console.log('csvData', csvData); const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_gov_users_' + new Date().getTime() + '.csv'); a.click() }) const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal); buttonLoadLocalNew?.addEventListener('click', async () => { console.log('load-local'); ((this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); }); const fileInput = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement; fileInput.value = ''; const fileInputNew = Util.clearListeners(fileInput); fileInputNew.addEventListener('change', (e: any) => { var frCsv = new FileReader(); frCsv.onload = () => { console.log('taggingarray onload called'); console.log('csv result', frCsv.result); const tempArr = Util.parseCsv(frCsv.result + ""); console.log('csv data', tempArr) let changeCount = 0; let tempModulesList: any = {} for (let obj of tempArr) { let locationModuleKey = obj.id + ";" + obj.moduleid; if (JSON.stringify(mappedModuleUsers[locationModuleKey]) != JSON.stringify(obj.users)) { if (mappedModuleUsers[locationModuleKey] == null && (obj.users == null || obj.users.length == 0)) { console.log('not adding to modules change', locationModuleKey, mappedModuleUsers[locationModuleKey], obj.users) } else { console.log('adding to modules change', locationModuleKey, mappedModuleUsers[locationModuleKey], obj.users) this.changedOnboardingItemIds.push(locationModuleKey) changeCount++ } } tempModulesList[locationModuleKey] = { moduleid: obj.moduleid, modulename: obj.modulename, users: obj.users } } this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [ () => { this.clearMessages(); this.changedOnboardingItemIds = []; (buttonToggleMoreBack as HTMLButtonElement).click(); }, () => { this.clearMessages(); this.renderOnboardingGovUsers(sourceLocationsArray, tempModulesList); } ]) // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}} // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}} } if (e.target.files[0].name.toLowerCase().indexOf("users".toLowerCase()) >= 0) { frCsv.readAsText(e.target.files[0]); } }) const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal); buttonSaveLocalNew?.addEventListener('click', async () => { console.log('save-local'); let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj let locationModuleKey = tempCsvObj.id + ";" + tempCsvObj.moduleid; tempCsvObj.users = mappedModuleUsers[locationModuleKey] ?? []; csvArray[i] = tempCsvObj } console.log('csv array', csvArray) const blob = new Blob([JSON.stringify(csvArray)], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_gov_users_' + new Date().toLocaleString() + '.txt'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; const buttonExportMappingCSV = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'none'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'none'; const buttonLoadLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'none'; const buttonSaveLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'none'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'none'; }); this.changedOnboardingItemIds = []; } renderOnboardingGovLocations = (sourceLocationsArray: any, modulesMapping: any, changedIndices: number[] = [], changedValue: any = null) => { console.log('sourceLocationsArray', sourceLocationsArray); console.log('modulesMapping', modulesMapping); if (changedIndices.length == 0) { this.changedOnboardingItemIds = [] } else { for (let changedIndex of changedIndices) { let changedId = sourceLocationsArray[changedIndex].id if (this.changedOnboardingItemIds.indexOf(changedId) < 0) { this.changedOnboardingItemIds.push(changedId) } modulesMapping[changedId] = changedValue } } let sourceCols = ["id", "name"] let uniqCols = ["modules"] var html: string = ''; html += '
'; html += '
'; let tagged = 0 var changed = 0 for (let item of sourceLocationsArray) { let locationKey = item.id console.log('locationKey', locationKey, item) if (modulesMapping[locationKey] != null && modulesMapping[locationKey].length > 0) { tagged++; } if (this.changedOnboardingItemIds.indexOf(locationKey) >= 0) { changed++; } } var status = ''; if (tagged < sourceLocationsArray.length) { status = 'pending'; } else { status = 'check_circle'; } html += (`

${status}   ${tagged} Locations mapped out of ${sourceLocationsArray.length}

`); if (changed > 0) { html += ('

pending  ' + changed + ' Items changed

') } html += ('

') html += '
'; // html += ''; html += '
'; html += '
' // html += '
' html += '
' html += '' // console.log('jobs', jobs); html += (''); html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += `
` html += ''; html += ''; html += '' for (let i = 0; i < sourceCols.length; i++) { html += '' } for (let i = 0; i < uniqCols.length; i++) { html += '' } html += ''; html += ''; for (let i = 0; i < sourceLocationsArray.length; i++) { var classBg = ""; let item = sourceLocationsArray[i] let locationid = item.id if (i % 2 === 0) { if (this.changedOnboardingItemIds.length > 0) { let changedId = locationid if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-light-selected'; } else { classBg = 'td-light'; } } else { classBg = 'td-light'; } } else { if (this.changedOnboardingItemIds.length > 0) { let changedId = locationid if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-dark-selected'; } else { classBg = 'td-dark'; } } else { classBg = 'td-dark'; } } html += ''; // html += ''; html += '' for (var l = 0; l < sourceCols.length; l++) { html += ''; } let modules = modulesMapping[locationid] ?? [] // let moduleNames = modules.map((m: any) => { // return m.locationname; // }) html += '' html += ''; //console.log('i=', i); } html += ''; html += '
' html += '
'; html += '
' html += sourceCols[i]; html += '' html += uniqCols[i]; html += '
' html += '
'; html += ''; html += '
'; html += '
'; html += '
'; html += ('' html += '
'; html += '
' html += `
${modules.map((m: any) => `
`).join('')}` html += ''; html += '
'; html += '
'; // html += '
'; html += '
'; (this._SfOnboardingGovLocationsContainer as HTMLDivElement).innerHTML = html; const selectAllCheckbox = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#select-all') as HTMLInputElement selectAllCheckbox.addEventListener('change', (e) => { let selCheckbox = e.target as HTMLInputElement let inputCheckboxes = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf console.log('input checkboxes found', inputCheckboxes.length, selCheckbox.checked) for (let inputCheckbox of inputCheckboxes) { inputCheckbox.checked = selCheckbox.checked; } }) let editButtons = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.button-edit-form') as NodeListOf console.log("edit buttons found", editButtons.length) for (let editButton of editButtons) { editButton.addEventListener('click', (e) => { let targetElement = e.target as HTMLButtonElement let targetId = targetElement.id ?? "" let index = targetId.split('button-edit-form-')[1] console.log('edit button clicked', index) let indices: number[] = [parseInt(index)] let inputCheckboxes = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf for (let inputCheckbox of inputCheckboxes) { let inputId = inputCheckbox.id ?? "" let inputIndex = inputId.split('locations-')[1] if (inputCheckbox.checked && inputIndex != null) { if (indices.indexOf(parseInt(inputIndex)) < 0) { indices.push(parseInt(inputIndex)) } } } this.populateMultipleSelectModal(indices, 'Modules', modulesMapping[sourceLocationsArray[index].id] ?? [], (indices: number[], value: any) => { this.renderOnboardingGovLocations(sourceLocationsArray, modulesMapping, indices, value) }) }) } const buttonApply = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; buttonApply.addEventListener('click', () => { this.renderOnboardingGovLocations(sourceLocationsArray, modulesMapping) }) const buttonSave = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.addEventListener('click', async () => { console.log('saving gov location', modulesMapping); let response = await this.uploadMappedGovLocations(modulesMapping) console.log('gov locations save response', response); this.loadOnboardingMappedGovLocations() }) const buttonToggleMoreBack = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonExportMappingCSV = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'flex'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'flex'; const buttonLoadLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'flex'; const buttonSaveLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'flex'; const buttonSave = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.style.display = 'flex'; const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV); buttonExportMappingCSVNew?.addEventListener('click', async () => { let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj let locationKey = tempCsvObj.id; tempCsvObj.modules = modulesMapping[locationKey] ?? []; csvArray[i] = tempCsvObj } console.log('csv array', csvArray) let csvData = Util.convertToCSV(csvArray); // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings); console.log('csvData', csvData); const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_gov_locations_' + new Date().getTime() + '.csv'); a.click() }) const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal); buttonLoadLocalNew?.addEventListener('click', async () => { console.log('load-local'); ((this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); }); const fileInput = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement; fileInput.value = ''; const fileInputNew = Util.clearListeners(fileInput); fileInputNew.addEventListener('change', (e: any) => { var frCsv = new FileReader(); frCsv.onload = () => { console.log('taggingarray onload called'); console.log('csv result', frCsv.result); const tempArr = Util.parseCsv(frCsv.result + ""); console.log('csv data', tempArr) let changeCount = 0; let tempModulesList: any = {} for (let obj of tempArr) { let locationKey = obj.id if (JSON.stringify(modulesMapping[locationKey]) != JSON.stringify(obj.modules)) { if (modulesMapping[locationKey] == null && (obj.modules == null || obj.modules.length == 0)) { console.log('not adding to modules change', locationKey, modulesMapping[locationKey], obj.modules) } else { console.log('adding to modules change', locationKey, modulesMapping[locationKey], obj.modules) this.changedOnboardingItemIds.push(locationKey) changeCount++ } } tempModulesList[locationKey] = obj.modules } this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [ () => { this.clearMessages(); this.changedOnboardingItemIds = []; (buttonToggleMoreBack as HTMLButtonElement).click(); }, () => { this.clearMessages(); this.renderOnboardingGovLocations(sourceLocationsArray, tempModulesList); } ]) // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}} // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}} } if (e.target.files[0].name.toLowerCase().indexOf("locations".toLowerCase()) >= 0) { frCsv.readAsText(e.target.files[0]); } }) const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal); buttonSaveLocalNew?.addEventListener('click', async () => { console.log('save-local'); const blob = new Blob([JSON.stringify(sourceLocationsArray)], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_suspense_' + new Date().toLocaleString() + '.txt'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; const buttonExportMappingCSV = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'none'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'none'; const buttonLoadLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'none'; const buttonSaveLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'none'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'none'; }); this.changedOnboardingItemIds = []; } populateMultipleSelectModal = (indices: number[], label: string, value: any, saveCallback: Function) => { if (value.length == 0) { value.push('') } let formHtml = `
${value.map((_: any, i: number) => `
`).join('')}
` console.log("rendering sf-i-muliple-subselect", indices) let selectContainer = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#sf-i-form-container') as HTMLDivElement selectContainer.innerHTML = formHtml let selectModalContainer = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#sf-i-form-modal-container') as HTMLDivElement selectModalContainer.style.display = 'block' let selectCloseButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#button-close-form') as HTMLButtonElement selectCloseButton.addEventListener('click', () => { selectModalContainer.style.display = 'none' }) let selectAddButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#' + 'add-' + indices[0]) as HTMLButtonElement selectAddButton.addEventListener('click', () => { let elementValue: any = [] if (value != null && value != '') { elementValue = value } if (elementValue.length == 0) { elementValue.push('') } console.log('add button clicked', elementValue); elementValue.push('') this.populateMultipleSelectModal(indices, label, elementValue, saveCallback); }) let selectSaveButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#button-save-form') as HTMLButtonElement let selectElements = selectContainer.querySelectorAll('sf-i-select') as NodeListOf console.log('populateMultipleSelectModal value', value) for (let [i, selectElement] of selectElements.entries()) { if (value[i] != null && value[i] != '') { console.log('value found', value[i]) let valObj = value[i] selectElement.selectedId = valObj.id selectElement.loadMode(); } selectElement.addEventListener('valueChanged', (e) => { let target = e.target as SfISelect let selectId = target.id let selectIndex = selectId.split('input-select-')[1] console.log('selected value changed', selectId, target.selectedValues(), target.selectedTexts()) let elementValue: any = [] if (value != null && value != '') { elementValue = value } elementValue[selectIndex] = { name: target.selectedTexts()[0], id: target.selectedValues()[0] } if (JSON.stringify(value) !== JSON.stringify(elementValue)) { this.populateMultipleSelectModal(indices, label, elementValue, saveCallback); } }) } let selectDeleteButtons = selectContainer.querySelectorAll('.delete-subselect-button') as NodeListOf for (let deleteButton of selectDeleteButtons) { deleteButton.addEventListener('click', () => { let targetId = deleteButton.id let index = parseInt(targetId.split('-').slice(-1)[0]) console.log('delete button clicked', targetId, index) let elementValue: any = [] if (value != null && value != '') { elementValue = value } elementValue.splice(index, 1) value = elementValue this.populateMultipleSelectModal(indices, label, elementValue, saveCallback); }) } selectSaveButton.addEventListener('click', async () => { let selectElements = selectContainer.querySelectorAll('sf-i-select') as NodeListOf let valArr = [] for (let selectElement of selectElements) { if (selectElement.selectedValues()[0] == null || selectElement.selectedValues()[0] == '') { continue; } let valObj: any = { name: selectElement.selectedTexts()[0], id: selectElement.selectedValues()[0] } valArr.push(valObj) } console.log('Values Selected', valArr) saveCallback(indices, valArr); selectModalContainer.style.display = 'none' }) /* if (childElement.dependencies != null && childElement.dependencies.length > 0) { this.updateShortlistedSearchPhrases(childElement.id); } */ } renderOnboardingSuspense = (sourceArray: any, suspenseList: any, year: string) => { console.log('sourceList', sourceArray); console.log('suspenseList', suspenseList, Object.keys(suspenseList).length); let sourceCols = ["shortid", "obligationtitle", "obligationtype"] let uniqCols = ["id", "entityname", "locationname"] let colName = 'suspense' var html: string = ''; html += '
'; html += '
'; var status = ''; status = 'check_circle'; let tagged = 0 var changed = 0 let tempSourceArray = sourceArray console.log('suspensekey length', tempSourceArray.data.mappings.mappings.length) for (let [itemIndex, item] of tempSourceArray.data.mappings.mappings.entries()) { let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id if (item.id == "de6ecf68-673d-41ef-9b13-4d2042910f16") { console.log('suspensekey', suspenseKey, suspenseList[suspenseKey], item) } if (suspenseList[suspenseKey] != null && suspenseList[suspenseKey] != false) { tagged++; } tempSourceArray.data.mappings.mappings[itemIndex].suspense = suspenseList[suspenseKey] != null if (this.changedOnboardingItemIds.indexOf(suspenseKey) >= 0) { changed++; } } let pastFiscals = [parseInt(this.getCurrentYearGeneric())] if (this.contractStartDate != null) { pastFiscals = this.getAllPastFiscals(new Date(this.contractStartDate)); } html += (`

${status}   ${tagged} in Suspense List out of ${sourceArray.data.mappings.mappings.length}

Year
`); if (changed > 0) { html += ('

pending  ' + changed + ' Items changed

') } html += ('

') html += '
'; // html += ''; html += '
'; html += '
' // html += '
' html += '
' html += '' // console.log('jobs', jobs); html += (''); html += '
'; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '

' html += '
' html += '
'; html += '
'; // html += '
'; html += ''; html += ''; // html += '' html += '' for (let i = 0; i < uniqCols.length; i++) { html += '' } for (let i = 0; i < sourceCols.length; i++) { html += '' } html += ''; html += ''; // console.log('changedIds', this.changedOnboardingItemIds); for (let i = 0; i < sourceArray.data.mappings.mappings.length; i++) { var classBg = ""; let item = sourceArray.data.mappings.mappings[i] let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id if (i % 2 === 0) { if (this.changedOnboardingItemIds.length > 0) { let changedId = suspenseKey if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-light-selected'; } else { classBg = 'td-light'; } } else { classBg = 'td-light'; } } else { if (this.changedOnboardingItemIds.length > 0) { let changedId = item.entityid + ';' + item.locationid + ';' + item.id if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) { classBg = 'td-dark-selected'; } else { classBg = 'td-dark'; } } else { classBg = 'td-dark'; } } html += ''; // html += ''; html += '' for (var l = 0; l < uniqCols.length; l++) { // console.log('uniqcolval', uniqCols[l], sourceArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i][uniqCols[l]]); html += '' } for (l = 0; l < sourceCols.length; l++) { for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) { if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) { if (sourceArray.data.mappings.mappings[i].data != null) { html += ''; } } } } html += ''; //console.log('i=', i); } html += ''; html += '
' // html += '
'; // html += '
' html += colName; html += '' html += uniqCols[i]; html += '' html += sourceCols[i]; html += '
' html += '
'; html += ''; html += '
'; html += '
' html += '
'; html += ''; html += '
'; html += '
'; html += '
'; //console.log('isArray', sourceCols[l], Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])); if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) { for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) { html += (''); } } else { html += ('') } html += '
'; html += '
'; // html += '
'; html += '
'; (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = html; const inputYear = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#select-year') as HTMLSelectElement; inputYear.addEventListener('change', (e: any) => { const selectedYear = e.currentTarget.value; this.loadOnboardingSuspense(selectedYear); }) const buttonApply = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; buttonApply.addEventListener('click', () => { let inputSuspenseCheckboxes = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelectorAll('.suspense-input') as NodeListOf; let tempSuspenseList: any = {} for (let inputSuspenseCheckbox of inputSuspenseCheckboxes) { let index = inputSuspenseCheckbox.id.split("-")[1] if (inputSuspenseCheckbox.checked) { let item = sourceArray.data.mappings.mappings[index] let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id tempSuspenseList[suspenseKey] = true } } this.renderOnboardingSuspense(sourceArray, tempSuspenseList, year) }) const buttonSave = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.addEventListener('click', async () => { console.log('saving suspense', suspenseList, Object.keys(suspenseList).length); let response = await this.uploadMappedSuspense(suspenseList, year) console.log('suspense save response', response); this.loadOnboardingSuspense(year) }) const buttonToggleMoreBack = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement; const buttonToggleMore = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement; buttonToggleMore.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMoreBack.classList.remove('hide'); const buttonExportMappingCSV = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'flex'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'flex'; const buttonLoadLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'flex'; const buttonSaveLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'flex'; const buttonSave = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; buttonSave.style.display = 'flex'; const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV); buttonExportMappingCSVNew?.addEventListener('click', async () => { let csvArray = JSON.parse(JSON.stringify(sourceArray.data.mappings.mappings)) for (let [i, obj] of csvArray.entries()) { let tempCsvObj = obj if (obj['cols'] != null && obj['data'] != null) { let dataArr = JSON.parse(obj['data']) let colsArr = JSON.parse(obj['cols']) for (let [j, colKey] of colsArr.entries()) { tempCsvObj['cols_' + colKey] = dataArr[j] } } let suspenseKey = tempCsvObj.entityid + ';' + tempCsvObj.locationid + ';' + tempCsvObj.id; tempCsvObj.suspense = (suspenseList[suspenseKey] != null && suspenseList[suspenseKey] != false) ? true : false; csvArray[i] = tempCsvObj } console.log('csv array', csvArray) let csvData = Util.convertToCSV(csvArray); // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings); console.log('csvData', csvData); const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_suspense_' + new Date().getTime() + '.csv'); a.click() }) const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal); buttonLoadLocalNew?.addEventListener('click', async () => { console.log('load-local'); ((this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click(); }); const fileInput = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement; fileInput.value = ''; const fileInputNew = Util.clearListeners(fileInput); fileInputNew.addEventListener('change', (e: any) => { var frCsv = new FileReader(); frCsv.onload = () => { console.log('taggingarray onload called'); console.log('csv result', frCsv.result); const tempArr = Util.parseCsv(frCsv.result + ""); console.log('csv data', tempArr) let changeCount = 0; let tempSuspenseList: any = {} for (let obj of tempArr) { let suspenseKey = obj.entityid + ';' + obj.locationid + ';' + obj.id if ((suspenseList[suspenseKey] == null && obj.suspense == true) || (suspenseList[suspenseKey] != null && obj.suspense == false)) { console.log('adding to suspense change', suspenseKey, suspenseList[suspenseKey], obj.suspense) this.changedOnboardingItemIds.push(suspenseKey) changeCount++ } tempSuspenseList[suspenseKey] = obj.suspense } this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [ () => { this.clearMessages(); this.changedOnboardingItemIds = []; (buttonToggleMoreBack as HTMLButtonElement).click(); }, () => { this.clearMessages(); this.renderOnboardingSuspense(sourceArray, tempSuspenseList, year); } ]) // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}} // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}} } if (e.target.files[0].name.toLowerCase().indexOf("suspense".toLowerCase()) >= 0) { frCsv.readAsText(e.target.files[0]); } }) const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal); buttonSaveLocalNew?.addEventListener('click', async () => { console.log('save-local'); const blob = new Blob([JSON.stringify(sourceArray)], { type: 'text/plain' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'mapping_suspense_' + new Date().toLocaleString() + '.txt'); a.click() }); }); buttonToggleMoreBack.addEventListener('click', async (ev: any) => { ev.target.classList.add('hide'); buttonToggleMore.classList.remove('hide'); const buttonDownloadBackups = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement; buttonDownloadBackups.style.display = 'none'; const buttonExportMapping = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement; buttonExportMapping.style.display = 'none'; const buttonExportMappingCSV = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement; buttonExportMappingCSV.style.display = 'none'; // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement; // buttonApply.style.display = 'none'; const buttonLoadLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement; buttonLoadLocal.style.display = 'none'; const buttonSaveLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement; buttonSaveLocal.style.display = 'none'; // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement; // buttonSave.style.display = 'none'; }); this.changedOnboardingItemIds = []; } renderOnboardingSuspenseOld = (_suspenseList: any) => { //console.log('calendarjobs', calendarJobs); var html = ''; html += '
'; html += '
'; if (Object.keys(_suspenseList).length === 0) { html += '
No Suspense Items
'; } else { html += ''; let tableBodyHtml = '' for (var j = 0; j < Object.keys(_suspenseList).length; j++) { let uniqueKey = Object.keys(_suspenseList)[j]; console.log('uniqueKey', uniqueKey); let eventid = uniqueKey.split(';')[2]; let suspenseObj = _suspenseList[uniqueKey]; console.log('suspenseObj', suspenseObj); tableBodyHtml += ''; tableBodyHtml += (''); tableBodyHtml += (''); tableBodyHtml += (''); tableBodyHtml += (''); tableBodyHtml += (''); tableBodyHtml += (''); let reporters = "" if (suspenseObj.reporters != null && suspenseObj.reporters.length > 0 && Array.isArray(suspenseObj.reporters)) { for (let reporter of suspenseObj.reporters) { reporters += reporter.split(';')[0] if (suspenseObj.reporters.indexOf(reporter) < suspenseObj.reporters.length - 1) { reporters += ', ' } } } tableBodyHtml += (''); let approvers = "" if (suspenseObj.approvers != null && suspenseObj.approvers.length > 0 && Array.isArray(suspenseObj.approvers)) { for (let approver of suspenseObj.approvers) { approvers += approver.split(';')[0] if (suspenseObj.approvers.indexOf(approver) < suspenseObj.approvers.length - 1) { approvers += ', ' } } } tableBodyHtml += (''); let functionheads = "" if (suspenseObj.functionheads != null && suspenseObj.functionheads.length > 0 && Array.isArray(suspenseObj.functionheads)) { for (let functionhead of suspenseObj.functionheads) { functionheads += functionhead.split(';')[0] if (suspenseObj.functionheads.indexOf(functionhead) < suspenseObj.functionheads.length - 1) { functionheads += ', ' } } } tableBodyHtml += (''); tableBodyHtml += (''); tableBodyHtml += ''; } html += ''; html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += ''; html += tableBodyHtml; html += '
Complaince Id
Obligation Title
Obligation
Entity
Location
Reporter
Approver
Functionhead
Message
'; } html += '
'; html += '
'; (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = html; const arrButtonsDone = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelectorAll('.button-icon-suspense-done') as NodeListOf; for (var i = 0; i < arrButtonsDone.length; i++) { arrButtonsDone[i].addEventListener('click', async (e: any) => { const id = e.currentTarget.id; const index = id.split("-")[4]; await this.deleteFromSuspense(Object.keys(_suspenseList)[index], this.getCurrentYearGeneric()); await this.loadOnboardingSuspense(); }); } } renderOnboardingCalendar = (_calendarJobs: any) => { //console.log('calendarjobs', calendarJobs); var html = ''; html += '
'; // html += '
'; // html += '

Calendar

'; // html += '
'; // if(calendarJobs.data != null) { // html += '
'; // html += '
'; // html += '
Job Status
'; // html += '
' + (calendarJobs.data.status == "0" ? "schedule Initialized" : calendarJobs.data.status == "1" ? "pending In-Progress" : "check_circle Complete" ) + '
'; // html += '
'; // html += '
'; // html += '
Last Updated
'; // html += '
' + new Date(calendarJobs.data.lastupdated).toLocaleString() + '
'; // html += '
'; // html += '
'; // } html += '
'; html += '' html += ''; html += '
'; html += '
'; (this._SfOnboardingCalendarContainer as HTMLDivElement).innerHTML = html; (this._SfOnboardingCalendarContainer as HTMLDivElement).querySelector('.button-submit')?.addEventListener('click', async () => { const year = ((this._SfOnboardingCalendarContainer as HTMLDivElement).querySelector('#select-year') as HTMLSelectElement).value; //console.log(year); await this.fetchGetMappedCalendar(year); // const usermap = await this.fetchGetMappedCalendar(year); this.setSuccess('Calendar Job scheduled. Please check back after a few minutes.') setTimeout(() => { this.clearMessages() }, 5000) // if(usermap == null || usermap.usermap == null) { // this.setError(usermap.error); // setTimeout(() => { // this.clearMessages() // }, 10000); // } else { // await this.fetchUpdateUsermap(usermap.usermap); // } }); //this.refreshCalendar(); } renderOnboardingTriggers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedTriggers: any) => { this.renderTaggingTableNew((this._SfOnboardingTriggersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedTriggers, ["shortid", "obligationtitle", "obligationtype"], this.uploadTriggersMapping, this.loadOnboardingTriggers, "triggers", ["id"], '', "", ["triggers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingInternalControls = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedInternalControls: any) => { this.renderTaggingTableNew((this._SfOnboardingInternalControlsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedInternalControls, ["shortid", "obligationtitle", "obligationtype"], this.uploadInternalControlsMapping, this.loadOnboardingInternalControls, "internalcontrols", ["id", "entityname", "locationname"], '', "", ["internalcontrols"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingReportedLocations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedReportedLocations: any) => { this.renderTaggingTableNew((this._SfOnboardingReportedLocationsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedReportedLocations, ["shortid", "obligationtitle", "obligationtype"], this.uploadReportedLocationsMapping, this.loadOnboardingReportedLocations, "reportedlocations", ["id", "entityname", "locationname"], '', "", ["reportedlocations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingActivations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedActivations: any) => { this.renderTaggingTableNew((this._SfOnboardingActivationListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedActivations, ["shortid", "obligationtitle", "obligationtype"], this.uploadActivationsMapping, this.loadOnboardingActivations, "activations", ["id", "entityname", "locationname"], '', "", ["activations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingInvalidations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedInvalidations: any) => { this.renderTaggingTableNew((this._SfOnboardingInvalidationListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedInvalidations, ["shortid", "obligationtitle", "obligationtype"], this.uploadInvalidationsMapping, this.loadOnboardingInvalidations, "invalidations", ["id", "entityname", "locationname"], '', "", ["invalidations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingAlertSchedules = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedAlertSchedules: any) => { this.renderTaggingTableNew((this._SfOnboardingAlertSchedulesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedAlertSchedules, ["shortid", "obligationtitle", "obligationtype"], this.uploadAlertSchedulesMapping, this.loadOnboardingAlertSchedules, "alertschedules", ["id", "entityname", "locationname"], '', "", ["alertschedules"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingExtensions = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedExtensions: any) => { this.renderTaggingTableNew((this._SfOnboardingExtensionsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedExtensions, ["shortid", "obligationtitle", "obligationtype"], this.uploadExtensionsMapping, this.loadOnboardingExtensions, "extensions", ["id", "entityname", "locationname"], '', "", ["extensions"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingDuedates = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedDuedates: any) => { this.renderTaggingTableNew((this._SfOnboardingDuedatesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedDuedates, ["shortid", "obligationtitle", "obligationtype"], this.uploadDuedatesMapping, this.loadOnboardingDuedates, "duedates", ["id", "entityname", "locationname"], '', "", ["duedates"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingReporters = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedReporters: any) => { this.renderTaggingTableNew((this._SfOnboardingReportersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedReporters, ["shortid", "obligationtitle", "obligationtype"], this.uploadReportersMapping, this.loadOnboardingReporters, "reporters", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["reporters"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", ""); } renderOnboardingApprovers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedApprovers: any) => { this.renderTaggingTableNew((this._SfOnboardingApproversListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedApprovers, ["shortid", "obligationtitle", "obligationtype"], this.uploadApproversMapping, this.loadOnboardingApprovers, "approvers", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["approvers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", ""); } renderOnboardingFunctionHeads = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedFunctionHeads: any) => { this.renderTaggingTableNew((this._SfOnboardingFunctionHeadsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedFunctionHeads, ["shortid", "obligationtitle", "obligationtype"], this.uploadFunctionHeadsMapping, this.loadOnboardingFunctionHeads, "functionheads", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["functionheads"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", ""); } renderOnboardingMakerCheckers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedMakerCheckers: any) => { this.renderTaggingTableNew((this._SfOnboardingMakerCheckersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedMakerCheckers, ["shortid", "obligationtitle", "obligationtype"], this.uploadMakerCheckersMapping, this.loadOnboardingMakerCheckers, "makercheckers", ["id", "entityname", "locationname"], this.apiIdTags, "&MakerChecker", ["makercheckers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingDocs = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedDocs: any) => { this.renderTaggingTableNew((this._SfOnboardingDocsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedDocs, ["shortid", "obligationtitle", "obligationtype"], this.uploadDocsMapping, this.loadOnboardingDocs, "docs", ["id", "entityname", "locationname"], this.apiIdTags, "&MakerChecker", ["docs"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingAuditors = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedAuditors: any) => { this.renderTaggingTableNew((this._SfOnboardingAuditorsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedAuditors, ["shortid", "obligationtitle", "obligationtype"], this.uploadAuditorsMapping, this.loadOnboardingAuditors, "auditors", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["auditors"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", ""); } renderOnboardingViewers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedViewers: any) => { this.renderTaggingTableNew((this._SfOnboardingViewersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedViewers, ["shortid", "obligationtitle", "obligationtype"], this.uploadViewersMapping, this.loadOnboardingViewers, "viewers", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["viewers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", ""); } renderOnboardingTags = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedTags: any) => { this.renderTaggingTableNew((this._SfOnboardingTagsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedTags, ["shortid", "obligationtitle", "obligationtype"], this.uploadTagsMapping, this.loadOnboardingTags, "tags", ["id", "entityname", "locationname"], this.apiIdTags, "&Tag", ["tags"], ["id", "countryid", "entityid", "locationid"], "tagtype", [], null, "", ""); } renderOnboardingFunctions = (selectedStatutes: any, mappedCompliances: any, mappedLocations: any, mappedFunctions: any) => { this.renderTaggingTableNew((this._SfOnboardingFunctionsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedLocations, mappedFunctions, ["shortid", "obligationtitle", "obligationtype"], this.uploadFunctionsMapping, this.loadOnboardingFunctions, "functions", ["id", "entityname", "locationname"], this.apiIdTags, "&Function", ["functions"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", ""); } renderOnboardingLocations = (selectedStatutes: any, mappedCompliances: any, mappedEntities: any, mappedLocations: any) => { this.renderTaggingTableNew((this._SfOnboardingLocationsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedEntities, mappedLocations, ["shortid", "applicability", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute", "reference", "activations", "invalidations"], this.uploadLocationsMapping, this.loadOnboardingLocations, "locations", ["id", "entityname"], this.apiIdTags, "&Location", ["locationname", "locationid"], ["id", "countryid", "entityid"], null, [], null, "", ""); } renderOnboardingStatutesDropdownMapping = (container: HTMLDivElement, mappedStatutes: any, selectedStatutes: any, fetchtaggingfunction: Function, rendermappingfunction: Function) => { console.log('rendering dropdown', mappedStatutes.length); var html = ''; html += '
'; html += '
'; html += ''; html += ''; html += '
'; html += '
'; html += '
'; html += '
'; console.log('attaching html', html); container.innerHTML = html; let multiselectStatute = container.querySelector('#statute-select') as SfMultiselectSearch; multiselectStatute.listelements = mappedStatutes; let selectedStatutesObj: any = {} for (let statuteObj of selectedStatutes) { selectedStatutesObj[statuteObj.id] = true } multiselectStatute.listselection = selectedStatutesObj; multiselectStatute.loadMode(); multiselectStatute.addEventListener('valueChanged', async (e: any) => { let multiselect = e.currentTarget as SfMultiselectSearch; console.log('selected statutes', multiselect.selectedValuesNames()); if (Object.keys(multiselect.selectedValuesNames()).length == 0) { return; } let selectedStatutes = []; const regex = /^\[.*?\] - /; for (let statuteid of Object.keys(multiselect.selectedValuesNames())) { selectedStatutes.push({ id: statuteid, selected: true, statutename: multiselect.selectedValuesNames()[statuteid].name.replace(regex, '') }); } let mappedCompliances = await fetchtaggingfunction(Object.keys(multiselect.selectedValuesNames())); rendermappingfunction({ data: { mappings: { mappings: selectedStatutes } } }, mappedCompliances); }) } renderOnboardingStatutesDropdownTagging = (container: HTMLDivElement, listcontainerid: string, mappedStatutes: any, selectedStatutes: any, fetchcompliancesfunction: Function, fetchsourcemapping: Function, fetchtaggingfunction: Function, rendertaggingfunction: Function) => { console.log('rendering dropdown', mappedStatutes.length); var html = ''; html += '
'; html += '' html += '
' html += '
' html += '
'; html += '
'; html += ''; html += ''; html += '
'; html += '
'; html += '
'; html += '
'; console.log('attaching html', html); container.innerHTML = html; let multiselectStatute = container.querySelector('#statute-select') as SfMultiselectSearch; multiselectStatute.listelements = mappedStatutes; let selectedStatutesObj: any = {} for (let statuteObj of selectedStatutes) { selectedStatutesObj[statuteObj.id] = true } multiselectStatute.listselection = selectedStatutesObj; multiselectStatute.loadMode(); multiselectStatute.addEventListener('valueChanged', async (e: any) => { let multiselect = e.currentTarget as SfMultiselectSearch; console.log('selected statutes', multiselect.selectedValuesNames()); if (Object.keys(multiselect.selectedValuesNames()).length == 0) { return; } let selectedStatutes = []; const regex = /^\[.*?\] - /; for (let statuteid of Object.keys(multiselect.selectedValuesNames())) { selectedStatutes.push({ id: statuteid, selected: true, statutename: multiselect.selectedValuesNames()[statuteid].name.replace(regex, '') }); } let sourceMappingArray = await fetchsourcemapping(Object.keys(multiselect.selectedValuesNames())); let mappingArray = await fetchtaggingfunction(Object.keys(multiselect.selectedValuesNames())); let mappedCompliances = await fetchcompliancesfunction(Object.keys(multiselect.selectedValuesNames())); let mappedCompliancesArr: any = { data: { mappings: {} } }; console.log('mapped compliances', mappedCompliances) for (let statuteObj of selectedStatutes) { for (let complianceid of Object.keys(mappedCompliances.data.mappings[statuteObj.id] ?? {})) { let pushObj = mappedCompliances.data.mappings[statuteObj.id][complianceid]; pushObj.id = complianceid; pushObj.statuteid = statuteObj.id; mappedCompliancesArr.data.mappings[complianceid] = pushObj; } } rendertaggingfunction(selectedStatutes, mappedCompliancesArr, sourceMappingArray, mappingArray); }) let mappingCountButton = container.querySelector('#mapping-count-button') as HTMLButtonElement mappingCountButton.addEventListener('click', () => { this.getMappingCount(container) }) } getMappingCount = async (container: HTMLDivElement) => { let id = container.id let onboardingstep = id.split('-')[0] let countResult = await this.fetchMappingCount(onboardingstep) console.log('count result', countResult) if (countResult.result == true) { let total = countResult.totalCount; let tagged = countResult.mappedCount; var status = ''; if (tagged < total) { status = 'pending'; } else { status = 'check_circle'; } let html = ('

' + status + '  Mapped ' + tagged + ' out of ' + total + '

'); (container.querySelector('#mapping-count-container') as HTMLDivElement).innerHTML = html } } renderOnboardingCompliances = async (mappedStatutes: any, mappedCompliancesArr: any) => { //console.log('mappedcompliances', mappedCompliances); //console.log('mappedstatutes', mappedStatutes); var searchString = ""; let mappedCompliances: any = { data: { mappings: { mappings: [] } } }; for (var i = 0; i < (mappedStatutes.data.mappings.mappings as Array).length; i++) { if ((mappedStatutes.data.mappings.mappings as Array)[i].selected) { let statuteid = (mappedStatutes.data.mappings.mappings as Array)[i].id if (mappedCompliancesArr.data.mappings[statuteid] != null) { for (let complianceid of Object.keys(mappedCompliancesArr.data.mappings[statuteid])) { let pushObj = mappedCompliancesArr.data.mappings[statuteid][complianceid]; pushObj.id = complianceid; mappedCompliances.data.mappings.mappings.push(pushObj); } } searchString += statuteid + "|"; } } searchString = searchString.slice(0, -1); //console.log('searchstring', searchString); var initCursor = ""; // var html = ''; // html += '
'; // html += '
'; // html += ''; // html += '
'; // html += '' // html += '' // html += '
'; // html += '
'; // html += '
'; // html += '
'; // html += '
'; // (this._SfOnboardingCompliancesContainer as HTMLDivElement).innerHTML = html; // (this._SfButtonSearch as HTMLButtonElement)?.addEventListener('click', async () => { // //console.log('clicked', mappedStatutes.data.mappings.mappings); // const searchString = (this._SfInputSearch as HTMLButtonElement).value; // //console.log('searchstring', searchString); // if (searchString.length > 0) { // const arrSearchString = searchString.split('|'); // const arrSearchStringProcessed: any = []; // arrSearchString.forEach((complianceId: string) => { // if (complianceId.length === 36) { // arrSearchStringProcessed.push(complianceId); // } // }); // var resultCompliances: any = {}; // resultCompliances.values = []; // const chunkSize = 20; // for (let k = 0; k < arrSearchStringProcessed.length; k += chunkSize) { // const chunk = arrSearchStringProcessed.slice(k, k + chunkSize); // console.log('chunk', chunk); // // do whatever // const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchStringProcessed.length); // console.log(tempResultCompliances) // resultCompliances.values.push(...tempResultCompliances.values); // //console.log(resultCompliances); // } // // var resultCompliances : any = {}; // // resultCompliances.values = []; // // const chunkSize = 20; // // for (let k = 0; k < arrSearchString.length; k += chunkSize) { // // const chunk = arrSearchString.slice(k, k + chunkSize); // // console.log('chunk', chunk); // // // do whatever // // const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchString.length); // // console.log(tempResultCompliances) // // resultCompliances.values.push(...tempResultCompliances.values); // // //console.log(resultCompliances); // // } // if (resultCompliances != null) { // const jsonData = []; // const arrCompliancesFrequencies: any = {}; // for (var i = 0; i < resultCompliances.values.length; i++) { // if (arrCompliancesFrequencies[resultCompliances.values[i].id] != null) { // continue; // } else { // arrCompliancesFrequencies[resultCompliances.values[i].id] = 0; // } // var mapped = false; // var extraFields = null; // var previousExtraFields = null; // console.log('mappedcompliances', mappedCompliances) // for (var j = 0; j < mappedCompliances.data.mappings.mappings.length; j++) { // if (mappedCompliances.data.mappings.mappings[j].id == resultCompliances.values[i].id) { // if (mappedCompliances.data.mappings.mappings[j].selected) { // mapped = true; // } // extraFields = mappedCompliances.data.mappings.mappings[j].extraFields; // } // } // for (j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) { // // console.log('mappedStatutes.data.mappings.mappings[j]', mappedStatutes.data.mappings.mappings[j]); // if (Array.isArray(mappedStatutes.data.mappings.mappings[j].statutename)) { // // sometimes this error occurs // continue; // } // if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == JSON.parse(resultCompliances.values[i].fields.data[0])[6][0].trim()) { // // if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == "Corporation Act, 2001") { // // console.log('pushpreviousvalues', mappedStatutes.data.mappings.mappings[j], Object.keys(mappedStatutes.data.mappings.mappings[j].extraFields[0])); // // } // previousExtraFields = mappedStatutes.data.mappings.mappings[j].extraFields // } // } // jsonData.push({ id: resultCompliances.values[i].id, mapped: mapped, data: resultCompliances.values[i].fields, cols: ["country", "jurisdiction", "state", "category", "subcategory", "statute", "applicability", "obligationtitle", "obligation", "risk", "riskarea", "frequency", "penalty", "reference", "form", "subfrequency", "obligationtype", "duedate"], extraFields: extraFields, previousExtraFields: previousExtraFields }) // } // this.renderMappingTable((this._SfOnboardingCompliancesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultCompliances.cursor }], this.fetchSearchCompliances, searchString, mappedCompliances, resultCompliances.values.length, this.uploadCompliancesMapping, this.loadOnboardingCompliances, ["Client remarks", "FlaggGRC response"], -1, 0, "compliances", "", "statute", ["optional", "optional"]); // } // } // }); //console.log('compliances searchstring', searchString); // if (searchString != "") { // (this._SfInputSearch as HTMLInputElement).value = searchString; // (this._SfButtonSearch as HTMLButtonElement).click(); // } if (searchString.length > 0) { const arrSearchString = searchString.split('|'); const arrSearchStringProcessed: any = []; arrSearchString.forEach((complianceId: string) => { if (complianceId.length === 36) { arrSearchStringProcessed.push(complianceId); } }); var resultCompliances: any = {}; resultCompliances.values = []; const chunkSize = 20; for (let k = 0; k < arrSearchStringProcessed.length; k += chunkSize) { const chunk = arrSearchStringProcessed.slice(k, k + chunkSize); console.log('chunk', chunk); // do whatever const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchStringProcessed.length); console.log(tempResultCompliances) resultCompliances.values.push(...tempResultCompliances.values); //console.log(resultCompliances); } // var resultCompliances : any = {}; // resultCompliances.values = []; // const chunkSize = 20; // for (let k = 0; k < arrSearchString.length; k += chunkSize) { // const chunk = arrSearchString.slice(k, k + chunkSize); // console.log('chunk', chunk); // // do whatever // const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchString.length); // console.log(tempResultCompliances) // resultCompliances.values.push(...tempResultCompliances.values); // //console.log(resultCompliances); // } if (resultCompliances != null) { const jsonData = []; const arrCompliancesFrequencies: any = {}; for (var i = 0; i < resultCompliances.values.length; i++) { if (arrCompliancesFrequencies[resultCompliances.values[i].id] != null) { continue; } else { arrCompliancesFrequencies[resultCompliances.values[i].id] = 0; } var mapped = false; var extraFields = null; var previousExtraFields = null; console.log('mappedcompliances', mappedCompliances) if (mappedCompliances.data.mappings.mappings == null) { for (var j = 0; j < Object.keys(mappedCompliances.data.mappings).length; j++) { let statuteKey = Object.keys(mappedCompliances.data.mappings)[j]; for (var k = 0; k < Object.keys(mappedCompliances.data.mappings[statuteKey]).length; k++) { let complianceKey = Object.keys(mappedCompliances.data.mappings[statuteKey])[k]; if (mappedCompliances.data.mappings[statuteKey][complianceKey].id == resultCompliances.values[i].id) { mapped = true; extraFields = mappedCompliances.data.mappings[statuteKey][complianceKey].extraFields; } } } } else { for (var j = 0; j < mappedCompliances.data.mappings.mappings.length; j++) { if (mappedCompliances.data.mappings.mappings[j].id == resultCompliances.values[i].id) { mapped = true; extraFields = mappedCompliances.data.mappings.mappings[j].extraFields; } } for (j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) { // console.log('mappedStatutes.data.mappings.mappings[j]', mappedStatutes.data.mappings.mappings[j]); if (Array.isArray(mappedStatutes.data.mappings.mappings[j].statutename)) { // sometimes this error occurs continue; } if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == JSON.parse(resultCompliances.values[i].fields.data[0])[6][0].trim()) { // if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == "Corporation Act, 2001") { // //console.log('pushpreviousvalues', mappedStatutes.data.mappings.mappings[j], Object.keys(mappedStatutes.data.mappings.mappings[j].extraFields[0])); // } previousExtraFields = mappedStatutes.data.mappings.mappings[j].extraFields } } } jsonData.push({ id: resultCompliances.values[i].id, mapped: mapped, data: resultCompliances.values[i].fields, cols: ["country", "jurisdiction", "state", "category", "subcategory", "statute", "applicability", "obligationtitle", "obligation", "risk", "riskarea", "frequency", "penalty", "reference", "form", "subfrequency", "obligationtype", "duedate"], extraFields: extraFields, previousExtraFields: previousExtraFields }) } this.renderMappingTable((this._SfOnboardingCompliancesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultCompliances.cursor }], this.fetchSearchCompliances, searchString, mappedCompliances, resultCompliances.values.length, this.uploadCompliancesMapping, this.loadOnboardingCompliances, [], -1, 0, "compliances", "", "statute", ["optional", "optional"], mappedStatutes.data.mappings.mappings); } } } renderOnboardingEntities = (selectedStatutes: any, mappedCompliances: any, mappedCountries: any, mappedEntities: any) => { this.renderTaggingTableNew((this._SfOnboardingEntitiesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedCountries, mappedEntities, ["shortid", "applicability", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute"], this.uploadEntitiesMapping, this.loadOnboardingEntities, "entities", ["id", "countryname"], this.apiIdTags, "&Entity", ["entityname", "entityid"], ["id", "countryid"], null, [], [], "Guideline", ""); } renderOnboardingCountries = (selectedStatutes: any, mappedCompliances: any, sourceMapping: any, mappedCountries: any) => { sourceMapping = {} this.renderTaggingTableNew((this._SfOnboardingCountriesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, sourceMapping, mappedCountries, ["shortid", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute", "state", "subcategory"], this.uploadCountriesMapping, this.loadOnboardingCountries, "countries", ["id"], this.apiIdTags, "-Country", ["countryname", "countryid"], ["id"], null, [], null, "", ""); } renderOnboardingStatutes = (mappedStatutes: any) => { var initCursor = ""; var html = ''; html += '
'; html += '
'; html += ''; html += '
'; html += '' html += '' html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; (this._SfOnboardingStatutesContainer as HTMLDivElement).innerHTML = html; (this._SfInputSearch as HTMLInputElement).addEventListener('keyup', (e: any) => { if (e.key == 'Enter') { (this._SfButtonSearch as HTMLButtonElement).click(); } }); (this._SfButtonSearch as HTMLButtonElement).addEventListener('click', async () => { //console.log('clicked', mappedStatutes.data.mappings.mappings); const searchString = (this._SfInputSearch as HTMLButtonElement).value; //console.log('clicked', searchString); if (searchString.length > 0) { const resultStatutes = await this.fetchSearchStatutes(searchString, ""); if (resultStatutes != null) { const jsonData = []; let countMapped = 0 for (var i = 0; i < resultStatutes.values.length; i++) { var mapped = false; var extraFields = null; if (mappedStatutes.data != null && mappedStatutes.data.mappings != null && mappedStatutes.data.mappings.mappings != null) { for (var j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) { if (mappedStatutes.data.mappings.mappings[j].id == resultStatutes.values[i].id) { countMapped++ console.log('comparing', mappedStatutes.data.mappings.mappings[j].id, resultStatutes.values[i].id, countMapped); // if (mappedStatutes.data.mappings.mappings[j].selected) { mapped = true; // } extraFields = mappedStatutes.data.mappings.mappings[j].extraFields; } } } jsonData.push({ id: resultStatutes.values[i].id, mapped: mapped, data: resultStatutes.values[i].fields, cols: ["country", "jurisdiction", "state", "name", "category", "subcategory", "applicability"], extraFields: extraFields }) } console.log('clicked', jsonData); // let diffArr = [] // for(let mappedObj of mappedStatutes.data.mappings.mappings){ // let flagFound = false // for(let jsonObj of jsonData){ // if(jsonObj.id == mappedObj.id){ // flagFound = true; // break; // } // } // if(!flagFound){ // diffArr.push(mappedObj) // } // } // console.log('compareDiff', diffArr) this.renderMappingTable((this._SfOnboardingStatutesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultStatutes.cursor }], this.fetchSearchStatutes, searchString, mappedStatutes, jsonData.length, this.uploadStatutesMapping, this.loadOnboardingStatutes, ["Client remarks
'; div.innerHTML += html; } renderRcmCompliances = (updatedCompliances: any) => { var html = '
'; html += '
Recently Updated Compliances
'; html += '
Show Completed
'; html += ''; html += ''; html += '' html += '' html += '' for (var i = 0; i < Object.keys(updatedCompliances[0].values).length; i++) { if (this.arrCols.includes(Object.keys(updatedCompliances[0].values)[i])) { html += '' } } html += '' html += '' for (var i = 0; i < updatedCompliances.length; i++) { var classBg = ""; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; html += ''; html += ''; html += ''; //let data = JSON.parse(jsonData[i].fields.data); for (var j = 0; j < Object.keys(updatedCompliances[i].values).length; j++) { const objectKey = Object.keys(updatedCompliances[i].values)[j]; if (this.arrCols.includes(objectKey)) { html += ''; } } html += ''; } html += '' html += '
' html += 'Select'; html += '' html += 'Complete'; html += '' html += 'Id'; html += '' html += Object.keys(updatedCompliances[0].values)[i] html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; html += ''; html += ''; if (Array.isArray(updatedCompliances[i].values[objectKey].value)) { for (var k = 0; k < updatedCompliances[i].values[objectKey].value.length; k++) { if (updatedCompliances[i].values[objectKey].text != null) { html += (''); } else { html += (''); } if (k < (updatedCompliances[i].values[objectKey].value.length - 1)) { html += "; "; } } } else { if (updatedCompliances[i].values[objectKey].text != null) { html += ('') } else { html += ('') } } html += '
'; html += '
'; (this._SfRcmComplianceContainer as HTMLDivElement).innerHTML = html; } renderRcmLockedCompliances = (lockedCompliances: any) => { //console.log('rendering locked', lockedCompliances); for (var i = 0; i < lockedCompliances.data.length; i++) { // //console.log(lockedCompliances.data[i].complianceid); // //console.log(((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement)); // ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'none'; ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#row-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'none'; ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).classList.add('gone'); } } renderRcmUnlockedCompliances = (lockedCompliances: any) => { //console.log('rendering unlocked', lockedCompliances); for (var i = 0; i < lockedCompliances.data.length; i++) { //console.log('#row-' + lockedCompliances.data[i].complianceid.S); ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#row-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'table-row'; } } renderRcmProjects = (div: HTMLDivElement, projects: any) => { //console.log('projects', projects); var html = '
'; html += '
Affected Projects
'; if (projects == null || projects.length === 0) { html += '

No projects found

'; div.innerHTML += html; return; } // //console.log(updatedCompliances); html += ''; html += ''; // html += '' html += ''; for (var i = 0; i < Object.keys(projects[0]).length; i++) { if (this.arrRcmProjectCols.includes(Object.keys(projects[0])[i])) { html += '' } } html += ''; html += ''; for (var i = 0; i < projects.length; i++) { var classBg = ""; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; // html += ''; html += ''; // //let data = JSON.parse(jsonData[i].fields.data); for (var j = 0; j < Object.keys(projects[i]).length; j++) { const objectKey = Object.keys(projects[i])[j]; if (this.arrRcmProjectCols.includes(objectKey)) { html += ''; } } html += ''; } html += '' html += '
' // html += 'Select'; // html += ''; html += 'Id'; html += '' html += Object.keys(projects[0])[i] html += '
'; // html += '
'; // html += '
'; html += ''; html += ''; //console.log('value',projects[i][objectKey]); if (Array.isArray(projects[i][objectKey])) { for (var k = 0; k < projects[i][objectKey].value.length; k++) { html += (''); } } else { //console.log('not array'); html += ('') } html += '
'; html += '
'; div.innerHTML += html; // const arrButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.button-icon') as NodeListOf; // for(i = 0; i < arrButtons.length; i++) { // arrButtons[i].addEventListener('click', (e: any) => { // const index = e.currentTarget.id.split('-')[1]; // this.rcmSelectedCompliance = updatedCompliances[index]; // ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects') as HTMLButtonElement).click(); // }) // } } renderRcmSelectedDate = (div: HTMLDivElement) => { var html = ""; html = '
'; html += '
Trigger Information
'; if (this.rcmSelectedDate == null || this.rcmSelectedMessage == null) { html += '

No trigger information found

'; div.innerHTML += html; return; } html += '
'; html += '

' + this.rcmSelectedDate + '

' html += '
'; html += '

' + this.rcmSelectedMessage + '

' html += '
'; div.innerHTML += html; } renderRcmDate = (div: HTMLDivElement) => { var html = '
'; html += '
Trigger Information
'; html += '
'; html += '

' html += '
'; html += '' html += '
'; div.innerHTML += html; } renderRcmJobs = (div: HTMLDivElement) => { var html = '
'; html += '
New RCM Update Job
'; html += '
'; html += '
'; div.innerHTML += html; } renderRcmSelectedJobs = (div: HTMLDivElement, jobs: any) => { var html = '
'; html += '
Previous Jobs For The Selected Compliance
'; if (jobs.data.length === 0) { html += '

No jobs found

'; div.innerHTML += html; return; } html += ''; html += ''; html += '' html += '' html += '' html += '' html += ''; html += ''; for (var i = jobs.data.length - 1; i >= 0; i--) { var classBg = ""; if (i % 2 === 0) { classBg = 'td-light'; } else { classBg = 'td-dark'; } html += ''; html += '' html += '' html += '' html += '' html += ''; } html += ''; html += ''; html += '
' html += 'Id'; html += '' html += 'Creation Time'; html += '' html += 'Status'; html += '' html += ''; html += '
'; html += jobs.data[i].id.S; html += ''; html += jobs.data[i].lastupdated.S; html += ''; html += jobs.data[i].status.S == "0" ? "created" : jobs.data[i].status.S == "1" ? "in-progress" : jobs.data[i].status.S == "2" ? "completed" : "notified"; html += ''; html += jobs.data[i].status.S == "0" ? "schedule" : jobs.data[i].status.S == "1" ? "pending" : jobs.data[i].status.S == "2" ? "check_circle" : "notifications"; html += '
'; div.innerHTML += html; } renderRcmNotifications = (notifs: any) => { var html = ''; //console.log('inside rcm notifications', notifs); if (notifs.data.length > 0) { if (this.flowRcmNotification === 0) { html += '
'; html += 'notifications'; html += '
Regulatory Alerts
'; html += ('
' + notifs.data.length + '
'); html += '' html += '
'; } else { html += '
'; html += '
'; html += 'notifications'; html += '
Regulatory Alerts
'; html += '
'; html += '
'; for (var i = 0; i < notifs.data.length; i++) { html += '
'; html += notifs.data[i].message; html += '
'; } html += '
'; html += '
'; } } else { } (this._SfRcmContainer as HTMLDivElement).innerHTML = html; if (notifs.data.length > 0) { if (this.flowRcmNotification === 0) { ((this._SfRcmContainer as HTMLDivElement).querySelector('#button-expand') as HTMLButtonElement).addEventListener('click', () => { this.flowRcmNotification = 1; this.renderRcmNotifications(notifs); }) } } } renderRcmTabs = () => { //console.log('render rcm tabs'); (this._SfRcmTabContainer as HTMLDivElement).innerHTML = ''; var html = ''; html += ''; html += ''; html += ''; html += ''; (this._SfRcmTabContainer as HTMLDivElement).innerHTML = html; (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-compliances')?.addEventListener('click', async () => { this.myRcmTab = this.TAB_RCM_COMPLIANCES; this.renderRcmTabs(); await this.loadRcmCompliances(); }); (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects')?.addEventListener('click', async () => { this.myRcmTab = this.TAB_RCM_PROJECTS; this.renderRcmTabs(); await this.loadRcmProjects(); //await this.loadOnboardingStatutes(); }); (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-date')?.addEventListener('click', async () => { this.myRcmTab = this.TAB_RCM_DATE; this.renderRcmTabs(); await this.loadRcmDate(); //await this.loadOnboardingStatutes(); }); (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-jobs')?.addEventListener('click', async () => { this.myRcmTab = this.TAB_RCM_JOBS; this.renderRcmTabs(); await this.loadRcmJobs(); //await this.loadOnboardingStatutes(); }); } proceedToCalendar = async () => { this.renderRoleTabs(); await this.fetchAndYearlyRenderUserCalendar_2(); this.enableCalendar(); if (this.events != null) { this.renderTabs(this.TAB_YEAR); this.renderCalendar(); } } renderRoleTabs = () => { //console.log('render role tabs'); (this._SfRoleTabContainer as HTMLDivElement).innerHTML = ''; var html = ''; html += ''; html += ''; html += ''; html += ''; html += ''; (this._SfRoleTabContainer as HTMLDivElement).innerHTML = html; (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-reporter')?.addEventListener('click', async () => { this.myRole = this.TAB_REPORTER; this.renderRoleTabs(); // this.proceedToCalendar(); if (this.selectedFeatures.indexOf('contracts') >= 0) { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-approver')?.addEventListener('click', async () => { this.myRole = this.TAB_APPROVER; this.renderRoleTabs(); // this.proceedToCalendar(); if (this.selectedFeatures.indexOf('contracts') >= 0) { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-functionhead')?.addEventListener('click', async () => { this.myRole = this.TAB_FUNCTION_HEAD; this.renderRoleTabs(); // this.proceedToCalendar(); if (this.selectedFeatures.indexOf('contracts') >= 0) { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-auditor')?.addEventListener('click', async () => { this.myRole = this.TAB_AUDITOR; this.renderRoleTabs(); // this.proceedToCalendar(); if (this.selectedFeatures.indexOf('contracts') >= 0) { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-viewer')?.addEventListener('click', async () => { this.myRole = this.TAB_VIEWER; this.renderRoleTabs(); // this.proceedToCalendar(); if (this.selectedFeatures.indexOf('contracts') >= 0) { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } }); } csvmaker = (data: any) => { // Empty array for storing the values let csvRows = []; // Headers is basically a keys of an // object which is id, name, and // profession const headers = Object.keys(data); // As for making csv format, headers // must be separated by comma and // pushing it into array csvRows.push(headers.join(',')); // Pushing Object values into array // with comma separation const values = Object.values(data).join(','); csvRows.push(values) // Returning the array joining with new line return csvRows.join('\n') } renderChartSettingsFilters = (container: HTMLDivElement, ctx: any) => { //console.log(container); var html = `
`; container.innerHTML = html; container.querySelector('#chart-control-plot')?.addEventListener('click', () => { const query = (container.querySelector('#input-multi-entry-tags') as SfIForm).selectedValues(); this.filterTags = query; let eventContainer = null; if (this.getCurrentTab() == this.TAB_STREAM) { eventContainer = (this._SfStreamContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_UPCOMING) { eventContainer = (this._SfUpcomingContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_THIS) { eventContainer = (this._SfThisContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_PAST) { eventContainer = (this._SfPastContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_CUSTOM) { eventContainer = (this._SfCustomContainer as HTMLDivElement); } const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf; const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf; const hiddenTitles = eventContainer!.querySelectorAll('.hidden-title') as NodeListOf; const hiddenFilternames = eventContainer!.querySelectorAll('.hidden-filtername') as NodeListOf; const filternames = eventContainer!.querySelectorAll('.filtername') as NodeListOf; const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement; if (this.filterTags.length > 0) { streamEventSummary.style.display = 'none'; } else { streamEventSummary.style.display = 'block'; } //console.log('divs', divs); for (var i = 0; i < divs.length; i++) { var found = false; var filterMatched = ""; const tagsEmbedded = JSON.parse((divs[i] as HTMLDivElement).querySelector('.hidden-tags')?.innerHTML + ""); //console.log(tagsEmbedded); for (var count1 = 0; count1 < tagsEmbedded.length; count1++) { for (var count2 = 0; count2 < this.filterTags.length; count2++) { if (tagsEmbedded[count1].toLowerCase().indexOf(this.filterTags[count2].toLowerCase()) >= 0) { found = true; filterMatched += (this.filterTags[count2].split(';')[0] + ", "); } } } if (!found) { (tables[i] as HTMLDivElement).style.display = 'none'; (hiddenTitles[i] as HTMLDivElement).style.display = 'block'; (hiddenFilternames[i] as HTMLDivElement).style.display = 'none'; filternames[i].innerHTML = ''; } else { (tables[i] as HTMLDivElement).style.display = 'block'; (hiddenTitles[i] as HTMLDivElement).style.display = 'none'; (hiddenFilternames[i] as HTMLDivElement).style.display = 'block'; filternames[i].innerHTML = filterMatched.replace(/,\s*$/, "");; } } this.filterEventsInWindow(query, ctx, eventContainer); }); container.querySelector('#chart-control-cancel')?.addEventListener('click', (e) => { let targetDiv = e.target as HTMLDivElement; let containerDiv = targetDiv.parentElement?.parentElement as HTMLDivElement; if (containerDiv != null) { containerDiv.innerHTML = ''; containerDiv.parentElement?.parentElement?.querySelector('#chart-control-settings')?.setAttribute('part', 'calendar-tab-button-not-selected'); containerDiv.parentElement?.parentElement?.querySelector('#chart-control-summary')?.setAttribute('part', 'calendar-tab-button-not-selected'); // containerDiv.dispatchEvent(new CustomEvent('canceled', { bubbles: true })); } // container.innerHTML = ''; // container.dispatchEvent(new CustomEvent('canceled', { bubbles: true })); }); } renderChartSettingsSettings = (container: HTMLDivElement, selectedTab: number = 1) => { var html = `` if (selectedTab == -1) { html = `
Reports
`; } else { html = `
Reports
`; } container.innerHTML = html; container.querySelector('#chart-control-cancel')?.addEventListener('click', (e) => { let targetDiv = e.target as HTMLDivElement; let containerDiv = targetDiv.parentElement?.parentElement as HTMLDivElement; console.log('containerDiv', containerDiv); if (containerDiv != null) { containerDiv.innerHTML = ''; containerDiv.parentElement?.parentElement?.querySelector('#chart-control-settings')?.setAttribute('part', 'calendar-tab-button-not-selected'); containerDiv.parentElement?.parentElement?.querySelector('#chart-control-summary')?.setAttribute('part', 'calendar-tab-button-not-selected'); // containerDiv.dispatchEvent(new CustomEvent('canceled', { bubbles: true })); } }); container.querySelector('#button-download-stats')?.addEventListener('click', async () => { const radioCsv = (container.querySelector('#radio-csv') as HTMLInputElement); const radioImage = (container.querySelector('#radio-image') as HTMLInputElement); const radioStats = (container.querySelector('#radio-stats') as HTMLInputElement); const radioList = (container.querySelector('#radio-list') as HTMLInputElement); const radioListCsv = (container.querySelector('#radio-list-csv') as HTMLInputElement); const radioConsolidated = (container.querySelector('#radio-consolidated') as HTMLInputElement); const radioCertificate = (container.querySelector('#radio-certificate') as HTMLInputElement); if (selectedTab === -1 && !(radioImage.checked)) { if (this.selectedFeatures.indexOf('compliances') >= 0) { await this.fetchAndYearlyRenderUserCalendar_2(this.sdate, this.edate, "", "no") } else if (this.selectedFeatures.indexOf('notices') >= 0) { await this.fetchAndRenderNotices(this.sdate, this.edate, "", "no"); } else if (this.selectedFeatures.indexOf('contracts') >= 0) { await this.fetchAndRenderContracts(this.sdate, this.edate, "", "no"); } else if (this.selectedFeatures.indexOf('licenses') >= 0) { await this.fetchAndRenderLicenses(this.sdate, this.edate, "", "no"); } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { await this.fetchAndRenderRCMResources(this.sdate, this.edate, "", "no"); } // await this.fetchAndYearlyRenderUserCalendar_2(this.sdate, this.edate, "", "no"); } //console.log('radiocsv checked', radioCsv.checked); //console.log('radioimage checked', radioImage.checked); if (radioCsv.checked) { const blob2 = new Blob([this.csvGraphStats], { type: 'text/csv' }); const url2 = window.URL.createObjectURL(blob2) const a2 = document.createElement('a') a2.setAttribute('href', url2) a2.setAttribute('download', 'download_' + new Date() + '.csv'); a2.click() } if (radioImage.checked) { setTimeout(() => { this.downloadChart(this.chart) // const a = document.createElement('a') // a.setAttribute('href', this.chartBase64) // a.setAttribute('download', 'download_' + new Date().getTime() + '.png'); // a.click() console.log('this.chart2', (this.chart2Base64)); // if (this.chart2Base64 != null) { this.downloadChart(this.chart2, 'completeness') // console.log('this.chart2 download', this.chart2Base64); // const a2 = document.createElement('a') // a2.setAttribute('href', this.chart2Base64) // a2.setAttribute('download', 'download_completeness_' + new Date().getTime() + '.png'); // a2.click() // } // if (this.chart3Base64 != null) { this.downloadChart(this.chart3, 'timeliness') // const a3 = document.createElement('a') // a3.setAttribute('href', this.chart3Base64) // a3.setAttribute('download', 'download_timeliness_' + new Date().getTime() + '.png'); // a3.click() // } // if (this.chart4Base64 != null) { this.downloadChart(this.chart4, 'compliance') // const a4 = document.createElement('a') // a4.setAttribute('href', this.chart4Base64) // a4.setAttribute('download', 'download_compliance_' + new Date().getTime() + '.png'); // a4.click() // } }, 2000) } if (radioStats.checked) { const ts = new Date().getTime(); console.log('htmlstatsfilter', this.htmlStatsFilter, selectedTab); var html = this.COMPLIANCES_HTML; html = html.replace(/PROJECT_NAME/g, this.projectName); if (selectedTab == -1) { html = html.replace(/FILTERS_DATA/g, ''); } else { let filtersHtml = `
${this.htmlStatsFilter}
` html = html.replace(/FILTERS_DATA/g, filtersHtml); } html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period); let tempHtml: string = ""; tempHtml += this.htmlDataStats; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { } else { tempHtml += ('
' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : "")); tempHtml += ('
' + (this.csvToHtmlTable(this.csvCompletenessStats) + '
' + this.csvToHtmlTable(this.csvTimelinessStats) + '
' + this.csvToHtmlTable(this.csvComplianceStats))); } html = html.replace(/PERSON_COMPLIANCES/g, tempHtml); const blob = new Blob([html], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + ts + '.html'); a.click() } if (radioList?.checked) { const ts = new Date(); var html = this.COMPLIANCES_HTML; html = html.replace(/PROJECT_NAME/g, this.projectName); html = html.replace(/FILTERS_DATA/g, ''); html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period); let tempHtml: string = ""; tempHtml += this.getFilteredString(); html = html.replace(/PERSON_COMPLIANCES/g, tempHtml); const blob = new Blob([html], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + ts + '.html'); a.click() } if (radioListCsv?.checked) { const ts = new Date(); console.log(this.csvDataCompliances); const blob = new Blob([this.csvDataCompliances], { type: 'text/csv' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + ts + '.csv'); a.click() } if (radioConsolidated?.checked) { const ts = new Date().getTime(); var html = this.COMPLIANCES_HTML; html = html.replace(/PROJECT_NAME/g, this.projectName); html = html.replace(/FILTERS_DATA/g, ''); html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period); let tempHtml: string = ""; tempHtml += this.htmlDataStats; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { } else { tempHtml += ('
' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : "")); tempHtml += ('
' + (this.csvToHtmlTable(this.csvCompletenessStats) + '
' + this.csvToHtmlTable(this.csvTimelinessStats) + '
' + this.csvToHtmlTable(this.csvComplianceStats))); } tempHtml += this.getFilteredString(); html = html.replace(/PERSON_COMPLIANCES/g, tempHtml); const blob = new Blob([html], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'report_' + ts + '.html'); a.click() } if (radioCertificate?.checked) { var html = this.CERTIFICATE_HTML; html = html.replace(/PERSON_NAME/g, this.userName); html = html.replace(/PERSON_DESIGNATION/g, this.myRole); html = html.replace(/PERSON_COMPANY/g, this.projectName); html = html.replace(/PERSON_CRITERIA/g, this.selectedCriteria); html = html.replace(/PERSON_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear()); let tempHtml: string = ""; tempHtml += this.htmlDataStats; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { } else { tempHtml += ('
' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : "")); tempHtml += ('
' + (this.csvToHtmlTable(this.csvCompletenessStats) + '
' + this.csvToHtmlTable(this.csvTimelinessStats) + '
' + this.csvToHtmlTable(this.csvComplianceStats))); } html = html.replace(/PERSON_COMPLIANCE_STATUS/g, tempHtml); html = html.replace(/PERSON_COMPLIANCES/g, this.getFilteredString()); html = html.replace(/PERSON_PERIOD/g, this.period); //console.log('downloaded certificate'); const blob = new Blob([html], { type: 'text/html' }); const url = window.URL.createObjectURL(blob) const a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('download', 'certificate.html'); a.click() } }) container.querySelector('.switch-solid')?.addEventListener('click', () => { this.fill = "solid"; if (this.getCurrentTab() == this.TAB_STREAM) { this.renderStream(0, true, false); } }); container.querySelector('.switch-pattern')?.addEventListener('click', () => { this.fill = "pattern"; if (this.getCurrentTab() == this.TAB_STREAM) { this.renderStream(0, true, false); } }); } renderChartSettings = (container: HTMLDivElement, selectedTab: number = -1, selectedSummary: number = -1, ctx: any) => { console.log('rendering chart settings', selectedSummary); var html = ''; html += '
'; if ((this.selectedFeatures.indexOf('compliances') >= 0) && (this.selectedFeatures.indexOf('notices') < 0) && (this.selectedFeatures.indexOf('contracts') < 0) && (this.selectedFeatures.indexOf('licenses') < 0) && (this.selectedFeatures.indexOf('rcmresources') < 0)) { html += ''; } if (selectedTab === 0) { //html += ''; } else { //html += ''; } if (selectedTab === 1) { html += ''; } else { html += ''; } // if (selectedTab === 1) { // html += ''; // } else { html += ''; // } if (selectedSummary === 1) { html += ''; } else if (selectedSummary !== 2) { html += ''; } html += '
'; if ((container.querySelector('#chart-settings-controls') as HTMLDivElement) != null) { (container.querySelector('#chart-settings-controls') as HTMLDivElement).innerHTML = html; (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings')?.addEventListener('click', () => { this.renderChartSettings(container, 1, selectedSummary, ctx); }); (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-summary')?.addEventListener('click', () => { console.log('summary clicked'); this.renderChartSummary(); }); const buttonRefresh = container.querySelector('#button-refresh') as HTMLButtonElement if (buttonRefresh != null) { const inputShowReportedLocations = container.querySelector('#input-show-reported-locations') as HTMLButtonElement inputShowReportedLocations?.addEventListener('click', () => { this.showReportedLocations = !this.showReportedLocations; let clickEvent = new Event('click', {}) buttonRefresh?.dispatchEvent(clickEvent); }) } const buttonChartExpand = container.querySelector('#chart-expand') as HTMLButtonElement if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { if (buttonChartExpand != null) { buttonChartExpand.classList.add('hide') } } else { if (buttonChartExpand != null) { buttonChartExpand.classList.remove('hide') } } buttonChartExpand?.addEventListener('click', () => { const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement chartModalContainer.classList.remove('hide'); // let chartModalTitle = chartModalContainer.querySelector('#chart-modal-title') as HTMLDivElement console.log('rendering chart', this.flowGraph); switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph(chartModalContainer); // chartModalTitle.innerHTML = "Completeness Distribution" break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph(chartModalContainer); // chartModalTitle.innerHTML = "Timeliness Distribution" break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph(chartModalContainer); // chartModalTitle.innerHTML = "Compliance Distribution" break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "RiskAreas Distribution" break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Risk Distribution" break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Locations Distribution" break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Functions Distribution" break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "ObligationTypes Distribution" break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Jurisdictions Distribution" break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Frequencies Distribution" break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph(chartModalContainer, false, true); // chartModalTitle.innerHTML = "Subcategories Distribution" break; default: this.renderCompletenessGraph(chartModalContainer); // chartModalTitle.innerHTML = "Completeness Distribution" break; } }) const buttonCloseChartModal = container.querySelector('#chart-modal-close') as HTMLButtonElement buttonCloseChartModal?.addEventListener('click', () => { const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement chartModalContainer.classList.add('hide'); this.clearGraph(chartModalContainer, 1) this.clearGraph(chartModalContainer, 2) this.clearGraph(chartModalContainer, 3) this.clearGraph(chartModalContainer, 4) let parentElement = chartModalContainer.parentElement as HTMLDivElement if (parentElement != null) { switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph(parentElement); break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph(parentElement); break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph(parentElement); break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph(parentElement); break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph(parentElement); break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph(parentElement); break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph(parentElement); break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph(parentElement); break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph(parentElement); break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph(parentElement); break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph(parentElement); break; default: this.renderCompletenessGraph(parentElement); break; } } }) const buttonChartTypeOld = container.querySelector('#chart-modal-chart-type') as HTMLButtonElement if (buttonChartTypeOld != null) { let buttonChartType = Util.clearListeners(buttonChartTypeOld); buttonChartType?.addEventListener('click', (e) => { let button = e.target as HTMLButtonElement const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement if (button.innerHTML === "bar_chart") { button.innerHTML = "donut_large" switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph(chartModalContainer); break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph(chartModalContainer); break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph(chartModalContainer); break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph(chartModalContainer, true, true); break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph(chartModalContainer, true, true); break; default: this.renderCompletenessGraph(chartModalContainer); break; } } else { button.innerHTML = "bar_chart" switch (this.flowGraph) { case this.FLOW_GRAPH_COMPLETENESS: this.renderCompletenessGraph(chartModalContainer); break; case this.FLOW_GRAPH_TIMELINESS: this.renderTimelinessGraph(chartModalContainer); break; case this.FLOW_GRAPH_COMPLIANCE: this.renderComplianceGraph(chartModalContainer); break; case this.FLOW_GRAPH_RISKAREAS: this.renderRiskGraph(chartModalContainer); break; case this.FLOW_GRAPH_RISKSEVERITY: this.renderRiskSeverityGraph(chartModalContainer); break; case this.FLOW_GRAPH_LOCATION: this.renderLocationGraph(chartModalContainer); break; case this.FLOW_GRAPH_FUNCTION: this.renderFunctionGraph(chartModalContainer); break; case this.FLOW_GRAPH_OBLIGATIONTYPE: this.renderObligationTypeGraph(chartModalContainer); break; case this.FLOW_GRAPH_JURISDICTION: this.renderJurisdictionGraph(chartModalContainer); break; case this.FLOW_GRAPH_FREQUENCY: this.renderFrequencyGraph(chartModalContainer); break; case this.FLOW_GRAPH_SUBCATEGORY: this.renderSubcategoryGraph(chartModalContainer); break; default: this.renderCompletenessGraph(chartModalContainer); break; } } }) } const buttonChartDownloadOld = container.querySelector('#chart-modal-download') as HTMLButtonElement if (buttonChartDownloadOld != null) { let buttonChartDownload = Util.clearListeners(buttonChartDownloadOld); buttonChartDownload?.addEventListener('click', () => { setTimeout(() => { this.downloadChart(this.chart) // const a = document.createElement('a') // a.setAttribute('href', this.chartBase64) // a.style.backgroundColor = '#fff' // a.setAttribute('download', 'download_' + new Date().getTime() + '.png'); // a.click() // console.log('this.chart2', (this.chart2Base64)); // if (this.chart2Base64 != null) { // console.log('this.chart2 download', this.chart2Base64); // const a2 = document.createElement('a') // a2.setAttribute('href', this.chart2Base64) // a2.style.backgroundColor = '#fff' // a2.setAttribute('download', 'download_completeness_' + new Date().getTime() + '.png'); // a2.click() this.downloadChart(this.chart2, 'completeness') // } // if (this.chart3Base64 != null) { // const a3 = document.createElement('a') // a3.setAttribute('href', this.chart3Base64) // a3.style.backgroundColor = '#fff' // a3.setAttribute('download', 'download_timeliness_' + new Date().getTime() + '.png'); // a3.click() this.downloadChart(this.chart3, 'timeliness') // } // if (this.chart4Base64 != null) { // const a4 = document.createElement('a') // a4.setAttribute('href', this.chart4Base64) // a4.style.backgroundColor = '#fff' // a4.setAttribute('download', 'download_compliance_' + new Date().getTime() + '.png'); // a4.click() this.downloadChart(this.chart4, 'compliance') // } }, 2000) }) } } // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters')?.addEventListener('click', () => { // this.renderChartSettings(container, 0, ctx); // }); if (selectedTab === 0) { const radioCompleteness = container.querySelector('#radio-completeness') as HTMLButtonElement; radioCompleteness.click(); this.renderChartSettingsFilters((container.querySelector('#chart-settings') as HTMLDivElement), ctx); } if (selectedTab === 1) { // const radioCompleteness = container.querySelector('#radio-completeness') as HTMLButtonElement; // radioCompleteness.click(); this.renderChartSettingsSettings((container.querySelector('#chart-settings') as HTMLDivElement), selectedSummary); } (container.querySelector('#chart-settings') as HTMLDivElement)?.addEventListener('canceled', () => { //console.log('canceled'); if (this.getCurrentTab() == this.TAB_STREAM) { this.renderChartSettings(container, -1, -1, ctx); this.renderStream(this.streamIndex, false, false); } // if(this.getCurrentTab() == this.TAB_UPCOMING) { // this.renderChartSettings(container, -1, ctx); // this.renderUpcoming(this.streamIndex); // } if (this.getCurrentTab() == this.TAB_THIS) { this.renderChartSettings(container, -1, -1, ctx); this.renderThis(this.streamIndex, false, false); } // if(this.getCurrentTab() == this.TAB_PAST) { // this.renderChartSettings(container, -1, ctx); // this.renderPast(this.streamIndex); // } if (this.getCurrentTab() == this.TAB_CUSTOM) { if (selectedSummary === 2) { this.processDateSelectionViewer(container) } else { this.processDateSelection(container); } } }) // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel')?.addEventListener('click', () => { // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'flex'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'flex'; // (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = ''; // }); // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel')?.addEventListener('click', () => { // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'flex'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'flex'; // (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = ''; // }); // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters')?.addEventListener('click', () => { // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'flex'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'none'; // ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'none'; // (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = ''; // this.renderChartSettingsFilters((container.querySelector('#chart-settings') as HTMLDivElement)); // }) } downloadChart = (chart: Chart, name: string = "") => { const pluginOptions = chart.options.plugins?.exportBackground; if (!pluginOptions) return; // Enable export mode pluginOptions.exporting = true; chart.update(); // Wait for next render frame requestAnimationFrame(() => { const image = chart.toBase64Image(); // Disable export mode pluginOptions.exporting = false; chart.update(); // Download const link = document.createElement('a'); link.href = image; link.download = 'download_' + ((name == "") ? "" : (name + '_')) + new Date().getTime() + '.png' link.click(); }); } renderChartSummary = () => { var html = `

Reporting Summary

`; html += this.htmlDataStats; html += '
'; html += this.getFilteredStringSummary(); // html += '
'; // html += this.htmlDataSummary; (this._SfReportSummaryContainer as HTMLDivElement).innerHTML = html; (this._SfReportSummaryContainer as HTMLDivElement).style.display = 'block'; (this._SfReportSummaryContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => { (this._SfReportSummaryContainer as HTMLDivElement).innerHTML = ''; (this._SfReportSummaryContainer as HTMLDivElement).style.display = 'none'; }); let summaryDocuments = (this._SfReportSummaryContainer as HTMLDivElement).querySelectorAll('.summary-report-doc') as NodeListOf; for (let summaryDocument of summaryDocuments) { summaryDocument.loadMode(); } } csvToHtmlTable = (strCsv: string) => { const htmlRows = []; const lines = strCsv.trim().split(/\r?\n/); const parseCsvLine = (line: string): string[] => { const result = []; let current = ''; let inQuotes = false; for (let i = 0; i < line.length; i++) { const char = line[i]; const nextChar = line[i + 1]; if (char === '"' && inQuotes && nextChar === '"') { current += '"'; // escaped quote i++; // skip next quote } else if (char === '"') { inQuotes = !inQuotes; } else if (char === ',' && !inQuotes) { result.push(current); current = ''; } else { current += char; } } result.push(current); return result; }; htmlRows.push('
' + parseCsvLine(lines[0])[0] + '

'); htmlRows.push(''); lines.forEach((line, index) => { const cells = parseCsvLine(line); const tag = index === 0 ? 'th' : 'td'; htmlRows.push(''); cells.forEach(cell => { htmlRows.push(`<${tag} class="${tag === 'td' ? 'text-center' : ''}">${cell}`); }); htmlRows.push(''); }); htmlRows.push('
'); return htmlRows.join(''); }; csvToHtmlTable1 = (strCsv: string) => { var html = ''; //console.log('csvToHtmlTable', strCsv); var strArr = strCsv.split("\n"); //console.log('csvToHtmlTable', strArr); html += '
' + strArr[0].split(',')[0] + '

'; html += ''; for (var i = 0; i < strArr.length; i++) { html += ''; if (i === 0) { const strArrArr = strArr[i].split(','); for (var j = 0; j < strArrArr.length; j++) { html += (''); } } else { const strArrArr = strArr[i].split(','); for (var j = 0; j < strArrArr.length; j++) { html += (''); } } html += ''; } html += '
' + strArrArr[j] + '' + strArrArr[j] + '
'; //console.log('csvToHtmlTable', html); return html; } getFilteredString = () => { //console.log('selectedfilter', this.selectedFilter); var tempDiv = document.createElement('div'); tempDiv.id = "div-filter-content"; tempDiv.innerHTML = this.htmlDataCompliances; const newArrList: Array = []; //console.log('tempDiv', this.htmlDataCompliances); const rows = tempDiv.querySelectorAll('tr'); for (var i = 0; i < rows.length; i++) { let cols = rows[i].querySelectorAll('td'); if (cols.length === 0) { cols = rows[i].querySelectorAll('th'); } if (i === 0) { newArrList.push(rows[i]); } else { if (cols.length > 0) { if (this.selectedFilters == null) { newArrList.push(rows[i]); } else { if (!this.selectedFilters.selected) { var found = false; for (var j = 0; j < this.selectedFilters.length; j++) { if (cols[cols.length - 1].innerHTML.toLowerCase().replace(/&/g, '&').indexOf(this.selectedFilters[j].value.toLowerCase().replace(/&/g, '&')) >= 0) { found = true; } } if (!found) { newArrList.push(rows[i]); } } else { //console.log('selected filter', this.selectedFilter, cols[cols.length - 1].innerHTML.toLowerCase(), '*-*', this.selectedFilter.value.toLowerCase()); if (cols[cols.length - 1].innerHTML.toLowerCase().replace(/&/g, '&').indexOf(this.selectedFilters.value.toLowerCase().replace(/&/g, '&')) >= 0) { newArrList.push(rows[i]); } } } } } } console.log('newarrlist', newArrList); let filteredHTML = ''; if (this.selectedFilters != null) { if (this.selectedFilters.selected) { filteredHTML += 'Filter (included parameters): ' + this.selectedFilters.value.charAt(0).toUpperCase() + this.selectedFilters.value.slice(1) + ''; } else { let params = ""; for (var i = 0; i < this.selectedFilters.length; i++) { params += this.selectedFilters[i].value.charAt(0).toUpperCase() + this.selectedFilters[i].value.slice(1); if (i < (this.selectedFilters.length - 1)) { params += ','; } } filteredHTML += 'Filter (excluded parameters): ' + params + ''; } } //console.log('newArrList', newArrList); filteredHTML += '

'; for (var i = 0; i < newArrList.length; i++) { //console.log('htmlrender', (newArrList[i] as HTMLTableRowElement).outerHTML); filteredHTML += (newArrList[i] as HTMLTableRowElement).outerHTML; } filteredHTML += '
'; // console.log('filteredHTML', filteredHTML); return filteredHTML; } getFilteredStringSummary = () => { console.log('selectedfilter', this.selectedFilters); var tempDiv = document.createElement('div'); tempDiv.id = "div-filter-content"; tempDiv.innerHTML = this.htmlDataSummary; const newArrList: Array = []; //console.log('tempDiv', this.htmlDataCompliances); const rows = tempDiv.querySelectorAll('tr'); for (var i = 0; i < rows.length; i++) { let cols = rows[i].querySelectorAll('td'); if (cols.length === 0) { cols = rows[i].querySelectorAll('th'); } if (i === 0) { newArrList.push(rows[i]); } else { if (cols.length > 0) { if (this.selectedFilters == null) { newArrList.push(rows[i]); } else { if (!this.selectedFilters.selected) { var found = false; for (var j = 0; j < this.selectedFilters.length; j++) { if (cols[cols.length - 2].innerHTML.toLowerCase().replace(/&/g, '&').indexOf(this.selectedFilters[j].value.toLowerCase().replace(/&/g, '&')) >= 0) { found = true; } } if (!found) { newArrList.push(rows[i]); } } else { console.log('selected filter', this.selectedFilters, cols[cols.length - 1].innerHTML.toLowerCase(), '*-*', this.selectedFilters.value.toLowerCase()); if (cols[cols.length - 2].innerHTML.toLowerCase().replace(/&/g, '&').indexOf(this.selectedFilters.value.toLowerCase().replace(/&/g, '&')) >= 0) { newArrList.push(rows[i]); } } } } } } console.log('newarrlist', newArrList); let filteredHTML = ''; if (this.selectedFilters != null) { if (this.selectedFilters.selected) { filteredHTML += 'Filter (included parameters): ' + this.selectedFilters.value.charAt(0).toUpperCase() + this.selectedFilters.value.slice(1) + ''; } else { let params = ""; for (var i = 0; i < this.selectedFilters.length; i++) { params += this.selectedFilters[i].value.charAt(0).toUpperCase() + this.selectedFilters[i].value.slice(1); if (i < (this.selectedFilters.length - 1)) { params += ','; } } filteredHTML += 'Filter (excluded parameters): ' + params + ''; } } //console.log('newArrList', newArrList); filteredHTML += '

'; for (var i = 0; i < newArrList.length; i++) { let tdClass = (i % 2 == 0) ? "td-even" : "td-odd"; console.log('tdClass', tdClass, i) filteredHTML += (newArrList[i] as HTMLTableRowElement).outerHTML.replace(/td-odd/g, tdClass).replace(/td-even/g, tdClass); } filteredHTML += '
'; return filteredHTML; } formatLabel = (str: string, maxwidth: number) => { const sections: any = []; var words = str.split(" "); var temp = ""; words.forEach(function (item, index) { if (temp.length > 0) { var concat = temp + ' ' + item; if (concat.length > maxwidth) { sections.push(temp); temp = ""; } else { if (index == (words.length - 1)) { sections.push(concat); return; } else { temp = concat; return; } } } if (index == (words.length - 1)) { sections.push(item); return; } if (item.length < maxwidth) { temp = item; } else { sections.push(item); } }); return sections; } renderChart4 = (ctx: any, type: any, data: any, title: string) => { if (this.chart4 != null) { (this.chart4 as Chart).destroy(); } this.chart4 = new Chart(ctx, { type: type, data: data, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, animation: { duration: 0, onComplete: () => { if (this.chart4 != null && this.chart4.ctx != null) { if (type == 'bar') { this.chart4.ctx.font = "bold 9pt 'Avenir'"; this.chart4.ctx.fillStyle = '#333'; this.chart4.ctx.textBaseline = "middle"; this.chart4.ctx.textAlign = "center"; console.log('chart 4 data', this.chart4.data.datasets); for (var i = 0; i < this.chart4.data.datasets.length; i++) { const dataset = this.chart4.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { if ((this.chart4.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) { this.chart4.ctx.fillStyle = '#fff'; } else { this.chart4.ctx.fillStyle = '#333'; } let val = 0 if (i > 0) { let tempI = 0 while (tempI < i) { if (parseInt(this.chart4.data.datasets[tempI].data[j]) > 0) { val = val == 0 ? 1 : 0; } tempI++; } } if (j % 2 == val) { this.chart4.ctx.fillText(dataset.data[j], this.chart4.getDatasetMeta(i).data[j].x - 5, this.chart4.getDatasetMeta(i).data[j].y - 15); } else { this.chart4.ctx.fillText(dataset.data[j], this.chart4.getDatasetMeta(i).data[j].x - 5, this.chart4.getDatasetMeta(i).data[j].y + 15); } } } } } else { //console.log('onanimation complete', this.chart4, this.chart4.data); for (var i = 0; i < this.chart4.data.datasets.length; i++) { const dataset = this.chart4.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { //console.log(this.chart4.getDatasetMeta(i)); //console.log(i + "," + j, this.chart4.getDatasetMeta(i).data[j]); // var total = this.chart4.getDatasetMeta(i).total; //console.log('total', total); var mid_radius = this.chart4.getDatasetMeta(i).data[j].innerRadius + (this.chart4.getDatasetMeta(i).data[j].outerRadius - this.chart4.getDatasetMeta(i).data[j].innerRadius) / 2; //console.log('mid_radius', mid_radius); var start_angle = this.chart4.getDatasetMeta(i).data[j].startAngle; //console.log('start_angle', start_angle); var end_angle = this.chart4.getDatasetMeta(i).data[j].endAngle; //console.log('end_angle', end_angle); var mid_angle = start_angle + (end_angle - start_angle) / 2; //console.log('mid_angle', mid_angle); var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); this.chart4.ctx.fillStyle = '#fff'; if (i == 3) { // Darker text color for lighter background this.chart4.ctx.fillStyle = '#444'; } // var percent = String(Math.round(dataset.data[j]/total*100)) + "%"; // var str = ""; // for(var k = 0; k <= dataset.data[j].length; k++) { // str += '█'; // } //console.log('outputting bg', str); this.chart4.ctx.fillStyle = '#333'; //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y); //const match = /(?\d+\.?\d*)/; let fillText = ''; if ((this.chart4.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) { this.chart4.ctx.font = "bold 20pt 'Avenir'"; fillText = dataset.data[j] + '✓'; } else { this.chart4.ctx.font = "bold 15pt 'Avenir'"; fillText = dataset.data[j]; } this.chart4.ctx.fillStyle = '#111'; this.chart4.ctx.textBaseline = "middle"; this.chart4.ctx.textAlign = "center"; //console.log('comparing labels', (this.chart4.data.labels[j] + "").toLowerCase().replace(/ /g, "-"), j, this.graphParam, this.chart4.getDatasetMeta(i).data[j]); this.chart4.ctx.fillText(fillText, this.chart4.getDatasetMeta(i).data[j].x + x, this.chart4.getDatasetMeta(i).data[j].y + y); } } } } } if (this.chart4 != null && this.chart4.ctx != null) { this.chart4Base64 = (this.chart4 as Chart).toBase64Image() } } }, scales: { x: { grid: { display: false, drawBorder: false }, ticks: { display: false, }, stacked: true, }, y: { grid: { display: false, drawBorder: false }, ticks: { font: { size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40, }, callback: (val: any, _index: any) => { // Hide every 2nd tick label let value = data.labels[val]; //console.log('callback', this.graphParam); if (this.graphParam.length > 0) { if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) { } else { value = ""; } } else { if (this.isSelectedLegend(val)) { return ""; } } return value; } }, stacked: true, } }, barPercentage: 0.8, barThickness: 10, categoryPercentage: 0.5, plugins: { legend: { display: true, position: "bottom", align: "center", labels: { font: { size: 10, }, boxWidth: 10, boxHeight: 10, }, onClick: () => { } }, title: { display: true, text: title, font: { size: 16, } }, exportBackground: { color: '#ffffff' } }, onClick: (_event: any = {}, array: any) => { // if(array == null) return; // if(array[0] == null) return; // const barIndex = array[0].index; // this.clickOnBar(false, 2, barIndex) // this.clickOnPie(true, barIndex) if (array == null) return; if (array[0] == null) return; const pieIndex = array[0].index; this.clickOnPie(false, pieIndex) if (this.chart2 != null && this.chart4 != null) { this.clickOnBar(true, 2, array[0].index); } }, }, }); //console.log('canvas parent node', this.chart4.canvas.parentNode); this.chart4.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px'; // this.chart4.canvas.parentNode.style.height = '100vh'; } renderChart3 = (ctx: any, type: any, data: any, title: string) => { if (this.chart3 != null) { (this.chart3 as Chart).destroy(); } this.chart3 = new Chart(ctx, { type: type, data: data, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, animation: { duration: 0, onComplete: () => { if (this.chart3 != null && this.chart3.ctx != null) { if (type == 'bar') { this.chart3.ctx.font = "bold 9pt 'Avenir'"; this.chart3.ctx.fillStyle = '#333'; this.chart3.ctx.textBaseline = "middle"; this.chart3.ctx.textAlign = "center"; for (var i = 0; i < this.chart3.data.datasets.length; i++) { const dataset = this.chart3.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { if ((this.chart3.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) { this.chart3.ctx.fillStyle = '#fff'; } else { this.chart3.ctx.fillStyle = '#333'; } let val = 0 if (i > 0) { let tempI = 0 while (tempI < i) { if (parseInt(this.chart3.data.datasets[tempI].data[j]) > 0) { val = val == 0 ? 1 : 0; } tempI++; } } if (j % 2 == val) { this.chart3.ctx.fillText(dataset.data[j], this.chart3.getDatasetMeta(i).data[j].x - 5, this.chart3.getDatasetMeta(i).data[j].y - 15); } else { this.chart3.ctx.fillText(dataset.data[j], this.chart3.getDatasetMeta(i).data[j].x - 5, this.chart3.getDatasetMeta(i).data[j].y + 15); } } } } } else { //console.log('onanimation complete', this.chart3, this.chart3.data); for (var i = 0; i < this.chart3.data.datasets.length; i++) { const dataset = this.chart3.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { //console.log(this.chart3.getDatasetMeta(i)); //console.log(i + "," + j, this.chart3.getDatasetMeta(i).data[j]); // var total = this.chart3.getDatasetMeta(i).total; //console.log('total', total); var mid_radius = this.chart3.getDatasetMeta(i).data[j].innerRadius + (this.chart3.getDatasetMeta(i).data[j].outerRadius - this.chart3.getDatasetMeta(i).data[j].innerRadius) / 2; //console.log('mid_radius', mid_radius); var start_angle = this.chart3.getDatasetMeta(i).data[j].startAngle; //console.log('start_angle', start_angle); var end_angle = this.chart3.getDatasetMeta(i).data[j].endAngle; //console.log('end_angle', end_angle); var mid_angle = start_angle + (end_angle - start_angle) / 2; //console.log('mid_angle', mid_angle); var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); this.chart3.ctx.fillStyle = '#fff'; if (i == 3) { // Darker text color for lighter background this.chart3.ctx.fillStyle = '#444'; } // var percent = String(Math.round(dataset.data[j]/total*100)) + "%"; // var str = ""; // for(var k = 0; k <= dataset.data[j].length; k++) { // str += '█'; // } //console.log('outputting bg', str); this.chart3.ctx.fillStyle = '#333'; //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y); //const match = /(?\d+\.?\d*)/; let fillText = ''; if ((this.chart3.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) { this.chart3.ctx.font = "bold 20pt 'Avenir'"; fillText = dataset.data[j] + '✓'; } else { this.chart3.ctx.font = "bold 15pt 'Avenir'"; fillText = dataset.data[j]; } this.chart3.ctx.fillStyle = '#111'; this.chart3.ctx.textBaseline = "middle"; this.chart3.ctx.textAlign = "center"; //console.log('comparing labels', (this.chart3.data.labels[j] + "").toLowerCase().replace(/ /g, "-"), j, this.graphParam, this.chart3.getDatasetMeta(i).data[j]); this.chart3.ctx.fillText(fillText, this.chart3.getDatasetMeta(i).data[j].x + x, this.chart3.getDatasetMeta(i).data[j].y + y); } } } } } if (this.chart3 != null && this.chart3.ctx != null) { this.chart3Base64 = (this.chart3 as Chart).toBase64Image(); } } }, scales: { x: { grid: { display: false, drawBorder: false }, ticks: { display: false, }, stacked: true, }, y: { grid: { display: false, drawBorder: false }, ticks: { font: { size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40, }, callback: (val: any, _index: any) => { // Hide every 2nd tick label let value = data.labels[val]; //console.log('callback', this.graphParam); if (this.graphParam.length > 0) { if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) { } else { value = ""; } } else { if (this.isSelectedLegend(val)) { return ""; } } return value; } }, stacked: true, } }, barPercentage: 0.8, barThickness: 10, categoryPercentage: 0.5, plugins: { legend: { display: true, position: "bottom", align: "center", labels: { font: { size: 10, }, boxWidth: 10, boxHeight: 10, }, onClick: () => { } }, title: { display: true, text: title, font: { size: 16, } }, exportBackground: { color: '#ffffff' } }, onClick: (_event: any = {}, array: any) => { // if(array == null) return; // if(array[0] == null) return; // const barIndex = array[0].index; // this.clickOnBar(false, 2, barIndex) // this.clickOnPie(true, barIndex) if (array == null) return; if (array[0] == null) return; const pieIndex = array[0].index; this.clickOnPie(false, pieIndex) if (this.chart2 != null && this.chart3 != null) { this.clickOnBar(true, 2, array[0].index); } }, }, }); //console.log('canvas parent node', this.chart3.canvas.parentNode); this.chart3.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px'; // this.chart3.canvas.parentNode.style.height = '100vh'; } renderChart2 = (ctx: any, type: any, data: any, title: string) => { if (this.chart2 != null) { (this.chart2 as Chart).destroy(); } console.log('chart2 context', ctx); this.chart2 = new Chart(ctx, { type: type, data: data, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, animation: { duration: 0, onComplete: () => { if (this.chart2 != null && this.chart2.ctx != null) { if (type == 'bar') { this.chart2.ctx.font = "bold 9pt 'Avenir'"; this.chart2.ctx.fillStyle = '#333'; this.chart2.ctx.textBaseline = "middle"; this.chart2.ctx.textAlign = "center"; // let count = 0 // let arrPos = [[],[]] for (var i = 0; i < this.chart2.data.datasets.length; i++) { const dataset = this.chart2.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { if ((this.chart2.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) { this.chart2.ctx.fillStyle = '#fff'; } else { this.chart2.ctx.fillStyle = '#333'; } let val = 0 if (i > 0) { let tempI = 0 while (tempI < i) { if (parseInt(this.chart2.data.datasets[tempI].data[j]) > 0) { val = val == 0 ? 1 : 0; } tempI++; } } if (j % 2 == val) { this.chart2.ctx.fillText(dataset.data[j], this.chart2.getDatasetMeta(i).data[j].x - 5, this.chart2.getDatasetMeta(i).data[j].y - 15); } else { this.chart2.ctx.fillText(dataset.data[j], this.chart2.getDatasetMeta(i).data[j].x - 5, this.chart2.getDatasetMeta(i).data[j].y + 15); } } } // count ++ } } else { for (var i = 0; i < this.chart2.data.datasets.length; i++) { const dataset = this.chart2.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { var mid_radius = this.chart2.getDatasetMeta(i).data[j].innerRadius + (this.chart2.getDatasetMeta(i).data[j].outerRadius - this.chart2.getDatasetMeta(i).data[j].innerRadius) / 2; var start_angle = this.chart2.getDatasetMeta(i).data[j].startAngle; var end_angle = this.chart2.getDatasetMeta(i).data[j].endAngle; var mid_angle = start_angle + (end_angle - start_angle) / 2; var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); this.chart2.ctx.fillStyle = '#fff'; if (i == 3) { // Darker text color for lighter background this.chart2.ctx.fillStyle = '#444'; } // var percent = String(Math.round(dataset.data[j]/total*100)) + "%"; // var str; // str = ""; // for(var k = 0; k <= dataset.data[j].length; k++) { // str += '█'; // } this.chart2.ctx.fillStyle = '#333'; //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y); //const match = /(?\d+\.?\d*)/; let fillText = ''; if ((this.chart2.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) { this.chart2.ctx.font = "bold 20pt 'Avenir'"; fillText = dataset.data[j] + '✓'; } else { this.chart2.ctx.font = "bold 15pt 'Avenir'"; fillText = dataset.data[j]; } this.chart2.ctx.fillStyle = '#111'; this.chart2.ctx.textBaseline = "middle"; this.chart2.ctx.textAlign = "center"; this.chart2.ctx.fillText(fillText, this.chart2.getDatasetMeta(i).data[j].x + x, this.chart2.getDatasetMeta(i).data[j].y + y); } } } } } if (this.chart2 != null && this.chart2.ctx != null) { this.chart2Base64 = (this.chart2 as Chart).toBase64Image(); } } }, scales: { x: { grid: { display: false, drawBorder: false }, ticks: { display: false, }, stacked: true, }, y: { grid: { display: false, drawBorder: false }, ticks: { font: { size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40, }, callback: (val: any, _index: any) => { // Hide every 2nd tick label let value = data.labels[val]; //console.log('callback', this.graphParam); if (this.graphParam.length > 0) { if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) { } else { value = ""; } } else { if (this.isSelectedLegend(val)) { return ""; } } return value; } }, stacked: true, } }, barPercentage: 0.8, barThickness: 10, categoryPercentage: 0.5, plugins: { legend: { display: true, position: "bottom", align: "center", labels: { font: { size: 10, }, boxWidth: 10, boxHeight: 10, }, onClick: () => { } }, title: { display: true, text: title, font: { size: 16, } }, exportBackground: { color: '#ffffff' } }, onClick: (_event: any = {}, array: any) => { // if(array == null) return; // if(array[0] == null) return; // const barIndex = array[0].index; // this.clickOnBar(false, 2, barIndex) // this.clickOnPie(true, barIndex) if (array == null) return; if (array[0] == null) return; const pieIndex = array[0].index; // const tempGraphParam = this.graphParam //console.log('pie bar trigger 0', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2)); this.clickOnPie(false, pieIndex) //console.log('pie bar trigger 1', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2)); if (this.chart2 != null && this.chart3 != null) { //console.log('pie bar trigger 2', this.graphParam, array[0].index); this.clickOnBar(true, 2, array[0].index); } }, }, }); //console.log('canvas parent node', this.chart2.canvas.parentNode); this.chart2.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px'; // this.chart2.canvas.parentNode.style.height = '100vh'; console.log('this.chart2 rendered', (this.chart2 as Chart)); } renderChart = (ctx: any, type: any, data: any, title: string | string[], flagFullWidth: boolean = true, flagInModal: boolean = false) => { //console.log('rendering chart', this.chart); if (this.chart != null) { //console.log('destroying chart', this.chart); (this.chart as Chart).destroy(); this.chart = null; } this.chart = new Chart(ctx, { type: type, data: data, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, cutout: '95%', animation: { duration: 0, onComplete: () => { if (this.chart != null) { if (type == 'bar') { // this.chart.ctx.font = "bold 10pt Courier"; this.chart.ctx.font = "bold 9pt 'Avenir'"; this.chart.ctx.fillStyle = '#333'; this.chart.ctx.textBaseline = "middle"; this.chart.ctx.textAlign = "center"; for (var i = 0; i < this.chart.data.datasets.length; i++) { const dataset = this.chart.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { //console.log('points', this.chart.getDatasetMeta(i).data[j]); this.chart.ctx.fillText(dataset.data[j], this.chart.getDatasetMeta(i).data[j].x + 15, this.chart.getDatasetMeta(i).data[j].y); } } } } else { //console.log('onanimation complete', this.chart, this.chart.data, this.graphParam); //console.log('onanimation complete', this.graphParam); var rendered = false; for (var i = 0; i < this.chart.data.datasets.length; i++) { const dataset = this.chart.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (parseInt(dataset.data[j]) > 0) { rendered = true; //console.log(this.chart.getDatasetMeta(i)); //console.log(i + "," + j, this.chart.getDatasetMeta(i).data[j]); // var total = this.chart.getDatasetMeta(i).total; //console.log('total', total); var mid_radius = (this.chart.getDatasetMeta(i).data[j].outerRadius - 25); if (j % 2 == 0) { mid_radius = (this.chart.getDatasetMeta(i).data[j].outerRadius + 10); } // var mid_radius = this.chart.getDatasetMeta(i).data[j].innerRadius + ((this.chart.getDatasetMeta(i).data[j].outerRadius - this.chart.getDatasetMeta(i).data[j].innerRadius) * 2) / 3; //console.log('mid_radius', mid_radius); var start_angle = this.chart.getDatasetMeta(i).data[j].startAngle; //console.log('start_angle', start_angle); var end_angle = this.chart.getDatasetMeta(i).data[j].endAngle; //console.log('end_angle', end_angle); var mid_angle = start_angle + (end_angle - start_angle) / 2; //console.log('mid_angle', mid_angle); var x = mid_radius * Math.cos(mid_angle); var y = mid_radius * Math.sin(mid_angle); this.chart.ctx.fillStyle = '#fff'; if (i == 3) { // Darker text color for lighter background this.chart.ctx.fillStyle = '#444'; } // var percent = String(Math.round(dataset.data[j]/total*100)) + "%"; // var str = ""; // for(var k = 0; k <= dataset.data[j].length; k++) { // str += '█'; // } //console.log('outputting bg', str); this.chart.ctx.fillStyle = '#333'; //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y); //const match = /(?\d+\.?\d*)/; let fillText = ''; let replaceText = ' '; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) { replaceText = '-'; } this.chart.ctx.fillStyle = '#111'; if ((this.chart.data.labels[j] + "").toLowerCase().replace(/ /g, replaceText) == this.graphParam) { // this.chart.ctx.font = "bold 20pt 'Source Sans Pro'"; this.chart.ctx.font = "bold 20pt 'Avenir'"; if (this.isSelectedLegend(j)) { fillText = ''; } else { this.chart.ctx.fillStyle = '#111'; fillText = dataset.data[j] + '✓'; } } else { // this.chart.ctx.font = "bold 8pt 'Source Sans Pro'"; this.chart.ctx.font = "bold 9pt 'Avenir'"; if (this.isSelectedLegend(j)) { fillText = ''; } else { this.chart.ctx.fillStyle = '#333'; // this.chart.ctx.fillStyle = '#fff'; fillText = dataset.data[j]; } } this.chart.ctx.textBaseline = "middle"; this.chart.ctx.textAlign = "center"; this.chart.ctx.fillText(fillText, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y); } } } if (!rendered) { const { chartArea: { left, top, right, bottom }, ctx } = this.chart; const centerX = (left + right) / 2; const centerY = (top + bottom) / 2; ctx.font = "15pt Arial"; ctx.fillStyle = '#666'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('No data to display', centerX, centerY); } } } if (this.chart != null) { this.chartBase64 = (this.chart as Chart).toBase64Image(); } } }, scales: { x: { grid: { display: false, drawBorder: false }, ticks: { display: false, }, stacked: true, }, y: { grid: { display: false, drawBorder: false }, ticks: { display: type == 'bar' ? true : false, font: { size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40, } }, stacked: true, } }, barPercentage: 0.8, barThickness: 10, categoryPercentage: 0.5, plugins: { legend: { display: type !== "bar", position: "bottom", align: "center", labels: { font: { size: 10, }, boxWidth: 10, boxHeight: 10, generateLabels: (chart: any) => chart.data.labels.map((l: any, i: any) => ({ datasetIndex: i, index: i, text: l, fillStyle: chart.data.datasets[0].backgroundColor[i], strokeStyle: chart.data.datasets[0].backgroundColor[i], hidden: chart.getDatasetMeta(0).data[i].hidden })) }, onClick: (_evt: any, legendItem: any, _legend: any) => { if (this.graphParam.length > 0) { this.clearSelectedGraphParam(); } // //console.log('index clicked', legendItem.index, this.chart.legend.legendItems[legendItem.index]); this.processClickOnLegend(legendItem.index, legendItem); } }, title: { display: true, text: title, font: { size: Array.isArray(title) ? 14 : 16, lineHeight: 1.5 }, padding: { bottom: 20 } }, exportBackground: { color: '#ffffff' } }, onClick: (_event: any, array: any) => { console.log('chartclick', array[0]); if (array == null) return; if (array[0] == null) return; const pieIndex = array[0].index; // const tempGraphParam = this.graphParam //console.log('pie bar trigger 0', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2)); this.clickOnPie(false, pieIndex) //console.log('pie bar trigger 1', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2)); if (this.chart2 != null && this.chart3 != null) { //console.log('pie bar trigger 2', this.graphParam, array[0].index); this.clickOnBar(true, 2, array[0].index); } } }, }); console.log('chartData', data); let chartHeight = '480px' if (flagFullWidth && flagInModal) { chartHeight = '100vh' } this.chart.canvas.parentNode.style.height = (type === 'bar') ? ((parseInt(data.labels.length) * 90 + 40) + 'px') : chartHeight; // if (type !== 'bar' && flagFullWidth) { // this.chart.canvas.parentNode.style.width = '100vh' // } this.chart.canvas.parentNode.style.width = chartHeight // this.chart.canvas.parentNode.style.height = '100vh' } copy = (aObject: any) => { // Prevent undefined objects // if (!aObject) return aObject; let bObject: any = Array.isArray(aObject) ? [] : {}; let value; for (const key in aObject) { // Prevent self-references to parent object // if (Object.is(aObject[key], aObject)) continue; value = aObject[key]; bObject[key] = (typeof value === "object") ? this.copy(value) : value; } return bObject; } processGraphHide = (clickedValue: string, hide: boolean) => { //console.log('processGraphHide', clickedValue, hide, this.selectedFilter); let eventContainer = null; if (this.getCurrentTab() == this.TAB_STREAM) { eventContainer = (this._SfStreamContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_UPCOMING) { eventContainer = (this._SfUpcomingContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_THIS) { eventContainer = (this._SfThisContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_PAST) { eventContainer = (this._SfPastContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_CUSTOM) { eventContainer = (this._SfCustomContainer as HTMLDivElement); } const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf; const eventTitles = eventContainer!.querySelectorAll('.stream-events-event-title') as NodeListOf; const eventSubTitles = eventContainer!.querySelectorAll('.stream-events-event-subtitle') as NodeListOf; const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf; const graphparamnames1 = eventContainer!.querySelectorAll('.graphparamname1') as NodeListOf; const graphparamnames2 = eventContainer!.querySelectorAll('.graphparamname2') as NodeListOf; const graphparamnames3 = eventContainer!.querySelectorAll('.graphparamname3') as NodeListOf; const eventUserLabelsContainers = eventContainer!.querySelectorAll('.event-user-labels-container') as NodeListOf; const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement; const streamEventFilters = eventContainer!.querySelector('#stream-event-filter') as HTMLDivElement; const buttonListReporting = eventContainer!.querySelector('.button-list-reporting') as HTMLButtonElement; if (hide) { //this.graphParam = clickedValue; streamEventSummary.style.display = 'none'; //console.log('selectedfilter', this.selectedFilter); if (this.selectedFilters == null) { this.selectedFilters = []; } this.selectedFilters.push({ selected: false, value: clickedValue }); var filterString = ""; for (var j = 0; j < this.selectedFilters.length; j++) { filterString += this.selectedFilters[j].value; if (j < (this.selectedFilters.length - 1)) { filterString += ','; } } (streamEventFilters as HTMLDivElement).style.display = 'block'; (streamEventFilters as HTMLDivElement).innerHTML = '
Filtered by  excluding ' + filterString + '
'; console.log('processGraphHide called'); (streamEventFilters as HTMLDivElement).querySelector('#button-filter-cancel')?.addEventListener('click', () => { this.clearSelectedLegend(); this.clearSelectedGraphParam(); }); } else { streamEventSummary.style.display = 'flex'; this.selectedFilters = null; (streamEventFilters as HTMLDivElement).style.display = 'none'; (streamEventFilters as HTMLDivElement).innerHTML = ''; } //console.log('selectedfilter', this.selectedFilter); for (var i = 0; i < divs.length; i++) { if (!hide) { if (tables[i] != null) { (tables[i] as HTMLDivElement).style.display = 'block'; (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'flex'; //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block'; (graphparamnames1[i] as HTMLDivElement).style.display = 'block'; if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'block'; if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'block'; if (eventSubTitles[i] != null) { (eventSubTitles[i] as HTMLDivElement).style.display = 'flex'; } buttonListReporting.style.display = "block"; } (eventTitles[i] as HTMLDivElement).style.display = 'flex'; } else { var found = false; if (this.selectedFilters != null) { for (var j = 0; j < this.selectedFilters.length; j++) { // if((graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&', '&').indexOf(this.selectedFilter[j].value) >= 0) { if ((graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&', '&').replace(/-/g, ' ') == this.selectedFilters[j].value.toLowerCase().replace('&', '&').replace(/-/g, ' ')) { found = true; break; } } } if (found) { if (tables[i] != null) { (tables[i] as HTMLDivElement).style.display = 'none'; (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'none'; //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none'; (graphparamnames1[i] as HTMLDivElement).style.display = 'none'; if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'none'; if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'none'; if (eventSubTitles[i] != null) { (eventSubTitles[i] as HTMLDivElement).style.display = 'none'; } buttonListReporting.style.display = 'none'; } (eventTitles[i] as HTMLDivElement).style.display = 'none'; } } let listReportingContainers = eventContainer!.querySelectorAll('.list-reporting-container') as NodeListOf for (let tempReportingContainer of listReportingContainers) { tempReportingContainer.style.display = 'none'; tempReportingContainer.innerHTML = ''; } let buttonListReportings = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReporting of buttonListReportings) { buttonListReporting.setAttribute('part', 'button-list-reporting') } let streamEventTitles = eventContainer!.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { streamEventTitle.removeAttribute('part') } // var found = false; // if(this.selectedFilter != null) { // for(var j = 0; j < this.selectedFilter.length; j++) { // if((graphparamnames[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&', '&').indexOf(this.selectedFilter[j].value) >= 0) { // found = true; // break; // } // } // } // if(found) { // if(hide) { // (tables[i] as HTMLDivElement).style.display = 'none'; // //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none'; // (graphparamnames[i] as HTMLDivElement).style.display = 'none'; // (eventTitles[i] as HTMLDivElement).style.display = 'none'; // } else { // (tables[i] as HTMLDivElement).style.display = 'block'; // //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block'; // (graphparamnames[i] as HTMLDivElement).style.display = 'block'; // (eventTitles[i] as HTMLDivElement).style.display = 'flex'; // } // } } } processGraphFilter = (clickedValue: string, detailsListContainer?: HTMLDivElement) => { let eventContainer = detailsListContainer; if (eventContainer == null) { console.log('processGraphFilter called', clickedValue); if (this.getCurrentTab() == this.TAB_STREAM) { eventContainer = (this._SfStreamContainer as HTMLDivElement); } // if(this.getCurrentTab() == this.TAB_UPCOMING) { // eventContainer = (this._SfUpcomingContainer as HTMLDivElement); // } if (this.getCurrentTab() == this.TAB_THIS) { eventContainer = (this._SfThisContainer as HTMLDivElement); } // if(this.getCurrentTab() == this.TAB_PAST) { // eventContainer = (this._SfPastContainer as HTMLDivElement); // } if (this.getCurrentTab() == this.TAB_CUSTOM) { eventContainer = (this._SfCustomContainer as HTMLDivElement); } if (this.getCurrentTab() == this.TAB_FIND) { eventContainer = (this._SfFindContainer as HTMLDivElement); } } if (eventContainer == null) return; this.graphFilter = clickedValue this.selectedItemIds = []; const buttonSelect = eventContainer!.querySelectorAll('.button-select') as NodeListOf; // for(let checkSelect of buttonSelect){ // checkSelect.checked = false // } const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf; const eventTitles = eventContainer!.querySelectorAll('.stream-events-event-title') as NodeListOf; const eventSubTitles = eventContainer!.querySelectorAll('.stream-events-event-subtitle') as NodeListOf; const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf; const graphparamnames1 = eventContainer!.querySelectorAll('.graphparamname1') as NodeListOf; const graphparamnames2 = eventContainer!.querySelectorAll('.graphparamname2') as NodeListOf; const graphparamnames3 = eventContainer!.querySelectorAll('.graphparamname3') as NodeListOf; const eventUserLabelsContainers = eventContainer!.querySelectorAll('.event-user-labels-container') as NodeListOf; const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement; const streamEventFilters = eventContainer!.querySelector('#stream-event-filter') as HTMLDivElement; const buttonListReporting = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf; if (streamEventSummary == null) { return; } console.log('recentlyReported', this.recentlyReported); if (this.graphParam == clickedValue) { this.graphParam = ""; streamEventSummary.style.display = 'flex'; this.selectedFilters = null; (streamEventFilters as HTMLDivElement).style.display = 'none'; (streamEventFilters as HTMLDivElement).innerHTML = ''; } else { this.graphParam = clickedValue; streamEventSummary.style.display = 'none'; this.selectedFilters = { selected: true, value: clickedValue }; (streamEventFilters as HTMLDivElement).style.display = 'block'; (streamEventFilters as HTMLDivElement).innerHTML = '
Filtered by  ' + clickedValue + '
' + (detailsListContainer == null ? '' : '') + '
'; (streamEventFilters as HTMLDivElement).querySelector('#button-filter-cancel')?.addEventListener('click', () => { this.graphFilter = ""; this.clearSelectedGraphParam(); }); setTimeout(() => { this.recentlyReported = {} }, 10000); } for (var i = 0; i < divs.length; i++) { // console.log('processGraphFilter', graphparamnames1[i], (graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&', '&').replace(/-/g, ' '), this.graphParam.toLowerCase().replace('&', '&').replace(/-/g, ' ')); if (graphparamnames1[i] == null) { continue; } let graphparamname1Arr = (graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&', '&').replace(/-/g, ' ').split(' • '); let filterFound = false; for (let tempFilterStr of graphparamname1Arr) { // console.log('graphparamname1Arr', tempFilterStr, this.graphParam.toLowerCase().replace('&', '&').replace(/-/g, ' '), tempFilterStr == this.graphParam.toLowerCase().replace('&', '&').replace(/-/g, ' ')); if (tempFilterStr == this.graphParam.toLowerCase().replace('&', '&').replace(/-/g, ' ') || this.graphParam.toLowerCase().replace('&', '&').replace(/-/g, ' ') == "") { filterFound = true; break; } } if (buttonSelect[i] != null) { buttonSelect[i].checked = false let selectid = buttonSelect[i].id let selectidArr = selectid.split('-') let selectMmdd = selectidArr[2] + '/' + selectidArr[3] let selectEntityid = selectidArr[7].replace(/_/g, '-') let selectLocationid = selectidArr[8].replace(/_/g, '-') let selectEventid = selectidArr[9].replace(/_/g, '-') if (this.recentlyReported[selectMmdd] != null) { for (let recentlyReportedEvent of this.recentlyReported[selectMmdd]) { if (recentlyReportedEvent.id == selectEventid && recentlyReportedEvent.locationid == selectLocationid && recentlyReportedEvent.entityid == selectEntityid) { filterFound = true; break; } } } } if (filterFound) { if (tables[i] != null) { (tables[i] as HTMLDivElement).style.display = 'block'; (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'flex'; //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block'; (graphparamnames1[i] as HTMLDivElement).style.display = 'block'; if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'block'; if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'block'; if (eventSubTitles[i] != null) { (eventSubTitles[i] as HTMLDivElement).style.display = 'flex'; } if (buttonListReporting[i] != null && buttonListReporting[i].id.indexOf('-reportedlocations') < 0) { buttonListReporting[i].style.display = 'block'; } } if (buttonSelect[i] != null && buttonSelect[i].id.indexOf('-bulk') < 0 && buttonSelect[i].id.indexOf('-reportformat') < 0 && buttonSelect[i].id.indexOf('-reportedlocations') < 0) buttonSelect[i].style.display = "flex" if (eventTitles[i] != null) (eventTitles[i]).style.display = 'flex'; divs[i].style.display = 'block' } else { if (tables[i] != null) { (tables[i] as HTMLDivElement).style.display = 'none'; (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'none'; //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none'; (graphparamnames1[i] as HTMLDivElement).style.display = 'none'; if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'none'; if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'none'; if (eventSubTitles[i] != null) { (eventSubTitles[i] as HTMLDivElement).style.display = 'none'; } if (buttonListReporting[i] != null) { buttonListReporting[i].style.display = 'none'; } } // console.log('eventTitle', divs[i]); if (buttonSelect[i] != null) buttonSelect[i].style.display = "none" if (eventTitles[i] != null) (eventTitles[i]).style.display = 'none'; if (divs[i] != null) divs[i].style.display = 'none' } } let listReportingContainers = eventContainer!.querySelectorAll('.list-reporting-container') as NodeListOf for (let tempReportingContainer of listReportingContainers) { tempReportingContainer.style.display = 'none'; tempReportingContainer.innerHTML = ''; } let buttonListReportings = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReporting of buttonListReportings) { buttonListReporting.setAttribute('part', 'button-list-reporting') } let streamEventTitles = eventContainer!.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { streamEventTitle.removeAttribute('part') } } processClickOnLegend = (index: number, legendItem: any) => { legendItem.hidden = true; const ci = this.chart; if (this.chart.legend.chart.data.datasets != null) { this.chart.legend.chart.data.datasets[0].data.forEach((_d: any, i: any) => { if (index === i) { let opHide = true; //console.log('dataset-found before before', this.isSelectedLegend(i), legendItem, this.chartSelectedLegend); if (!this.isSelectedLegend(i)) { //this.clearSelectedLegend(); opHide = true; this.chart.legend.chart.getDatasetMeta(0).data[index].hidden = true; this.chartSelectedLegend.push(index); ci.update(); } else { opHide = false; for (var j = 0; j < this.chartSelectedLegend.length; j++) { this.chart.legend.chart.getDatasetMeta(0).data[this.chartSelectedLegend[j]].hidden = false; } this.removeFromSelectedLegend(index) ci.update(); } this.clickOnLegend(this.isSelectedLegend(i), legendItem.text); if (this.chart2 != null && this.chart3 != null) { if (opHide) { // if(this.barCharDataSet2Arr.length > 0) { // this.chart2.data.datasets = this.barCharDataSet2Arr.pop(); // } // if(this.barCharDataSet3Arr.length > 0) { // this.chart3.data.datasets = this.barCharDataSet3Arr.pop(); // } // this.barCharDataSet2Arr.push({index: index, value: this.copy(this.chart2.data.datasets)}); // this.barCharDataSet3Arr.push({index: index, value: this.copy(this.chart3.data.datasets)}); this.barCharDataSet2Arr.push(this.copy(this.chart2.data.datasets)); this.barCharDataSet3Arr.push(this.copy(this.chart3.data.datasets)); for (var k = 0; k < this.chart2.data.datasets.length; k++) { const dataset = this.chart2.data.datasets[k]; for (var j = 0; j < dataset.data.length; j++) { if (j === index) { dataset.data[j] = 0; } else { } } } for (var k = 0; k < this.chart3.data.datasets.length; k++) { const dataset = this.chart3.data.datasets[k]; for (var j = 0; j < dataset.data.length; j++) { if (j === index) { dataset.data[j] = 0; } else { } } } //console.log('dataset-found before', this.barCharDataSet3Arr); } else { do { this.chart2.data.datasets = this.barCharDataSet2Arr.pop(); this.chart3.data.datasets = this.barCharDataSet3Arr.pop(); } while (this.barCharDataSet2Arr.length > 0); this.chartSelectedLegend = []; } this.chart2.update(); this.chart3.update(); } ////console.log('modified datasets', this.chart2.data.datasets); //console.log('dataset-found after', this.chartSelectedLegend); } }) } } clickOnLegend = (hide: boolean, label: string) => { //console.log(hide, label); let labelClicked = ''; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) { labelClicked = (label).toLowerCase().replace(/ /g, "-").replace('status-', ''); } else { labelClicked = (label).toLowerCase(); } this.processGraphHide(labelClicked, hide); } clickOnPie = (callingFromBar: boolean, pieIndex: number) => { //console.log('pie bar trigger 1 0', JSON.stringify(this.barCharDataSet2)); //console.log('pieIndex', pieIndex); if (this.barCharDataSet2Arr.length > 0) { this.clearSelectedLegend(); } //console.log('pie bar trigger 1 1', JSON.stringify(this.barCharDataSet2)); let labelClicked = ''; if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) { labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase().replace(/ /g, "-").replace('status-', ''); } else { labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase(); } console.log('pieIndex', labelClicked); if (!callingFromBar) { console.log('pieIndex', labelClicked); console.log('calling processGraphFilter 2') this.processGraphFilter(labelClicked); } } clickOnBar = (callingFromPie: boolean, graphNumber: number, barIndex: number) => { let labelClicked = ''; if (graphNumber === 2 || graphNumber === 3 || graphNumber === 4) { if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) { labelClicked = (this.chart2.data.labels[barIndex].join(" ") + "").toLowerCase().replace(/ /g, "-").replace('status-', ''); } else { labelClicked = (this.chart2.data.labels[barIndex].join(" ") + "").toLowerCase(); } } if (!callingFromPie) { console.log('calling processGraphFilter 3') this.processGraphFilter(labelClicked); } //console.log('clickonbar trigger', this.graphParam, '><', this.barCharDataSet2); if (this.graphParam.length > 0) { if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) { this.chart2.data.datasets = this.barCharDataSet2.pop(); this.chart3.data.datasets = this.barCharDataSet3.pop(); this.chart4.data.datasets = this.barCharDataSet4.pop(); } this.barCharDataSet2.push(this.copy(this.chart2.data.datasets)); for (var i = 0; i < this.chart2.data.datasets.length; i++) { const dataset = this.chart2.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (j === barIndex) { } else { dataset.data[j] = 0; } } } this.barCharDataSet3.push(this.copy(this.chart3.data.datasets)); for (var i = 0; i < this.chart3.data.datasets.length; i++) { const dataset = this.chart3.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (j === barIndex) { } else { dataset.data[j] = 0; } } } this.barCharDataSet4.push(this.copy(this.chart4.data.datasets)); for (var i = 0; i < this.chart4.data.datasets.length; i++) { const dataset = this.chart4.data.datasets[i]; for (var j = 0; j < dataset.data.length; j++) { if (j === barIndex) { } else { dataset.data[j] = 0; } } } //console.log('clickonbar trigger latest values', this.chart2.data.datasets); //console.log('clickonbar trigger in storage', this.barCharDataSet2); } else { this.chart2.data.datasets = this.barCharDataSet2.pop(); this.chart3.data.datasets = this.barCharDataSet3.pop(); this.chart4.data.datasets = this.barCharDataSet4.pop(); } //console.log(this.chart2.data); this.chart2.update(); this.chart3.update(); this.chart4.update(); } getCurrentTab = () => { if (this.mode == "next") { return; } if ((this._SfCalendarContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_YEAR; } if ((this._SfStreamContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_STREAM; } if ((this._SfUpcomingContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_UPCOMING; } if ((this._SfThisContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_THIS; } if ((this._SfPastContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_PAST; } if ((this._SfCustomContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_CUSTOM; } if ((this._SfFindContainer as HTMLDivElement).style.display == 'flex') { return this.TAB_FIND; } return ""; } renderTabs = (selectedTab: string) => { this.selectedTab = selectedTab; this.clearAllCalendars(); this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; var html = ''; html += ''; html += ''; if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0) { html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; } // html += ''; // html += ''; (this._SfTabContainer as HTMLDivElement).innerHTML = html; (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-next')?.addEventListener('click', async (e: any) => { const buttons = (this._SfTabContainer as HTMLDivElement).querySelectorAll('.tab-button-secondary') as NodeListOf; buttons.forEach(button => { button.style.display = 'block'; }); const button = (e.currentTarget as HTMLButtonElement); button.style.display = 'none'; }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-year')?.addEventListener('click', async () => { //console.log('calclicked', this.mode); if (this.mode == "consumer") { this.renderTabs(this.TAB_YEAR); this.enableCalendar(); await this.fetchAndYearlyRenderUserCalendar_2(); //this.renderCalendar(); // this.loadMode(); } else { this.enableCalendar(); this.renderTabs(this.TAB_YEAR); } }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month')?.addEventListener('click', async () => { this.enableStream(); this.renderTabs(this.TAB_STREAM); const currMonth = ("0" + (new Date().getMonth() + 1)).slice(-2); //console.log('currMonth', currMonth); let idx = 0; for (var i = 0; i < 12; i++) { //console.log('currMonth compare', currMonth, (parseInt(this.calendarStartMM) + i)%12); if ((parseInt(currMonth) === 12 && (parseInt(this.calendarStartMM) + i) % 12 === 0) || parseInt(currMonth) === (parseInt(this.calendarStartMM) + i) % 12) { idx = i; break; } } this.currentColumnIndex = idx + ""; const dateResult = this.calculateStartAndEndDateOfStream(idx); const monthResult = this.calculateMonthFromIndex(idx); if (dateResult != null) { await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2)); } this.renderStream(idx, true, false); }); // (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-upcoming')?.addEventListener('click', async () => { // this.enableUpcoming(); // this.renderTabs(this.TAB_UPCOMING); // const dateResult = this.calculateStartAndEndDateOfUpcoming(1); // //console.log('dateresult', dateResult) // this.currentColumnIndex = 1 + "" // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); // this.renderUpcoming(); // }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-this')?.addEventListener('click', async () => { this.enableThis(); this.renderTabs(this.TAB_THIS); const dateResult = this.calculateStartAndEndDateOfThis(1); let idx = 0; const currMonth = ("0" + (new Date().getMonth() + 1)).slice(-2); for (var i = 0; i < 12; i++) { //console.log('currMonth compare', currMonth, (parseInt(this.calendarStartMM) + i)%12); if ((parseInt(currMonth) === 12 && (parseInt(this.calendarStartMM) + i) % 12 === 0) || parseInt(currMonth) === (parseInt(this.calendarStartMM) + i) % 12) { idx = i; break; } } const monthResult = this.calculateMonthFromIndex(idx); //console.log('dateresult', dateResult) this.currentColumnIndex = 1 + "" await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2)); this.renderThis(0, true, false); }); // (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-past')?.addEventListener('click', async () => { // this.enablePast(); // this.renderTabs(this.TAB_PAST); // const dateResult = this.calculateStartAndEndDateOfPast(1); // //console.log('dateresult', dateResult) // this.currentColumnIndex = 1 + "" // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate); // this.renderPast(); // }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom')?.addEventListener('click', () => { this.enableCustom(); this.renderTabs(this.TAB_CUSTOM); console.log('stats clicked'); if (this.myRole == this.TAB_VIEWER) { this.renderCustomViewer() } else { this.renderCustom(); } }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-find')?.addEventListener('click', () => { this.enableFind(); this.renderTabs(this.TAB_FIND); this.renderFind(); }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-adhoc')?.addEventListener('click', () => { this.enableAdhoc(); this.renderTabs(this.TAB_ADHOC); this.renderAdhoc(); }); (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-register')?.addEventListener('click', () => { this.enableRegisters(); this.renderTabs(this.TAB_REGISTERS); this.renderRegister(); }); } renderMappingTabs = (selectedTab: string) => { var html = ''; html += ''; html += ''; (this._SfMappingTabContainer as HTMLDivElement).innerHTML = html; if (this.myRole == this.TAB_REPORTER) { //console.log('sync mapping reporter'); (this._SfButtonBackSyncMapping as HTMLButtonElement).style.visibility = 'visible'; } else { //console.log('sync mapping approver'); (this._SfButtonBackSyncMapping as HTMLButtonElement).style.visibility = 'hidden'; } (this._SfMappingTabContainer as HTMLDivElement).querySelector('#mapping-tab-reporter')?.addEventListener('click', () => { this.myRole = this.TAB_REPORTER; this.fetchEventMap(); this.renderMappingTabs(this.TAB_REPORTER) }); (this._SfMappingTabContainer as HTMLDivElement).querySelector('#mapping-tab-approver')?.addEventListener('click', () => { this.myRole = this.TAB_APPROVER; this.fetchEventMap(); this.renderMappingTabs(this.TAB_APPROVER) }); } renderExpandEvent = (events: any, index: any) => { var html = ''; for (var k = 0; k < Object.keys(events[index]).length; k++) { if (!this.getEventPreviewFields().includes(Object.keys(events[index])[k])) { html += ''; if (events[index][Object.keys(events[index])[k]].indexOf("[") >= 0) { html += this.getEventTexts(Object.keys(events[index])[k], JSON.parse(events[index][Object.keys(events[index])[k]]), events[index]); } else { html += ''; } html += ''; } } //console.log((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-'+index)!.innerHTML); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-' + index)!.insertAdjacentHTML('beforeend', html); html = ''; for (var k = 0; k < Object.keys(events[index]).length; k++) { if (!this.getEventPreviewFields().includes(Object.keys(events[index])[k])) { html += ''; html += Object.keys(events[index])[k]; html += ''; } } (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-head-' + index)!.insertAdjacentHTML('beforeend', html); ((this._SfMappingContainer as HTMLDivElement).querySelector('#th-expand-' + index) as HTMLElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#td-expand-' + index) as HTMLElement).style.display = 'none'; } renderMapping = (unmappedEvents: any) => { this.mappedValuesDueDates = {}; this.mappedValuesTags = {}; this.mappedValuesUsers = {}; //console.log('rendering mapping1', unmappedEvents, this.mappedValuesDueDates, this.mappedValuesUsers, this.mappedValuesTags) var html = ''; html += '
'; html += '
'; html += '
Completed 0
'; html += '
'; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += '
'; html += 'Duedate'; html += ''; html += 'Tags'; html += ''; html += 'Users'; html += ''; html += ''; html += '
'; html += ''; html += ''; html += ''; //html += ''; html += ''; html += ''; //html += ''; html += ''; html += '
'; html += '
'; html += '
Filter
'; html += '
' html += '
' html += '
' html += '
' html += '
'; for (var i = 0; i < unmappedEvents.length; i++) { // var moveOn = false; // if(filter != "all") { // if(filter == "mapped") { // if(this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") { // moveOn = true; // } // } // if(filter == "unmapped") { // if(this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") { // moveOn = true; // } // } // } // if(moveOn) { // continue; // } //console.log(unmappedEvents[i]); html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; for (var k = 0; k < Object.keys(unmappedEvents[i]).length; k++) { if (this.getEventPreviewFields().includes(Object.keys(unmappedEvents[i])[k])) { html += ''; } } html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; html += ''; for (var k = 0; k < Object.keys(unmappedEvents[i]).length; k++) { if (this.getEventPreviewFields().includes(Object.keys(unmappedEvents[i])[k])) { html += ''; } } html += ''; html += ''; html += ''; html += '
'; html += 'Select'; html += ''; html += 'Status'; html += ''; html += 'Duedate'; html += ''; html += 'Tags'; html += ''; html += 'Users'; html += ''; html += Object.keys(unmappedEvents[i])[k]; html += ''; html += '
'; html += '' html += ''; html += '' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? 'check_circle' : 'pending') + ''; html += ''; html += '
'; html += ''; html += '
' + ((this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : '') + '
'; html += '
'; html += '
'; html += ''; //html += ''; html += '
' + ((this.mappedValuesTags[i] != null && this.mappedValuesTags[i] != "") ? this.mappedValuesTags[i] : '') + '
'; html += '
'; html += ''; //html += ''; html += '
' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? this.mappedValuesUsers[i] : '') + '
'; html += '
'; if (unmappedEvents[i][Object.keys(unmappedEvents[i])[k]].indexOf("[") >= 0) { html += this.getEventTexts(Object.keys(unmappedEvents[i])[k], JSON.parse(unmappedEvents[i][Object.keys(unmappedEvents[i])[k]]), unmappedEvents[i]); } else { html += ' '; } html += ''; html += '' html += '
'; } html += '
'; html += ''; (this._SfMappingContainer as HTMLDivElement).innerHTML = html; for (var i = 0; i < unmappedEvents.length; i++) { // var moveOn = false; // if(filter != "all") { // if(filter == "mapped") { // if(this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") { // moveOn = true; // } // } // if(filter == "unmapped") { // if(this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") { // moveOn = true; // } // } // } // if(moveOn) { // continue; // } (this._SfMappingContainer as HTMLDivElement).querySelector('#button-unmapped-expand-' + i)?.addEventListener('click', (ev: any) => { const clickIndex = ev.target.id.split("-")[3]; //console.log('clickindex', clickIndex) this.renderExpandEvent(unmappedEvents, clickIndex); }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-select-' + i) as HTMLInputElement).addEventListener('change', (ev: any) => { const clickIndex = ev.target.id.split("-")[3]; //console.log('clickcheckbox', clickIndex) if (((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-select-' + clickIndex) as HTMLInputElement).checked) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement).style.display = 'block'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLInputElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as HTMLInputElement).style.display = 'block'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLInputElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as HTMLInputElement).style.display = 'block'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLInputElement).style.display = 'none'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLInputElement).style.display = 'block'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as HTMLInputElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLInputElement).style.display = 'block'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as HTMLInputElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLInputElement).style.display = 'block'; } if (this.checkAndShowBulk()) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'flex'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'none'; } }); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + i)?.addEventListener('keyup', (ev: any) => { const clickIndex = ev.target.id.split("-")[5]; const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLDivElement); const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement); div.innerHTML = input.value; this.mappedValuesDueDates[clickIndex] = input.value; }); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + i)?.addEventListener('valueChanged', (ev: any) => { const clickIndex = ev.target.id.split("-")[4]; const form = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as SfIForm); const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLDivElement); div.innerHTML = ''; var html = ''; for (var i = 0; i < form.selectedValues().length; i++) { html += form.selectedValues()[i]; if (i < (form.selectedValues().length - 1)) { html += ","; } } div.innerHTML = ''; this.mappedValuesTags[clickIndex] = form.selectedValues(); // const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-'+clickIndex) as HTMLDivElement); // const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-'+clickIndex) as HTMLInputElement); // div.innerHTML = input.value; }); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + i)?.addEventListener('valueChanged', (ev: any) => { const clickIndex = ev.target.id.split("-")[4]; const form = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as SfIForm); //console.log('valuechanged called', form.selectedValues()); const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLDivElement); div.innerHTML = ''; var html = ''; for (var i = 0; i < form.selectedValues().length; i++) { html += form.selectedValues()[i]; if (i < (form.selectedValues().length - 1)) { html += ","; } } div.innerHTML = ''; this.mappedValuesUsers[clickIndex] = form.selectedValues(); this.updateMappingStatus(form.selectedValues(), clickIndex); this.calculateAndShowSummary(); }); } (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-users')?.addEventListener('valueChanged', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-users') as SfIForm); //console.log('valuechanged users', input.selectedValues()); this.updateInAllSelections("users", input.selectedValues()); }); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-date')?.addEventListener('keyup', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-date') as HTMLInputElement); this.updateInAllSelections("duedate", input.value) }); (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-tags')?.addEventListener('valueChanged', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-tags') as SfIForm); this.updateInAllSelections("tags", input.selectedValues()); }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement).addEventListener('change', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement); if (input.checked) { this.showAllEvents(); } }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement).addEventListener('change', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement); if (input.checked) { this.showMappedEvents(); } }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement).addEventListener('change', () => { const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement); if (input.checked) { this.showUnmappedEvents(); } }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry-cancel') as HTMLInputElement).addEventListener('click', () => { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'none'; this.clearAllMappingSelections(); }); ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.addEventListener('click', async () => { this.uploadMapping(); }); } applyFilter = (filter: string = "all") => { for (var i = 0; i < this.unmappedEvents.length; i++) { if (filter == "mapped") { if (this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'none'; } } if (filter == "unmapped") { if (this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'none'; } } if (filter == "all") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block'; } if (this.myRole == this.TAB_APPROVER) { ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf)[0].style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf)[1].style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-' + i) as HTMLElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-head-' + i) as HTMLElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf)[0].style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf)[1].style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-' + i) as HTMLElement).style.display = 'none'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-head-' + i) as HTMLElement).style.display = 'none'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf)[0].style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf)[1].style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-' + i) as HTMLElement).style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-head-' + i) as HTMLElement).style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf)[0].style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf)[1].style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-' + i) as HTMLElement).style.display = 'table-cell'; ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-head-' + i) as HTMLElement).style.display = 'table-cell'; } } if (filter == "all") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement).checked = true; } if (filter == "mapped") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement).checked = true; } if (filter == "unmapped") { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement).checked = true; } } getIndexFromId = (id: string) => { for (var i = 0; i < this.unmappedEvents.length; i++) { if (this.unmappedEvents[i].id == id) { return i; } } return -1; } prepopulateMapping = (mappings: any) => { //console.log('mappings5', mappings, this.mappedValuesUsers); if (mappings == null) { return; } for (var i = 0; i < Object.keys(mappings.duedates).length; i++) { const eventId = Object.keys(mappings.duedates)[i]; const index = this.getIndexFromId(eventId); if (index >= 0) { this.mappedValuesDueDates[index] = mappings.duedates[eventId]; } } for (var i = 0; i < Object.keys(mappings.tags).length; i++) { const eventId = Object.keys(mappings.tags)[i]; const index = this.getIndexFromId(eventId); if (index >= 0) { this.mappedValuesTags[index] = mappings.tags[eventId]; } } for (var i = 0; i < Object.keys(mappings.users).length; i++) { const eventId = Object.keys(mappings.users)[i]; const index = this.getIndexFromId(eventId); //console.log('mapping users', index); if (index >= 0) { this.mappedValuesUsers[index] = mappings.users[eventId]; } } //console.log(this.mappedValuesDueDates); //console.log(this.mappedValuesTags); //console.log(this.mappedValuesUsers); for (var i = 0; i < this.unmappedEvents.length; i++) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + i) as HTMLDivElement)!.innerHTML = (this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : ""; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + i) as HTMLInputElement)!.value = (this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : ""; if (this.mappedValuesTags[i] != null) { var html = ''; for (var j = 0; j < this.mappedValuesTags[i].length; j++) { html += this.mappedValuesTags[i][j]; if (j < (this.mappedValuesTags[i].length - 1)) { html += ','; } } ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + i) as HTMLDivElement)!.innerHTML = ''; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + i) as SfIForm)!.preselectedValues = JSON.stringify(this.mappedValuesTags[i]); //((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-'+i) as SfIForm)!.populatePreselected(); } if (this.mappedValuesUsers[i] != null) { html = ''; for (var j = 0; j < this.mappedValuesUsers[i].length; j++) { html += this.mappedValuesUsers[i][j]; if (j < (this.mappedValuesUsers[i].length - 1)) { html += ','; } } ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + i) as HTMLDivElement)!.innerHTML = ''; ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + i) as SfIForm)!.preselectedValues = JSON.stringify(this.mappedValuesUsers[i]); //((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-'+i) as SfIForm)!.populatePreselected(); } if (this.mappedValuesUsers[i] != null) { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + i) as HTMLDivElement).innerHTML = 'check_circle'; } else { ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + i) as HTMLDivElement).innerHTML = 'pending'; } } this.calculateAndShowSummary(); } clearAllMappingSelections = () => { const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf; for (var i = 0; i < inputArr.length; i++) { if (inputArr[i].checked) { inputArr[i].checked = false; inputArr[i].dispatchEvent(new Event('change')); } } } clearAllCalendars = () => { //(this._SfCalendarContainer as HTMLDivElement).innerHTML = ""; (this._SfStreamContainer as HTMLDivElement).innerHTML = ""; (this._SfUpcomingContainer as HTMLDivElement).innerHTML = ""; (this._SfThisContainer as HTMLDivElement).innerHTML = ""; (this._SfPastContainer as HTMLDivElement).innerHTML = ""; (this._SfCustomContainer as HTMLDivElement).innerHTML = ""; (this._SfAdhocContainer as HTMLDivElement).innerHTML = ""; (this._SfRegisterContainer as HTMLDivElement).innerHTML = ""; } transformMappingsForUpload = (mapping: any) => { const duedates = mapping.duedates; const tags = mapping.tags; const users = mapping.users; const transformedDuedates: any = {}; const transformedTags: any = {}; const transformedUsers: any = {}; //console.log('unmappedevents[i] duedates',duedates); for (var i = 0; i < Object.keys(duedates).length; i++) { //console.log('unmappedevents[i]',i,this.unmappedEvents[i]); const index = Object.keys(duedates)[i]; const eventId = this.unmappedEvents[i].id; transformedDuedates[eventId] = duedates[index]; } for (var i = 0; i < Object.keys(tags).length; i++) { const index = Object.keys(tags)[i]; const eventId = this.unmappedEvents[i].id; transformedTags[eventId] = tags[index]; } for (var i = 0; i < Object.keys(users).length; i++) { const index = Object.keys(users)[i]; const eventId = this.unmappedEvents[i].id; transformedUsers[eventId] = users[index]; } return { duedates: transformedDuedates, tags: transformedTags, users: transformedUsers } } uploadTriggersMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'triggers', statuteids); } uploadInternalControlsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'internalcontrols', statuteids); } uploadReportedLocationsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'reportedlocations', statuteids); } uploadAlertSchedulesMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'alertschedules', statuteids); } uploadActivationsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'activations', statuteids); } uploadInvalidationsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'invalidations', statuteids); } uploadDuedatesMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'duedates', statuteids); } uploadExtensionsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'extensions', statuteids); } uploadApproversMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'approvers', statuteids); } uploadFunctionHeadsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'functionheads', statuteids); } uploadMakerCheckersMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'makercheckers', statuteids); } uploadDocsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'docs', statuteids); } uploadAuditorsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'auditors', statuteids); } uploadViewersMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'viewers', statuteids); } uploadReportersMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'reporters', statuteids); } uploadTagsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'tags', statuteids); } uploadFunctionsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'functions', statuteids); } uploadLocationsMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'locations', statuteids); } uploadEntitiesMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'entities', statuteids); } uploadCountriesMapping = async (data: any, statuteids: string[]) => { await this.uploadOnboardingMapping(data, 'countries', statuteids); } uploadMappedGovUsers = async (data: any) => { console.log('uploading..', data); let url = "https://" + this.apiId + "/updatemappedgovusers"; let body: any = { "projectid": this.projectId, "presigned": true } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { let jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "key": jsonRespose.key } console.log('body', body); authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse gov users', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadMappedGovLocations = async (data: any) => { console.log('uploading..', data); let url = "https://" + this.apiId + "/updatemappedgovlocations"; let body: any = { "projectid": this.projectId, "presigned": true } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { let jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "key": jsonRespose.key } console.log('body', body); authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse gov locations', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadMappedSuspense = async (data: any, year: string) => { //console.log('uploading..', data); let url = "https://" + this.apiId + "/updatemappedsuspense"; // const body = { // "projectid": this.projectId, // "data": JSON.stringify(data), // "year": year // } let body: any = { "projectid": this.projectId, "presigned": true, "year": year } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { let jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "key": jsonRespose.key, "year": year } console.log('body', body); authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse suspense', jsonRespose); return jsonRespose; } // let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); // let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; // this._SfLoader.innerHTML = ''; // if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); // console.log('jsonResponse suspense', jsonRespose); // return jsonRespose; // } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadOnboardingMapping = async (data: any, onboardingstep: string, statuteids: string[]) => { //console.log('uploading..', data); let url = "https://" + this.apiId + "/updatemappedonboarding1"; // const body = { // "projectid": this.projectId, // "data": JSON.stringify(data), // "onboardingstep": onboardingstep, // } let body: any = { "projectid": this.projectId, "presigned": true, "onboardingstep": onboardingstep, "statuteids": statuteids } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "key": jsonRespose.key, "onboardingstep": onboardingstep, "statuteids": statuteids } console.log('body', body); authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadToPresignedUrl = async (data: any, url: string) => { const xhr: any = (await this.prepareXhrPresigned(data, url, this._SfLoader)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { } } uploadCompliancesMapping = async (data: any, mappedstatutes: Array) => { console.log('uploading..', data, mappedstatutes); let url = "https://" + this.apiId + "/updatemappedcompliances1"; let statuteids = [] for (let statuteObj of mappedstatutes) { statuteids.push(statuteObj.id); } let body: any = { "projectid": this.projectId, "presigned": true, } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "statuteids": statuteids, "key": jsonRespose.key } authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadStatutesMapping = async (data: any) => { // console.log('uploading..', data); let url = "https://" + this.apiId + "/updatemappedstatutes1"; // var searchstring = ''; // for (var i = 0; i < data.mappings.length; i++) { // // const dataItem = JSON.parse(data.mappings[i].data); // const dataId = data.mappings[i].id; // // console.log(dataItem[3]) // if (data.mappings[i].selected == true) { // searchstring += dataId; // // if (i < (data.mappings.length - 1)) { // searchstring += '|'; // // } // } // } // if(searchstring.length > 0){ // searchstring = searchstring.slice(0, -1); // } // const bodyUpload = { // "projectid": this.projectId, // // "data": JSON.stringify(data), // "compliancessearchstring": searchstring // } // console.log("upload body", bodyUpload) // return; let body: any = { "projectid": this.projectId, "presigned": true, } let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); await this.uploadToPresignedUrl(data, jsonRespose.signedUrl) body = { "projectid": this.projectId, "key": jsonRespose.key, } authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadUnTriggerEvent = async (untrigger: any) => { let url = "https://" + this.apiId + "/untriggerevent1"; const body = untrigger; console.log('uploading...', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse sync', jsonRespose); this.setSuccess("Your trigger has been retracted successfully. The changes will reflect in your calendar shortly."); setTimeout(() => { this.clearMessages(); }, 3000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 2000); } } uploadTriggerMyEvent = async (complianceid: string, message: string, countryname: string, entityname: string, locationname: string, statute: string, subcategory: string, suspenseVal: any = {}) => { let url = "https://" + this.apiId + "/triggermyevent"; const body = { "projectid": this.projectId, "complianceid": complianceid, "message": message, "userid": this.userProfileId, "username": this.userName, "countryname": countryname, "entityname": entityname, "locationname": locationname, "statute": statute, "subcategory": subcategory, "suspenseval": suspenseVal } console.log('uploading...', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse sync', jsonRespose); this.setSuccess("Feedback sent successfully!"); setTimeout(() => { this.clearMessages(); }, 5000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 3000); } } uploadAdHocCheckTime = async (showSuccess: boolean = true) => { let url = "https://" + this.apiIdDashboard + "/updateadhocchecktime"; const body = { "projectid": this.projectId, "userid": this.userProfileId } console.log('uploading...', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse sync', jsonRespose); if (showSuccess) { this.setSuccess("AdHoc Questions reviewed for this month."); setTimeout(() => { this.clearMessages(); }, 3000); } Util.putUserAdhocCheckTime(jsonRespose.adhocCheckTime) this.loadMode(); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 10000); } } uploadTriggerEvent = async (triggeredCompliances: any) => { let url = "https://" + this.apiId + "/triggerevent2"; const body = { "projectid": this.projectId, "triggers": triggeredCompliances } console.log('uploading...', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse sync', jsonRespose); this.setSuccess("Your trigger request is registered successfully. The associated compliances will be available in your calendar shortly."); setTimeout(() => { this.clearMessages(); }, 3000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 10000); } } uploadAudit = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, approved: any, module: string = "compliance") => { let url = "https://" + this.apiId + "/uploadaudit1"; const body = { "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "audit", "eventid": eventid, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "userid": this.userProfileId, "username": this.userName, "module": module } let retValue = true; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); this.setSuccess("Audit report uploaded successfully!"); setTimeout(() => { this.clearMessages() // this.showChosenMapping(); // this.fetchEventMap(); // if(this.myRole == this.TAB_REPORTER) { // this.renderMappingTabs(this.TAB_REPORTER); // } else { // this.renderMappingTabs(this.TAB_APPROVER); // } }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); retValue = false; } return retValue; } uploadAuditsBulk = async (bulkBody: any) => { let url = "https://" + this.apiId + "/uploadauditsbulk1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete."); setTimeout(() => { this.clearMessages() }, 10000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } uploadReview = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, approved: any, module: string = "compliance") => { let url = "https://" + this.apiId + "/uploadreview"; if (module == "rcmresource" && this.apiId2 != null) { url = "https://" + this.apiId2 + "/uploadreview1"; } const body = { "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "review", "eventid": eventid, "comments": comments, "approved": approved, "entityid": entityId, "locationid": locationId, "userid": this.userProfileId, "username": this.userName, "module": module } let retValue = true; console.log('uploading review', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); this.setSuccess("Report uploaded successfully!"); setTimeout(() => { this.clearMessages() // this.showChosenMapping(); // this.fetchEventMap(); // if(this.myRole == this.TAB_REPORTER) { // this.renderMappingTabs(this.TAB_REPORTER); // } else { // this.renderMappingTabs(this.TAB_APPROVER); // } }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); retValue = false; } return retValue; } uploadReportsReviewsBulk = async (bulkBody: any) => { let url = "https://" + this.apiId + "/uploadreportsreviewsbulk1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete."); setTimeout(() => { this.clearMessages() }, 10000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); } } uploadReviewsBulk = async (bulkBody: any) => { let url = "https://" + this.apiId + "/uploadreviewsbulk1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete."); setTimeout(() => { this.clearMessages() }, 10000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); } } uploadReport = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, doc: string, docs: any, event: any, reportformatvalues: string = "", reportformatschema: string = "", module: string = "compliance", percentage: string = "100", makercheckers: any, reportedlocations: string = "") => { let url = "https://" + this.apiId + "/uploadreport"; if (module == "rcmresource" && this.apiId2 != null) { url = "https://" + this.apiId2 + "/uploadreport"; } let yearStr = this.getFinancialYear(mmddyyyy) let body = { "mmddyyyy": mmddyyyy, "projectid": this.projectId, "type": "report", "eventid": eventid, "comments": comments, "dateofcompletion": doc, "percentage": percentage, "entityid": entityId, "locationid": locationId, "event": event == null ? null : JSON.stringify(event), "docs": JSON.stringify(docs), "username": this.userName, "reportformatvalues": reportformatvalues, "reportformatschema": reportformatschema, "userid": this.userProfileId, "userrole": this.myRole, "year": yearStr, "module": module, "makercheckers": makercheckers, "reportedlocations": reportedlocations } console.log('reportingbody', body); let retValue = true; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); this.setSuccess("Report uploaded successfully!"); setTimeout(() => { this.clearMessages() // this.showChosenMapping(); // this.fetchEventMap(); // if(this.myRole == this.TAB_REPORTER) { // this.renderMappingTabs(this.TAB_REPORTER); // } else { // this.renderMappingTabs(this.TAB_APPROVER); // } }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); console.log() this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); retValue = false; } return retValue; } uploadReportsBulk = async (bulkBody: any, showSuccess: boolean = true) => { let url = "https://" + this.apiId + "/uploadreportsbulk1" const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any; if (showSuccess) { this._SfLoader.innerHTML = ''; } if (xhr.status == 200) { if (showSuccess) { this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete."); setTimeout(() => { this.clearMessages() }, 10000); } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); } } sendSuggestions = async (eventid: string, eventdelta: any) => { let url = "https://" + this.apiIdRCMResources + "/sendsuggestions"; const body = { "projectid": this.projectId, "objectid": eventid, "objectdelta": JSON.stringify(eventdelta), } let retValue = true; console.log('uploading suggestion', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); this.setSuccess("Suggestion sent successfully!"); setTimeout(() => { this.clearMessages() // this.showChosenMapping(); // this.fetchEventMap(); // if(this.myRole == this.TAB_REPORTER) { // this.renderMappingTabs(this.TAB_REPORTER); // } else { // this.renderMappingTabs(this.TAB_APPROVER); // } }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 3000); retValue = false; } return retValue; } exportRegister = async () => { let url = "https://" + this.apiId + "/scheduleregisterexportjob"; const body = { "projectid": this.projectId, "userid": this.userProfileId, "role": this.myRole, "admin": (this.showRegisterExport && this.showRegisterExport == "true") } console.log('exporting Register...', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonResponse sync', jsonRespose); this.setSuccess("Register export started successfully! You will get an email with your register landscape."); setTimeout(() => { this.clearMessages(); }, 5000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages() }, 3000); } } uploadMapping = async () => { let url = "https://" + this.apiId + "/mapevents"; const mapping = this.transformMappingsForUpload({ duedates: this.mappedValuesDueDates, tags: this.mappedValuesTags, users: this.mappedValuesUsers }); const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "role": this.myRole, "mapping": JSON.stringify(mapping) } const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); this.setSuccess("Mapping uploaded successfully!"); setTimeout(() => { this.clearMessages() this.showChosenMapping(); this.fetchEventMap(); if (this.myRole == this.TAB_REPORTER) { this.renderMappingTabs(this.TAB_REPORTER); } else { this.renderMappingTabs(this.TAB_APPROVER); } }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } uploadEvents = async () => { let url = "https://" + this.apiId + "/synccalendar"; const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "compliance": JSON.stringify(this.events) } const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); // this.loadMode(); this.showChosenMapping(); this.fetchEventMap(); this.renderMappingTabs(this.TAB_REPORTER); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } uploadReprogramTrigger = async (eventid: string, timestamp: string) => { let url = "https://" + this.apiId + "/reprogramtrigger"; const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "eventid": eventid, "timestamp": timestamp + "" } const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse sync', jsonRespose); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } processEvent = (value: any) => { //console.log('processing due date', value); //console.log('processing due date', value.duedate.replace(/['"]+/g, '')); //console.log('processing due date', this.mappings); var duedate = value.duedate; if (this.mappings != null && this.mappings.duedates != null && this.mappings.duedates[value.id] != null && this.mappings.duedates[value.id] != "") { duedate = this.mappings.duedates[value.id]; } const duedateArr = duedate.replace(/['"]+/g, '').split(",") as Array; const startMonth = parseInt(this.calendarStartMM); for (var i = 0; i < duedateArr.length; i++) { const dateArr = duedateArr[i].split("/"); //console.log('datearr', dateArr); if (dateArr[2] == "*") { if (dateArr[1] == "*") { var j = startMonth; while (true) { //console.log('processing event',dateArr[2],dateArr[1],j); const mmdd = ("0" + j).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2); if (this.events == null) { this.events = {}; } if (this.events[mmdd] == null) { this.events[mmdd] = []; } (this.events[mmdd] as Array).push(value); if (startMonth !== 12) { if (j === (startMonth - 1)) { break; } } j++; if (j === 13) { j = 0; } } } else { const mmdd = ("0" + (parseInt(dateArr[1]))).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2); if (this.events == null) { this.events = {}; } if (this.events[mmdd] == null) { this.events[mmdd] = []; } (this.events[mmdd] as Array).push(value); } } else { if ((new Date().getFullYear() + "") == dateArr[2]) { const mmdd = ("0" + (parseInt(dateArr[1]))).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2); if (this.events == null) { this.events = {}; } if (this.events[mmdd] == null) { this.events[mmdd] = []; } (this.events[mmdd] as Array).push(value); } } } //console.log('calendar processed', this.calendar); //console.log('event processed', this.events); } renderChosenProject = (events: any = null) => { if (events == null) { var html = ''; html += '
'; html += '
'; html += '
Calender doesn\'t exist!    
'; html += ''; html += '
'; html += '
'; (this._SfContainerChosenProject as HTMLDivElement).innerHTML = html; (((this._SfContainerChosenProject as HTMLDivElement) as HTMLDivElement).querySelector('#button-generate-chosen-project') as HTMLButtonElement).addEventListener('click', async () => { await this.fetchList(); }); } else { } } fetchRcmLockedCompliances = async (lockedCompliances: Array) => { let url = "https://" + this.apiId + "/getrcmlockedcompliances"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ data: lockedCompliances }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('lockedcompliances', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchCancelOnboardingJob = async (onboardingStep: string) => { let url = "https://" + this.apiId + "/cancelonboardingjob"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingStep }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('fetchCancelnboardingJob', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchGetStoredMapping = async (flow: string) => { let url = "https://" + this.apiId + "/getstoredmapping"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "flow": flow }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('fetchGetStoredMapping', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchUpdateUsermap = async (usermap: any) => { let url = "https://" + this.apiIdUsers + "/updatefield"; this.setSuccess('Updating usermaps, please wait...') //console.log('updating usermap', usermap); const arrUserIds = Object.keys(usermap); for (var i = 0; i < arrUserIds.length; i++) { const userId = arrUserIds[i]; const map = usermap[userId]; const strMap = JSON.stringify(map).replace(/"/g, '_QUOTES_'); const body = { id: userId, field: "usermap", value: "\"" + strMap + "\"" }; //console.log('updating', userId, body, url) let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { } } setTimeout(() => { this.clearMessages(); }, 1000); } fetchUpdateRcmLock = async (complianceId: string) => { let url = "https://" + this.apiId + "/updatercmlock"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "complianceid": complianceId, "locked": true }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('fetchUpdateRcmLock', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchDetailProject = async (projectId: string) => { let url = "https://" + this.apiIdProjects + "/detail"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "id": projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('searchprojects', jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchDeleteReview = async (eventId: string, mmddyyyy: string, entityId: string, locationId: string) => { let url = "https://" + this.apiId + "/deletereview"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "entityid": entityId, "locationid": locationId, "mmddyyyy": mmddyyyy, "eventid": eventId, }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchStatuteDefinitionDetails = async (statuteName: string) => { const statuteDetails = await this.fetchSearchStatutes(statuteName); console.log('statuteDetails', statuteDetails); statuteDetails.values.forEach(async (statute: any) => { const nameIndex = (JSON.parse(statute.fields.cols[0]) as Array).indexOf('name'); const statuteNameFound = JSON.parse(statute.fields.data[0])[nameIndex]; if (statuteNameFound == statuteName) { if (statute.fields.cols[0].indexOf('definitions') >= 0) { const definitionsIndex = (JSON.parse(statute.fields.cols[0]) as Array).indexOf('definitions'); const definitionsFound = JSON.parse(statute.fields.data[0])[definitionsIndex]; if (definitionsFound.length > 0) { console.log(JSON.parse(statute.fields.data[0])[definitionsIndex]); const definitionsName = JSON.parse(statute.fields.data[0])[definitionsIndex][0].trim(); console.log('statute', statute, JSON.parse(statute.fields.cols[0]), nameIndex, statuteNameFound, definitionsFound, definitionsName); const definitionDetails = await this.fetchSearchDefinitions(definitionsName); definitionDetails.values.forEach(async (definition: any) => { const definitionNameIndex = (JSON.parse(definition.fields.cols[0]) as Array).indexOf('name'); const definitionNameFound = JSON.parse(definition.fields.data[0])[definitionNameIndex]; if (definitionNameFound == definitionsName) { const attachmentIndex = (JSON.parse(definition.fields.cols[0]) as Array).indexOf('attachment'); const attachmentKey = JSON.parse(definition.fields.data[0])[attachmentIndex][0] console.log('definition', definition, attachmentKey); (this._SfDetailContainer as HTMLDivElement).querySelector('#container-definition')!.innerHTML = '
Definitions
'; ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-show-definition') as HTMLButtonElement)!.addEventListener('click', (_e: any) => { (this._SfDetailContainer as HTMLDivElement).querySelector('#container-definition')!.innerHTML = `
Definitions
`; ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).classList.remove('gone'); ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).prepopulatedInputArr = JSON.stringify([attachmentKey]); ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).loadMode(); }); } }); } } } }); } fetchSearchDefinitions = async (searchString: string, cursor: string = "") => { let url = "https://" + this.apiIdDefinitions + "/listlarge"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('searchstatutes', jsonRespose); let newCursor = jsonRespose.cursor; let i = 0; while (true) { url = "https://" + this.apiIdDefinitions + "/listlarge"; authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose1 = JSON.parse(xhr.responseText); //console.log('found', jsonRespose1.values); jsonRespose.values.push(...jsonRespose1.values); if (newCursor == jsonRespose1.cursor) { break; } newCursor = jsonRespose1.cursor; //console.log('newcursor', i, jsonRespose1.cursor); i += jsonRespose1.values.length; } else { break; } } return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchReportFormat = async (reportingContainer: HTMLDivElement, searchName: string, reportformatschema: string = "", reportformatvalues: string = "") => { let jsonContentIndex: number; let jsonContentFound: string = ""; if (reportformatschema == "") { let reportformats = await this.fetchSearchReportformats(searchName); if (reportformats.values == null || reportformats.values.length == 0) { return; } for (let format of reportformats.values) { let data = JSON.parse(format.fields.data[0]) let cols = JSON.parse(format.fields.cols[0]) if (data[cols.indexOf('name')] == searchName) { jsonContentIndex = (JSON.parse(format.fields.cols[0]) as Array).indexOf('jsoncontent'); jsonContentFound = JSON.parse(format.fields.data[0])[jsonContentIndex]; break; } } } else { jsonContentFound = reportformatschema } console.log('format found', JSON.parse(jsonContentFound)); if (jsonContentFound == "") { console.log('format not found'); return; } if (reportingContainer.querySelector('#report-format-container') != null) { reportingContainer.querySelector('#report-format-container')!.innerHTML = ``; console.log('innerhtml', reportingContainer.querySelector('#report-format-container')!.innerHTML); (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).name = searchName; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).mode = reportformatvalues != "" ? "edit" : "new"; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).flow = "reporting"; (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).configjson = jsonContentFound; if (reportformatvalues != "") { (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).prepopulateValJson = reportformatvalues } (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).loadMode(); } else { console.log('report format container not found'); } } fetchSearchReportformats = async (searchString: string, cursor: string = "") => { let url = "https://" + this.apiidReportformats + "/listlarge"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('searchstatutes', jsonRespose); let newCursor = jsonRespose.cursor; let i = 0; while (true) { url = "https://" + this.apiidReportformats + "/listlarge"; authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose1 = JSON.parse(xhr.responseText); //console.log('found', jsonRespose1.values); jsonRespose.values.push(...jsonRespose1.values); if (newCursor == jsonRespose1.cursor) { break; } newCursor = jsonRespose1.cursor; //console.log('newcursor', i, jsonRespose1.cursor); i += jsonRespose1.values.length; } else { break; } } return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchSearchStatutes = async (searchString: string, cursor: string = "") => { console.log('cursor', cursor); let url = "https://" + this.apiIdStatutes + "/listlarge"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('searchstatutes', { "searchstring": searchString, "cursor": cursor }, jsonRespose); let newCursor = jsonRespose.cursor; let i = 0; while (true) { url = "https://" + this.apiIdStatutes + "/listlarge"; authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose1 = JSON.parse(xhr.responseText); //console.log('found', jsonRespose1.values); jsonRespose.values.push(...jsonRespose1.values); if (newCursor == jsonRespose1.cursor) { break; } newCursor = jsonRespose1.cursor; //console.log('newcursor', i, jsonRespose1.cursor); i += jsonRespose1.values.length; } else { break; } } return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchSearchCompliances = async (searchString: string, cursor: string = "", count: number, length: number) => { let url = "https://" + this.apiIdCompliances + "/listlarge"; let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); // //console.log(jsonRespose); let newCursor = jsonRespose.cursor; ////console.log('newcursor', newCursor); while (true) { url = "https://" + this.apiIdCompliances + "/listlarge"; authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((count) * 100 / length) + "") + "%")) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose1 = JSON.parse(xhr.responseText); // //console.log('newcursor response', jsonRespose1); jsonRespose.values.push(...jsonRespose1.values); if (newCursor == jsonRespose1.cursor) { break; } newCursor = jsonRespose1.cursor; ////console.log('newcursor', i, jsonRespose1.cursor); } else { break; } } return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchMappedProjects = async () => { let url = "https://" + this.apiId + "/getmappedprojects"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "complianceid": this.rcmSelectedCompliance.id }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchOnboardingStatus = async () => { let url = "https://" + this.apiId + "/getonboardingstatus"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchGetSignOff = async () => { let url = "https://" + this.apiId + "/getsignoff"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchUpdateSignOff = async (signoffText: string, signature: string) => { let url = "https://" + this.apiId + "/updatesignoff"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "signofftext": signoffText, "signature": signature, "username": this.userName }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchMappedCompliances = async (statuteids = []) => { let url = "https://" + this.apiId + "/getmappedcompliances1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "statuteids": statuteids }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { var jsResponse = JSON.parse(xhr.responseText); let resultPresigned: any = null; resultPresigned = {}; resultPresigned.data = {}; resultPresigned.data.mappings = await this.fetchPresignedUrl(jsResponse.signedUrlGet); console.log(resultPresigned); await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete) return resultPresigned; // const jsonRespose = JSON.parse(xhr.responseText); // return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } // let jsonResponse : any = null; // let lastEvaluatedKey : any = 0; // do { // //console.log(lastEvaluatedKey); // let url = "https://"+this.apiId+"/getmappedcompliances"; // const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); // const xhr : any = (await this.prepareXhr({"projectid": this.projectId, "lastevaluatedkey": lastEvaluatedKey}, url, this._SfLoader, authorization)) as any; // this._SfLoader.innerHTML = ''; // if(xhr.status == 200) { // const jsResponse = JSON.parse(xhr.responseText); // //console.log(jsResponse); // if(jsResponse == null) return; // if(lastEvaluatedKey === 0) { // jsonResponse = {}; // jsonResponse.data = {} // jsonResponse.data = jsResponse.data; // } else { // jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings); // } // if(jsResponse.lastEvaluatedKey < 0) break; // lastEvaluatedKey = jsResponse.lastEvaluatedKey; // } else { // const jsonRespose = JSON.parse(xhr.responseText); // this.setError(jsonRespose.error); // break; // } // } while(true); // return jsonResponse; } fetchMappedSerializedExtensions = async () => { return (await this.fetchSerializedMapping("extensions")); } fetchMappedSerializedAlertSchedules = async () => { return (await this.fetchSerializedMapping("alertschedules")); } fetchMappedSerializedTriggers = async () => { return (await this.fetchSerializedMapping("triggers")); } fetchMappedSerializedDuedates = async () => { return (await this.fetchSerializedMapping("duedates")); } fetchMappedSerializedApprovers = async () => { return (await this.fetchSerializedMapping("approvers")); } fetchMappedSerializedFunctionheads = async () => { return (await this.fetchSerializedMapping("functionheads")); } fetchMappedSerializedMakerCheckers = async () => { return (await this.fetchSerializedMapping("makercheckers")); } fetchMappedSerializedDocs = async () => { return (await this.fetchSerializedMapping("docs")); } fetchMappedSerializedAuditors = async () => { return (await this.fetchSerializedMapping("auditors")); } fetchMappedSerializedViewers = async () => { return (await this.fetchSerializedMapping("viewers")); } fetchMappedSerializedReporters = async () => { return (await this.fetchSerializedMapping("reporters")); } fetchMappedSerializedTags = async () => { return (await this.fetchSerializedMapping("tags")); } fetchMappedSerializedLocations = async () => { return (await this.fetchSerializedMapping("locations")); } fetchMappedSerializedFunctions = async () => { return (await this.fetchSerializedMapping("functions")); } fetchMappedSerializedEntities = async () => { return (await this.fetchSerializedMapping("entities")); } fetchPresignedUrl = async (url: string) => { const xhr: any = (await this.prepareXhrPresignedGet(url, this._SfLoader, 'Downloading')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsResponse = JSON.parse(xhr.responseText); console.log('jsResponse', jsResponse); return jsResponse; } } fetchPresignedUrlDelete = async (url: string) => { const xhr: any = (await this.prepareXhrPresignedDelete(url, this._SfLoader)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsResponse = JSON.parse(xhr.responseText); console.log('jsResponse', jsResponse); return jsResponse; } } fetchSerializedMapping = async (onboardingstep: string) => { const url = "https://" + this.apiId + "/getmappedserializedonboarding"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { var jsResponse = JSON.parse(xhr.responseText); let resultPresigned: any = null; resultPresigned = {}; resultPresigned.data = {}; resultPresigned.data.mappings = await this.fetchPresignedUrl(jsResponse.signedUrlGet); console.log(resultPresigned); await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete) return resultPresigned; // if(jsResponse != null && jsResponse.lastEvaluatedKey == null) { // jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings); // break; // } else { // if(jsonResponse == null) { // jsonResponse = {}; // jsonResponse.data = {} // jsonResponse.data = jsResponse.data; // } else { // jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings); // } // lastEvaluatedKey = jsResponse.lastEvaluatedKey; // } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchSerializedPartByPart = async (url: string) => { let jsonResponse: any = null; let lastEvaluatedKey: any = null; do { //console.log(lastEvaluatedKey); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "lastevaluatedkey": lastEvaluatedKey }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsResponse = JSON.parse(xhr.responseText); //console.log(jsResponse); if (jsResponse != null && jsResponse.lastEvaluatedKey == null) { jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings); break; } else { if (jsonResponse == null) { jsonResponse = {}; jsonResponse.data = {} jsonResponse.data = jsResponse.data; } else { jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings); } lastEvaluatedKey = jsResponse.lastEvaluatedKey; } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } while (true); //console.log(jsonResponse); return jsonResponse; } fetchMappedSerializedCountries = async () => { // return (await this.fetchSerializedPartByPart("https://"+this.apiId+"/getmappedserializedcountries")); return (await this.fetchSerializedMapping("countries")); } fetchMappedTriggers = async (statuteids = []) => { return (await this.fetchMappedOnboarding('triggers', statuteids)); } fetchMappedInternalControls = async (statuteids = []) => { return (await this.fetchMappedOnboarding('internalcontrols', statuteids)); } fetchMappedReportedLocations = async (statuteids = []) => { return (await this.fetchMappedOnboarding('reportedlocations', statuteids)); } fetchMappedAlertSchedules = async (statuteids = []) => { return (await this.fetchMappedOnboarding('alertschedules', statuteids)); } fetchMappedActivations = async (statuteids = []) => { return (await this.fetchMappedOnboarding('activations', statuteids)); } fetchMappedInvalidations = async (statuteids = []) => { return (await this.fetchMappedOnboarding('invalidations', statuteids)); } fetchMappedExtensions = async (statuteids = []) => { return (await this.fetchMappedOnboarding('extensions', statuteids)); } fetchMappedDuedates = async (statuteids = []) => { return (await this.fetchMappedOnboarding('duedates', statuteids)); } fetchMappedReporters = async (statuteids = []) => { return (await this.fetchMappedOnboarding('reporters', statuteids)); } fetchMappedApprovers = async (statuteids = []) => { return (await this.fetchMappedOnboarding('approvers', statuteids)); } fetchMappedFunctionHeads = async (statuteids = []) => { return (await this.fetchMappedOnboarding('functionheads', statuteids)); } fetchMappedMakerCheckers = async (statuteids = []) => { return (await this.fetchMappedOnboarding('makercheckers', statuteids)); } fetchMappedDocs = async (statuteids = []) => { return (await this.fetchMappedOnboarding('docs', statuteids)); } fetchMappedAuditors = async (statuteids = []) => { return (await this.fetchMappedOnboarding('auditors', statuteids)); } fetchMappedViewers = async (statuteids = []) => { return (await this.fetchMappedOnboarding('viewers', statuteids)); } fetchMappedTags = async (statuteids = []) => { return (await this.fetchMappedOnboarding('tags', statuteids)); } fetchMappedLocations = async (statuteids = []) => { return (await this.fetchMappedOnboarding('locations', statuteids)); } fetchMappedFunctions = async (statuteids = []) => { return (await this.fetchMappedOnboarding('functions', statuteids)); } fetchMappedEntities = async (statuteids = []) => { return (await this.fetchMappedOnboarding('entities', statuteids)); } fetchMappedCountries = async (statuteids = []) => { return (await this.fetchMappedOnboarding('countries', statuteids)); } fetchMappedOnboarding = async (onboardingstep: string, statuteids: string[]) => { const url = "https://" + this.apiId + "/getmappedonboarding1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep, "statuteids": statuteids }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { var jsResponse = JSON.parse(xhr.responseText); let resultPresigned: any = null; resultPresigned = {}; resultPresigned.data = {}; let tempObj = await this.fetchPresignedUrl(jsResponse.signedUrlGet) let tempArr = []; for (let statuteid of statuteids) { for (let foundObjId of Object.keys(tempObj[statuteid] ?? [])) { let tempPushObj = tempObj[statuteid][foundObjId]; tempPushObj.id = foundObjId.split(';')[foundObjId.split(';').length - 1]; tempPushObj.statuteid = statuteid; tempArr.push(tempPushObj); } } // resultPresigned.data.mappings = (tempObj.mappings != null) ? tempObj : { mappings: [] }; resultPresigned.data.mappings = tempArr; console.log('resultPresigned onboarding1', tempObj); console.log('resultPresigned onboarding', resultPresigned); // await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete) return resultPresigned; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchLocaltions = async () => { let cursor = ""; let arrList: any = []; do { const url = "https://" + this.apiIdTags + "/listlarge"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "searchstring": this.projectName + "&Location", "cursor": cursor }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { var jsResponse = JSON.parse(xhr.responseText); console.log('response', jsResponse) arrList = [...arrList, ...jsResponse.values] if (jsResponse.cursor == cursor) { break; } cursor = jsResponse.cursor } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); break; } } while (cursor != "" && cursor != null) return arrList } fetchMappingCount = async (onboardingstep: string) => { const url = "https://" + this.apiId + "/getmappedonboardingcount"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { var jsResponse = JSON.parse(xhr.responseText); return jsResponse; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchUpdatedCompliances = async (nextBackwardToken: string = "") => { let url = "https://" + this.apiIdCompliances + "/logs"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "nextBackwardToken": nextBackwardToken }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchMappedStatutes = async () => { let url = "https://" + this.apiId + "/getmappedstatutes1"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchMappedStatutesList = async () => { let url = "https://" + this.apiId + "/getmappedstatuteslist"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose.data; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchCreateRcmJob = async (complianceid: string, data: any, triggerDate: string, triggerMessage: string, projects: any) => { data.trigger = {}; data.trigger.date = triggerDate; data.trigger.message = triggerMessage; data.projects = []; data.projects.push(...projects) let url = "https://" + this.apiId + "/creatercmjob"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "complianceid": complianceid, "data": data }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchRcmNotifications = async (projectid: string) => { let url = "https://" + this.apiId + "/getrcmnotifications"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": projectid }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchRcmJobs = async (complianceid: string) => { let url = "https://" + this.apiId + "/getrcmjobs"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "complianceid": complianceid }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchCalendarJobs = async () => { let url = "https://" + this.apiId + "/getcalendarjobs"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchExternalMapping = async () => { let url = "https://" + this.apiId + "/getexternalmapping"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } deleteFromSuspense = async (suspenseKey: any, year: string) => { let url = "https://" + this.apiId + "/deletefromsuspense"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "eventid": suspenseKey.split(';')[2], "entityid": suspenseKey.split(';')[0], "locationid": suspenseKey.split(';')[1], "year": year }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('jsonResponse', jsonResponse); return jsonResponse; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } markReviewed = async (suspenseKey: any, year: string, review: boolean) => { let url = "https://" + this.apiId + "/markreviewed"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "eventid": suspenseKey.split(';')[2], "entityid": suspenseKey.split(';')[0], "locationid": suspenseKey.split(';')[1], "year": year, "mark": review }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('jsonResponse', jsonResponse); return jsonResponse; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchMappedGovUsersList = async () => { let url = "https://" + this.apiId + "/getmappedgovuserslist"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) return retData ?? {}; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchMappedGovLocationsList = async () => { let url = "https://" + this.apiId + "/getmappedgovlocationslist"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) return retData ?? {}; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchSuspenseList = async (year: string = "") => { let url = "https://" + this.apiId + "/getsuspenselist"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); if (year == "") { year = this.getCurrentYearGeneric(); } const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "year": year }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) console.log('retData', retData); return retData ?? {}; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchDetail = async (value: any) => { const body: any = this.getApiBodyList(); body.id = value; //console.log('detail', value, body); let url = "https://" + this.apiIdDetail + "/" + this.apiMethodDetail; //console.log('fetch events detail url', url); //console.log('fetch events detail body', body); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('jsonResponse fetch events detail', jsonRespose.data.value.duedate); this.processEvent(jsonRespose.data.value) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchGetMappedCalendar = async (year: string) => { // let url = "https://"+this.apiId+"/getmappedcalendar"; // let url = "https://3mefupehxkw4pwsq3oyk7lf2pq0pisdx.lambda-url.us-east-1.on.aws/schedulegetcalendarjob"; let url = "https://" + this.apiId + "/schedulegetcalendarjob"; const body: any = { "projectid": this.projectId, "year": year }; if (this.contractStartDate != "") { body.contractstartdate = this.contractStartDate; } const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); return jsonRespose; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); return jsonRespose; } } sleepFunction = async (ms: number) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); } renderAppropriateStream = (startDate: string, endDate: string, showGraph: boolean = false, showBackgroundButton: boolean = false) => { if (startDate == "" && endDate == "") this.renderCalendar(); // yearly if (this.selectedTab == this.TAB_STREAM) { this.renderStream(parseInt(this.currentColumnIndex), showGraph, showBackgroundButton); } // if(this.selectedTab == this.TAB_UPCOMING) { // this.renderUpcoming(parseInt(this.currentColumnIndex), false); // } if (this.selectedTab == this.TAB_THIS) { this.renderThis(parseInt(this.currentColumnIndex), showGraph, showBackgroundButton); } if (this.selectedTab == this.TAB_CUSTOM) { this.processDateSelection((this._SfCustomContainer as HTMLDivElement), false, showBackgroundButton) } // if(this.selectedTab == this.TAB_PAST) { // this.renderPast(parseInt(this.currentColumnIndex), false); // } } fetchRegisters = async (searchString: string = "", meta: string = "", selectedCountry: string = "", selectedStatute: string = "") => { let path = ""; path = "getallfunctionevents1"; let url = "https://" + this.apiId + "/" + path; let locationId = ""; let entityId = ""; if (this.locationId != null && this.locationId.length > 2) { locationId = this.locationId; } if (this.entityId != null && this.entityId.length > 2) { entityId = this.entityId; } //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "searchstring": searchString, "locationid": locationId, "entityid": entityId, meta: meta, country: selectedCountry, statute: selectedStatute }; //console.log('urlbody', url, urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); const registers = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) this.registerFilters = {}; // this.renderAppropriateStream(startDate, endDate); // const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); return registers; } else if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } } markUnderstoodBulk = async (complianceids: any, userid: string, review: number) => { let url = "https://" + this.apiId + "/markunderstoodbulk"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "eventids": complianceids, "userid": userid, "mark": review }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('jsonResponse', jsonResponse); return jsonResponse; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } markUnderstood = async (complianceid: any, userid: string, review: number) => { let url = "https://" + this.apiId + "/markunderstood"; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "eventid": complianceid, "userid": userid, "mark": review }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('jsonResponse', jsonResponse); this.setSuccess('Review saved') setTimeout(() => { this.clearMessages() }, 3000) return jsonResponse; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderWithFeatures = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { this.selectedFeatures = Util.getFeatures(); for (let feature of this.selectedFeatures) { if (this.getFeatures().indexOf(feature) < 0) { this.selectedFeatures = ['compliances'] break; } } this.events = [] console.log('rendering and fetching', startDate, endDate, searchString, list, month) if (this.selectedFeatures.indexOf('compliances') >= 0) { this.fetchAndYearlyRenderUserCalendar_2(startDate, endDate, searchString, list, month, year) } else if (this.selectedFeatures.indexOf('notices') >= 0) { this.fetchAndRenderNotices(startDate, endDate, searchString, list, month, year); } else if (this.selectedFeatures.indexOf('contracts') >= 0) { this.fetchAndRenderContracts(startDate, endDate, searchString, list, month, year); } else if (this.selectedFeatures.indexOf('licenses') >= 0) { this.fetchAndRenderLicenses(startDate, endDate, searchString, list, month, year); } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) { this.fetchAndRenderRCMResources(startDate, endDate, searchString, list, month, year); } } fetchAndYearlyRenderUserCalendar_2 = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { let path = "", view = ""; this.sdate = startDate; this.edate = endDate; this.suspenseCount = this.suspenseFlag ? this.suspenseCount : 0; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } path = "getallcountryevents5"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "https://" + this.apiId + "/" + path; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month, "suspense": this.suspenseFlag, "contractstartdate": this.contractStartDate }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } if (this.showReportedLocations) { urlBody["reportedlocations"] = "yes"; } //console.log('urlbody', urlBody); this.getallcountryevetsParams = JSON.stringify(urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); if (JSON.stringify(urlBody) == this.getallcountryevetsParams) { this.events = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); } await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) if (JSON.stringify(urlBody) == this.getallcountryevetsParams) { this.lastupdated = Util.getDateTimeStrings(new Date().getTime()) this.suspenseCount = this.suspenseFlag ? this.suspenseCount : (jsonRespose.suspensecount ?? 0); console.log('rendering appropriate string', list, this.selectedTab); this.renderAppropriateStream(startDate, endDate, true); this.fetchBulkReportingData(); } // if(this.selectedFeatures.indexOf('notices') >= 0){ // this.fetchAndRenderNotices(startDate, endDate); // } // this.events = {} // this.events = {...JSON.parse(JSON.stringify(jsonRespose.data.events))}; // let lastEvaluatedKey = jsonRespose.lastEvaluatedKey; // //console.log('lastevaluatedkey0', lastEvaluatedKey); // var recallCount = 0; // do { // if(recallCount > 3) break; // if(lastEvaluatedKey != null) { // let urlBody2 : any = {"projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": lastEvaluatedKey, "sdate": sDate, "edate": eDate, "view": view, "year": this.calendarStartYYYY} // if(searchString.length > 0) { // urlBody2["searchstring"] = searchString; // } // const xhr2 : any = (await this.prepareXhr(urlBody2, url, this._SfLoader, authorization)) as any; // this._SfLoader.innerHTML = ''; // if(xhr2.status == 200) { // const jsonRespose2 = JSON.parse(xhr2.responseText); // for(var i = 0; i < Object.keys(JSON.parse(JSON.stringify(jsonRespose2.data.events))).length; i++) { // const key = Object.keys(JSON.parse(JSON.stringify(jsonRespose2.data.events)))[i]; // this.events[key].push(...JSON.parse(JSON.stringify(jsonRespose2.data.events))[key]); // } // //console.log('consolidated', this.events) // //console.log(jsonRespose2); // this.renderAppropriateStream(startDate, endDate); // lastEvaluatedKey = jsonRespose2.lastEvaluatedKey; // //console.log('lastevaluatedkey1', lastEvaluatedKey); // } else { // //console.log('calendar fetching error breaking'); // break; // } // } else { // //console.log('calendar fetching breaking'); // break; // } // } while(1) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchOnlyYearlyUserCalendar = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY, userprofileid: string = this.userProfileId, userrole: string = this.myRole, entityid = this.entityId, countryid = this.countryId, locationid = this.locationId, tagid = this.tagId, functionid = this.functionId) => { let path = "", view = ""; this.suspenseCount = 0; if (tagid != null && tagid != "") { view = "tag"; } else if (countryid != null && countryid != "") { view = "tag"; } else if (locationid != null && locationid != "") { view = "tag"; } else { view = "entity"; } path = "getallcountryevents5"; let url = "https://" + this.apiId + "/" + path; let temptagid = tagid; if (temptagid == "" && locationid != "") { temptagid = locationid } else if (temptagid == "" && (userprofileid != this.userProfileId || userrole != this.myRole)) { temptagid = "allevents" } //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": userprofileid, "role": userrole, "entityid": entityid, "countryid": countryid, "functionid": functionid, "locationid": "", "tagid": temptagid, "adhoc": "false", "exclusivestartkey": 0, "sdate": startDate, "edate": endDate, "view": view, "year": year, "list": list, "month": month, "viewerrole": this.myRole, "viewerid": this.userProfileId, "contractstartdate": this.contractStartDate }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } if (this.showReportedLocations) { urlBody["reportedlocations"] = "yes"; } console.log('fetchOnlyYearlyUserCalendar', `TagId:${this.tagId}, CountryId:${this.countryId}, LocationId:${this.locationId}, EntityId:${this.entityId}, FunctionId:${this.functionId}, View:${view}, urlBody:`, urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); // if (JSON.stringify(urlBody) == this.getallcountryevetsParams) { this.events = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); // } this.suspenseCount = jsonRespose.suspensecount ?? 0; await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchAndRenderNotices = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { let path = "", view = ""; this.sdate = startDate; this.edate = endDate; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } path = "getallcountrynotices"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "https://" + this.apiIdNotices + "/" + path; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); let notices = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); this.suspenseCount = jsonRespose.suspensecount ?? 0; await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) this.lastupdated = Util.getDateTimeStrings(new Date().getTime()) let tempEvents = this.events for (let mmddyyyy of Object.keys(notices)) { tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...notices[mmddyyyy]] } this.events = tempEvents; this.renderAppropriateStream(this.sdate, this.edate, true); console.log('notices', notices, tempEvents); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchAndRenderContracts = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { let path = "", view = ""; this.sdate = startDate; this.edate = endDate; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } path = "getallcountryobjects"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "https://" + this.apiIdAgreements + "/" + path; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); let contracts = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); this.suspenseCount = jsonRespose.suspensecount ?? 0; await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) this.lastupdated = Util.getDateTimeStrings(new Date().getTime()) // let tempEvents = this.events // for (let mmddyyyy of Object.keys(contracts)) { // tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...contracts[mmddyyyy]] // } // this.events = tempEvents; this.events = contracts; this.renderAppropriateStream(this.sdate, this.edate, true); console.log('contracts', contracts); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchAndRenderLicenses = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { let path = "", view = ""; this.sdate = startDate; this.edate = endDate; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } path = "getallcountryobjects"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "https://" + this.apiIdLicenses + "/" + path; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); let licenses = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); this.suspenseCount = jsonRespose.suspensecount ?? 0; await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) this.lastupdated = Util.getDateTimeStrings(new Date().getTime()) // let tempEvents = this.events // for (let mmddyyyy of Object.keys(licenses)) { // tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...licenses[mmddyyyy]] // } // this.events = tempEvents; this.events = licenses; this.renderAppropriateStream(this.sdate, this.edate, true); console.log('licenses', licenses); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchAndRenderRCMResources = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => { let path = "", view = ""; this.sdate = startDate; this.edate = endDate; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } path = "getallcountryobjects"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "https://" + this.apiIdRCMResources + "/" + path; //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month }; if (searchString.length > 0) { urlBody["searchstring"] = searchString; } //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); let rcmresources = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); this.suspenseCount = jsonRespose.suspensecount ?? 0; await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) this.lastupdated = Util.getDateTimeStrings(new Date().getTime()) this.events = rcmresources; this.renderAppropriateStream(this.sdate, this.edate, true); console.log('rcmresources', rcmresources); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchStatistics = async (startDate: string = "", endDate: string = "", filtercriteria: string, filterid: string, subfiltercriteria: string, subfilterid: string) => { let path = ""; this.sdate = startDate; this.edate = endDate; path = "getstatistics"; let sDate = ""; let eDate = ""; //console.log('currenttab', this.getCurrentTab()); if (this.getCurrentTab() == this.TAB_YEAR) { sDate = "03/31/" + this.calendarStartYYYY; eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1); } else { sDate = startDate; eDate = endDate; } let url = "" if (this.selectedFeatures.indexOf('compliances') >= 0) { url = "https://" + this.apiId + "/" + path; } else if (this.selectedFeatures.indexOf('notices') >= 0) { url = "https://" + this.apiIdNotices + "/" + path; } else if (this.selectedFeatures.indexOf('contracts') >= 0) { url = "https://" + this.apiIdAgreements + "/" + path; } else if (this.selectedFeatures.indexOf('licenses') >= 0) { url = "https://" + this.apiIdLicenses + "/" + path; } else if (this.selectedFeatures.indexOf('rcmresource') >= 0) { url = "https://" + this.apiIdRCMResources + "/" + path; } //console.log('fetch calendar url', url); let urlBody: any = { "projectid": this.projectId, "userid": this.userProfileId, "role": this.myRole, "sdate": sDate, "edate": eDate, "filtercriteria": filtercriteria, "subfiltercriteria": subfiltercriteria, "subfilterid": subfilterid }; if (filtercriteria == 'function') { urlBody["functionid"] = filterid; urlBody["locationid"] = ''; urlBody["filteruserrole"] = ''; urlBody["filteruserid"] = ''; } else if (filtercriteria == 'location') { urlBody["functionid"] = ''; urlBody["locationid"] = filterid; urlBody["filteruserrole"] = ''; urlBody["filteruserid"] = ''; } else { urlBody["functionid"] = ''; urlBody["locationid"] = ''; urlBody["filteruserrole"] = filtercriteria; urlBody["filteruserid"] = filterid; } console.log('urlbody', urlBody); this.getallcountryevetsParams = JSON.stringify(urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200 && this.getallcountryevetsParams == JSON.stringify(urlBody)) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose Statistics', jsonRespose); this.statistics = jsonRespose.data this.lastupdated = Util.getDateTimeStrings(new Date(jsonRespose.lastupdated).getTime()) console.log('statistics date', this.lastupdated); this.statisticsFiltersData = jsonRespose.filtersdata ?? {} if (jsonRespose.meta != null) this.statisticsMeta = jsonRespose.meta return jsonRespose.meta } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } fetchBulkReportingData = async () => { let path = "getbulkreportjobs" let urlBody: any = { "projectid": this.projectId } let url = "https://" + this.apiId + "/" + path; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('bulk reports jsonResponse', jsonResponse); let flagBulk = false; if (jsonResponse.result == true) { for (let sortid of Object.keys(jsonResponse.data)) { let sortidArr = sortid.split(';') let mmddyyyy = sortidArr[0] let entityid = sortidArr[1] let locationid = sortidArr[2] let eventid = sortidArr[3] let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1] if (this.mode == "next") { console.log('mmdd', mmdd, Object.keys(this.nextEvents[this.nextTabRole])); if (this.nextEvents[this.nextTabRole][mmdd] != null) { for (let i = 0; i < this.nextEvents[this.nextTabRole][mmdd].length; i++) { if (this.nextEvents[this.nextTabRole][mmdd][i].entityid == entityid && this.nextEvents[this.nextTabRole][mmdd][i].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][i].id == eventid) { this.nextEvents[this.nextTabRole][mmdd][i].isbulk = true; flagBulk = true break } } } } else { console.log('mmdd', mmdd, Object.keys(this.events)); if (this.events[mmdd] != null) { for (let i = 0; i < this.events[mmdd].length; i++) { if (this.events[mmdd][i].entityid == entityid && this.events[mmdd][i].locationid == locationid && this.events[mmdd][i].id == eventid) { this.events[mmdd][i].isbulk = true; flagBulk = true break } } } } } // All Bulk for testing // for(let mmdd of Object.keys(this.events)){ // for (let i = 0 ; i < this.events[mmdd].length; i ++){ // this.events[mmdd][i].isbulk = true; // flagBulk = true // } // } if (flagBulk) { // backgroundProcessButton.classList.remove('hide'); // backgroundProcessButton.style.display = 'flex' // console.log('backgroundprocessbutton', backgroundProcessButton); // backgroundProcessButton.addEventListener('click',() => { // console.log('bulk-progress clicked') // let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement // bulkLoader.scrollIntoView(); // }) if (this.mode == "next") { this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole) } else { this.renderAppropriateStream(this.sdate, this.edate, true, true) } } else { // backgroundProcessButton.classList.add('hide') // backgroundProcessButton.style.display = 'none' } } } else if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } } fetchUserCalendar = async () => { let url = "https://" + this.apiId + "/getuserevents"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); this.showChosenProject(); //console.log(jsonRespose); this.events = (jsonRespose.data.events) if (this.events != null) { this.renderTabs(this.TAB_YEAR); this.renderCalendar(); } // this.renderChosenProject(events); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchCalendar = async () => { //this.apiBodyList = '{"id": "' +(this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0]+ '"}' let url = "https://3mefupehxkw4pwsq3oyk7lf2pq0pisdx.lambda-url.us-east-1.on.aws/schedulegetcalendarjob"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0] }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true); this.events = JSON.parse(jsonRespose.data.value.events) // //console.log(events); if (this.events != null) { this.renderTabs(this.TAB_YEAR); this.renderCalendar(); } // this.renderChosenProject(events); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } fetchReprogramAdhoc = async () => { let url = "https://" + this.apiId + "/reprogramtrigger"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": this.mode == "admin" ? (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0] : this.projectId }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { // const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); this.fetchList(); setTimeout(() => { this.clearMessages(); }, 3000); } } fetchAdhoc = async () => { let path = "getallmyevents", view = ""; if (this.tagId != null && this.tagId != "") { view = "tag"; } else if (this.countryId != null && this.countryId != "") { view = "country"; } else if (this.locationId != null && this.locationId != "") { view = "location"; } else { view = "entity"; } let url = "https://" + this.apiId + "/" + path; let urlBody = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "true", "year": this.calendarStartYYYY, "view": view }; //console.log('urlbody', urlBody); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log(jsonRespose); let responseData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) return responseData; } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); this.fetchList(); setTimeout(() => { this.clearMessages(); }, 3000); } } fetchEventMap = async () => { let url = "https://" + this.apiId + "/getunmappedevents"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr({ "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "role": this.myRole }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log(jsonRespose); this.unmappedEvents = jsonRespose.data.unmappedEvents; this.mappings = jsonRespose.data.mappings; //console.log('mappings-1', 'fetcheventmap', this.mappings) //console.log('mappings0', 'fetcheventmap', this.mappedValuesUsers) this.renderMapping(this.unmappedEvents) //console.log('mappings1', 'fetcheventmap', this.mappedValuesUsers) this.prepopulateMapping(this.mappings); //console.log('mappings2', 'fetcheventmap', this.mappedValuesUsers) this.applyFilter(); if (jsonRespose.data.mappings != null && this.myRole != this.TAB_APPROVER) { (this._SfButtonBackCalendarMapping as HTMLButtonElement).style.visibility = 'visible'; } else { (this._SfButtonBackCalendarMapping as HTMLButtonElement).style.visibility = 'hidden'; } } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); this.fetchList(); setTimeout(() => { this.clearMessages(); }, 3000); } } fetchList = async () => { //console.log('calendar fetching list', this.apiIdList); const body: any = this.getApiBodyList(); if (this.apiIdList != null) { body.id = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0]; let url = "https://" + this.apiIdList + "/" + this.apiMethodList; //console.log('fetch events url', url); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; //console.log('fetch events body', body); if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); //console.log('list response', JSON.stringify(jsonRespose)); const fieldArr = JSON.parse(jsonRespose.data.value[this.apiResponseFieldList]) as Array; this.events = null; for (var i = 0; i < fieldArr.length; i++) { //console.log('events', fieldArr[i]); await this.fetchDetail(fieldArr[i]) } //console.log('all events processed'); await this.uploadEvents(); await this.fetchReprogramAdhoc(); //await this.fetchAdhoc(true); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } initCalendar = async () => { var newDate = null; var newMonth = null; var newYear = null; var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY); //console.log('startDate', startDate); do { this.calendar.push(startDate); startDate.setDate(startDate.getDate() + 1); newDate = ("0" + startDate.getDate()).slice(-2); newMonth = ("0" + startDate.getMonth()).slice(-2); newYear = (startDate.getFullYear()); } while (!(newDate == this.calendarStartDD && newMonth == (("0" + ((parseInt(this.calendarStartMM) - 1) + "")).slice(-2)) && newYear === (parseInt(this.calendarStartYYYY) + 1))); //console.log(this.calendar); } initInputs = () => { this.calendarStartDD = ("0" + this.calendarStartDD).slice(-2); this.calendarStartMM = ("0" + this.calendarStartMM).slice(-2); } showChooseProject = () => { var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf; var index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'flex' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } } showChosenProject = () => { var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf; var index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'flex' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } } showChosenMapping = () => { var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf; var index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'none' } elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf; index = 0, length = elems.length; for (; index < length; index++) { elems[index].style.display = 'flex' } } formatIndianNumber = (num: number) => { if (num === null || num === undefined || isNaN(num)) return ''; num = Number(num); if (num >= 10000000) { // 1 Crore = 10,000,000 return (num / 10000000).toFixed(num % 10000000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' Cr'; } else if (num >= 100000) { // 1 Lakh = 100,000 return (num / 100000).toFixed(num % 100000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' Lac'; } else if (num >= 1000) { return (num / 1000).toFixed(num % 1000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' K'; } else { return num.toString(); } } truncate = (str: string, n: number, useWordBoundary: boolean, ellipsis: boolean = true) => { if (str.length <= n) { return str; } const subString = str.slice(0, n - 1); // the original check return (useWordBoundary ? subString.slice(0, subString.lastIndexOf(" ")) : subString) + (ellipsis ? "…" : "..."); }; initListenersAdmin = () => { var old_element = null; var new_element = null; old_element = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); this._SfProject[0].querySelector('#sf-i-project').addEventListener('valueChanged', async () => { (this._SfTitleChosenMapping as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true); this.showChosenMapping(); this.fetchEventMap(); this.renderMappingTabs(this.TAB_REPORTER); }); old_element = (this._SfButtonBackChosenProject as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonBackChosenProject as HTMLButtonElement).addEventListener('click', async () => { this.loadMode(); }); old_element = (this._SfButtonSyncChosenProject as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonSyncChosenProject as HTMLButtonElement).addEventListener('click', async () => { this.fetchList(); }); old_element = (this._SfButtonBackChosenMapping as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonBackChosenMapping as HTMLButtonElement).addEventListener('click', async () => { this.loadMode(); }); old_element = (this._SfButtonMapChosenProject as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonMapChosenProject as HTMLButtonElement).addEventListener('click', async () => { (this._SfTitleChosenMapping as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true); this.showChosenMapping(); this.fetchEventMap(); this.renderMappingTabs(this.TAB_REPORTER); }); old_element = (this._SfButtonBackCalendarMapping as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonBackCalendarMapping as HTMLButtonElement).addEventListener('click', async () => { this.fetchCalendar() }); old_element = (this._SfButtonBackSyncMapping as HTMLButtonElement); new_element = old_element!.cloneNode(true); old_element?.parentElement?.replaceChild(new_element, old_element!); (this._SfButtonBackSyncMapping as HTMLButtonElement).addEventListener('click', async () => { this.fetchList(); }); } isAdmin = () => { return Util.readCookie('admin') == "true" } initDecryptView = () => { if (this.isAdmin()) { let divsArr = this._SfDecryptContainer.querySelectorAll("#decrypt-container > div") console.log('decrypt divs', divsArr); for (let divElement of divsArr) { (divElement as HTMLElement).classList.remove('hide'); } this.initDecryptListeners() } else { let divsArr = this._SfDecryptContainer.querySelectorAll("#decrypt-container > div") console.log('decrypt divs', divsArr); for (let divElement of divsArr) { (divElement as HTMLElement).classList.add('hide'); } } } initDecryptListeners = () => { (this._SfDecryptProjectInput as SfIForm).addEventListener('valueChanged', () => { let projectId = (this._SfDecryptProjectInput as SfIForm).selectedValues()[0] this.decryptProjectId = projectId.split(';')[projectId.split(';').length - 1]; this.evalDecrypt() }); (this._SfDecryptFileInput as HTMLInputElement).addEventListener('keyup', () => { console.log('keyup called'); this.decryptFileName = (this._SfDecryptFileInput as HTMLInputElement).value; this.evalDecrypt() }); (this._SfDecryptButton as HTMLButtonElement).addEventListener('click', () => { console.log('decrypt clicked', this.decryptProjectId, this.decryptFileName); this.submitDecrypt() }) } evalDecrypt = () => { console.log((this._SfDecryptFileInput as HTMLInputElement)) console.log('evalDecrypt', this.decryptProjectId, this.decryptFileName) if (this.decryptProjectId != null && this.decryptProjectId != "" && this.decryptFileName != null && this.decryptFileName.length > 3) { (this._SfDecryptContainer?.querySelector('#button-decrypt') as HTMLButtonElement).removeAttribute('disabled'); } else { (this._SfDecryptContainer?.querySelector('#button-decrypt') as HTMLButtonElement).setAttribute('disabled', 'true'); } } submitDecrypt = async () => { this.clearMessages(); console.log('submitDecrypt called'); const body: any = {}; let url = "https://" + this.apiId + "/getdecryptedjson"; body["projectid"] = this.decryptProjectId; body["key"] = this.decryptFileName + ".json"; console.log(body); console.log(JSON.stringify(body)); const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); let data = await this.fetchPresignedUrl(jsonRespose.signedUrlGet); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) console.log('decrypt response', jsonRespose) this.setSuccess('Operation Successful!'); const a = document.createElement("a"); a.style.display = "none"; a.href = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data)); a.download = this.decryptFileName + ".json"; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => { this.clearMessages(); }, 2000); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 5000); } } fetchNext = async (page: number, role: string, status: string) => { //this.apiBodyList = '{"id": "' +(this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0]+ '"}' this.nextPage = page; let url = "https://" + this.apiId + "/getnextuserevents"; let statusArr: string[] = [] if (status == this.TAB_ALL) { statusArr = [this.STATUS_NOT_STARTED, this.STATUS_PENDING_APPROVAL, this.STATUS_REJECTED, this.STATUS_APPROVED] } else if (status == this.TAB_PENDING_ON_ME) { if (role == this.TAB_REPORTER) { statusArr = [this.STATUS_NOT_STARTED, this.STATUS_REJECTED] } else if (role == this.TAB_APPROVER) { statusArr = [this.STATUS_PENDING_APPROVAL] } } else if (status == this.TAB_PENDING_ON_REPORTER) { statusArr = [this.STATUS_NOT_STARTED, this.STATUS_REJECTED] } else if (status == this.TAB_PENDING_ON_APPROVER) { statusArr = [this.STATUS_PENDING_APPROVAL] } else if (status == this.TAB_DONE) { statusArr = [this.STATUS_APPROVED] } const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); console.log('params', JSON.stringify({ "projectid": this.projectId, "userprofileid": this.userProfileId, "roles": [role], "year": this.calendarStartYYYY, "page": this.nextPage, "blocksize": parseInt(this.blocksize), "status": statusArr })) console.log('authorization', authorization) const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "roles": [role], "year": this.calendarStartYYYY + "", "page": this.nextPage, "blocksize": parseInt(this.blocksize), "status": statusArr, "list": "yes" }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('next response', jsonRespose) // this.renderChosenProject(events); // this.renderRoleTabsNext(jsonRespose.data, page) this.nextEvents = jsonRespose.data; this.renderNextEvents(this.nextEvents, page, role); this.fetchBulkReportingData(); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } clearButtonSelectionNext = () => { const buttonSelect = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf; for (var i = 0; i < buttonSelect.length; i++) { (buttonSelect[i] as HTMLInputElement).checked = false; } } renderRoleTabsNext = (page: number, loadData: boolean = true) => { //console.log('render role tabs'); (this._SfRoleTabContainer as HTMLDivElement).innerHTML = ''; if (this.nextTabRole == "") { // if(JSON.parse(this.myroles).length > 1){ // this.nextTabRole = this.TAB_ALL_ROLES // }else{ this.nextTabRole = JSON.parse(this.myroles)[0] // } } console.log('rendering tabs', this.nextTabRole); var html = ''; // if(JSON.parse(this.myroles).length > 1 && eventsData[this.TAB_ALL_ROLES] != null){ // html += ''; // } if (JSON.parse(this.myroles).indexOf(this.TAB_VIEWER) >= 0) { html += ''; } if (JSON.parse(this.myroles).indexOf(this.TAB_APPROVER) >= 0) { html += ''; } if (JSON.parse(this.myroles).indexOf(this.TAB_REPORTER) >= 0) { html += ''; } if (JSON.parse(this.myroles).indexOf(this.TAB_FUNCTION_HEAD) >= 0) { html += ''; } if (JSON.parse(this.myroles).indexOf(this.TAB_AUDITOR) >= 0) { html += ''; } (this._SfRoleTabContainer as HTMLDivElement).innerHTML = html; (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-all-roles')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_ALL_ROLES; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-reporter')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_REPORTER; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-approver')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_APPROVER; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-functionhead')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_FUNCTION_HEAD; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-auditor')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_AUDITOR; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-viewer')?.addEventListener('click', async () => { this.nextTabRole = this.TAB_VIEWER; this.nextTabStatus = this.TAB_ALL; // this.fetchNext(0, this.nextTabRole); this.renderRoleTabsNext(0, loadData); }); if (loadData) { this.renderStatusTabsNext(page); } else { (this._SfIEventsC.querySelector('#next-calendar-data').querySelector('#button-load-next') as HTMLButtonElement).addEventListener('click', () => { (this._SfIEventsC.querySelector('#next-calendar-data').querySelector('#button-load-next') as HTMLButtonElement).style.display = 'none'; (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).classList.add('flex-col'); this.renderRoleTabsNext(0) }) let changeEvent = new CustomEvent('valueChanged', { bubbles: true }); this.dispatchEvent(changeEvent); } let roleChangeEvent = new CustomEvent("roleChanged", { detail: { selectedRole: this.nextTabRole } }); this.dispatchEvent(roleChangeEvent) } renderStatusTabsNext = (page: number) => { (this._SfStatusTabContainer as HTMLDivElement).innerHTML = ''; if (this.nextTabStatus == "") { this.nextTabStatus = this.TAB_ALL } console.log('rendering status tabs', this.nextTabStatus); var html = ''; html += ''; if (this.nextTabRole == this.TAB_REPORTER || this.nextTabRole == this.TAB_APPROVER) { html += ''; } if (this.nextTabRole == this.TAB_APPROVER || this.nextTabRole == this.TAB_FUNCTION_HEAD || this.nextTabRole == this.TAB_AUDITOR || this.nextTabRole == this.TAB_VIEWER) { html += ''; } if (this.nextTabRole == this.TAB_REPORTER || this.nextTabRole == this.TAB_FUNCTION_HEAD || this.nextTabRole == this.TAB_AUDITOR || this.nextTabRole == this.TAB_VIEWER) { html += ''; } html += ''; (this._SfStatusTabContainer as HTMLDivElement).innerHTML = html; (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-all')?.addEventListener('click', async () => { this.nextTabStatus = this.TAB_ALL; this.renderStatusTabsNext(0); }); (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-me')?.addEventListener('click', async () => { this.nextTabStatus = this.TAB_PENDING_ON_ME; this.renderStatusTabsNext(0); }); (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-reporter')?.addEventListener('click', async () => { this.nextTabStatus = this.TAB_PENDING_ON_REPORTER; this.renderStatusTabsNext(0); }); (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-approver')?.addEventListener('click', async () => { this.nextTabStatus = this.TAB_PENDING_ON_APPROVER; this.renderStatusTabsNext(0); }); (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-done')?.addEventListener('click', async () => { this.nextTabStatus = this.TAB_DONE; this.renderStatusTabsNext(0); }); this.fetchNext(page, this.nextTabRole, this.nextTabStatus); } renderNextEvents = (eventsData: any, page: number, role: string) => { console.log('eventsData', eventsData) console.log('role', role) // if(Object.keys(eventsData[role]).length > 0){ var notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0, inTime = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0, lateReported = 0, scheduled = 0, partiallyComplied = 0, notComplied = 0, complied = 0, compliedWithGaps = 0, reportedNonCompliance = 0; var html = ''; this.selectedItemIds = []; this.selectedStatus = ""; html += '
'; for (var i = 0; i < Object.keys(eventsData[role]).length; i++) { let mmdd: string = Object.keys(eventsData[role])[i]; //console.log('mmdd', mmdd); //console.log('mmddevent', mmdd,eventsData[role][mmdd]); if (eventsData[role][mmdd] != null) { html += '
'; html += '
' + (mmdd.split("/")[1] + "/" + mmdd.split("/")[0]) + ' |
'; html += '
' for (var j = 0; j < (eventsData[role][mmdd] as Array).length; j++) { let eventHtml = ''; eventsData[role][mmdd][j]['mmdd'] = mmdd let functionStr = eventsData[role][mmdd][j]['functions'][0] if (functionStr.indexOf(';') >= 0) { functionStr = functionStr.split(';')[0].replace(/\([^)]*\)/g, ""); } // let reporterArr = [] // for(let reporter of eventsData[role][mmdd][j]['reporters']) { // reporterArr.push(reporter.split(';')[0]) // } console.log('function', functionStr) var partStatus = ""; var lateStatus = ""; var complianceStatus = ""; partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(eventsData[role][mmdd][j]))); lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(eventsData[role][mmdd][j])), partStatus); complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(eventsData[role][mmdd][j])).percentage, JSON.parse(JSON.stringify(eventsData[role][mmdd][j]))); notStarted = notStarted + (partStatus == "not-started" ? 1 : 0); pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0); rejected = rejected + (partStatus == "rejected" ? 1 : 0); approved = approved + (partStatus == "approved" ? 1 : 0); inTime = inTime + (lateStatus == "in-time" ? 1 : 0); pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0); lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0); lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0); lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0); scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0); partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0); notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0); complied = complied + (complianceStatus == "complied" ? 1 : 0); compliedWithGaps = compliedWithGaps + (complianceStatus == "complied-with-gaps" ? 1 : 0); reportedNonCompliance = reportedNonCompliance + (complianceStatus == "reported-non-compliance" ? 1 : 0); eventsData[role][mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus; eventsData[role][mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus; eventsData[role][mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus; // let thisRole = "" // if ((JSON.stringify(eventsData[role][mmdd][j].reporters)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Reporter' // } else if ((JSON.stringify(eventsData[role][mmdd][j].approvers)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Approver' // } else if ((JSON.stringify(eventsData[role][mmdd][j].functionheads)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Functionhead' // } else if ((JSON.stringify(eventsData[role][mmdd][j].auditors)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Auditor' // } else if ((JSON.stringify(eventsData[role][mmdd][j].viewers)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Viewer' // } let reportersStr = this.getReporterStringFromEvent(eventsData[role][mmdd][j]).replace(/mb-20/g, '') eventHtml += '
'; eventHtml += '
' + JSON.stringify(eventsData[role][mmdd][j]['tags']) + '
' eventHtml += '
not filtered
' eventHtml += '
' + (eventsData[role][mmdd][j].isbulk ? ('
') : ('')) + (eventsData[role][mmdd][j].isbulk ? '' : ('')) + '  ' + '
  
' + functionStr + '
' + reportersStr + '  ' + this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i) console.log('next isBulk', eventsData[role][mmdd][j].isbulk); if (eventsData[role][mmdd][j].isbulk == null || eventsData[role][mmdd][j].isbulk == false) { eventHtml += '' } eventHtml += '
'; eventHtml += '
' eventHtml += '
'; html += eventHtml } html += '
'; html += '
'; } } console.log('eventsData Role length', Object.keys(eventsData[role]).length) if (Object.keys(eventsData[role]).length == 0) { html += `

check_circle

Nothing to show here.
`; } else { html += '
' html += ''; html += '

Page ' + (page >= 0 ? (page + 1) : page) + '

' html += ''; html += '
'; } html += '
'; let nextEventsContainer = (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement); nextEventsContainer.innerHTML = html; nextEventsContainer.style.display = "flex"; this.myRole = role; let buttonListReports = nextEventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf for (let buttonListReport of buttonListReports) { buttonListReport?.addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const yyyy = this.getCurrentYear(idArr[3]); // const i = idArr[5]; const j = idArr[5]; let listReportingContainer = nextEventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement console.log('mmddyyyy', eventsData[role][mmdd][j], listReportingContainer, '#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j); if (listReportingContainer.style.display == 'none' || listReportingContainer.style.display == '') { this.renderListReporting(listReportingContainer, eventsData[role][mmdd][j], mmdd + '/' + yyyy, nextEventsContainer) } else { listReportingContainer.innerHTML = ''; listReportingContainer.style.display = 'none'; ev.target.setAttribute('part', 'button-list-reporting') let streamEventTitles = nextEventsContainer.querySelectorAll('.stream-event-title') as NodeListOf for (let streamEventTitle of streamEventTitles) { streamEventTitle.removeAttribute('part') } } // console.log('part', ev.target.getAttribute('part')); }) } // }else{ // let innerDivHtml = (this._SfIEventsC.querySelector('#stream-event-next') as HTMLDivElement).innerHTML; // innerDivHtml.replace('',''); // console.log('innerDivHtml', innerDivHtml) // innerDivHtml += html; // innerDivHtml += ''; // (this._SfIEventsC.querySelector('#stream-event-next') as HTMLDivElement).innerHTML = innerDivHtml; // } // if(page != 0){ let buttonPrev = this._SfIEventsC.querySelector('#button-prev') as HTMLButtonElement; buttonPrev?.addEventListener('click', () => { this.myRole = role; this.fetchNext(page - 1, this.nextTabRole, this.nextTabStatus) }); // } let buttonNext = this._SfIEventsC.querySelector('#button-next') as HTMLButtonElement; // buttonExpand = Util.clearListeners(buttonExpand) as HTMLButtonElement; buttonNext?.addEventListener('click', () => { this.myRole = role; this.fetchNext(page + 1, this.nextTabRole, this.nextTabStatus) }) const buttonArr = this._SfIEventsC.querySelectorAll('.button-expand') as NodeListOf; for (var i = 0; i < buttonArr.length; i++) { let indexPrevNext = i; buttonArr[i].addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; let found = false; for (var k = 0; k < this.selectedItemIds.length; k++) { if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) { found = true; } } if (!found) { this.selectedItemIds = []; this.clearButtonSelectionNext(); } // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'` var yyyy = this.getCurrentYear(idArr[3]); console.log('yyyy', yyyy, idArr[3]); console.log(eventsData[role][mmdd][j]) if (role == this.TAB_ALL_ROLES) { if (JSON.stringify(eventsData[role][mmdd][j]['viewers']).indexOf(this.userProfileId) >= 0) { this.myRole = this.TAB_VIEWER } if (JSON.stringify(eventsData[role][mmdd][j]['auditors']).indexOf(this.userProfileId) >= 0) { this.myRole = this.TAB_AUDITOR } if (JSON.stringify(eventsData[role][mmdd][j]['functionheads']).indexOf(this.userProfileId) >= 0) { this.myRole = this.TAB_FUNCTION_HEAD } if (JSON.stringify(eventsData[role][mmdd][j]['approvers']).indexOf(this.userProfileId) >= 0) { this.myRole = this.TAB_APPROVER } if (JSON.stringify(eventsData[role][mmdd][j]['reporters']).indexOf(this.userProfileId) >= 0) { this.myRole = this.TAB_REPORTER } } else { this.myRole = this.nextTabRole } console.log('redering detail', this.myRole) // this.renderEventDetail(eventsData[role][mmdd][j], mmdd + "/" + yyyy, null); let prevString = ""; if (indexPrevNext > 0) { prevString = (buttonArr[indexPrevNext - 1] as HTMLButtonElement).id; } let nextString = ""; if (indexPrevNext < buttonArr.length - 1) { nextString = (buttonArr[indexPrevNext + 1] as HTMLButtonElement).id; } this.fetchEventDetails(eventsData[role][mmdd][j], mmdd + "/" + yyyy, null, (this._SfIEventsC as HTMLDivElement), prevString, nextString); }) } const streamEventsContainer = this._SfIEventsC.querySelectorAll('.stream-events-container') as NodeListOf; const buttonSelect = this._SfIEventsC.querySelectorAll('.button-select') as NodeListOf; for (i = 0; i < buttonSelect.length; i++) { buttonSelect[i].addEventListener('click', (ev: any) => { //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length); const id = ev.target.id; const idArr = id.split("-") // const mmdd = idArr[2] + "/" + idArr[3]; // const j = idArr[4]; // const makercheckers = idArr[5]; const docs = idArr[6]; if ((ev.target as HTMLInputElement).checked) { this.selectedItemIds.push(id); } else { this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1); } if (this.selectedItemIds.length === 0) { for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const isbulk = idArr1[15] == "bulk" console.log('isBulk button-select3', id1, isbulk) if (isbulk) { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; } else { (buttonSelect[k] as HTMLInputElement).style.display = 'block'; } (streamEventsContainer[k] as HTMLDivElement).style.display = 'block'; } } else { if (this.selectedItemIds.length === 1) { const id1 = id; const idArr1 = id1.split("-") const status = idArr1[13].replace(/_/g, '-'); this.selectedStatus = status; } for (var k = 0; k < buttonSelect.length; k++) { const id1 = buttonSelect[k].id; const idArr1 = id1.split("-") const docs1 = idArr1[6]; const status = idArr1[13].replace(/_/g, '-'); if (docs == docs1 && status == this.selectedStatus) { } else { (buttonSelect[k] as HTMLInputElement).style.display = 'none'; (streamEventsContainer[k] as HTMLDivElement).style.display = 'none'; } } } }) let changeEvent = new CustomEvent('valueChanged', { bubbles: true }); this.dispatchEvent(changeEvent); } // return html; // }else{ // let html = ` //
//
//

check_circle

//
All good! Nothing is due.
//
//
`; // (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).innerHTML = html; // // (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).style.display = "none"; // let emptyEvent = new CustomEvent('valueChanged',{bubbles:false}); // this.dispatchEvent(emptyEvent); // } } fetchReports = async () => { let url = "https://" + this.apiId + "/getreports"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); console.log('this.myroles', this.myroles) const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "year": this.calendarStartYYYY }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); let arrReports = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete) console.log('reports response', Object.keys(arrReports).length); console.log('report', arrReports); this.renderReports(arrReports) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } renderReports = (reportsData: any) => { let html = '
' html += '
' for (let reportKey of Object.keys(reportsData)) { if (reportKey == '3/31/*,30;c989a44e-7d3d-427e-b712-90eacf585075;38dc8c53-643f-4fee-83fe-f15239606277;0a5fb99f-c36f-46c0-85b4-7fa3d48fa134') { continue; } let report = JSON.parse(reportsData[reportKey]) if (report['event'] == null) { continue; } html += '
' html += ''; html += ''; html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += '' html += ''; html += ''; html += '' html += `` html += ``; html += ``; html += ``; html += ``; html += ``; let locationname = "" let eventHtml = "" if (report['event'] != null) { locationname = JSON.parse(report['event'])['locationname'] ?? ""; for (var i = 0; i < Object.keys(JSON.parse(report['event'])).length; i++) { if (!this.EXCLUDE_COLS_FROM_REGS.includes(Object.keys(JSON.parse(report['event']))[i].toLowerCase())) { eventHtml += ''; } } } html += ``; html += ''; html += ''; html += '
SelectProcessedDateDocsCommentsLastUpdatedCompletionDateLocationCompliance
${report['processed'] ?? false ? "done_all" : ""}${reportKey.split(';')[0]}${JSON.parse(report['docs']).length}${report['comments'].length}${Util.getDateTimeStrings(new Date(report['lastupdated']).getTime())}${new Date(parseInt(report['dateofcompletion'])).toLocaleDateString('en-US', { timeZone: 'Asia/Kolkata' })}'; eventHtml += ('' + Object.keys(JSON.parse(report['event']))[i] + ''); eventHtml += ('' + ''); eventHtml += '${locationname}'; // const jsonReportEvent = JSON.parse(report['comments'].reportevent); // console.log('jsonReportEvent', report['event']); if (report['event'] != null) { html += ''; html += ''; html += eventHtml; html += ''; html += '
'; } html += '
'; html += '
'; } html += '
'; html += '
'; (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html; const arrButtonSelect = this._SfIEventsC.querySelectorAll('.button-select') as NodeListOf; for (let buttonSelect of arrButtonSelect) { buttonSelect.addEventListener('click', (ev: any) => { const id = ev.target.id; console.log('id', id) const idArr = id.split("-") console.log('idArr', idArr) const sortid = idArr[2].replace(/_/g, '-') console.log('selected sortid', sortid) let reportData = JSON.parse(reportsData[sortid]); console.log('selectedReportData', reportData); this.renderComplianceSelector(sortid, reportData.processed ?? false); }) } const arrButtonCheck = this._SfIEventsC.querySelectorAll('.button-check') as NodeListOf; for (let buttonCheck of arrButtonCheck) { buttonCheck.addEventListener('click', async (ev: any) => { const id = ev.target.id; console.log('id', id) const idArr = id.split("-") console.log('idArr', idArr) const sortid = idArr[2].replace(/_/g, '-') console.log('selected sortid', sortid) let complianceEntityId = sortid.split(';')[1] let complianceLocationId = sortid.split(';')[2] let complianceId = sortid.split(';')[3] let mmddyyyy = sortid.split(';')[0]; let mm = mmddyyyy.split('/')[0]; let dd = mmddyyyy.split('/')[1]; let yyyy = mmddyyyy.split('/')[2]; let date = new Date(parseInt(yyyy), parseInt(mm) - 1, parseInt(dd)); let sDateObj = date sDateObj.setDate(date.getDate() - 3) let day = '' + sDateObj.getDate(); let month = '' + (sDateObj.getMonth() + 1); let year = '' + sDateObj.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; let sDate = month + "/" + day + "/" + year let eDateObj = date eDateObj.setDate(date.getDate() + 6) day = '' + eDateObj.getDate(); month = '' + (eDateObj.getMonth() + 1); year = '' + eDateObj.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; let eDate = month + "/" + day + "/" + year let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": complianceEntityId, "countryid": "", "functionid": "", "locationid": complianceLocationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": "location", "year": this.calendarStartYYYY, "contractstartdate": this.contractStartDate }; let url = "https://" + this.apiId + "/getallcountryevents5"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonRespose = JSON.parse(xhr.responseText); console.log('jsonRespose', jsonRespose); let arrCompliances = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet)); if (arrCompliances == null || Object.keys(arrCompliances).length === 0) { this.setSuccess('Zombie detected!') setTimeout(() => { this.clearMessages() }, 5000); } else { let zombie: boolean = true; Object.keys(arrCompliances).forEach((key: string) => { console.log('checking', key, mm + "/" + dd); if (key == mm + "/" + dd) { const compliances = arrCompliances[key] as Array; compliances.forEach((compliance: any) => { console.log('checking', compliance.id, complianceId); if (compliance.id == complianceId) { zombie = false; } }) } }); if (zombie) { this.setSuccess('Zombie detected!') setTimeout(() => { this.clearMessages() }, 5000); } else { this.setSuccess('Not a Zombie!') setTimeout(() => { this.clearMessages() }, 5000); } } await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete); console.log('receivedCompliacnes', arrCompliances) // this.renderReportsComplainces(arrCompliances, sortid); } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { this.showChosenProject(); (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0]; this.renderChosenProject(); } else { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); setTimeout(() => { this.clearMessages(); }, 5000); } } }) } } renderComplianceSelector = (sortid: string, processed: boolean = false) => { let html = '' html += '
' html += '
' html += '' html += '
' html += `` html += `` html += `` html += '
' html += '' html += `` html += '
'; html += '
'; (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html; let inputReporter = (this._SfIEventsC.querySelector('#input-user') as SfIForm) let inputEntityForm = (this._SfIEventsC.querySelector('#input-entity-tags') as SfIForm); let inputLocationForm = (this._SfIEventsC.querySelector('#input-location-tags') as SfIForm); inputReporter.loadMode(); inputReporter.addEventListener('valueChanged', (ev: any) => { let targetForm = ev.target as SfIForm; let selectedReporter = targetForm.selectedTexts()[0] console.log('reporter selected', selectedReporter) checkButtonSearch() }) let entityId = sortid.split(';')[1] inputEntityForm.selectedSearchId = entityId; inputEntityForm.loadMode(); inputEntityForm.addEventListener('valueChanged', (ev: any) => { let targetForm = ev.target as SfIForm; let selectedEntity = targetForm.selectedTexts()[0] console.log('entity selected', selectedEntity) inputLocationForm.searchPhrase = this.projectName + '&Location&' + selectedEntity.replace(/\([^)]*\)/g, ""); inputLocationForm.loadMode(); checkButtonSearch() }) let locationId = sortid.split(';')[2] inputLocationForm.selectedSearchId = locationId; inputLocationForm.loadMode(); inputLocationForm.addEventListener('valueChanged', (ev: any) => { let targetForm = ev.target as SfIForm; let selectedLocation = targetForm.selectedTexts()[0] console.log('location selected', selectedLocation) checkButtonSearch() }) let buttonBack = (this._SfIEventsC.querySelector('#button-reports-date-selector-back') as HTMLButtonElement) buttonBack.addEventListener('click', () => { this.fetchReports() }) let buttonSearch = (this._SfIEventsC.querySelector('#button-reports-search') as HTMLButtonElement) buttonSearch.addEventListener('click', () => { let selectedReporterId = inputReporter.selectedValues()[0]; let selectedEntityId = inputEntityForm.selectedValues()[0]; let selectedLocationId = inputLocationForm.selectedValues()[0]; this.fetchReportCompliances(selectedReporterId, selectedEntityId, selectedLocationId, sortid, processed) }) let buttonMark = (this._SfIEventsC.querySelector('#button-reports-mark') as HTMLButtonElement) buttonMark.addEventListener('click', () => { let [mmddyyyy, entityid, locationid, complianceid] = sortid.split(';'); let year = this.getFinancialYear(mmddyyyy) this.markReport(mmddyyyy, entityid, locationid, complianceid, year, !processed) }) function checkButtonSearch() { let selectedReporterId = inputReporter.selectedValues()[0]; let selectedEntityId = inputEntityForm.selectedValues()[0]; let selectedLocationId = inputLocationForm.selectedValues()[0]; if (selectedReporterId != null && selectedEntityId != null && selectedLocationId != null) { buttonSearch.disabled = false; } else { buttonSearch.disabled = true; } } } markReport = async (mmddyyyy: string, entityid: string, locationid: string, eventid: string, year: string, processed: boolean) => { console.log('marking report', eventid, processed) let url = "https://" + this.apiId + "/markreportprocessed"; let urlBody: any = { "projectid": this.projectId, "eventid": eventid, "mmddyyyy": mmddyyyy, "entityid": entityid, "locationid": locationid, "year": year, "processed": processed }; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { this.setSuccess("Report " + ((processed == true) ? "marked" : "unmarked") + " successfully."); this.fetchReports(); setTimeout(() => { this.clearMessages(); }, 5000); } else { const jsonResponse = JSON.parse(xhr.responseText); this.setError(jsonResponse.error); setTimeout(() => { this.clearMessages(); }, 5000); } } fetchReportCompliances = async (reporterid: string, entityid: string, locationid: string, sortid: string, processed: boolean) => { console.log('fetching compliances', sortid) let url = "https://" + this.apiId + "/geteventfromreport"; let urlBody: any = { "projectid": this.projectId, "sortid": sortid, "reporterid": reporterid, "entityid": entityid, "locationid": locationid }; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { const jsonResponse = JSON.parse(xhr.responseText); console.log('fetch compliances jsonRespose', jsonResponse); if (jsonResponse.event == null) { this.setError("Compliance status is - " + jsonResponse.completenessstatus); setTimeout(() => { this.clearMessages(); }, 5000); } else { let returnedEvent = jsonResponse.event let arrCompliances = [(returnedEvent)]; let assocEvents: any = {}; let mmdd = (returnedEvent.duedate).split('/')[1] + "/" + (returnedEvent.duedate).split('/')[0]; assocEvents[mmdd] = arrCompliances; this.renderReportsCompliances(assocEvents, sortid, processed); } } else { const jsonResponse = JSON.parse(xhr.responseText); this.setError(jsonResponse.error); setTimeout(() => { this.clearMessages(); }, 5000); } } renderReportsCompliances = (compliancesData: any, sortid: string, processed: boolean) => { let eventsData: any = {} let complianceId = sortid.split(';')[3] console.log('renderReportsComplainces', compliancesData, complianceId); for (let dateStr of Object.keys(compliancesData)) { for (var j = 0; j < (compliancesData[dateStr] as Array).length; j++) { console.log('renderReportsComplainces comparing id', compliancesData[dateStr][j].id, complianceId); if (compliancesData[dateStr][j].id == complianceId && this.getCompletenessStatus(JSON.parse(JSON.stringify(compliancesData[dateStr][j]))) == "not-started") { console.log(compliancesData[dateStr][j]) // if(compliancesData[dateStr][j].id == complianceId){ if (eventsData[dateStr] == null) { eventsData[dateStr] = [] } eventsData[dateStr].push(compliancesData[dateStr][j]) } } } console.log('eventsData', eventsData) let html = ''; html += '
' html += '' html += '
' html += '
'; for (var i = 0; i < Object.keys(eventsData).length; i++) { let mmdd: string = Object.keys(eventsData)[i]; //console.log('mmdd', mmdd); //console.log('mmddevent', mmdd,eventsData[role][mmdd]); if (eventsData[mmdd] != null) { html += '
'; html += '
' + (mmdd.split("/")[1] + "/" + mmdd.split("/")[0]) + ' |
'; html += '
' for (var j = 0; j < (eventsData[mmdd] as Array).length; j++) { let eventHtml = ''; eventsData[mmdd][j]['mmdd'] = mmdd let functionStr = eventsData[mmdd][j]['functions'][0] if (functionStr.indexOf(';') >= 0) { functionStr = functionStr.split(';')[0].replace(/\([^)]*\)/g, ""); } console.log('function', functionStr) var partStatus = ""; var lateStatus = ""; var complianceStatus = ""; partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(eventsData[mmdd][j]))); if (partStatus != "not-started") { continue; } lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(eventsData[mmdd][j])), partStatus); complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(eventsData[mmdd][j])).percentage, JSON.parse(JSON.stringify(eventsData[mmdd][j]))); // notStarted = notStarted + (partStatus == "not-started" ? 1 : 0); // pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0); // rejected = rejected + (partStatus == "rejected" ? 1 : 0); // approved = approved + (partStatus == "approved" ? 1 : 0); // inTime = inTime + (lateStatus == "in-time" ? 1 : 0); // pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0); // lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0); // lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0); // lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0); // scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0); // partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0); // notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0); // complied = complied + (complianceStatus == "complied" ? 1 : 0); eventsData[mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus; eventsData[mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus; eventsData[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus; // let thisRole = "" // if ((JSON.stringify(eventsData[role][mmdd][j].reporters)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Reporter' // } else if ((JSON.stringify(eventsData[role][mmdd][j].approvers)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Approver' // } else if ((JSON.stringify(eventsData[role][mmdd][j].functionheads)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Functionhead' // } else if ((JSON.stringify(eventsData[role][mmdd][j].auditors)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Auditor' // } else if ((JSON.stringify(eventsData[role][mmdd][j].viewers)).indexOf(this.userProfileId) >= 0){ // thisRole = 'Viewer' // } eventHtml += '
'; eventHtml += '
' + JSON.stringify(eventsData[mmdd][j]['tags']) + '
' eventHtml += '
not filtered
' eventHtml += '
' + '' + '  ' + '
  
' + functionStr + '
  ' + this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i) + '
'; eventHtml += '
'; html += eventHtml } html += '
'; html += '
'; } } html += '
'; (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html; const arrButtonSelect = this._SfIEventsC.querySelectorAll('.button-expand') as NodeListOf; for (let buttonSelect of arrButtonSelect) { buttonSelect.addEventListener('click', (ev: any) => { const id = ev.target.id; const idArr = id.split("-") const mmdd = idArr[3] + "/" + idArr[4]; const j = idArr[5]; let eventObj = eventsData[mmdd][j]; console.log('move reporting', mmdd + '/' + this.calendarStartYYYY, sortid) this.submitUpdateReporting(mmdd + '/' + this.calendarStartYYYY, eventObj['entityid'], eventObj['locationid'], sortid); }) } let buttonBack = (this._SfIEventsC.querySelector('#button-reports-date-selector-back') as HTMLButtonElement) buttonBack.addEventListener('click', () => { this.renderComplianceSelector(sortid, processed) }) } submitUpdateReporting = async (mmddyyyy: string, entityid: string, locationid: string, sortid: string) => { let url = "https://" + this.apiId + "/updatereportdate"; const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken')); console.log('this.myroles', this.myroles) const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "mmddyyyy": mmddyyyy, "entityid": entityid, "locationid": locationid, "sortid": sortid }, url, this._SfLoader, authorization)) as any; this._SfLoader.innerHTML = ''; if (xhr.status == 200) { this.setSuccess("update successful!"); setTimeout(() => { this.clearMessages(); this.fetchReports(); }, 3000) } else { if (xhr.status == 401) { let changeEvent = new CustomEvent('tokenExpired', { bubbles: true }); this.dispatchEvent(changeEvent); } if (xhr.status === 404) { const jsonRespose = JSON.parse(xhr.responseText); this.setError(jsonRespose.error); } } } loadMode = async () => { Chart.register(...registerables); Chart.register(exportBackgroundPlugin); //Chart.register(Colors); if (this.mode == "rcmnotifications") { this.loadRcmNotifications(); } else if (this.mode == "rcm") { this.renderRcmTabs(); ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-compliances') as HTMLButtonElement).click(); } else if (this.mode == "onboarding") { //this.myOnboardingTab = this.TAB_STATUTES; this.renderOnboardingTabs(); // this.clickOnboardingTabs(); //this.loadOnboardingStatutes(); //((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-compliances') as HTMLButtonElement).click(); } else if (this.mode == "admin") { this.showChooseProject(); this.initListenersAdmin(); } else if (this.mode == "downloader") { setTimeout(() => { this.initDecryptView(); }, 500) } else if (this.mode == "next") { // this.fetchNext(0) this.renderRoleTabsNext(0, false) } else if (this.mode == "reports") { this.fetchReports(); } else if (this.mode == "viewer") { this.enableCustom(); this.selectedTab = this.TAB_CUSTOM this.renderCustom(); this.renderWithFeatures(this.sdate, this.edate, "", "yes") } else { this.flowGraph = this.FLOW_GRAPH_COMPLETENESS; this.enableCalendar(); this.initInputs(); this.initCalendar(); let tempRole = this.myRole; if (tempRole == "") { this.myRole = this.TAB_REPORTER; } this.renderRoleTabs(); if (tempRole != "") { this._SfRoleTabContainer.innerHTML = ''; } // this.selectedFeatures = this.getFeatures() //console.log('stream received', this.stream, this.TAB_STREAM, this.TAB_YEAR); if (this.stream == this.TAB_YEAR) { this.renderTabs(this.TAB_YEAR); ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-year') as HTMLButtonElement)?.click(); } else { //console.log('stream received rendering year', this.stream); this.selectedFeatures = Util.getFeatures(); for (let feature of this.selectedFeatures) { if (this.getFeatures().indexOf(feature) < 0) { this.selectedFeatures = ['compliances'] break; } } if (this.selectedFeatures.indexOf('contracts') >= 0) { this.renderTabs(this.TAB_CUSTOM); ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { if (this.myRole == this.TAB_VIEWER) { this.renderTabs(this.TAB_CUSTOM); ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click(); } else { let userAdHocCheckTime = Util.getUserAdhocCheckTime(); this.flagAdhoc = true; if (userAdHocCheckTime != null) { let adHocCheckTime = new Date(parseInt(userAdHocCheckTime)); let currentTime = new Date(); if (adHocCheckTime.getMonth() == currentTime.getMonth()) { this.flagAdhoc = false } } console.log('FlagAdHoc', this.flagAdhoc, this.selectedFeatures) if (this.flagAdhoc && this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0) { this.renderTabs(this.TAB_ADHOC); ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-adhoc') as HTMLButtonElement)?.click(); } else { this.renderTabs(this.TAB_STREAM); ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } } } // this.renderTabs(this.TAB_STREAM); // ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click(); } //await this.fetchUserCalendar_2(); // if(this.events != null && !this.foundCalendarInLocal()) { // this.renderTabs(this.TAB_YEAR); // this.renderCalendar(); // } } } constructor() { super(); } protected override firstUpdated(_changedProperties: PropertyValueMap | Map): void { this.loadMode(); } override connectedCallback() { super.connectedCallback() } override render() { console.log('rendering', this.mode); if (this.mode == "rcmnotifications") { return html`
`; } else if (this.mode == "rcm") { return html`
`; } else if (this.mode == "onboarding") { return html`
`; } else if (this.mode == "admin") { return html`

${this.name}

Admin

Choose Project

   

Project Name

   
 

Project Name

 
`; } else if (this.mode == "downloader") { /* eslint-disable lit/no-unknown-attribute */ return html`

${this.name}

.json  
`; /* eslint-disable lit/no-unknown-attribute */ } else if (this.mode == "next") { return html`
`; } else if (this.mode == "reports") { return html`
`; } else { return html`
`; } } } declare global { interface HTMLElementTagNameMap { 'sf-i-events': SfIEvents; } }