Merge pull request #3467 from kkazala/main

Upgrade to SPFx 1.16: react-appinsights-dashboard
This commit is contained in:
Hugo Bernier 2023-02-09 00:09:11 -05:00 committed by GitHub
commit 88828ea361
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 16447 additions and 26115 deletions

View File

@ -0,0 +1,378 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/default'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {
'no-new': 0,
'class-name': 0,
'export-name': 0,
forin: 0,
'label-position': 0,
'member-access': 2,
'no-arg': 0,
'no-console': 0,
'no-construct': 0,
'no-duplicate-variable': 2,
'no-eval': 0,
'no-function-expression': 2,
'no-internal-module': 2,
'no-shadowed-variable': 2,
'no-switch-case-fall-through': 2,
'no-unnecessary-semicolons': 2,
'no-unused-expression': 2,
'no-with-statement': 2,
semicolon: 2,
'trailing-comma': 0,
typedef: 0,
'typedef-whitespace': 0,
'use-named-parameter': 2,
'variable-name': 0,
whitespace: 0
}
}
]
};

View File

@ -22,8 +22,8 @@ This web part displays different statistics data captured in the **Azure Applica
## Compatibility
![SPFx 1.10](https://img.shields.io/badge/SPFx-1.10.0-green.svg)
![Node.js v10 | v8](https://img.shields.io/badge/Node.js-v10%20%7C%20v8-green.svg)
![SPFx 1.16.1](https://img.shields.io/badge/SPFx-1.16.1-green.svg)
![Node.js v16](https://img.shields.io/badge/Node.js-v16-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
@ -37,7 +37,7 @@ This web part displays different statistics data captured in the **Azure Applica
* [Injecting JavaScript with SharePoint Framework Extensions - Azure Application Insights](https://github.com/pnp/sp-dev-fx-extensions/tree/main/samples/js-application-appinsights)
* [JS Application AppInsights Advanced](https://github.com/pnp/sp-dev-fx-extensions/tree/main/samples/js-application-appinsights-advanced)
Following are required to access the data using **[App Insights API](https://dev.applicationinsights.io/)**. The API has been provided in a very simple way with **[API Explorer](https://dev.applicationinsights.io/apiexplorer)** for the developers to play around the API to understand the schema and the methods that can used.
Following are required to access the data using **[App Insights API](https://learn.microsoft.com/en-us/rest/api/application-insights/)**. To try the API without writing any code, see [Trying the Log Analytics API](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/api/overview#trying-the-log-analytics-api)
* **Application ID** of the Application Insights
* **API Key** for the data access
@ -82,6 +82,7 @@ react-appinsights-dashboard | [Sudharsan K.](https://github.com/sudharsank)([@su
Version|Date|Comments
-------|----|--------
1.0.1.0| February 06, 2023 | Upgrade to SPFx 1.16
1.0.0.0|May 10, 2020|Initial release
1.0.0.1|June 16, 2020|Initial release
@ -90,7 +91,7 @@ Version|Date|Comments
- Clone this repository
- From your command line, change your current directory to the directory containing this sample (`react-appinsights-dashboard`, located under `samples`)
- in the command line run:
- `npm install`
- `npm install` (or even better, `pnpm install` )
- `gulp bundle --ship && gulp package-solution --ship`
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.

View File

@ -3,7 +3,7 @@
"solution": {
"name": "React AppInsights Dashboard",
"id": "6696970c-955e-4d95-82a3-35c0d2a5818c",
"version": "1.0.0.0",
"version": "1.0.1.0",
"includeClientSideAssets": true,
"isDomainIsolated": false
},

View File

@ -4,4 +4,13 @@ const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
{
"name": "react-appinsights-dashboard",
"version": "0.0.1",
"version": "1.0.1",
"private": true,
"main": "lib/index.js",
"engines": {
"node": ">=0.10.0"
"node": ">=16.13.0 <17.0.0"
},
"scripts": {
"build": "gulp bundle",
@ -12,34 +12,42 @@
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.10.0",
"@microsoft/sp-lodash-subset": "1.10.0",
"@microsoft/sp-office-ui-fabric-core": "1.10.0",
"@microsoft/sp-property-pane": "1.10.0",
"@microsoft/sp-webpart-base": "1.10.0",
"@pnp/spfx-controls-react": "1.17.0",
"@types/es6-promise": "0.0.33",
"@types/react": "16.8.8",
"@types/react-dom": "16.8.3",
"@types/webpack-env": "1.13.1",
"@fluentui/react": "~8.105.2",
"@microsoft/applicationinsights-react-js": "^3.4.0",
"@microsoft/applicationinsights-web": "^2.8.9",
"@microsoft/sp-core-library": "1.16.1",
"@microsoft/sp-http": "^1.16.1",
"@microsoft/sp-lodash-subset": "1.16.1",
"@microsoft/sp-office-ui-fabric-core": "1.16.1",
"@microsoft/sp-property-pane": "1.16.1",
"@microsoft/sp-webpart-base": "1.16.1",
"@pnp/spfx-controls-react": "^3.12.0",
"chart.js": "^4.2.0",
"history": "~5.3.0",
"lodash": "^4.17.21",
"moment": "^2.29.2",
"office-ui-fabric-react": "6.189.2",
"react": "16.8.5",
"react-dom": "16.8.5"
"moment": "^2.29.4",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"resolutions": {
"@types/react": "16.8.8"
"@types/react": "17.0.45"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.16.1",
"@microsoft/eslint-plugin-spfx": "1.16.1",
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@microsoft/sp-build-web": "1.16.1",
"@microsoft/sp-tslint-rules": "1.10.0",
"@microsoft/sp-module-interfaces": "1.10.0",
"@microsoft/sp-webpart-workbench": "1.12.1",
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
"gulp": "~3.9.1",
"@types/chai": "3.4.34",
"@types/mocha": "2.2.38",
"ajv": "~5.2.2"
"@microsoft/sp-module-interfaces": "1.16.1",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"@types/lodash": "~4.14.184",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.5.5"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -21,4 +21,7 @@ export interface IPerfDurationProps {
PerDur_50: number;
PerDur_95: number;
PerDur_99: number;
}
}
export interface Dictionary<T> {
[index: string]: T;
}

View File

@ -1,8 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';
import { TimeInterval, TimeSpan, Segments } from './enumHelper';
import { IPageViewCountProps, IPageViewDetailProps, defaultDateFormat, chartDateFormat } from './CommonProps';
const moment: any = require('moment');
import { IPageViewCountProps, IPageViewDetailProps, defaultDateFormat, chartDateFormat, Dictionary } from './CommonProps';
import moment from 'moment';
export default class Helper {
private _appid: string = '';
@ -11,8 +12,9 @@ export default class Helper {
private requestHeaders: Headers = new Headers();
private httpClientOptions: IHttpClientOptions = {};
private httpClient: HttpClient = null;
private cultureName:string=null;
constructor(appid: string, appkey: string, httpclient: HttpClient) {
constructor(appid: string, appkey: string, httpclient: HttpClient, cultureName:string) {
this._appid = appid;
this._appkey = appkey;
this.httpClient = httpclient;
@ -20,15 +22,16 @@ export default class Helper {
this.requestHeaders.append('Content-type', 'application/json; charset=utf-8');
this.requestHeaders.append('x-api-key', this._appkey);
this.httpClientOptions = { headers: this.requestHeaders };
this.cultureName= cultureName;
}
public getPageViewCount = async (timespan: TimeSpan, timeinterval: TimeInterval): Promise<IPageViewCountProps[]> => {
let finalRes: IPageViewCountProps[] = [];
let finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}`;
let response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
let responseJson: any = await response.json();
const finalRes: IPageViewCountProps[] = [];
const finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}`;
const response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
const responseJson: any = await response.json();
if (responseJson.value && responseJson.value.segments.length > 0) {
let segments: any[] = responseJson.value.segments;
const segments: any[] = responseJson.value.segments;
segments.map((seg: any) => {
finalRes.push({
oriDate: seg.start,
@ -41,21 +44,21 @@ export default class Helper {
}
public getPageViews = async (timespan: TimeSpan, timeinterval: TimeInterval, segment: Segments[]): Promise<IPageViewDetailProps[]> => {
let finalRes: IPageViewDetailProps[] = [];
let finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}&segment=${encodeURIComponent(segment.join(','))}`;
let response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
let responseJson: any = await response.json();
const finalRes: IPageViewDetailProps[] = [];
const finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}&segment=${encodeURIComponent(segment.join(','))}`;
const response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
const responseJson: any = await response.json();
if (responseJson.value && responseJson.value.segments.length > 0) {
let mainSegments: any[] = responseJson.value.segments;
const mainSegments: any[] = responseJson.value.segments;
mainSegments.map(mainseg => {
if (mainseg.segments.length > 0) {
mainseg.segments.map((seg: any) => {
finalRes.push({
oriStartDate: mainseg.start,
oriEndDate: mainseg.end,
start: this.getFormattedDate(mainseg.start),
end: this.getFormattedDate(mainseg.end),
date: `${this.getFormattedDate(mainseg.start)} - ${this.getFormattedDate(mainseg.end)}`,
start: this.getFormattedDate(mainseg.start, 'L'),
end: this.getFormattedDate(mainseg.end, 'L'),
date: `${this.getFormattedDate(mainseg.start, 'L')} - ${this.getFormattedDate(mainseg.end, 'L')}`,
Url: seg[segment[0]],
count: seg['pageViews/count'].sum
});
@ -66,11 +69,11 @@ export default class Helper {
return finalRes;
}
public getResponseByQuery = async (query: string, useTimespan: boolean, timespan?: TimeSpan): Promise<any[]> => {
let finalRes: any[] = [];
let urlQuery: string = useTimespan ? `timespan=${timespan}&query=${encodeURIComponent(query)}` : `query=${encodeURIComponent(query)}`;
let finalPostUrl: string = this._postUrl + `/query?${urlQuery}`;
let responseJson: any = await this.getAPIResponse(finalPostUrl);
public getResponseByQuery = async <T>(query: string, useTimespan: boolean, timespan?: TimeSpan): Promise<T[]> => {
let finalRes: T[] = [];
const urlQuery: string = useTimespan ? `timespan=${timespan}&query=${encodeURIComponent(query)}` : `query=${encodeURIComponent(query)}`;
const finalPostUrl: string = this._postUrl + `/query?${urlQuery}`;
const responseJson: any = await this.getAPIResponse(finalPostUrl);
if (responseJson.tables.length > 0) {
finalRes = responseJson.tables[0].rows;
}
@ -78,19 +81,19 @@ export default class Helper {
}
public getUserPageViews = async (timespan: TimeSpan | string, timeinterval: TimeInterval, segment: Segments[]): Promise<IPageViewDetailProps[]> => {
let finalRes: any[] = [];
let finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${encodeURIComponent(timespan)}&interval=${timeinterval}&segment=${encodeURIComponent(segment.join(','))}`;
let response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
let responseJson: any = await response.json();
const finalRes: any[] = [];
const finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${encodeURIComponent(timespan)}&interval=${timeinterval}&segment=${encodeURIComponent(segment.join(','))}`;
const response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
const responseJson: any = await response.json();
if (responseJson.value && responseJson.value.segments.length > 0) {
let mainSegments: any[] = responseJson.value.segments;
const mainSegments: any[] = responseJson.value.segments;
mainSegments.map(mainseg => {
if (mainseg.segments.length > 0) {
let childSegments: any[] = mainseg.segments;
const childSegments: any[] = mainseg.segments;
childSegments.map(childseg => {
let grandChildSegments: any[] = childseg.segments;
const grandChildSegments: any[] = childseg.segments;
grandChildSegments.map(grandchildseg => {
if (grandchildseg['pageView/urlPath'] != '') {
if (grandchildseg['pageView/urlPath'] !== '') {
finalRes.push({
oriStartDate: mainseg.start,
oriEndDate: mainseg.end,
@ -111,12 +114,12 @@ export default class Helper {
}
public getAPIResponse = async (urlWithQuery: string): Promise<any> => {
let response: HttpClientResponse = await this.httpClient.get(urlWithQuery, HttpClient.configurations.v1, this.httpClientOptions);
const response: HttpClientResponse = await this.httpClient.get(urlWithQuery, HttpClient.configurations.v1, this.httpClientOptions);
return await response.json();
}
public getTimeSpanMenu = (): any[] => {
let items: any[] = [];
public getTimeSpanMenu = (): Dictionary<string>[] => {
const items: Dictionary<string>[] = [];
Object.keys(TimeSpan).map(key => {
items.push({
text: key,
@ -126,8 +129,8 @@ export default class Helper {
return items;
}
public getTimeIntervalMenu = (): any[] => {
let items: any[] = [];
public getTimeIntervalMenu = (): Dictionary<string>[] => {
const items: Dictionary<string>[] = [];
Object.keys(TimeInterval).map(key => {
items.push({
text: key,
@ -138,11 +141,12 @@ export default class Helper {
}
public getLocalTime = (utcTime: string): string => {
return moment(utcTime).local().format(chartDateFormat);
}
public getFormattedDate = (datetime: string, format?: string): string => {
return moment(datetime).local().format(format ? format : defaultDateFormat);
public getFormattedDate = (datetime: string, format: string=defaultDateFormat): string => {
return moment(datetime).locale(this.cultureName).format(format ? format : defaultDateFormat);
}
public getQueryDateFormat = (datetime: string): string => {
@ -157,7 +161,7 @@ export default class Helper {
return moment(datetime).format('YYYY-MM-DDTHH:MM:00.000Z');
}
public getRandomColor = () => {
public getRandomColor = () : string => {
return "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," +
Math.floor(Math.random() * 255) + ")";
}

View File

@ -1,12 +1,12 @@
import { PivotItem, Pivot } from '@fluentui/react';
import * as React from 'react';
import styles from '../CommonControl.module.scss';
import { Pivot, PivotItem } from 'office-ui-fabric-react/lib/Pivot';
export interface IPivotProps {
ShowLabel: boolean;
LabelText: string;
SelectedKey: string;
Items: any[];
Items: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any
OnMenuClick: (item: PivotItem) => void;
}

View File

@ -1,12 +1,11 @@
import * as React from 'react';
import styles from '../CommonControl.module.scss';
import { DetailsList, IColumn, DetailsListLayoutMode, ConstrainMode, SelectionMode, IGroup } from 'office-ui-fabric-react/lib/DetailsList';
const groupBy: any = require('lodash/groupBy');
const findIndex: any = require('lodash/findIndex');
import { IColumn, DetailsListLayoutMode, ConstrainMode, SelectionMode, IGroup, ShimmeredDetailsList } from '@fluentui/react';
import { findIndex, groupBy } from '@microsoft/sp-lodash-subset';
import { Dictionary } from '../CommonProps';
export interface IDataListProps {
Items: any[];
Items: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any
Columns: IColumn[];
GroupBy: boolean;
GroupByCol?: string;
@ -16,15 +15,16 @@ export interface IDataListProps {
const DataList: React.FunctionComponent<IDataListProps> = (props) => {
const [columns, setColumns] = React.useState<IColumn[]>([]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [items, setItems] = React.useState<any[]>([]);
const [groups, setGroups] = React.useState<IGroup[]>([]);
const _getItemIndex = (key): number => {
return findIndex(props.Items, (o) => { return o.date == key; });
const _getItemIndex = (key: string): number => {
return findIndex(props.Items, (o) => { return o.date === key; });
};
const _buildGroups = () => {
let grouped: any[] = groupBy(props.Items, props.GroupByCol);
let groupsTemp: IGroup[] = [];
const _buildGroups = ():void => {
const grouped: Dictionary<string[]> = groupBy(props.Items, props.GroupByCol);
const groupsTemp: IGroup[] = [];
Object.keys(grouped).map((key, index) => {
groupsTemp.push({
key: key,
@ -35,7 +35,7 @@ const DataList: React.FunctionComponent<IDataListProps> = (props) => {
});
setGroups(groupsTemp);
};
const _loadDataList = () => {
const _loadDataList = ():void => {
setColumns(props.Columns);
if (props.GroupBy && props.GroupByCol.length > 0 && props.CountCol.length > 0) _buildGroups();
setItems(props.Items);
@ -50,7 +50,7 @@ const DataList: React.FunctionComponent<IDataListProps> = (props) => {
return (
<div className={styles.dataList}>
{(groups.length > 0 && props.GroupBy && props.GroupByCol.length > 0 && props.CountCol.length > 0) ? (
<DetailsList
<ShimmeredDetailsList
items={items}
setKey="set"
columns={columns}
@ -63,9 +63,9 @@ const DataList: React.FunctionComponent<IDataListProps> = (props) => {
constrainMode={ConstrainMode.unconstrained}
isHeaderVisible={true}
selectionMode={SelectionMode.none}
enableShimmer={true} />
enableShimmer={!items} />
) : (
<DetailsList
<ShimmeredDetailsList
items={items}
setKey="set"
columns={columns}
@ -74,9 +74,8 @@ const DataList: React.FunctionComponent<IDataListProps> = (props) => {
constrainMode={ConstrainMode.unconstrained}
isHeaderVisible={true}
selectionMode={SelectionMode.none}
enableShimmer={true} />
enableShimmer={!items} />
)}
</div>
);
};

View File

@ -1,22 +1,18 @@
import * as React from 'react';
import * as strings from 'AppInsightsDashboardWebPartStrings';
import styles from '../CommonControl.module.scss';
import { IconType, Icon } from 'office-ui-fabric-react/lib/Icon';
import { ChartControl, ChartType } from '@pnp/spfx-controls-react/lib/ChartControl';
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { PivotItem } from 'office-ui-fabric-react/lib/Pivot';
import { IColumn } from 'office-ui-fabric-react/lib/DetailsList';
import { css } from 'office-ui-fabric-react/lib/Utilities';
import { AppInsightsProps } from '../../webparts/appInsightsDashboard/components/AppInsightsDashboard';
import { TimeInterval, TimeSpan, Segments } from '../enumHelper';
import { IPageViewDetailProps, IPageViewCountProps } from '../CommonProps';
import { IPageViewDetailProps, IPageViewCountProps, Dictionary } from '../CommonProps';
import SectionTitle from '../components/SectionTitle';
import CustomPivot from '../components/CustomPivot';
import DataList from '../components/DataList';
import Helper from '../Helper';
import { IColumn, PivotItem, Icon, css, Spinner, MessageBar, MessageBarType } from '@fluentui/react';
const map: any = require('lodash/map');
import {map} from 'lodash'
import { ChartData, ChartOptions } from 'chart.js';
export interface IPageViewsProps {
helper: Helper;
@ -28,43 +24,47 @@ const PageViews: React.FunctionComponent<IPageViewsProps> = (props) => {
const [loadingChart, setLoadingChart] = React.useState<boolean>(true);
const [loadingList, setLoadingList] = React.useState<boolean>(true);
const [noData, setNoData] = React.useState<boolean>(false);
const [timespanMenus, setTimeSpanMenus] = React.useState<any[]>([]);
const [timeintervalMenus, setTimeIntervalMenus] = React.useState<any[]>([]);
const [timespanMenus, setTimeSpanMenus] = React.useState<Dictionary<string>[]>([]);
const [timeintervalMenus, setTimeIntervalMenus] = React.useState<Dictionary<string>[]>([]);
const [selTimeSpan, setSelTimeSpan] = React.useState<string>('');
const [selTimeInterval, setSelTimeInterval] = React.useState<string>('');
const [menuClick, setMenuClick] = React.useState<boolean>(false);
const [chartData, setChartData] = React.useState<any>(null);
const [chartOptions, setChartOptions] = React.useState<any>(null);
const [chartData, setChartData] = React.useState<ChartData>(null);
const [chartOptions, setChartOptions] = React.useState<ChartOptions>(null);
const [listCols, setListCols] = React.useState<IColumn[]>([]);
const [items, setItems] = React.useState<any[]>([]);
const [items, setItems] = React.useState<IPageViewDetailProps[]>([]);
const _loadMenus = () => {
let tsMenus: any[] = props.helper.getTimeSpanMenu();
const _loadMenus = ():void => {
const tsMenus: Dictionary<string>[] = props.helper.getTimeSpanMenu();
setTimeSpanMenus(tsMenus);
setSelTimeSpan(tsMenus[4].key);
let tiMenus: any[] = props.helper.getTimeIntervalMenu();
const tiMenus: Dictionary<string>[] = props.helper.getTimeIntervalMenu();
setTimeIntervalMenus(tiMenus);
setSelTimeInterval(tiMenus[3].key);
};
const handleTimeSpanMenuClick = (item: PivotItem) => {
const handleTimeSpanMenuClick = (item: PivotItem):void => {
setMenuClick(true);
setSelTimeSpan(item.props.itemKey);
};
const handleTimeIntervalMenuClick = (item: PivotItem) => {
const handleTimeIntervalMenuClick = (item: PivotItem):void => {
setMenuClick(true);
setSelTimeInterval(item.props.itemKey);
};
const _loadPageViewsCount = async () => {
const _loadPageViewsCount = async (selTimeSpan:string, selTimeInterval:string) :Promise<void>=> {
if (menuClick) setLoadingChart(true);
let response: IPageViewCountProps[] = await props.helper.getPageViewCount(TimeSpan[selTimeSpan], TimeInterval[selTimeInterval]);
const response: IPageViewCountProps[] = await props.helper.getPageViewCount(
TimeSpan[selTimeSpan as keyof typeof TimeSpan],
TimeInterval[selTimeInterval as keyof typeof TimeInterval]);
//'as keyof typeof' added above because of the error:
//error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof xxx'
if (response.length > 0) {
const data: Chart.ChartData = {
const data : ChartData= { //
labels: map(response, 'date'),
datasets: [
{
label: 'Total Page Views',
fill: true,
lineTension: 0,
tension:0,
data: map(response, 'sum'),
backgroundColor: 'rgba(255, 159, 64, 0.2)',
borderColor: 'rgb(255, 159, 64)',
@ -73,13 +73,15 @@ const PageViews: React.FunctionComponent<IPageViewsProps> = (props) => {
]
};
setChartData(data);
const options: Chart.ChartOptions = {
legend: {
display: false
},
title: {
display: false,
text: "Page Views"
const options:ChartOptions= {
plugins:{
legend: {
display: false
},
title: {
display: false,
text: "Page Views"
}
},
responsive: true,
animation: {
@ -95,15 +97,15 @@ const PageViews: React.FunctionComponent<IPageViewsProps> = (props) => {
setMenuClick(false);
}
};
const _generateColumns = () => {
let cols: IColumn[] = [];
const _generateColumns = ():void => {
const cols: IColumn[] = [];
cols.push({
key: 'Url', name: 'Url', fieldName: 'Url', minWidth: 100, maxWidth: 350,
onRender: (item: any, index: number, column: IColumn) => {
onRender: (item: IPageViewDetailProps, index: number, column: IColumn) => {
return (
<div className={styles.textWithIcon}>
<div className={styles.fileiconDiv}>
<Icon iconName="FileASPX" ariaLabel={item.Url} iconType={IconType.Default} />
<Icon iconName="FileASPX" aria-label={item.Url}/>
</div>
{item.Url ? (
<a href={item.Url} target="_blank" className={styles.pageLink}>{item.Url}</a>
@ -125,9 +127,12 @@ const PageViews: React.FunctionComponent<IPageViewsProps> = (props) => {
});
setListCols(cols);
};
const _loadPageViews = async () => {
const _loadPageViews = async (selTimeSpan:string, selTimeInterval:string):Promise<void> => {
if (menuClick) setLoadingList(true);
let response: IPageViewDetailProps[] = await props.helper.getPageViews(TimeSpan[selTimeSpan], TimeInterval[selTimeInterval], [Segments.PV_URL]);
const response: IPageViewDetailProps[] = await props.helper.getPageViews(
TimeSpan[selTimeSpan as keyof typeof TimeSpan],
TimeInterval[selTimeInterval as keyof typeof TimeInterval],
[Segments.PV_URL]);
if (response.length > 0) {
_generateColumns();
setItems(response);
@ -141,11 +146,15 @@ const PageViews: React.FunctionComponent<IPageViewsProps> = (props) => {
};
React.useEffect(() => {
if (selTimeSpan && selTimeInterval) {
setNoData(false);
_loadPageViewsCount();
_loadPageViews();
const fetchaData=async(selTimeSpan:string, selTimeInterval:string):Promise<void> =>{
if (selTimeSpan && selTimeInterval) {
setNoData(false);
await _loadPageViewsCount(selTimeSpan, selTimeInterval);
await _loadPageViews(selTimeSpan, selTimeInterval);
}
}
fetchaData(selTimeSpan, selTimeInterval)
.catch(console.error);
}, [selTimeSpan, selTimeInterval]);
React.useEffect(() => {

View File

@ -2,17 +2,14 @@ import * as React from 'react';
import * as strings from 'AppInsightsDashboardWebPartStrings';
import styles from '../CommonControl.module.scss';
import { ChartControl, ChartType } from '@pnp/spfx-controls-react/lib/ChartControl';
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import { css } from 'office-ui-fabric-react/lib/Utilities';
import { DatePicker } from 'office-ui-fabric-react/lib/DatePicker';
import { addDays } from 'office-ui-fabric-react/lib/utilities/dateMath/DateMath';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { AppInsightsProps } from '../../webparts/appInsightsDashboard/components/AppInsightsDashboard';
import { IPerfDurationProps } from '../CommonProps';
import SectionTitle from '../components/SectionTitle';
import Helper from '../Helper';
import { addDays, DatePicker, css, Spinner, MessageBar, MessageBarType } from '@fluentui/react';
const map: any = require('lodash/map');
import {map} from 'lodash'
import { ChartData, ChartOptions } from 'chart.js';
const today: Date = new Date(Date.now());
const startMaxDate: Date = addDays(today, -1);
@ -28,13 +25,13 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
const mainProps = React.useContext(AppInsightsProps);
const [menuClick, setMenuClick] = React.useState<boolean>(false);
const [message, setMessage] = React.useState<string>('');
const [loadingChart1, setLoadingChart1] = React.useState<boolean>(true);
const [noDataChart1, setNoDataChart1] = React.useState<boolean>(false);
const [loadingChart, setloadingChart] = React.useState<boolean>(true);
const [noDataChart, setnoDataChart] = React.useState<boolean>(false);
const [startDate, setStartDate] = React.useState<Date>(null);
const [endDate, setEndDate] = React.useState<Date>(null);
const [chartData1, setChartData1] = React.useState<any>(null);
const [chartOptions1, setChartOptions1] = React.useState<any>(null);
const [chartData, setChartData] = React.useState<ChartData>(null);
const [chartOptions, setChartOptions] = React.useState<ChartOptions>(null);
const handleStartDateChange = (selDate: Date | null | undefined): void => {
setStartDate(selDate);
@ -42,8 +39,8 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
const handleEndDateChange = (selDate: Date | null | undefined): void => {
setEndDate(selDate);
};
const _loadOperationsDurations = async () => {
if (menuClick) setLoadingChart1(true);
const _loadOperationsDurations = async ():Promise<void> => {
if (menuClick) setloadingChart(true);
let query: string = ``;
if (startDate && endDate) {
query += `let start=datetime("${props.helper.getQueryStartDateFormat(startDate.toUTCString())}");
@ -58,13 +55,14 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
| summarize count_=sum(itemCount), avg(duration), percentiles(duration, 50, 95, 99))
| order by count_ desc
`;
let response: any[] = await props.helper.getResponseByQuery(query, false);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response: any[] = await props.helper.getResponseByQuery(query, false);
if (response.length > 0) {
if (response[0][1] == 0 && response[0][2] == 'NaN') {
if (response[0][1] === 0 && response[0][2] === 'NaN') {
setMessage(strings.Msg_InvalidDate);
setNoDataChart1(true);
setnoDataChart(true);
} else {
let finalRes: IPerfDurationProps[] = [];
const finalRes: IPerfDurationProps[] = [];
response.map(res => {
finalRes.push({
PageName: res[0] ? res[0].indexOf('ModernDev -') >= 0 ? res[0].replace('ModernDev -', '') : res[0] : 'OverAll',
@ -75,91 +73,98 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
PerDur_99: res[5]
});
});
const data: Chart.ChartData = {
const data: ChartData= {
labels: map(finalRes, 'PageName'),
datasets: [
{
label: 'Count',
fill: true,
lineTension: 0,
tension:0,
data: map(finalRes, 'count'),
backgroundColor: props.helper.getRandomColor()
},
{
label: 'Avg Duration',
label: 'Avg Duration [ms]',
fill: true,
lineTension: 0,
tension:0,
data: map(finalRes, 'AvgDuration'),
backgroundColor: props.helper.getRandomColor()
},
{
label: 'Percentile Duration 50',
fill: true,
lineTension: 0,
tension:0,
data: map(finalRes, 'PerDur_50'),
backgroundColor: props.helper.getRandomColor()
},
{
label: 'Percentile Duration 95',
fill: true,
lineTension: 0,
tension:0,
data: map(finalRes, 'PerDur_95'),
backgroundColor: props.helper.getRandomColor()
},
{
label: 'Percentile Duration 99',
fill: true,
lineTension: 0,
tension:0,
data: map(finalRes, 'PerDur_99'),
backgroundColor: props.helper.getRandomColor()
}
]
};
setChartData1(data);
const options: Chart.ChartOptions = {
legend: {
display: false
},
title: {
display: false,
text: ""
},
setChartData(data);
const options :ChartOptions = {
responsive: true,
animation: {
animation:{
easing: 'easeInQuad'
},
plugins:{
legend: {
display: false
},
title: {
display: false,
text: ""
},
},
scales:
{
xAxes: [{
x: {
stacked: true
}],
yAxes: [{
ticks: { beginAtZero: true },
},
y: {
min: 0 ,
stacked: true
}],
},
}
};
setChartOptions1(options);
setChartOptions(options);
}
} else {
setNoDataChart1(true);
setnoDataChart(true);
}
} else {
setMessage(strings.Msg_NoDate);
setNoDataChart1(true);
setnoDataChart(true);
}
setLoadingChart1(false);
setloadingChart(false);
setMenuClick(false);
};
React.useEffect(() => {
if (startDate && endDate) {
setMenuClick(true);
setNoDataChart1(false);
setMessage('');
_loadOperationsDurations();
const fetchData= async(startDate:Date, endDate:Date): Promise<void>=>{
if (startDate && endDate) {
setMenuClick(true);
setnoDataChart(false);
setMessage('');
await _loadOperationsDurations();
}
}
fetchData(startDate, endDate)
.catch(console.error);
}, [startDate, endDate]);
React.useEffect(() => {
@ -177,6 +182,7 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
<label className={styles.dataLabel} style={{ paddingTop: '5px' }}>{"Date Range: "}</label>
<div style={{ paddingRight: '5px' }}>
<DatePicker
isRequired={false}
placeholder="Start Date..."
ariaLabel="Select start date"
@ -185,7 +191,7 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
allowTextInput={false}
highlightSelectedMonth={true}
initialPickerDate={startMaxDate}
formatDate={(date?: Date) => { return props.helper.getFormattedDate(date.toUTCString()); }}
formatDate={(date?: Date) => { return props.helper.getFormattedDate(date.toUTCString(),'L'); }}
onSelectDate={handleStartDateChange}
value={startDate}
/>
@ -199,7 +205,7 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
maxDate={maxDate}
allowTextInput={false}
highlightSelectedMonth={true}
formatDate={(date?: Date) => { return props.helper.getFormattedDate(date.toUTCString()); }}
formatDate={(date?: Date) => { return props.helper.getFormattedDate(date.toUTCString(),'L'); }}
onSelectDate={handleEndDateChange}
value={endDate}
/>
@ -209,15 +215,15 @@ const PerformanceStatistics: React.FunctionComponent<IPerformanceProps> = (props
</div>
<div className={css("ms-Grid-row", styles.content)}>
<div style={{ minHeight: '450px', maxHeight: '450px' }}>
{loadingChart1 ? (
{loadingChart ? (
<Spinner label={strings.Msg_LoadChart} labelPosition={"bottom"} />
) : (
<>
{!noDataChart1 ? (
{!noDataChart ? (
<ChartControl
type={ChartType.Bar}
data={chartData1}
options={chartOptions1}
data={chartData}
options={chartOptions}
/>
) : (
<MessageBar messageBarType={MessageBarType.error}>{message ? message : strings.Msg_NoData}</MessageBar>

View File

@ -1,11 +1,6 @@
import * as React from 'react';
import * as strings from 'AppInsightsDashboardWebPartStrings';
import styles from '../CommonControl.module.scss';
import { css } from 'office-ui-fabric-react/lib/Utilities';
import { PivotItem } from 'office-ui-fabric-react/lib/Pivot';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar';
import { DatePicker } from 'office-ui-fabric-react/lib/DatePicker';
import { addDays } from 'office-ui-fabric-react/lib/utilities/dateMath/DateMath';
import { ChartControl, ChartType } from '@pnp/spfx-controls-react/lib/ChartControl';
import { AppInsightsProps } from '../../webparts/appInsightsDashboard/components/AppInsightsDashboard';
import { TimeSpan, TimeInterval, Segments } from '../enumHelper';
@ -13,12 +8,12 @@ import SectionTitle from '../components/SectionTitle';
import CustomPivot from './CustomPivot';
import Helper from '../Helper';
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import { IColumn } from 'office-ui-fabric-react/lib/DetailsList';
import { Icon, IconType } from 'office-ui-fabric-react/lib/Icon';
import DataList from './DataList';
import { addDays, IColumn, PivotItem, Icon, DatePicker, css, Spinner, MessageBar, MessageBarType } from '@fluentui/react';
import { Dictionary, IPageViewDetailProps } from '../CommonProps';
const map: any = require('lodash/map');
import {map} from 'lodash'
import { ChartData, ChartOptions } from 'chart.js';
const today: Date = new Date(Date.now());
const startMaxDate: Date = addDays(today, -1);
@ -34,24 +29,24 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
const mainProps = React.useContext(AppInsightsProps);
const [loadingChart, setLoadingChart] = React.useState<boolean>(true);
const [loadingList, setLoadingList] = React.useState<boolean>(true);
const [timespanMenus, setTimeSpanMenus] = React.useState<any[]>([]);
const [timespanMenus, setTimeSpanMenus] = React.useState<Dictionary<string>[]>([]);
const [selTimeSpan, setSelTimeSpan] = React.useState<string>('');
const [menuClick, setMenuClick] = React.useState<boolean>(false);
const [noData, setNoData] = React.useState<boolean>(false);
const [noListData, setNoListData] = React.useState<boolean>(false);
const [chartData, setChartData] = React.useState<any>(null);
const [chartOptions, setChartOptions] = React.useState<any>(null);
const [chartData, setChartData] = React.useState<ChartData>(null);
const [chartOptions, setChartOptions] = React.useState<ChartOptions>(null);
const [startDate, setStartDate] = React.useState<Date>(null);
const [endDate, setEndDate] = React.useState<Date>(null);
const [listCols, setListCols] = React.useState<IColumn[]>([]);
const [items, setItems] = React.useState<any[]>([]);
const [items, setItems] = React.useState<IPageViewDetailProps[]>([]);
const _loadMenus = () => {
let tsMenus: any[] = props.helper.getTimeSpanMenu();
const _loadMenus = (): void => {
const tsMenus: Dictionary<string>[] = props.helper.getTimeSpanMenu();
setTimeSpanMenus(tsMenus);
setSelTimeSpan(tsMenus[4].key);
};
const handleTimeSpanMenuClick = (item: PivotItem) => {
const handleTimeSpanMenuClick = (item: PivotItem): void => {
setMenuClick(true);
setSelTimeSpan(item.props.itemKey);
setStartDate(null);
@ -63,7 +58,7 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
const handleEndDateChange = (selDate: Date | null | undefined): void => {
setEndDate(selDate);
};
const _loadUserStatistics = async () => {
const _loadUserStatistics = async (): Promise<void> => {
if (menuClick) setLoadingChart(true);
let query: string = ``;
if (startDate && endDate) {
@ -80,50 +75,50 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
| order by timestamp asc
`;
}
let response: any[] = await props.helper.getResponseByQuery(query, (startDate && endDate) ? false : true, TimeSpan[selTimeSpan]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response: any[] = await props.helper.getResponseByQuery(query, (startDate && endDate) ? false : true, TimeSpan[selTimeSpan as keyof typeof TimeSpan]);
if (response.length > 0) {
let results: any[] = [];
response.map((res: any[]) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const results: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
response.map((res: any) => {
results.push({
oriDate: res[0],
date: props.helper.getLocalTime(res[0]),
sum: res[1]
});
});
const data: Chart.ChartData = {
const data: ChartData = {
labels: map(results, 'date'),
datasets: [
{
label: 'Total Users',
fill: true,
lineTension: 0,
tension:0,
data: map(results, 'sum'),
}
]
};
setChartData(data);
const options: Chart.ChartOptions = {
legend: {
display: false
},
title: {
display: false,
text: ""
},
const options :ChartOptions= {
responsive: true,
animation: {
easing: 'easeInQuad'
},
scales:
{
yAxes: [
{
ticks:
{
beginAtZero: true
}
}
]
plugins:{
legend: {
display: false
},
title: {
display: false,
text: ""
},
},
scales:{
y: {
min:0
}
}
};
setChartOptions(options);
@ -135,35 +130,38 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
setMenuClick(false);
}
};
const _generateColumns = () => {
let cols: IColumn[] = [];
const _generateColumns = ():void => {
const cols: IColumn[] = [];
cols.push({
key: 'user', name: 'User', fieldName: 'user', minWidth: 100, maxWidth: 150,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onRender: (item: any, index: number, column: IColumn) => {
return (
<div className={styles.textWithIcon}>
{item.user ? (
<span>{item.user}</span>
) : (
<span>{strings.Msg_NoUser}</span>
)}
<span>{strings.Msg_NoUser}</span>
)}
</div>
);
}
});
cols.push({
key: 'Url', name: 'Url', fieldName: 'Url', minWidth: 100, maxWidth: 350,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onRender: (item: any, index: number, column: IColumn) => {
return (
<div className={styles.textWithIcon}>
<div className={styles.fileiconDiv}>
<Icon iconName="FileASPX" ariaLabel={item.Url} iconType={IconType.Default} />
<Icon iconName="FileASPX" aria-label={item.Url}/>
</div>
{item.Url ? (
<a href={item.Url} target="_blank" className={styles.pageLink}>{item.Url}</a>
) : (
<span>{strings.Msg_NoUrl}</span>
)}
<span>{strings.Msg_NoUrl}</span>
)}
</div>
);
}
@ -173,14 +171,15 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
});
setListCols(cols);
};
const _loadUsersPageViewsList = async () => {
const _loadUsersPageViewsList = async (): Promise<void> => {
if (menuClick) setLoadingList(true);
let response: any[] = [];
let response: IPageViewDetailProps[] = [];
if (startDate && endDate) {
response = await props.helper.getUserPageViews(`${props.helper.getFormattedDate(startDate.toUTCString(), 'YYYY-MM-DD')}/${props.helper.getFormattedDate(addDays(endDate, 1).toUTCString(), 'YYYY-MM-DD')}`,
TimeInterval["1 Hour"], [Segments.Cust_UserTitle, Segments.PV_URL]);
} else {
response = await props.helper.getUserPageViews(TimeSpan[selTimeSpan], TimeInterval["1 Hour"], [Segments.Cust_UserTitle, Segments.PV_URL]);
response = await props.helper.getUserPageViews(TimeSpan[selTimeSpan as keyof typeof TimeSpan], TimeInterval["1 Hour"], [Segments.Cust_UserTitle, Segments.PV_URL]);
}
if (response.length > 0) {
_generateColumns();
@ -194,15 +193,21 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
}
};
React.useEffect(() => {
if (selTimeSpan || (startDate && endDate)) {
setNoData(false);
setNoListData(false);
_loadUserStatistics();
_loadUsersPageViewsList();
React.useEffect((): void => {
const fetchData= async(selTimeSpan:string, startDate:Date, endDate:Date): Promise<void>=>{
if (selTimeSpan || (startDate && endDate)) {
setNoData(false);
setNoListData(false);
await _loadUserStatistics();
await _loadUsersPageViewsList();
}
}
fetchData(selTimeSpan, startDate, endDate)
.catch(console.error);
}, [selTimeSpan, startDate, endDate]);
React.useEffect(() => {
React.useEffect(():void => {
if (props.helper) {
_loadMenus();
}
@ -253,32 +258,32 @@ const UserStatistics: React.FunctionComponent<IUserStatisticsProps> = (props) =>
{loadingList ? (
<Spinner label={strings.Msg_LoadList} labelPosition={"bottom"} />
) : (
<>
{!noListData ? (
<DataList Items={items} Columns={listCols} GroupBy={true} GroupByCol={"date"} CountCol={"count"} />
) : (
<MessageBar messageBarType={MessageBarType.error}>{strings.Msg_NoData}</MessageBar>
)}
</>
)}
<>
{!noListData ? (
<DataList Items={items} Columns={listCols} GroupBy={true} GroupByCol={"date"} CountCol={"count"} />
) : (
<MessageBar messageBarType={MessageBarType.error}>{strings.Msg_NoData}</MessageBar>
)}
</>
)}
</div>
<div className={"ms-Grid-col ms-xxxl6 ms-xxl6 ms-xl6 ms-lg6"} style={{ minHeight: '358px' }}>
{loadingChart ? (
<Spinner label={strings.Msg_LoadChart} labelPosition={"bottom"} />
) : (
<>
{!noData ? (
<ChartControl
type={ChartType.Bar}
data={chartData}
options={chartOptions}
className={styles.chart}
/>
) : (
<MessageBar messageBarType={MessageBarType.error}>{strings.Msg_NoData}</MessageBar>
)}
</>
)}
<>
{!noData ? (
<ChartControl
type={ChartType.Bar}
data={chartData}
options={chartOptions}
className={styles.chart}
/>
) : (
<MessageBar messageBarType={MessageBarType.error}>{strings.Msg_NoData}</MessageBar>
)}
</>
)}
</div>
</div>
</div>

View File

@ -22,11 +22,12 @@ export default class AppInsightsDashboardWebPart extends BaseClientSideWebPart<I
const element: React.ReactElement<IAppInsightsDashboardProps> = React.createElement(
AppInsightsDashboard,
{
AppId: this.properties.AppId,
AppId: this.properties.AppId ,
AppKey: this.properties.AppKey,
DisplayMode: this.displayMode,
onConfigure: this._onConfigure,
httpClient: this.context.httpClient
httpClient: this.context.httpClient,
cultureName: this.context.pageContext.legacyPageContext.currentCultureName
}
);
@ -45,7 +46,7 @@ export default class AppInsightsDashboardWebPart extends BaseClientSideWebPart<I
return true;
}
public _onConfigure = () => {
public _onConfigure = ():void => {
this.context.propertyPane.open();
}

View File

@ -1,4 +1,4 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
@import '~@fluentui/react/dist/sass/References.scss';
.appInsightsDashboard {
.container {
@ -7,7 +7,7 @@
}
.row {
@include ms-Grid-row;
// background-color: $ms-color-themeDark;
background-color: $ms-color-themeDark;
padding: 20px;
}
}

View File

@ -1,5 +1,4 @@
import * as React from 'react';
import styles from './AppInsightsDashboard.module.scss';
import * as strings from 'AppInsightsDashboardWebPartStrings';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { DisplayMode } from '@microsoft/sp-core-library';
@ -8,6 +7,8 @@ import PageViews from '../../../common/components/PageViews';
import UserStatistics from '../../../common/components/UserStatistics';
import PerformanceStatistics from '../../../common/components/PerformanceStatistics';
import Helper from '../../../common/Helper';
import styles from './AppInsightsDashboard.module.scss';
export interface IAppInsightsDashboardProps {
AppId: string;
@ -15,16 +16,17 @@ export interface IAppInsightsDashboardProps {
DisplayMode: DisplayMode;
onConfigure: () => void;
httpClient: HttpClient;
cultureName:string;
}
export const AppInsightsProps = React.createContext<IAppInsightsDashboardProps>(null);
const AppInsightsDashboard: React.FunctionComponent<IAppInsightsDashboardProps> = (props) => {
const [helper, setHelper] = React.useState<any>(null);
const [helper, setHelper] = React.useState<Helper>(null); //KK
React.useEffect(() => {
setHelper(new Helper(props.AppId, props.AppKey, props.httpClient));
setHelper(new Helper(props.AppId, props.AppKey, props.httpClient, props.cultureName));
}, [props.AppId, props.AppKey]);
return (

View File

@ -1,38 +1,38 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es6",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"noImplicitAny": true,
"allowSyntheticDefaultImports": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es2021",
"dom",
"es2015.collection",
"es2015.promise",
"es2021.string"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules",
"lib"
]
}
}

View File

@ -1,30 +0,0 @@
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}