Merge pull request #3717 from kkazala/samples/react-dashboards

Samples/react dashboards
This commit is contained in:
Hugo Bernier 2023-06-05 09:54:59 -04:00 committed by GitHub
commit 7ab9d51ba8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
104 changed files with 22040 additions and 0 deletions

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
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: {}
}
]
};

34
samples/react-dashboards/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,4 @@
{
"MD013": false,
"MD034":false
}

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"packageManager": "pnpm",
"plusBeta": false,
"isCreatingSolution": false,
"nodeVersion": "16.14.2",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.4.1"
},
"version": "1.16.1",
"libraryName": "spfx-applicationinsights",
"libraryId": "09af0554-67db-4a65-baa6-872dee7117a8",
"environment": "spo",
"solutionName": "spfx-applicationinsights",
"solutionShortDescription": "spfx-applicationinsights description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,190 @@
# Application Insights and Cost Management Dashboards
## Summary
Sharing Application Insights and solution's cost information with your stakeholders typically requires either using _Azure Dashboards_ or using _Power BI_. This sample solution allows displaying this dashboards directly in a SharePoint site or a tab in MS Teams, moving it close to the users.
This solution consists of two web parts:
- **Application Insights** executes Kusto query against the Application Insights service in your Azure tenant
![Application insights](./assets/AppInsights.png)
- **Cost Insights** queries the usage data for the specified scope (management group, subscription, resource group)
![Cost Insights](./assets/CostInsights.png)
## Compatibility
This sample is optimally compatible with the following environment configuration:
![SPFx 1.16.1](https://img.shields.io/badge/SPFx-1.16.1-green.svg)
![Node.js v16 | v14 | v12](https://img.shields.io/badge/Node.js-v16%20%7C%20v14%20%7C%20v12-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")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Authors
Kinga Kazala [@kinga_kazala](https://twitter.com/kinga_kazala), ETHZ
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | May 30, 2023 | Initial release |
## Prerequisites
- Azure tenant
- Application Insights resource (for Application Insights web part)
- Read access to Cost Management data (for Cost Insights web part), see **Required access to view data** in the [Azure EA subscription scopes](https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/assign-access-acm-data#azure-ea-subscription-scopes) table
- SharePoint Administrator or Global Administrator to install the solution
- Global Administrator permissions to approve required API access:
- Windows Azure Service Management API: user_impersonation
- Application Insights API: user_impersonation
## Minimal Path to Awesome
- Clone this repository
- Ensure that you are at the solution folder
- to debug, in the command-line run:
- **npm install** / **pnpm install**
- **gulp serve --nobrowser**
- to deploy, in the command-line run:
- **gulp bundle --ship**
- **gulp package-solution --ship**
## Configuration
### API Connection
Configuration dashboard allows defining connection settings.
**Application Insights** requires **Application ID**, which you may find by navigating to **Application Insights** / **API Access** (Configure group)
**Cost Management** access may be **scoped** to a management group, subscription and resource group.
Both APIs are accessed using **user impersonation**.
![Edit API Connection](./assets/EditApiConnection.png)
> **Optionally**, and for **Application Insights only**, you may enable access with Application ID and Key. To do so, open the web part properties panel and in the Developer Settings section, enable authentication with ApiKey and AppId:
>
> ![Enable access with API Key](./assets/EnableApiKey.png)
### Kusto Query / Cost Query
Both web parts have example queries that you may use to test the solution, or to treat as a starting point for defining your own queries.
![EditQuery](./assets/EditQuery.gif)
**Application Insights logs** are retrieved using the **Application Insights API** and your custom Kusto query.
In case you want to refer to the _time range_ defined in the web part, type `{TimeRange:start}` in the Kusto query:
![Time Range](./assets/TimeRange.png)
> Please **test** your query using either [Application Insights / Query - Get](https://learn.microsoft.com/en-us/rest/api/application-insights/query/get?tabs=HTTP#code-0) or query editor in Azure portal (Application Insights / Logs) to ensure the query is correct. Some expression you may use in Workspaces will not work in Application Insights Logs API and therefore, will also fail when executed using this web part.
**Cost information** is retrieved using the **Cost Management Usage API** and your custom JSON request. Please test it using [Cost Management / Query - Usage](https://learn.microsoft.com/en-us/rest/api/cost-management/query/usage?tabs=HTTP#code-try-0)
### Rendering results
Results may be displayed in a **table**, a **chart**, or **both**.
Table may be optionally formatted as a **heatmap**, chart supports _line chart_, _area chart_, _bar chart_, _column chart_ and _pie chart_ styles.
![Edit layout](./assets/EditLayout.gif)
Colors may be changed to either SharePoint theme's accent colors, or gradient colors using one of the SharePoint accents.
![Edit colors and chart type](./assets/EditColors.gif)
Chart is rendered using [Chart Control](https://pnp.github.io/sp-dev-fx-controls-react/controls/ChartControl/) with dependency on `chart.js 2.9.4`. Labels and data series are detected based on the data types, e.g. _datetime_, _string_ or _number_; currently there is no option to define custom data mappings.
### Authentication
User impersonation is executed using [AadHttpClient](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient). To call the APIs, the solution requires the following **Application** API permissions:
- Windows Azure Service Management API: user_impersonation
- Application Insights API: user_impersonation
These permissions will be requested automatically once the solution is deployed, and must be granted by a Global Admin using [API access](https://kingasws1e5-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx#/webApiPermissionManagement) page in SharePoint Administration
Authentication with `Application ID` and `API key` is also allowed for Application Insights dashboard (see _Api Connection_ above)
### Caching
`PnPClientStorage` is used to cache query results in local storage to avoid [throttling](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/request-limits-and-throttling). This is especially important when querying cost management APIs (see more information below).
By default, caching duration is set to:
- **15 minutes** for **Application Insights Dashboard**, and
- **1 day** for **Cost Insights Dashboard**
Cache duration for **Application Insights Dashboard** may be extended or disabled using web part properties panel. In case you want to delete the cache manually, the key names for this solution start with **spfxDashboard**.
## Accessing Application Insights Data
To query Application Insights using the Application Insights Data Access API, you must **authenticate**:
- To query your workspaces, use Azure Active Directory (Azure AD) authentication.
- To quickly explore the API without using Azure AD authentication, you can use an API key to query sample data in a non-production environment. You may try it here [here](https://learn.microsoft.com/en-us/rest/api/application-insights/query/get?tabs=HTTP#code-0), by adding **x-api-key** header set to **ApiKey** value
The Log Analytics API supports Azure AD authentication with three different Azure AD OAuth2 flows: authorization code, **implicit**, client credentials.
Client-side applications that are incapable of storing a secret, such as SharePoint Framework solutions, use **OAuth implicit flow**. In SharePoint Framework solutions, authorization by using the OAuth implicit flow is done as part of the framework through MSGraphClient and AadHttpClient, both of which are introduced in SharePoint Framework v1.4.1.
Developers building a SharePoint Framework solution that requires access to specific resources secured with Azure AD list these resources along with the required permission scopes in the solution manifest. When deploying the solution package to the app catalog, SharePoint creates permission requests and prompts the administrator to manage the requested permissions. For each requested permission, a **global administrator** can decide whether they want to grant or deny the specific permission.
All permissions are granted to the whole tenant and not to a specific application that has requested them. When the administrator grants a specific permission, its added to the SharePoint Online Client Extensibility Azure AD application, which is provisioned by Microsoft in every Azure AD and which is used by the SharePoint Framework in the OAuth flow to provide solutions with valid access tokens.
## References
### Application Insights
- [Application Insights overview](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview)
- [Application Insights API](https://learn.microsoft.com/en-us/rest/api/application-insights/)
- [Application Insights demo data](https://aka.ms/AIAnalyticsDemo)
- [KQL quick reference](https://learn.microsoft.com/en-us/azure/data-explorer/kql-quick-reference)
-[Fun With KQL Variants Of Project](https://arcanecode.com/2022/06/06/fun-with-kql-variants-of-project/)
- [Resources, roles, and access control in Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/resources-roles-access-control) - Assign access to users in the resource group or subscription to which your application resource belongs, not in the resource itself.
### Cost Management
- [Cost Management API](https://learn.microsoft.com/en-us/rest/api/cost-management/)
- [Cost Management Dimensions](https://learn.microsoft.com/en-us/rest/api/cost-management/dimensions/list?tabs=HTTP#code-try-0)
- [How to optimize your cloud investment with Cost Management](https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/cost-mgt-best-practices)
- [Retrieve large cost datasets recurringly with exports](https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/ingest-azure-usage-at-scale)
- [Manage costs with automation](https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/manage-automation
)
>If you want to get the latest cost data, query at most once per day. Reports are refreshed every four hours. If you call more frequently, you'll receive identical data.
>The data in Usage Details is provided on a per meter basis, per day.
>
>If you want to get large amounts of exported data regularly, see [Retrieve large cost datasets recurringly with exports](https://learn.microsoft.com/en-us/azure/cost-management-billing/costs/ingest-azure-usage-at-scale).
>
>
>If you have scopes with a large amount of usage data (for example a Billing Account), consider placing multiple calls to child scopes so you get more manageable files that you can download. If your dataset is more than 2 GB month-to-month, consider using exports as a more scalable solution.
### Using Azure APIs
- [Connect to Azure AD-secured APIs in SharePoint Framework solutions](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient)
- [Application IDs of commonly used Microsoft applications](https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/verify-first-party-apps-sign-in#application-ids-of-commonly-used-microsoft-applications)
- [Throttling](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/request-limits-and-throttling) - The resource provider requests are also throttled per principal user ID and per hour.
- [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development
#### Used Application API
- `f5c26e74-f226-4ae8-85f0-b4af0080ac9e` Application Insights API
- `797f4846-ba00-4fd7-ba43-dac1f8f63013` Windows Azure Service Management API
## Disclaimer
**THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1,30 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"application-insights-dashboard-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/applicationInsightsLogs/ApplicationInsightsLogsWebPart.js",
"manifest": "./src/webparts/applicationInsightsLogs/ApplicationInsightsLogsWebPart.manifest.json"
}
]
},
"cost-insights-dashboard-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/costInsightsDashboard/CostInsightsDashboardWebPart.js",
"manifest": "./src/webparts/costInsightsDashboard/CostInsightsDashboardWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js",
"CommonDasboardWebPartStrings": "lib/loc/{locale}.js",
"AppInsightsDasboardWebPartStrings": "lib/webparts/applicationInsightsLogs/loc/{locale}.js",
"CostInsightsWebPartStrings": "lib/webparts/costInsightsDashboard/loc/{locale}.js",
"ApplicationInsightsMetricsWebPartStrings": "lib/webparts/applicationInsightsMetrics/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "spfx-applicationinsights",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,66 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "Application Insights and Cost Management dashboards",
"id": "09af0554-67db-4a65-baa6-872dee7117a8",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "Windows Azure Service Management API",
"scope": "user_impersonation"
},
{
"resource": "Application Insights API",
"scope": "user_impersonation"
}
// {
// "resource": "Microsoft Graph", //Microsoft Graph
// "scope": "user_impersonation"
// },
// {
// "resource": "Office 365 SharePoint Online", //Office 365 SharePoint Online
// "scope": "user_impersonation"
// }
],
"developer": {
"name": "Kinga Kazala (ETHZ)",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.16.1"
},
"metadata": {
"shortDescription": {
"default": "Display data and charts from Application Insights and Cost Management"
},
"longDescription": {
"default": "Display data and charts from Application Insights and Cost Management. \n\n The solution uses REST API endpoints: \n\n - Application Insights: https://learn.microsoft.com/en-us/rest/api/application-insights/query/get \n\n - Cost Management: https://learn.microsoft.com/en-us/rest/api/cost-management/query/usage"
},
"screenshotPaths": [
"assets/Cost.png",
"assets/OperationsPerformance.png",
"assets/PagesViews.png",
"assets/PagesViewTrend.png",
"assets/EditKusto.png"
],
"videoUrl": ""
},
"features": [
{
"title": "SPFx ApplicationInsights and Cost Management Dashboards Feature",
"description": "The feature that activates elements of the spfx-applicationinsights solution.",
"id": "b3316c57-f3f8-4d2b-9b95-7250831dc33f",
"version": "1.0.0.0"
}
],
"supportedLocales": [
"en-us"
]
},
"paths": {
"zippedPackage": "solution/spfx-applicationinsights.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

16
samples/react-dashboards/gulpfile.js vendored Normal file
View File

@ -0,0 +1,16 @@
'use strict';
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'));

View File

@ -0,0 +1,52 @@
{
"name": "spfx-applicationinsights",
"version": "1.0.0",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@fluentui/react": "^8.106.5",
"@fluentui/react-hooks": "^8.6.16",
"@microsoft/sp-component-base": "1.16.1",
"@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/core": "^3.13.0",
"@pnp/logging": "^3.13.0",
"@pnp/spfx-controls-react": "^3.12.0",
"@pnp/telemetry-js": "^2.0.0",
"chart.js": "2.9.4",
"color": "4.2.3",
"moment": "^2.29.4",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"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-module-interfaces": "1.16.1",
"@rushstack/eslint-config": "2.5.1",
"@types/chart.js": "2.9.37",
"@types/color": "^3.0.3",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"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

@ -0,0 +1 @@


Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 636 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 636 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 850 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 851 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 598 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 845 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 651 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 611 B

View File

@ -0,0 +1,132 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
interface colInfo {
name: string;
type: string;
}
interface responseBody {
columns: colInfo[];
rows: any[];
}
interface IApiResponseError {
code: string;
message?: string;
innererror?: {
code: string;
message: string;
innererror: {
line: number;
message: string;
pos: number;
token: string;
}
}
}
export interface IResponseJson {
error?: IApiResponseError
tables: any[],
columns: Map<string, string>
}
export interface ICostMngmtResponseJson {
properties?: {
columns: [],
rows: [],
// nextLink: string
}
error?: {
code: string;
message: string;
}
}
export interface IAppInsightsResponseJson {
tables: {
columns: [],
rows: [],
// nextLink: string
}[],
error?: IApiResponseError
}
export default class ApiHelper {
private static parseColumns = (responseColumns: any, colRenames?: Map<string, string>): string[] => {
const columns = responseColumns.reduce((acc: any, currVal: colInfo) => {
if (colRenames?.has(currVal.name)) {
acc.push(colRenames.get(currVal.name));
}
else {
acc.push(currVal.name);
}
return acc;
}, []);
return columns;
}
//suport for data types returned Application Insights API and Cost Management API
public static get NumericTypes(): string[] {
return ['int', 'long', 'real', 'decimal', 'Number'];
}
public static get StringTypes(): string[] {
return ['string', 'String'];
}
public static get DateTimeTypes(): string[] {
return ['datetime'];
}
public static IsNumericalType = (type: string): boolean => {
return ApiHelper.NumericTypes.includes(type);
}
public static IsStringType = (type: string): boolean => {
return ApiHelper.StringTypes.includes(type);
}
public static IsDateTimeType = (type: string): boolean => {
return ApiHelper.DateTimeTypes.includes(type);
}
public static GetParsedResponse = <T>(response: { body: responseBody, error: any }, colRenames?: Map<string, string>): IResponseJson => {
if (response.error) {
return {
error: response.error,
tables: [],
columns: new Map()
}
}
else if (response.body) {
return ApiHelper.ParseResponse<T>(response.body, colRenames);
}
}
public static ParseResponse = <T>(responseBody: responseBody, colRenames?: Map<string, string>): IResponseJson => {
const response: IResponseJson = {
tables: [],
columns: new Map()
}
const columns = ApiHelper.parseColumns(responseBody.columns, colRenames)
response.tables = responseBody.rows.reduce((acc: any[], currRow: []) => {
const v: Map<string, any> = new Map();
for (let i = 0; i < columns.length; ++i) {
v.set(columns[i], currRow[i]);
}
acc.push(Object.fromEntries<T>(v));
return acc;
}, []);
response.columns = responseBody.columns.reduce((acc: any, currVal: colInfo) => {
if (colRenames?.has(currVal.name)) {
acc.set(colRenames.get(currVal.name), currVal.type);
}
else {
acc.set(currVal.name, currVal.type);
}
return acc;
}, new Map<string, string>());
return response;
}
public static GetColByType = (colInfo: Map<string, string>, type: string): string[] => {
return [...colInfo.entries()]
.filter(({ 1: v }) => { return (v === type); })
.map(([k]) => k);
}
public static GetColByTypes = (colInfo: Map<string, string>, type: string[]): string[] => {
return [...colInfo.entries()]
.filter(({ 1: v }) => { return (type.includes(v)); })
.map(([k]) => k);
}
}

View File

@ -0,0 +1,93 @@
import { PnPClientStorage } from "@pnp/core";
import moment from "moment";
import { IResponseJson } from "./ApiHelper";
import { CacheExpiration } from "./CommonProps";
export interface DropDownOption {
key: number;
text: string;
}
export interface QueryPreset extends DropDownOption {
description: string;
query: string;
columnsOrdering?: string[];
sortby?: string;
}
export default class ApiQueryHelper {
protected static queries: QueryPreset[];
public static get Queries(): DropDownOption[] {
return this.queries;
}
public static get Presets(): QueryPreset[] {
return this.queries;
}
public static GetQueryById(key: number): QueryPreset {
return this.queries.find((q) => q.key === key);
}
public static GetSanitisedQuery = (query: string): string => {
return query
.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
.replace(/\s+/gm, ' ');
}
public static GetHash(str: string): string {
let hash = 0, i, chr;
if (str.length === 0) return hash.toString();
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return `spfxDashboard_${hash.toString()}`;
}
public static GetCachedResponse = (hash: string): IResponseJson => {
const pnpStorage = new PnPClientStorage();
pnpStorage.local
.deleteExpired()
.catch((e) => console.log(e));
const lastResponseT = pnpStorage.local.get(`${hash}_data`);
const lastResponseC = JSON.parse(pnpStorage.local.get(`${hash}_columns`));
if (lastResponseT && lastResponseC) {
return {
tables: lastResponseT,
columns: new Map(Object.entries(lastResponseC))
};
}
return null;
}
public static SaveCachedResponse(hash: string, response: IResponseJson, cacheExpiration: CacheExpiration): void {
//By default, the local cache size is 1 GB.
const pnpStorage = new PnPClientStorage();
const expiry = ApiQueryHelper.getExpirationDate(cacheExpiration);
if (expiry) {
pnpStorage.local.put(
`${hash}_data`,
response.tables,
expiry
);
pnpStorage.local.put(
`${hash}_columns`,
JSON.stringify(Object.fromEntries(response.columns)),
expiry
);
}
}
private static getExpirationDate(expiration: string): Date {
const key = CacheExpiration[expiration as keyof typeof CacheExpiration]
switch (key) {
case CacheExpiration.FifteenMinutes:
return moment().add(15, 'minutes').toDate();
case CacheExpiration.OneHour:
return moment().add(1, 'hour').toDate();
case CacheExpiration.OneDay:
return moment().endOf('day').toDate()
default:
return null;
}
}
}

View File

@ -0,0 +1,166 @@
import { AadHttpClient, AadHttpClientFactory, HttpClient, HttpClientResponse, IHttpClientOptions } from "@microsoft/sp-http";
import ApiHelper, { IAppInsightsResponseJson, IResponseJson } from "./ApiHelper";
import ApiQueryHelper from "./ApiQueryHelper";
import { AppInsightsQueryHelper } from "./AppInsightsQueryHelper";
import { AppInsightsEndpointType, AppInsights_AuthSSO, CacheExpiration, IAppInsightsConfig, IAppInsightsQuery, ICacheConfig } from "./CommonProps";
export class AppInsightsHelperSSO {
private _postUrl: string = '';
private requestHeaders: Headers = new Headers();
private httpClientOptions: IHttpClientOptions = {};
private aadHttpClientFactory: AadHttpClientFactory = null;
private spfxSpoApiConnectClient: AadHttpClient = null;
private endpointType: AppInsightsEndpointType;
private cacheDuration: CacheExpiration;
private cacheKey: string;
constructor(config: AppInsights_AuthSSO, cache: ICacheConfig,) {
this.aadHttpClientFactory = config.aadHttpClientFactory;
this._postUrl = AppInsightsQueryHelper.GetAPIEndpoint(config.appId, config.endpoint);
this.requestHeaders.append("Content-type", "application/json; charset=utf-8");
this.httpClientOptions = { headers: this.requestHeaders };
this.endpointType = config.endpoint;
this.cacheDuration = cache.cacheDuration;
this.cacheKey = `${config.appId}-${cache.userLoginName}`
}
public GetAPIResponse = async (config: IAppInsightsQuery): Promise<IResponseJson> => {
const urlQuery = (AppInsightsEndpointType[this.endpointType as keyof typeof AppInsightsEndpointType] === AppInsightsEndpointType.query)
? `query=${AppInsightsQueryHelper.GetUrlQuery(config.query, config.dateSelection)}`
: AppInsightsQueryHelper.GetUrlQuery(config.query, config.dateSelection)
const requestHash = ApiQueryHelper.GetHash(`${this.cacheKey}-${urlQuery}`);//TODO: this.cacheKey
const cacheEnabled = CacheExpiration[this.cacheDuration.toString() as keyof typeof CacheExpiration] !== CacheExpiration.Disabled;
if (cacheEnabled) {
const lastResponse = ApiQueryHelper.GetCachedResponse(requestHash);
if (lastResponse) {
console.info("AppInsightsHelper: Using cached response")
return lastResponse;
}
}
//if cache disabled or no cached response, get live response
try {
console.info("AppInsightsHelper: Using live response")
await this.init();
const response = await this.getParsedResponse(urlQuery);
if (response && !response.error && cacheEnabled) {
console.info("AppInsightsHelper: Saving response to cache")
ApiQueryHelper.SaveCachedResponse(
requestHash,
response,
this.cacheDuration);//expiration at end of day
}
return response;
} catch (error) {
console.error(error);
}
}
public GetGroupBy = (query: string): string[] => {
return [];
}
private init = async (): Promise<void> => {
return await this.aadHttpClientFactory
.getClient(AppInsightsQueryHelper.ClientId)
.then((client: AadHttpClient): void => {
this.spfxSpoApiConnectClient = client;
})
.catch(err => {
console.error(err)
});
}
private getParsedResponse = async<T>(urlQuery: string, colRenames?: Map<string, string>): Promise<IResponseJson> => {
const response = await this.spfxSpoApiConnectClient.get(`${this._postUrl}${urlQuery}`, AadHttpClient.configurations.v1, this.httpClientOptions);
const responseJson: IAppInsightsResponseJson = await response.json();
return ApiHelper.GetParsedResponse<T>(
{
body: responseJson.tables
? responseJson.tables[0]
: { columns: [], rows: [] },
error: responseJson.error
},
colRenames);
}
}
export default class AppInsightsHelper {
private _postUrl: string = "";
private requestHeaders: Headers = new Headers();
private httpClientOptions: IHttpClientOptions = {};
private httpClient: HttpClient = null;
private endpointType: AppInsightsEndpointType;
private cacheDuration: CacheExpiration;
private cacheKey: string;
constructor(config: IAppInsightsConfig, cache: ICacheConfig, httpclient: HttpClient) {
this.httpClient = httpclient;
this._postUrl = AppInsightsQueryHelper.GetAPIEndpoint(config.appId, config.endpoint);
this.requestHeaders.append("Content-type", "application/json; charset=utf-8");
this.requestHeaders.append("x-api-key", config.appKey);
this.httpClientOptions = { headers: this.requestHeaders };
this.endpointType = config.endpoint;
this.cacheDuration = cache.cacheDuration;
this.cacheKey = `${config.appId}-${config.appKey}`
}
public GetAPIResponse = async (config: IAppInsightsQuery): Promise<IResponseJson> => {
const urlQuery = (AppInsightsEndpointType[this.endpointType as keyof typeof AppInsightsEndpointType] === AppInsightsEndpointType.query)
? `query=${AppInsightsQueryHelper.GetUrlQuery(config.query, config.dateSelection)}`
: AppInsightsQueryHelper.GetUrlQuery(config.query, config.dateSelection)
const requestHash = ApiQueryHelper.GetHash(`${this.cacheKey}-${urlQuery}`);
const cacheEnabled = CacheExpiration[this.cacheDuration.toString() as keyof typeof CacheExpiration] !== CacheExpiration.Disabled;
if (cacheEnabled) {
const lastResponse = ApiQueryHelper.GetCachedResponse(requestHash);
if (lastResponse) {
console.info("AppInsightsHelper: Using cached response")
return lastResponse;
}
}
//if cache disabled or no cached response, get live response
try {
console.info("AppInsightsHelper: Using live response")
const response = await this.getParsedResponse(`${this._postUrl}${urlQuery}`);
if (response && !response.error && cacheEnabled) {
console.info("AppInsightsHelper: Saving response to cache")
ApiQueryHelper.SaveCachedResponse(
requestHash,
response,
this.cacheDuration)
}
return response;
} catch (error) {
console.error(error);
}
}
public GetGroupBy = (query: string): string[] => {
return [];
}
private getParsedResponse = async<T>(urlQuery: string, colRenames?: Map<string, string>): Promise<IResponseJson> => {
const response: HttpClientResponse = await this.httpClient.get(urlQuery, HttpClient.configurations.v1, this.httpClientOptions);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const responseJson: IAppInsightsResponseJson = await response.json();
return ApiHelper.GetParsedResponse<T>(
{
body: responseJson.tables
? responseJson.tables[0]
: { columns: [], rows: [] },
error: responseJson.error
},
colRenames);
};
}

View File

@ -0,0 +1,162 @@
import moment from "moment";
import ApiQueryHelper, { QueryPreset } from "./ApiQueryHelper";
import { ChartStyles } from "./DashboardHelper";
import TimeHelper from "./TimeHelper";
enum TimeSpanKusto {
"PT1H" = "1h",
"PT6H" = "6h",
"PT12H" = "12h",
"P1D" = "1d",
"P3D" = "3d",
"P7D" = "7d",
"P15D" = "15d",
"P30D" = "30d",
"P45D" = "45d",
"P60D" = "60d",
"P75D" = "75d",
"P90D" = "90d"
}
export interface ChartConfig {
chartStyle: ChartStyles;
settings: string;
isSupported: boolean;
}
class AppInsightsQueryHelper extends ApiQueryHelper {
public static get ClientId(): string {
return "https://api.applicationinsights.io";
}
public static GetUrlQuery = (query: string, dateSpan: string): string => {
const _setTimeRange = (query: string, dateSpan: string): string => {
if (dateSpan.includes('-')) {
const dates: string[] = dateSpan.split('-')
.map(dt => {
return `"${TimeHelper.getQueryDateFormat(moment(Number(dt)).utc().format())}"`;
})
return query.replaceAll('{TimeRange:start}', dates[0]).replaceAll('{TimeRange:end}', dates[1]);
}
else {
const start = `ago(${AppInsightsQueryHelper.GetKustoTime(dateSpan)})`;
const end = 'now()';
return query.replaceAll('{TimeRange:start}', start).replaceAll('{TimeRange:end}', end);
}
}
const queryParam = encodeURIComponent(
_setTimeRange(
AppInsightsQueryHelper.GetSanitisedQuery(query),
dateSpan)
);
const timeStamp = dateSpan.includes('-')
? dateSpan.split('-')
.map(dt => {
return moment(Number(dt)).format('YYYY-MM-DDThh:mm:ss')
})
.join('/')
: dateSpan
return (query.indexOf('where timestamp') > 0)
? `${queryParam}`
: `${queryParam}&timespan=${timeStamp}`;
}
public static GetKustoTime = (dateSpan: string): string => {
return TimeSpanKusto[dateSpan as keyof typeof TimeSpanKusto]
}
public static GetChartConfig = (query: string): ChartConfig => {
const regexObj = /render(\s)+(?<vis>\S+)((\s)+with(\s)+\((?<settings>[^)]+))*/g
const found = regexObj.exec(
AppInsightsQueryHelper.GetSanitisedQuery(query)
);
const chartName = found?.groups?.vis ?? "";
return {
chartStyle: ChartStyles[chartName as keyof typeof ChartStyles] ?? null,
settings: found?.groups?.settings ?? "",
isSupported: Object.keys(ChartStyles).includes(chartName)
}
}
public static GetAPIEndpoint = (appId: string, dataEndpoint: string): string => {
return `${AppInsightsQueryHelper.ClientId}/v1/apps/${appId ?? '____'}/${dataEndpoint}?`
}
public static IsConfigValid = (isDevMode: boolean, appId: string, appKey?: string): boolean => {
return isDevMode
? appId !== "" && appKey !== ""
: appId !== ""
}
}
class AppInsightsQueryLogsHelper extends AppInsightsQueryHelper {
private static empty: QueryPreset = {
key: 100,
text: "---",
description: "Write your custom Kusto query",
query: "",
};
private static pageViewsTrend: QueryPreset = {
key: 1,
text: "Page views trend",
description: "Chart the page views count",
query: `pageViews
| where client_Type == 'Browser'
| summarize pageViews = sum(itemCount) by bin(timestamp,30m)
| sort by timestamp asc
| render linechart
`,
};
private static slowestPages: QueryPreset = {
key: 2,
text: "Slowest pages",
description: "What are the 3 slowest pages, and how slow are they? ",
query: `pageViews
| where notempty(duration) and client_Type == 'Browser'
| extend total_duration=duration*itemCount
| summarize avgDuration=(sum(total_duration)/sum(itemCount)) by operation_Name
| top 3 by avgDuration desc
`,
};
private static operationsPerformance: QueryPreset = {
key: 3,
text: "Operations performance ",
description: "Calculate request count and duration by operations. ",
query: `requests
| summarize RequestsCount=sum(itemCount), AverageDuration=avg(duration), percentiles(duration, 50, 95, 99) by operation_Name // you can replace 'operation_Name' with another value to segment by a different property
| order by RequestsCount desc // order from highest to lower (descending)`,
};
private static pageViewsHeatmap: QueryPreset = {
key: 4,
text: "Page views heatmap",
description: "Display page views heatmap per calendarweek",
query: `let start = startofweek({TimeRange:start});
let end= endofweek({TimeRange:end});
let dow = dynamic(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]);
pageViews
| where timestamp >= start
| where client_Type == 'Browser'
| make-series Metric=sum(itemCount) default=0 on timestamp in range(start, end, 1d)
| mvexpand timestamp to typeof(datetime), Metric to typeof(long)
| extend WeekDay = toint(dayofweek(timestamp) / 1d), KW=week_of_year(timestamp)
| extend WeekDayName=tostring(dow[WeekDay])
| order by timestamp asc
| project-away timestamp,WeekDay
| evaluate pivot(WeekDayName, sum(Metric))
| project tostring(KW),column_ifexists("Mon",""),column_ifexists("Tue",""),column_ifexists("Wed",""),column_ifexists("Thu",""),column_ifexists("Fri",""),column_ifexists("Sat",""),column_ifexists("Sun","")`,
};
protected static override queries: QueryPreset[] = [this.empty, this.pageViewsTrend, this.slowestPages, this.operationsPerformance, this.pageViewsHeatmap];
}
export { AppInsightsQueryHelper, AppInsightsQueryLogsHelper };

View File

@ -0,0 +1,231 @@
import { ChartLegendOptions, ChartOptions, ChartXAxe, TickOptions, TimeUnit } from "chart.js";
import ChartHelper from "./ChartHelper";
//#region DataSetStylesConfig
const dataSetPropStyle_Line = {
lineTension: 0,
borderWidth: 1
}
const dataSetPropStyle_Bar = {
barThickness: 'flex',
}
const dataSetPropStyle_BarTime = {
barThickness: 'flex',
maxBarThickness: 10,
minBarLength: 2,
}
const dataSetPropStyle_Pie = {
}
const dataSetPropStyle_None = {
}
const DataSetStylesConfig = {
Line: dataSetPropStyle_Line,
Bar: dataSetPropStyle_Bar,
BarTime: dataSetPropStyle_BarTime,
Pie: dataSetPropStyle_Pie,
None: dataSetPropStyle_None
}
//#endregion
//#region ChartOptionsConfig
const legendOptions: ChartLegendOptions = {
display: true,
position: 'bottom',
labels: {
usePointStyle: true,
boxWidth: 5,
},
onClick: () => { return false; }, // disable legend onClick functionality that filters datasets
}
const timeAxeConfig: ChartXAxe = {
type: "time",
time: {
unit: 'day',
},
gridLines: {
color: 'rgba(0, 0, 0, 0.1)',
zeroLineColor: 'rgba(0, 0, 0, 0.1)',
lineWidth: 0.5,
zeroLineWidth: 0.5
}
}
const xAxeTicksOptions: TickOptions = {
fontSize: 12,
maxRotation: 90,
callback: (value) => { return ChartHelper.GetText(value, 25) }
}
const yAxeTicksOptions: TickOptions = {
fontSize: 12,
callback: (value) => { return ChartHelper.GetText(value, 20) }
}
const xAxesOptions: ChartXAxe = {
offset: true,
ticks: {
source: 'auto',
...xAxeTicksOptions
}
}
const xAxesOptions_Bar: ChartXAxe = {
ticks:
{
beginAtZero: true,
...xAxeTicksOptions
}
}
const yAxesOptions: ChartXAxe = {
ticks: {
min: 0,
...yAxeTicksOptions
}
}
const yAxesOptions_Bar: ChartXAxe = {
ticks: {
min: 0,
beginAtZero: true,
...yAxeTicksOptions
},
scaleLabel: {
display: false,
labelString: 'Y'
}
}
const chartOptionsBase: ChartOptions = {
legend: legendOptions,
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 10
},
elements: {
point: {
radius: 2,
hitRadius: 5,
hoverRadius: 3,
},
}
}
const chartOptionsLine: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [
xAxesOptions
],
yAxes: [
yAxesOptions
]
}
}
const chartOptionsLine_TimeX: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [{
...xAxesOptions,
...timeAxeConfig,
offset: true,
}],
yAxes: [
yAxesOptions
]
}
}
const chartOptions_TimeXGranularity = (timeGranularity: TimeUnit): ChartOptions => {
return {
scales: {
xAxes: [{
time: {
unit: timeGranularity,
}
}]
}
}
}
const chartOptions_TimeYGranularity = (timeGranularity: TimeUnit): ChartOptions => {
return {
scales: {
yAxes: [{
time: {
unit: timeGranularity,
}
}]
}
}
}
const chartOptionsHorizontalBar: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [
xAxesOptions_Bar
],
yAxes: [
yAxesOptions_Bar
]
}
}
const chartOptionsHorizontalBar_TimeY: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [
xAxesOptions_Bar
],
yAxes: [{
...yAxesOptions_Bar,
...timeAxeConfig,
offset: true,
}]
}
}
const chartOptionsVerticalBar: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [
xAxesOptions_Bar
],
yAxes: [
yAxesOptions_Bar
]
}
}
const chartOptionsVerticalBar_TimeX: ChartOptions = {
...chartOptionsBase,
scales: {
xAxes: [{
...xAxesOptions_Bar,
...timeAxeConfig,
offset: true,
}],
yAxes: [
yAxesOptions_Bar
]
}
}
const chartOptionsPie: ChartOptions = {
...chartOptionsBase,
}
const ChartOptionsConfig = {
Line: chartOptionsLine,
Line_TimeX: chartOptionsLine_TimeX,
BarHorizontal: chartOptionsHorizontalBar,
BarHorizontal_TimeY: chartOptionsHorizontalBar_TimeY,
BarVertical: chartOptionsVerticalBar,
BarVertical_TimeX: chartOptionsVerticalBar_TimeX,
TimeAxe: timeAxeConfig,
TimeXGranularity: chartOptions_TimeXGranularity,
TimeYGranularity: chartOptions_TimeYGranularity,
Pie: chartOptionsPie
}
//#endregion
export { DataSetStylesConfig, ChartOptionsConfig };

View File

@ -0,0 +1,417 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { cloneDeep, merge, uniq } from "@microsoft/sp-lodash-subset";
import { ChartType, PaletteGenerator } from "@pnp/spfx-controls-react";
import { ChartData, ChartDataSets, ChartOptions, TimeUnit } from "chart.js";
import stringsCommon from "CommonDasboardWebPartStrings";
import moment from "moment";
import { ColumnsInfo, DataTypesInfo } from "../components/InsightsChart/IInsightsChartProps";
import ApiHelper from "./ApiHelper";
import { ChartOptionsConfig, DataSetStylesConfig } from "./ChartConfigHelper";
import ColorsHelper, { ThemedPalette } from "./ColorsHelper";
import { ChartStyles } from "./DashboardHelper";
export enum ChartAxis {
"x",
"y"
}
export default class ChartHelper {
private static OPACITY = 0.7;
private static GetColValues_TimeAxisX = (items: any[], colName_Label: string, colName_Value: string): { x: number; y: Date; }[] => {
return items.map(
i => {
return {
x: Number(Number(i[colName_Value]).toFixed(3)),
y: moment(i[colName_Label]).toDate(),
}
}
)
}
private static GetColValues_TimeAxisY = (items: any[], colName_Label: string, colName_Value: string): { x: Date; y: number; }[] => {
return items.map(
i => {
return {
x: moment(i[colName_Label]).toDate(),
y: Number(Number(i[colName_Value]).toFixed(3))
}
}
)
}
private static GetColValues_PointFormat = (items: any[], colName_Label: string, colName_Value: string): { x: number; y: number; }[] => {
return items.map(
i => {
return {
x: Number(Number(i[colName_Label]).toFixed(3)),
y: Number(Number(i[colName_Value]).toFixed(3))
}
}
)
}
private static GetColValues_Number = (items: any[], colName_Value: string): number[] => {
return items.map(i => Number(Number(i[colName_Value]).toFixed(3)));
}
private static GetLabels = (items: any[], colName_Label: string): string[] | Date[] => {
return items.map(i => i[colName_Label]);
}
public static GetText = (value: string | number, length: number): string => {
const val = value.toString();
return val.length > length ? val.substring(0, length) + '...' : val;
}
public static GetDataInfo = (items: any[], dataTypes: Map<string, string>, chartType?: ChartStyles): DataTypesInfo => {
const _getStackingSupport = (chartType: ChartStyles, colLength: number): boolean => {
return (chartType === ChartStyles.barchart || chartType === ChartStyles.columnchart) && (colLength > 1)
}
const _getTimeAxisSupport = (chartType: ChartStyles, colLength: number): boolean => {
return colLength > 0 && chartType !== ChartStyles.piechart;
}
const _getChartTypeSupport = (dataTypes: Map<string, string>, chartStyle?: ChartStyles): { isSupported: boolean, error?: string } => {
const supportedChartTypes: ChartType[] = ChartHelper.GetSupportedChartTypes(dataTypes);
const currChartType: ChartType = ChartHelper.GetChartType(chartStyle);
if (supportedChartTypes.includes(currChartType)) {
return {
isSupported: true
}
}
else {
switch (currChartType) {
case ChartType.Pie:
return {
isSupported: false,
error: stringsCommon.Msg_FailedVisErrPie// "Pie needs 1 num column"
}
default:
return {
isSupported: false,
error: stringsCommon.Msg_FailedVisErrOneNumerical// "No num columns found"
}
}
}
}
const _hasDifferentDates = (items: any[], colName_DateTime: string): boolean => {
const i = items.map(i => i[colName_DateTime]);
return uniq(i).length > 1;
}
const _getTimeGranularity = (items: any[], colName_DateTime: string): TimeUnit => {
const i = items.map(i => i[colName_DateTime]);
const uniqDates = uniq(i);
if (uniqDates.length > 1) {
const diff = moment(uniqDates[1]).diff(moment(uniqDates[0]));
if (diff < 1000 * 60 * 60 * 24) {
return 'hour';
}
else if (diff < 1000 * 60 * 60 * 24 * 30) {
return 'day';
}
else if (diff < 1000 * 60 * 60 * 24 * 365) {
return 'month';
}
else {
return 'year';
}
}
else {
return 'day';
}
}
//not supported in a chart:'bool', 'boolean', 'dynamic','guid', 'timespan', 'time'
const colName_Number = ApiHelper.GetColByTypes(dataTypes, ApiHelper.NumericTypes);
const colName_DateTime = ApiHelper.GetColByTypes(dataTypes, ApiHelper.DateTimeTypes);
const colName_String = ApiHelper.GetColByTypes(dataTypes, ApiHelper.StringTypes);
//stacking is suppored only for barchart and columnchart
const stackSupported = _getStackingSupport(chartType, colName_Number.length);
const timeAxisSupported = _getTimeAxisSupport(chartType, colName_DateTime.length) && _hasDifferentDates(items, colName_DateTime[0]);
const chartTypeSupported = _getChartTypeSupport(dataTypes, chartType);
const timeGranularity = timeAxisSupported ? _getTimeGranularity(items, colName_DateTime[0]) : undefined;
return {
colNumber: colName_Number,
colDateTime: colName_DateTime,
colString: colName_String,
isStacked: stackSupported,
hasTimeAxis: timeAxisSupported,
timeGranularity: timeGranularity,
isSupported: chartTypeSupported.isSupported, //isChartTypeSupported
errorMsg: chartTypeSupported.error
}
}
public static GetChartType = (chartStyle?: ChartStyles): ChartType => {
switch (chartStyle) {
case ChartStyles.barchart:
return ChartType.HorizontalBar;
case ChartStyles.columnchart:
return ChartType.Bar;
case ChartStyles.piechart:
return ChartType.Pie;
case ChartStyles.areachart:
case ChartStyles.linechart:
default:
return ChartType.Line;
}
}
public static GetChartData = (items: any[], hasTimeAxis: boolean, isHorizontal: boolean, columnsInfo: ColumnsInfo, chartType: ChartType, fillChart: boolean, chartPalette: ThemedPalette): ChartData => {
const _getColors = (chartType: ChartType, itemsLength: number, valuesLength: number): string[] => {
return chartType === ChartType.Pie
? ColorsHelper.GetThemeMonochromaticColors(chartPalette as ThemedPalette, itemsLength).Colors
: ColorsHelper.GetThemeMonochromaticColors(chartPalette as ThemedPalette, valuesLength).Colors
}
const _getColumnsInfo = (columnsInfo: ColumnsInfo, hasTimeAxis: boolean): { label: string, values: string[], series: string[] } => {
if (hasTimeAxis) {
return {
label: columnsInfo.colDateTime[0],
values: columnsInfo.colNumber,
series: columnsInfo.colString
}
} else if (columnsInfo.colString[0] ?? columnsInfo.colDateTime[0]) {
return {
label: columnsInfo.colString[0] ?? columnsInfo.colDateTime[0],
values: columnsInfo.colNumber,
series: columnsInfo.colString.splice(0, 1)
}
}
else {
return {
label: columnsInfo.colNumber[0],
values: columnsInfo.colNumber.slice(1),
series: columnsInfo.colString
}
}
}
const _getGroupedBySeries = (series: string[], items: any[]): Map<string, any> => {
const groupBy = series[0]
return items.reduce((prev: Map<string, any>, curr) => {
const { [groupBy]: groupByVal, ...rest } = curr;
prev.set(groupByVal, prev.has(groupByVal) ? [...prev.get(groupByVal), rest] : [rest]);
return prev;
}, new Map<string, any>());
}
const _getDataTimeAxis = (items: any[], colName_Label: string, colName_Values: string[], series: string[], chartDataConfig: ChartDataSets, isHorizontal: boolean, fillChart: boolean): ChartData => {
if (colName_Values.length === 1 && series.length > 0) {
let count = 0;
const dataSets: ChartDataSets[] = []
const groupedBySeries = _getGroupedBySeries(series, items);
const colors = ColorsHelper.GetThemeMonochromaticColors(chartPalette as ThemedPalette, groupedBySeries.size).Colors
groupedBySeries.forEach((value: any, key: string) => {
const _color = colors[count++];
const dataSet: ChartDataSets = {
label: key,
data: isHorizontal
? ChartHelper.GetColValues_TimeAxisX(value, colName_Label, colName_Values[0])
: ChartHelper.GetColValues_TimeAxisY(value, colName_Label, colName_Values[0]),
fill: fillChart,
backgroundColor: PaletteGenerator.alpha(_color, ChartHelper.OPACITY),
borderColor: _color,
...chartDataConfig
}
dataSets.push(dataSet);
});
console.log(dataSets);
return {
datasets: dataSets
}
}
else {
const colors = ColorsHelper.GetThemeMonochromaticColors(chartPalette as ThemedPalette, colName_Values.length).Colors
return {
datasets: colName_Values.map((col: string, index: number) => {
const _color = colors[index];
return {
label: col,
data: isHorizontal
? ChartHelper.GetColValues_TimeAxisX(items, colName_Label, col)
: ChartHelper.GetColValues_TimeAxisY(items, colName_Label, col),
fill: fillChart,
backgroundColor: PaletteGenerator.alpha(_color, ChartHelper.OPACITY),
borderColor: _color,
...chartDataConfig
}
})
};
}
}
const _getDataPie = (items: any[], colName_Label: string, colName_Values: string[], chartDataConfig: ChartDataSets, fillChart: boolean, colors: string[]): ChartData => {
return {
labels: ChartHelper.GetLabels(items, colName_Label),
datasets: colName_Values.map((col: string, index: number) => {
return {
label: col,
data: ChartHelper.GetColValues_Number(items, col),
fill: fillChart,
backgroundColor: PaletteGenerator.alpha(colors, ChartHelper.OPACITY),
borderWidth: 0,
...chartDataConfig
}
})
};
}
const _getData = (items: any[], colName_Label: string, colName_Values: string[], chartDataConfig: ChartDataSets, fillChart: boolean, colors: string[]): ChartData => {
return {
labels: ChartHelper.GetLabels(items, colName_Label),
datasets: colName_Values.map((col: string, index: number) => {
return {
label: col,
data: ChartHelper.GetColValues_Number(items, col),
fill: fillChart,
backgroundColor: PaletteGenerator.alpha(colors[index], ChartHelper.OPACITY),
borderColor: colors[index],
...chartDataConfig
}
})
};
}
const dataSetStylesConfig = ChartHelper.GetDataSetStylesConfig(chartType, hasTimeAxis);
const colsInfo = _getColumnsInfo(columnsInfo, hasTimeAxis);
const colors = _getColors(chartType, items.length, colsInfo.values.length);
//no time axis, all other charts => [labels, data]
//time Axis but just 1 date => hasTimeAxis=false, get string column as label
if (chartType === ChartType.Pie) {
return _getDataPie(
items,
colsInfo.label,
colsInfo.values,
dataSetStylesConfig,
fillChart,
colors
);
}
else if (hasTimeAxis) {
return _getDataTimeAxis(
items,
colsInfo.label,
colsInfo.values,
colsInfo.series,
dataSetStylesConfig,
isHorizontal,
fillChart,
);
}
else {
return _getData(
items,
colsInfo.label,
colsInfo.values,
dataSetStylesConfig,
fillChart,
colors
)
}
}
public static GetDataSetStylesConfig = (chartType: ChartType, hasTimeAxis: boolean): {} => {
switch (chartType) {
case ChartType.Line:
return DataSetStylesConfig.Line;
case ChartType.Bar://column
return hasTimeAxis ? DataSetStylesConfig.BarTime : DataSetStylesConfig.Bar;
case ChartType.HorizontalBar:
return hasTimeAxis ? DataSetStylesConfig.BarTime : DataSetStylesConfig.Bar;
case ChartType.Pie:
return DataSetStylesConfig.Pie;
default:
return DataSetStylesConfig.None;
}
}
public static GetSupportedChartTypes = (dataTypes: Map<string, string>): ChartType[] => {
const colName_Number = ApiHelper.GetColByTypes(dataTypes, ApiHelper.NumericTypes);
const colName_DateTime = ApiHelper.GetColByTypes(dataTypes, ApiHelper.DateTimeTypes);
const colName_String = ApiHelper.GetColByTypes(dataTypes, ApiHelper.StringTypes);
const chartTypes: ChartType[] = [];
if (colName_Number.length > 0) {
chartTypes.push(ChartType.Line);
chartTypes.push(ChartType.Bar);
chartTypes.push(ChartType.HorizontalBar);
}
if (colName_DateTime.length > 0) {
chartTypes.push(ChartType.Line);
chartTypes.push(ChartType.Bar);
chartTypes.push(ChartType.HorizontalBar);
}
if (colName_String.length > 0 && colName_Number.length < 2) {
chartTypes.push(ChartType.Pie);
}
return chartTypes;
}
public static GetChartOptions = (chartType: ChartType, hasTimeAxis: boolean, timeGranularity: TimeUnit, isStacked: boolean): ChartOptions => {
const options = ChartHelper.getOptions(chartType, hasTimeAxis, timeGranularity)
if (hasTimeAxis && timeGranularity !== undefined) {
if (options.scales.xAxes[0].time?.unit) {
options.scales.xAxes[0].time.unit = timeGranularity;
}
if (options.scales.yAxes[0].time?.unit) {
options.scales.yAxes[0].time.unit = timeGranularity;
}
}
return isStacked
? ChartHelper.configureStacked(options)
: options;
}
private static mergeOptionsX = (options: ChartOptions, timeGranularity: TimeUnit): ChartOptions => {
if (timeGranularity !== undefined)
return merge({}, options, ChartOptionsConfig.TimeXGranularity(timeGranularity))
else
return options;
}
private static mergeOptionsY = (options: ChartOptions, timeGranularity: TimeUnit): ChartOptions => {
if (timeGranularity !== undefined)
return merge({}, options, ChartOptionsConfig.TimeYGranularity(timeGranularity))
else
return options;
}
private static getOptions = (chartType: ChartType, hasTimeAxis: boolean, timeGranularity: TimeUnit): ChartOptions => {
let chartOption = {}
switch (chartType) {
case ChartType.Line: {
chartOption = hasTimeAxis
? ChartHelper.mergeOptionsX(ChartOptionsConfig.Line_TimeX, timeGranularity)
: ChartOptionsConfig.Line;
break;
}
case ChartType.Bar: { //column
chartOption = hasTimeAxis
? ChartHelper.mergeOptionsX(ChartOptionsConfig.BarVertical_TimeX, timeGranularity)
: ChartOptionsConfig.BarVertical;
break;
}
case ChartType.HorizontalBar: {
chartOption = hasTimeAxis
? ChartHelper.mergeOptionsY(ChartOptionsConfig.BarHorizontal_TimeY, timeGranularity)
: ChartOptionsConfig.BarHorizontal;
break;
}
case ChartType.Pie:
chartOption = ChartOptionsConfig.Pie;
break;
}
return chartOption;
}
private static configureStacked = (chartOptions: ChartOptions): ChartOptions => {
const options = cloneDeep(chartOptions)
if (options.scales.xAxes && options.scales.yAxes) {
options.scales.yAxes[0].stacked = true;
options.scales.xAxes[0].stacked = true;
}
return options;
}
}

View File

@ -0,0 +1,147 @@
import { PaletteGenerator } from "@pnp/spfx-controls-react";
import Color from 'color';
import { theme } from "./ComponentStyles";
interface ThemeColorsInfo {
Colors: string[],
Name: string,
Id: string
}
export enum ThemedPalette {
ThemeAccents = 1,
ThemeMonochromatic = 2,
AccentYellow = 3,
AccentOrange = 4,
AccentRed = 5,
AccentMagenta = 6,
AccentPurple = 7,
AccentBlue = 8,
AccentTeal = 9,
AccentGreen = 10,
}
export default class ColorsHelper {
private static _themeAccentColorsLong: string[] = [
theme.palette.yellowDark,
theme.palette.yellow,
theme.palette.yellowLight,
theme.palette.orange,
theme.palette.orangeLight,
theme.palette.orangeLighter,
theme.palette.orangeLighter,
theme.palette.redDark,
theme.palette.red,
theme.palette.magentaDark,
theme.palette.magenta,
theme.palette.magentaLight,
theme.palette.purpleDark,
theme.palette.purple,
theme.palette.purpleLight,
theme.palette.blueDark,
theme.palette.blueMid,
theme.palette.blue,
theme.palette.blueLight,
theme.palette.tealDark,
theme.palette.teal,
theme.palette.tealLight,
theme.palette.greenDark,
theme.palette.green,
theme.palette.greenLight,
]
private static _themeAccentColors: string[] = [
theme.palette.blue,
theme.palette.orangeLight,
theme.palette.neutralSecondary,
theme.palette.yellow,
theme.palette.blueLight,
theme.palette.greenLight,
]
public static GetThemeMonochromaticColors(palette: ThemedPalette, _length: number): ThemeColorsInfo {
//fix for PaletteGenerator.generateNonRepeatingGradient(,1) dividing by 0
//https://github.com/pnp/sp-dev-fx-controls-react/blob/564f4edd0a14f871f8b2debcb314cfb3f531de6a/src/controls/chartControl/PaletteGenerator.ts#L133
const length = palette !== ThemedPalette.ThemeAccents && _length===1
? 2
: _length;
switch (palette) {
case ThemedPalette.ThemeAccents:
return {
Colors: PaletteGenerator.generateRepeatingPattern(ColorsHelper._themeAccentColors, length).slice(0, length), //ColorsHelper._themeAccentColors.slice(0, length),
Name: "Theme Accents",
Id: "1"
}
case ThemedPalette.ThemeMonochromatic:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.themeDarkAlt, theme.palette.themeLighter], length),
Name: "Current Theme",
Id: "2"
}
case ThemedPalette.AccentYellow:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.yellow, theme.palette.white], length),
Name: "Yellow",
Id: "3"
}
case ThemedPalette.AccentOrange:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.orangeLight, theme.palette.white], length),
Name: "Orange",
Id: "4"
}
case ThemedPalette.AccentRed:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.red, theme.palette.white], length),
Name: "Red",
Id: "5"
}
case ThemedPalette.AccentMagenta:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.magenta, theme.palette.white], length),
Name: "Magenta",
Id: "6"
}
case ThemedPalette.AccentPurple:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.purple, theme.palette.white], length),
Name: "Purple",
Id: "7"
}
case ThemedPalette.AccentBlue:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.blue, theme.palette.white], length),
Name: "Blue",
Id: "8"
}
case ThemedPalette.AccentTeal:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.teal, theme.palette.white], length),
Name: "Teal",
Id: "9"
}
case ThemedPalette.AccentGreen:
return {
Colors: PaletteGenerator.generateNonRepeatingGradient([theme.palette.green, theme.palette.white], length),
Name: "Green",
Id: "10"
}
}
}
public static GetContrastColor(colorRGBA: string): string {
const color = Color(colorRGBA);
//for background white
if(color.isLight()){
return theme.palette.black;
}
else if(color.isDark() && color.alpha() < 0.5){
return theme.palette.black;
}
else{
return theme.palette.white;
}
}
}

View File

@ -0,0 +1,91 @@
import { DisplayMode } from "@microsoft/sp-core-library";
import { AadHttpClientFactory, HttpClient } from "@microsoft/sp-http";
import { ThemedPalette } from "./ColorsHelper";
import { CostManagementScope } from "./CostMngmtQueryHelper";
import { ChartStyles, LayoutStyles, ListStyles } from "./DashboardHelper";
export enum ConfigType {
ApplicationInsightsLogs=1,
CostManagement=2,
ApplicationInsightsMetrics = 3,
}
export enum AppInsightsEndpointType {
query="query",
metrics="metrics"
}
export enum CacheExpiration {
"FifteenMinutes" = "Fifteen Minutes",
"OneHour" = "One Hour",
"OneDay" = "One Day",
"Disabled"="No caching"
}
export interface IDashboardContextProps {
httpClient: HttpClient;
aadHttpClientFactory: AadHttpClientFactory
cultureName: string;
DisplayMode: DisplayMode;
width: number;
}
export interface ICacheConfig{
cacheDuration: CacheExpiration;
userLoginName:string;
}
//#region AppInsights Interfaces
export interface IAppInsightsConfig {
appId: string;
appKey: string;
endpoint: AppInsightsEndpointType;
}
export interface AppInsights_AuthSSO {
appId: string;
aadHttpClientFactory: AadHttpClientFactory;
endpoint: AppInsightsEndpointType;
}
export interface IAppInsightsQuery{
query: string;
dateSelection: string;
}
//#endregion
//#region CostManagement Interfaces
export interface ICostManagementConfig {
scope: CostManagementScope,
subscriptionId?: string,
resourceGroupName?: string,
managementGroupId?: string
}
export interface ICostManagementQuery{
query: string;
dateSelection: string;
}
//#endregion
export interface ILayoutConfig{
showList: boolean;
listStyle: ListStyles;
listPalette: ThemedPalette;
showChart: boolean;
chartStyle: ChartStyles;
chartPalette: ThemedPalette;
layoutSettings: LayoutStyles;
}
export interface IDashboardConfig{
preset: number;
pivotKey: string;
showTimePicker: boolean;
width: number;
}
export interface IAppInsightsWebPartProps extends IAppInsightsConfig, IAppInsightsQuery, ICacheConfig, ILayoutConfig, IDashboardConfig {
isDevMode: boolean;
logLevel?: number;
}
export interface ICostManagementWebPartProps extends ICostManagementConfig, ICostManagementQuery, ICacheConfig, ILayoutConfig, IDashboardConfig {
logLevel?: number;
}

View File

@ -0,0 +1,203 @@
import { createTheme, getColorFromString, getTheme, IButtonStyles, IChoiceGroupStyles, IColor, IIconProps, ILinkStyles, IPivotStyles, IShimmerStyles, IStackItemStyles, IStackStyles, IStackTokens, ISwatchColorPickerStyles, ITextStyles } from "@fluentui/react";
const theme = (process.env.NODE_ENV !== 'production')
? createTheme({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
palette: (window as any).__themeState__.theme
})
: getTheme();
const padding4px = theme.spacing.s2;
const padding8px = theme.spacing.s1;
const fontSmall = theme.fonts.small.fontSize;
const minWidth=280;
const getColorRGB = (color: string): string => {
const col: IColor = getColorFromString(color);
return `${col.r},${col.g},${col.b}`;
}
const getColorRGBA = (color: string, opacity: string | number): string => {
const col: IColor = getColorFromString(color);
return `rgba(${col.r},${col.g},${col.b},${opacity})`;
}
const stackTokens: IStackTokens = { childrenGap: `${padding8px} ${padding8px}` }; //rowGap columnGap 8px 4px
const stackStylesMain: Partial<IStackStyles> = {
root: {
backgroundColor: 'inherit'
}
}
const stackStylesDatePicker: Partial<IStackStyles> = {
root: {
display: 'flex',
borderWidth: 1,
borderStyle: 'solid',
borderColor: theme.palette.neutralTertiaryAlt,
borderRadius: theme.effects.roundedCorner6,
alignItems: 'center',
width: 'fit-content',
backgroundColor: theme.palette.neutralQuaternary,
paddingTop: 1,
paddingBottom: 1,
paddingLeft: padding8px,
paddingRight: padding8px
},
}
const stackItemStyles: Partial<IStackItemStyles> = {
root: {
alignItems: 'center',
display: 'block',
justifyContent: 'center',
fontSize: fontSmall,
minWidth: minWidth
},
};
const stackItemStyles100: Partial<IStackItemStyles> = {
root: {
width: '100%'
}
}
const stackItemStyles50: Partial<IStackItemStyles> = {
root: {
width: `calc(50% - ${padding8px})`,
}
}
const stackItemStyles66: Partial<IStackItemStyles> = {
root: {
width: `calc(60% - ${padding4px})`,
}
}
const stackItemStyles33: Partial<IStackItemStyles> = {
root: {
width: `calc(30% - ${padding4px})`,
}
}
const headerStyles: Partial<ITextStyles> = {
root: {
fontWeight: theme.fonts.medium.fontWeight
}
}
const applyBtnStyles: Partial<IButtonStyles> = {
root: {
width: 100,
alignSelf: 'end'
}
}
const pivotStylesDashboard: Partial<IPivotStyles> = {
root: {
backgroundColor: theme.palette.neutralTertiary,
color: theme.palette.neutralDark,
display: 'flex',
flexFlow:'wrap'
},
itemContainer: {
padding: padding8px,
paddingTop:0,
backgroundColor: theme.palette.neutralTertiaryAlt
}
}
const linkStyles: Partial<ILinkStyles> = {
root: {
alignSelf: 'end',
fontSize: fontSmall,
maxWidth:'100%',
textAlign:'end'
}
}
const helpIcon: IIconProps = { iconName: 'Info' };
const shimmerStyleChart: Partial<IShimmerStyles> = {
root: {
minHeight: '200px'
},
shimmerWrapper: {
height: '100%'
}
}
const chartTheme = createTheme({
semanticColors: {
bodyBackground: getColorRGBA(theme.semanticColors.bodyBackground, 0.85),
},
fonts:{
medium: {
fontSize: theme.fonts.small.fontSize,
fontWeight: theme.fonts.medium.fontWeight
},
small: {
fontSize: theme.fonts.small.fontSize,
fontWeight: theme.fonts.small.fontWeight
},
}
})
// transparent theme
const transparentTheme = createTheme({
semanticColors: {
bodyBackground: getColorRGBA(theme.semanticColors.bodyBackground, 0.5),
},
palette: {
white: getColorRGBA(theme.semanticColors.bodyBackground, 0.7),
}
});
const heatmapStyles = {
minWidth:minWidth
}
const datePickerStyles: { stack: Partial<IStackStyles>, text: Partial<ITextStyles> } ={
stack: stackStylesDatePicker,
text: headerStyles
}
const dashboardStyles: { applyBtn: Partial<IButtonStyles>, link: Partial<ILinkStyles>, pivot: Partial<IPivotStyles>, helpIcon: IIconProps }={
applyBtn:applyBtnStyles,
link:linkStyles,
pivot:pivotStylesDashboard,
helpIcon:helpIcon
}
const stackStyles:{item:Partial<IStackItemStyles>,item100:Partial<IStackItemStyles>,item33:Partial<IStackItemStyles>,item50:Partial<IStackItemStyles>,item66:Partial<IStackItemStyles>}={
item:stackItemStyles,
item100:stackItemStyles100,
item33:stackItemStyles33,
item50:stackItemStyles50,
item66:stackItemStyles66
}
const disabledPickerStyle: Partial<ISwatchColorPickerStyles> = {
tableCell: {
'button': {
border: 'none',
padding: '0px',
},
'button:hover': {
padding: '0px',
border: 'none',
cursor: 'auto',
}
}
}
const colorPickerStyles: Partial<IChoiceGroupStyles> = {
flexContainer: { display: 'flex', flexDirection: 'row', flexWrap: 'wrap' },
label: { display: 'flex', flexDirection: 'column' }
}
export {
theme,
stackTokens,
heatmapStyles,
datePickerStyles,
dashboardStyles,
stackStyles,
stackStylesMain,
shimmerStyleChart,
transparentTheme,
chartTheme,
disabledPickerStyle,
colorPickerStyles,
linkStyles,
getColorRGB,
getColorRGBA,
};

View File

@ -0,0 +1,144 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { AadHttpClient, AadHttpClientFactory, IHttpClientOptions } from "@microsoft/sp-http";
import moment from "moment";
import ApiHelper, { ICostMngmtResponseJson, IResponseJson } from "./ApiHelper";
import ApiQueryHelper from "./ApiQueryHelper";
import { CacheExpiration, ICacheConfig, ICostManagementConfig, ICostManagementQuery } from "./CommonProps";
import CostMngmtQueryHelper from "./CostMngmtQueryHelper";
export default class CostMngmtHelper {
private _postUrl: string = '';
private requestHeaders: Headers = new Headers();
private httpClientOptions: IHttpClientOptions = {};
private aadHttpClientFactory: AadHttpClientFactory = null;
private spfxSpoApiConnectClient: AadHttpClient = null;
private cacheDuration: CacheExpiration;
private cacheKey: string;
constructor(config: ICostManagementConfig, cache: ICacheConfig, aadHttpClientFactory: AadHttpClientFactory) {
this.aadHttpClientFactory = aadHttpClientFactory;
this._postUrl = CostMngmtQueryHelper.GetAPIEndpoint(
config.scope, {
subscriptionId: config.subscriptionId,
resourceGroupName: config.resourceGroupName,
managementGroupId: config.managementGroupId
}
);
this.requestHeaders.append("Content-type", "application/json; charset=utf-8");
this.httpClientOptions = { headers: this.requestHeaders };
this.cacheDuration = cache.cacheDuration;
this.cacheKey = `${config.subscriptionId ?? ''}-${config.resourceGroupName ?? ''}-${config.managementGroupId ?? ''}-${cache.userLoginName}`
}
public GetAPIResponse = async (config: ICostManagementQuery): Promise<IResponseJson> => {
const body = JSON.stringify(JSON.parse(config.query), null, 0);
const requestHash = ApiQueryHelper.GetHash(`${this.cacheKey}-${body}`);
const lastResponse = ApiQueryHelper.GetCachedResponse(requestHash);
if (lastResponse) {
return lastResponse;
}
else {
await this.init();
const response = await this.getParsedResponse(body);
if (response && !response.error) {
ApiQueryHelper.SaveCachedResponse(
requestHash,
response,
this.cacheDuration);
}
return response;
}
}
public GetGroupBy = (query: string): string[] => {
return CostMngmtQueryHelper.GetGroupBy(query);
}
private init = async (): Promise<void> => {
return await this.aadHttpClientFactory
.getClient(CostMngmtQueryHelper.ClientId)
.then((client: AadHttpClient): void => {
this.spfxSpoApiConnectClient = client;
})
.catch(err => {
console.error(err)
});
}
private getParsedResponse = async<T>(requestBody: string, colRenames?: Map<string, string>): Promise<IResponseJson> => {
this.httpClientOptions.body = requestBody;
const resp = await this.spfxSpoApiConnectClient.post(
CostMngmtQueryHelper.GetAPIEndpointFull(this._postUrl),
AadHttpClient.configurations.v1,
this.httpClientOptions);
const responseJson: ICostMngmtResponseJson = await resp.json();
const response = ApiHelper.GetParsedResponse<T>(
{
body: responseJson.properties,
error: responseJson.error
},
colRenames);
this.printoQuotaInfo(resp.headers)
this.setDateColumnFormat(response, 'BillingMonth', 'YYYY-MM-DDThh:mm:ss', 'YYYY-MM-DDThh:mm:ssZ');
this.setDateColumnFormat(response, 'UsageDate', 'YYYYMMDD', 'L');
//reorder columns in response.tables, move Cost & Currency to the end
if (response.tables.length > 0 && response.columns.has('Cost') && response.columns.has('Currency')) {
this.getReorderedColumns(response);
}
return response;
}
private setDateColumnFormat = (response: IResponseJson, dateColName: string, initialFormat: string, targetFormat: string): void => {
if (response.columns.has(dateColName)) {
response.columns.forEach((value: string, key: string) => {
if (key === dateColName) {
response.columns.set(key, 'datetime')
}
})
response.tables.forEach((row: any) => {
if (row[dateColName]) {
row[dateColName] = moment(row[dateColName], initialFormat).format(targetFormat)
}
});
}
}
private getReorderedColumns = (response: IResponseJson): void => {
//move Cost & Currency in response.columns to the end
const costCol = response.columns.get('Cost');
const currencyCol = response.columns.get('Currency');
response.columns.delete('Cost');
response.columns.delete('Currency');
response.columns.set('Cost', costCol);
response.columns.set('Currency', currencyCol);
//move Cost & Currency to the end
response.tables = response.tables.reduce((prev, curr) => {
const { Cost, Currency, ...rest } = curr;
const newRow = { ...rest, Cost, Currency };
prev.push(newRow);
return prev;
}, []);
}
private printoQuotaInfo(headers: Headers): void {
console.info(`x-ms-ratelimit-microsoft.costmanagement-qpu-consumed (QPUs consumed by an API call): ${headers.get('x-ms-ratelimit-microsoft.costmanagement-qpu-consumed')}`)
console.info(`x-ms-ratelimit-microsoft.costmanagement-qpu-remaining (list of remaining quotas): ${headers.get('x-ms-ratelimit-microsoft.costmanagement-qpu-remaining')}`)
console.info(`x-ms-ratelimit-remaining-microsoft.costmanagement-clienttype-requests: ${headers.get('x-ms-ratelimit-remaining-microsoft.costmanagement-clienttype-requests')} `)
console.info(`x-ms-ratelimit-remaining-microsoft.costmanagement-entity-requests: ${headers.get('x-ms-ratelimit-remaining-microsoft.costmanagement-entity-requests')}`)
console.info(`x-ms-ratelimit-remaining-microsoft.costmanagement-tenant-requests: ${headers.get('x-ms-ratelimit-remaining-microsoft.costmanagement-tenant-requests')}`)
console.info(`x-ms-ratelimit-remaining-subscription-resource-requests: ${headers.get('x-ms-ratelimit-remaining-subscription-resource-requests')}`)
}
}

View File

@ -0,0 +1,232 @@
import moment from "moment";
import ApiQueryHelper, { DropDownOption, QueryPreset } from "./ApiQueryHelper";
import { ICostManagementConfig } from "./CommonProps";
import { TimeSpanCost } from "./TimeHelper";
export enum CostManagementScope {
Subscription = 1,
ResourceGroup,
ManagementGroup,
}
//#region Cost Management Query Presets
const jsonCostByService = {
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "Monthly",
"filter": {
"tags": {
"name": "Environment",
"operator": "In",
"values": [
"Build",
"Dev",
"Test",
"UAT",
"Prod"
]
}
},
"grouping": [
{
"type": "Dimension",
"name": "ServiceName"
}
],
"aggregation": {
"totalCost": {
"name": "Cost",
"function": "Sum"
}
}
}
}
const jsonAzureMonitorCosts = {
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "Monthly",
"filter": {
"dimensions": {
"name": "MeterCategory",
"operator": "In",
"values": [
"Azure Monitor",
"Log Analytics"
]
}
},
"grouping": [
{
"type": "Dimension",
"name": "ServiceName"
},
{
"type": "TagKey",
"name": "Environment"
}
],
"aggregation": {
"totalCost": {
"name": "PreTaxCost",
"function": "Sum"
}
}
}
}
const jsonAccumulatedCosts = {
"type": "Usage",
"timeframe": "MonthToDate",
"dataset": {
"granularity": "Accumulated",
"filter": {
"tags": {
"name": "Environment",
"operator": "In",
"values": [
"Build",
"Dev",
"Test",
"UAT",
"Prod"
]
}
},
"grouping": [
{
"type": "Dimension",
"name": "ServiceName"
}
],
"aggregation": {
"totalCost": {
"name": "PreTaxCost",
"function": "Sum"
}
}
}
}
//#endregion
export default class CostMngmtQueryHelper extends ApiQueryHelper {
//#region query presets
private static empty: QueryPreset = {
key: 100,
text: "---",
description: "Write your custom body",
query: "",
};
private static getCostBilling: QueryPreset = {
key: 1,
text: "Cost by service",
description: "Get usage cost by service for the current billing period",
query: JSON.stringify(jsonCostByService, null, 2),
columnsOrdering: ['ServiceName', 'Cost', 'Currency'], //String, Number,String
}
private static getAccumulatedCostBilling: QueryPreset = {
key: 2,
text: "Accumulated costs",
description: "Get Accumulated usage costs for the last month",
query: JSON.stringify(jsonAccumulatedCosts, null, 2),
columnsOrdering: ['ServiceName', 'PreTaxCost', 'Currency'], //String, Number,String
}
private static getAzMonitorCostBilling: QueryPreset = {
key: 3,
text: "Azure Monitor costs",
description: "Get Azure Monitor usage cost for the last month",
query: JSON.stringify(jsonAzureMonitorCosts, null, 2),
columnsOrdering: ['ServiceName', 'PreTaxCost', 'Currency'],
}
//#endregion
protected static queries: QueryPreset[] = [this.empty, this.getCostBilling, this.getAccumulatedCostBilling, this.getAzMonitorCostBilling];
public static get Scopes(): DropDownOption[] {
return [
{ key: CostManagementScope.Subscription, text: "Subscription" },
{ key: CostManagementScope.ResourceGroup, text: "Resource Group" },
{ key: CostManagementScope.ManagementGroup, text: "Management Group" },
]
}
public static get ClientId(): string {
return "https://management.azure.com";
}
public static get ApiVersion(): string {
return "2022-10-01";
}
public static GetAPIEndpoint(scope: CostManagementScope, config: { subscriptionId?: string, resourceGroupName?: string, managementGroupId?: string }): string {
const scopePath = this.getEndpoint(scope, config);
return `${CostMngmtQueryHelper.ClientId}/${scopePath}/providers/Microsoft.CostManagement`;
}
public static GetAPIEndpointFull(baseUrl: string): string {
return `${baseUrl}/query?api-version=${CostMngmtQueryHelper.ApiVersion}`;
}
public static IsConfigValid(config: ICostManagementConfig): boolean {
switch (config.scope) {
case CostManagementScope.Subscription:
return !!config.subscriptionId //!== "";
case CostManagementScope.ResourceGroup:
return !!config.resourceGroupName && !!config.subscriptionId
case CostManagementScope.ManagementGroup:
return !!config.managementGroupId
default:
return false;
}
}
public static GetSanitisedQuery = (query: string): string => {
return JSON.stringify(
JSON.parse(query),
null,
0);
}
public static ShouldShowForecast(query: string): boolean {
const queryObj = JSON.parse(query);
if (queryObj.timeframe) {
const timeframe = queryObj.timeframe;
if (Object.keys(TimeSpanCost).includes(timeframe)) {
switch (TimeSpanCost[timeframe as keyof typeof TimeSpanCost]) {
case TimeSpanCost.BillingMonthToDate:
case TimeSpanCost.MonthToDate:
return true;
default:
return false;
}
}
}
else if (queryObj.timePeriod) {
const timePeriod = queryObj.timePeriod;
if (moment(timePeriod.from).isValid() && moment(timePeriod.to).isValid()) {
//is timeperiod.from this month?
if (moment(timePeriod.from).isSame(moment(), 'month')) {
return true;
}
}
}
return false;
}
public static GetGroupBy(query: string): string[] {
const queryObj = JSON.parse(query);
if (queryObj.dataset && queryObj.dataset.grouping) {
return queryObj.dataset.grouping.map((g: {name:string}) => g.name);
}
return [];
}
private static getEndpoint(scope: CostManagementScope, config: { subscriptionId?: string, resourceGroupName?: string, managementGroupId?: string }): string {
switch (scope) {
case CostManagementScope.Subscription:
return `subscriptions/${config.subscriptionId ?? '____'}`; //'/subscriptions/{subscriptionId}/' for subscription scope,
case CostManagementScope.ResourceGroup:
return `subscriptions/${config.subscriptionId ?? '____'}/resourceGroups/${config.resourceGroupName ?? '____'}`; //'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for resourceGroup scope,
case CostManagementScope.ManagementGroup:
return `/providers/Microsoft.Management/managementGroups/${config.managementGroupId ?? '____'}` //'/providers/Microsoft.Management/managementGroups/{managementGroupId} for Management Group scope,
default:
return "____";
}
}
}

View File

@ -0,0 +1,176 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { IChoiceGroupOption } from "@fluentui/react"
import { ChartPalette } from "@pnp/spfx-controls-react"
import stringsCommon from "CommonDasboardWebPartStrings"
import { ChartStyles, LayoutStyles, ListStyles } from "./DashboardHelper"
//https://developer.microsoft.com/en-us/fluentui#/styles/web/icons#fabric-react
const imageSize = {
width: 100,
height: 15
}
export const configLayoutStyles: IChoiceGroupOption[] = [
{
text: '100%',
key: LayoutStyles.SingleColumn.toString(),
iconProps: {
iconName: 'SingleColumn'
},
},
{
text: '1:1',
key: LayoutStyles.DoubleColumn.toString(),
iconProps: {
iconName: 'DoubleColumn'
},
},
{
text: '1:2',
key: LayoutStyles.ColumnRightTwoThirds.toString(),
iconProps: {
iconName: 'ColumnRightTwoThirds'
},
},
{
text: '2:1',
key: LayoutStyles.ColumnLeftTwoThirds.toString(),
iconProps: {
iconName: 'ColumnLeftTwoThirds'
}
},
]
export const configListStyles: IChoiceGroupOption[] = [
{
text: stringsCommon.LookListList,
key: ListStyles.list.toString(),
iconProps: {
iconName: 'ShowResults'
}
},
{
text: stringsCommon.LookListHeatmap,
key: ListStyles.heatmap.toString(),
iconProps: {
iconName: 'Waffle'
}
}
]
export const configChartStyles: IChoiceGroupOption[] = [
{
text: stringsCommon.lookChartLine,
key: ChartStyles.linechart.toString(),
iconProps: {
iconName: 'LineChart'
}
},
{
text: stringsCommon.lookChartArea,
key: ChartStyles.areachart.toString(),
iconProps: {
iconName: 'AreaChart'
}
},
{
text: stringsCommon.lookChartBar,
key: ChartStyles.barchart.toString(),
iconProps: {
iconName: 'BarChartHorizontal'
}
},
{
text: stringsCommon.lookChartColumn,
key: ChartStyles.columnchart.toString(),
iconProps: {
iconName: 'BarChartVertical'
}
},
{
text: stringsCommon.lookChartPie,
key: ChartStyles.piechart.toString(),
iconProps: {
iconName: 'PieDouble'
}
}
]
export const configChartPalette: IChoiceGroupOption[] = [
{
key: ChartPalette.OfficeColorful1.toString(),
text: stringsCommon.paletteCol1,
imageSrc: String(require('./../assets/OfficeColorful1.png')),
selectedImageSrc: String(require('./../assets/OfficeColorful1.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeColorful2.toString(),
text: stringsCommon.paletteCol2,
imageSrc: String(require('./../assets/OfficeColorful2.png')),
selectedImageSrc: String(require('./../assets/OfficeColorful2.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeColorful3.toString(),
text: stringsCommon.paletteCol3,
imageSrc: String(require('./../assets/OfficeColorful3.png')),
selectedImageSrc: String(require('./../assets/OfficeColorful3.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeColorful4.toString(),
text: stringsCommon.paletteCol4,
imageSrc: String(require('./../assets/OfficeColorful4.png')),
selectedImageSrc: String(require('./../assets/OfficeColorful4.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic1.toString(),
text: stringsCommon.paletteMono1,
imageSrc: String(require('./../assets/OfficeMono1.png')),
selectedImageSrc: String(require('./../assets/OfficeMono1.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic2.toString(),
text: stringsCommon.paletteMono2,
imageSrc: String(require('./../assets/OfficeMono2.png')),
selectedImageSrc: String(require('./../assets/OfficeMono2.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic3.toString(),
text: stringsCommon.paletteMono3,
imageSrc: String(require('./../assets/OfficeMono3.png')),
selectedImageSrc: String(require('./../assets/OfficeMono3.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic4.toString(),
text: stringsCommon.paletteMono4,
imageSrc: String(require('./../assets/OfficeMono4.png')),
selectedImageSrc: String(require('./../assets/OfficeMono4.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic5.toString(),
text: stringsCommon.paletteMono5,
imageSrc: String(require('./../assets/OfficeMono5.png')),
selectedImageSrc: String(require('./../assets/OfficeMono5.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic6.toString(),
text: stringsCommon.paletteMono6,
imageSrc: String(require('./../assets/OfficeMono6.png')),
selectedImageSrc: String(require('./../assets/OfficeMono6.png')),
imageSize: imageSize
},
{
key: ChartPalette.OfficeMonochromatic7.toString(),
text: stringsCommon.paletteMono7,
imageSrc: String(require('./../assets/OfficeMono7.png')),
selectedImageSrc: String(require('./../assets/OfficeMono7.png')),
imageSize: imageSize
}
]

View File

@ -0,0 +1,109 @@
import { IStackItemStyles, mergeStyleSets } from "@fluentui/react";
import { stackStyles } from "./ComponentStyles";
export enum ListStyles {
"list"=1,
"heatmap",
"heatmapCol"
}
export enum ChartStyles {
"linechart"=1,
"areachart",
"barchart",
"columnchart",
"piechart",
}
export enum LayoutStyles {
"SingleColumn"=1,
"DoubleColumn",
"ColumnRightTwoThirds",
"ColumnLeftTwoThirds"
}
export const enum PanelSize {
Small = 1,
Medium = 2,
Large = 3,
XLarge = 4
}
const gridWidth = {
small: 380,
medium: 586,
large: 792
}
export default class DashboardHelper {
private static getSize = (parentWidth: number): PanelSize => {
if (parentWidth <= gridWidth.small) {
return PanelSize.Small;
}
else if (parentWidth > gridWidth.small && parentWidth <= gridWidth.medium) {
return PanelSize.Medium;
}
else if (parentWidth > gridWidth.medium && parentWidth <= gridWidth.large) {
return PanelSize.Large;
}
else {
return PanelSize.XLarge;
}
}
public static GetStackItemStyle = (layoutSettings: LayoutStyles, parentWidth: number): { list: IStackItemStyles, chart: IStackItemStyles } => {
const areaSize = DashboardHelper.getSize(parentWidth);
let stackItemStylesList: IStackItemStyles = {}
let stackItemStylesChart: IStackItemStyles = {}
switch (layoutSettings) {
case LayoutStyles.SingleColumn:
stackItemStylesList = mergeStyleSets(stackStyles.item, stackStyles.item100);
stackItemStylesChart = mergeStyleSets(stackStyles.item, stackStyles.item100);
break;
case LayoutStyles.DoubleColumn:
{
const style = (areaSize === PanelSize.Small)
? stackStyles.item100
: stackStyles.item50;
stackItemStylesList = mergeStyleSets(stackStyles.item, style);
stackItemStylesChart = mergeStyleSets(stackStyles.item, style);
}
break;
case LayoutStyles.ColumnLeftTwoThirds:
{
const styleList = (areaSize === PanelSize.Small || areaSize === PanelSize.Medium)
? stackStyles.item100
: stackStyles.item66;
const styleChart = (areaSize === PanelSize.Small || areaSize === PanelSize.Medium)
? stackStyles.item100
: stackStyles.item33;
stackItemStylesList = mergeStyleSets(stackStyles.item, styleList);
stackItemStylesChart = mergeStyleSets(stackStyles.item, styleChart);
}
break;
case LayoutStyles.ColumnRightTwoThirds:
{
const styleList = (areaSize === PanelSize.Small || areaSize === PanelSize.Medium)
? stackStyles.item100
: stackStyles.item33;
const styleChart = (areaSize === PanelSize.Small || areaSize === PanelSize.Medium)
? stackStyles.item100
: stackStyles.item66;
stackItemStylesList = mergeStyleSets(stackStyles.item, styleList);
stackItemStylesChart = mergeStyleSets(stackStyles.item, styleChart);
}
break;
default:
stackItemStylesList = mergeStyleSets(stackStyles.item, stackStyles.item100);
stackItemStylesChart = mergeStyleSets(stackStyles.item, stackStyles.item100);
break;
}
return {
list: stackItemStylesList,
chart: stackItemStylesChart
};
}
public static GetStackItemStyleFull = (): IStackItemStyles=> {
return mergeStyleSets(stackStyles.item, stackStyles.item100);
}
}

View File

@ -0,0 +1,741 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ICostMngmtResponseJson } from "./ApiHelper";
export default class MockCostMngmtHttpClient{
private static jsonCostByServiceResponse: any = {
"id": "subscriptions/9733fd99-1122-46e0-9482-732c52b24906/providers/Microsoft.CostManagement/query/b5fec646-d757-4038-802e-59409dc845ba",
"name": "b5fec646-d757-4038-802e-59409dc845ba",
"type": "Microsoft.CostManagement/query",
"location": null,
"sku": null,
"eTag": null,
"properties": {
"nextLink": null,
"columns": [
{
"name": "Cost",
"type": "Number"
},
{
"name": "BillingMonth",
"type": "Datetime"
},
{
"name": "ServiceName",
"type": "String"
},
{
"name": "Currency",
"type": "String"
}
],
"rows": [
[
0.000092997,
"2023-03-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-03-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.087794830785556,
"2023-03-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000020633456,
"2023-03-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.005274053900649,
"2023-03-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.015254984412827,
"2023-03-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.061422169469731,
"2023-03-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.006661324854989,
"2023-03-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.007355223968911,
"2023-03-01T00:00:00",
"Storage",
"CHF"
]
]
}
}
private static jsonCostByServiceResponse2Months: any = {
"id": "subscriptions/9733fd99-1122-46e0-9482-732c52b24906/providers/Microsoft.CostManagement/query/c43d6bd5-7820-49d2-95ab-65af865edbe9",
"name": "c43d6bd5-7820-49d2-95ab-65af865edbe9",
"type": "Microsoft.CostManagement/query",
"location": null,
"sku": null,
"eTag": null,
"properties": {
"nextLink": null,
"columns": [
{
"name": "Cost",
"type": "Number"
},
{
"name": "BillingMonth",
"type": "Datetime"
},
{
"name": "ServiceName",
"type": "String"
},
{
"name": "Currency",
"type": "String"
}
],
"rows": [
[
0.00144662,
"2023-04-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-04-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.189942030499408,
"2023-04-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000314895648,
"2023-04-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.00019695375,
"2023-04-01T00:00:00",
"Functions",
"CHF"
],
[
0.0571033866,
"2023-04-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.207743937182644,
"2023-04-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.132635152278146,
"2023-04-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.02803100599,
"2023-04-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.186290417208,
"2023-04-01T00:00:00",
"Storage",
"CHF"
],
[
0.000041332000000000003,
"2023-05-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-05-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.011375349462366,
"2023-05-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.0000042808,
"2023-05-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.0006140784,
"2023-05-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.02179392561248,
"2023-05-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.008128346841146,
"2023-05-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.00171794337,
"2023-05-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.002776281948,
"2023-05-01T00:00:00",
"Storage",
"CHF"
]
]
}
}
private static jsonCostByServiceResponse3Months: any = {
"id": "subscriptions/9733fd99-1122-46e0-9482-732c52b24906/providers/Microsoft.CostManagement/query/7df65308-d6bb-417a-a158-e7b290ccab2e",
"name": "7df65308-d6bb-417a-a158-e7b290ccab2e",
"type": "Microsoft.CostManagement/query",
"location": null,
"sku": null,
"eTag": null,
"properties": {
"nextLink": null,
"columns": [
{
"name": "Cost",
"type": "Number"
},
{
"name": "BillingMonth",
"type": "Datetime"
},
{
"name": "ServiceName",
"type": "String"
},
{
"name": "Currency",
"type": "String"
}
],
"rows": [
[
0.001022967,
"2023-03-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-03-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.19625302311354,
"2023-03-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000143663648,
"2023-03-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.00001773,
"2023-03-01T00:00:00",
"Functions",
"CHF"
],
[
0.013159858079222,
"2023-03-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.048084173706564,
"2023-03-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.1372803378781,
"2023-03-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.014949191881894,
"2023-03-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.050661344537648,
"2023-03-01T00:00:00",
"Storage",
"CHF"
],
[
0.00144662,
"2023-04-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-04-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.189942030499408,
"2023-04-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000314895648,
"2023-04-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.00019695375,
"2023-04-01T00:00:00",
"Functions",
"CHF"
],
[
0.0571033866,
"2023-04-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.207743937182644,
"2023-04-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.132635152278146,
"2023-04-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.028031005990000003,
"2023-04-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.186290417208,
"2023-04-01T00:00:00",
"Storage",
"CHF"
],
[
0.000041332000000000003,
"2023-05-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-05-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.011375349462366,
"2023-05-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.0000042808,
"2023-05-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.0006140784,
"2023-05-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.02179392561248,
"2023-05-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.008128346841146,
"2023-05-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.00171794337,
"2023-05-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.002776281948,
"2023-05-01T00:00:00",
"Storage",
"CHF"
]
]
}
}
private static jsonAzureMonitorCostsResponse3Months: any = {
"id": "subscriptions/9733fd99-1122-46e0-9482-732c52b24906/providers/Microsoft.CostManagement/query/45562f62-7a1d-47c3-9a31-cc3ffe722524",
"name": "45562f62-7a1d-47c3-9a31-cc3ffe722524",
"type": "Microsoft.CostManagement/query",
"location": null,
"sku": null,
"eTag": null,
"properties": {
"nextLink": null,
"columns": [
{
"name": "Cost",
"type": "Number"
},
{
"name": "BillingMonth",
"type": "Datetime"
},
{
"name": "ServiceName",
"type": "String"
},
{
"name": "Currency",
"type": "String"
}
],
"rows": [
[
0.0001394955,
"2023-01-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-01-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.0976166599122,
"2023-01-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000088698176,
"2023-01-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.00000772875,
"2023-01-01T00:00:00",
"Functions",
"CHF"
],
[
0.0087476649,
"2023-01-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.058432889294037,
"2023-01-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.068534767511377,
"2023-01-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.01503025771,
"2023-01-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.071955170944,
"2023-01-01T00:00:00",
"Storage",
"CHF"
],
[
0.0005631485,
"2023-02-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-02-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.08017600546442101,
"2023-02-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000058047648,
"2023-02-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.00002806875,
"2023-02-01T00:00:00",
"Functions",
"CHF"
],
[
0.010254085560388999,
"2023-02-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.032445557445422,
"2023-02-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.061779158062478,
"2023-02-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.00840390849843,
"2023-02-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.035626819870988,
"2023-02-01T00:00:00",
"Storage",
"CHF"
],
[
0.00030999,
"2023-03-01T00:00:00",
"API Management",
"CHF"
],
[
0,
"2023-03-01T00:00:00",
"Azure App Service",
"CHF"
],
[
0.093761336149811,
"2023-03-01T00:00:00",
"Azure Monitor",
"CHF"
],
[
0.000055222319999999996,
"2023-03-01T00:00:00",
"Bandwidth",
"CHF"
],
[
0.000008865,
"2023-03-01T00:00:00",
"Functions",
"CHF"
],
[
0.006207939239611,
"2023-03-01T00:00:00",
"Key Vault",
"CHF"
],
[
0.02013784546086,
"2023-03-01T00:00:00",
"Log Analytics",
"CHF"
],
[
0.065684391022086,
"2023-03-01T00:00:00",
"Logic Apps",
"CHF"
],
[
0.007143397085947,
"2023-03-01T00:00:00",
"Service Bus",
"CHF"
],
[
0.021916624388824,
"2023-03-01T00:00:00",
"Storage",
"CHF"
]
]
}
}
private static jsonAzureMonitorCostsResponse: any = {
"id": "subscriptions/9733fd99-1122-46e0-9482-732c52b24906/providers/Microsoft.CostManagement/query/5eb960c9-2fc7-4650-bc09-8e6c4e8eb13f",
"name": "5eb960c9-2fc7-4650-bc09-8e6c4e8eb13f",
"type": "Microsoft.CostManagement/query",
"location": null,
"sku": null,
"eTag": null,
"properties": {
"nextLink": null,
"columns": [
{
"name": "PreTaxCost",
"type": "Number"
},
{
"name": "BillingMonth",
"type": "Datetime"
},
{
"name": "ServiceName",
"type": "String"
},
{
"name": "TagKey",
"type": "String"
},
{
"name": "TagValue",
"type": "String"
},
{
"name": "Currency",
"type": "String"
}
],
"rows": [
[
0.164214312108748,
"2023-03-01T00:00:00",
"Azure Monitor",
"environment",
"build",
"CHF"
],
[
0.003019580329528,
"2023-03-01T00:00:00",
"Log Analytics",
"environment",
"dev",
"CHF"
],
[
0.025171445441918,
"2023-03-01T00:00:00",
"Log Analytics",
"environment",
"build",
"CHF"
]
]
}
}
public static GetJsonCostByService(): Promise<ICostMngmtResponseJson>{
return new Promise<ICostMngmtResponseJson>((resolve, reject) => {
resolve(MockCostMngmtHttpClient.jsonCostByServiceResponse);
});
}
public static GetJsonCostByService2Mo(): Promise<ICostMngmtResponseJson> {
return new Promise<ICostMngmtResponseJson>((resolve, reject) => {
resolve(MockCostMngmtHttpClient.jsonCostByServiceResponse2Months);
});
}
public static GetJsonCostByService3Mo(): Promise<ICostMngmtResponseJson> {
return new Promise<ICostMngmtResponseJson>((resolve, reject) => {
resolve(MockCostMngmtHttpClient.jsonCostByServiceResponse3Months);
});
}
public static GetJsonAzureMonitorCosts(): Promise<ICostMngmtResponseJson> {
return new Promise<ICostMngmtResponseJson>((resolve, reject) => {
resolve(MockCostMngmtHttpClient.jsonAzureMonitorCostsResponse);
});
}
public static GetJsonAzureMonitorCosts3Mo(): Promise<ICostMngmtResponseJson> {
return new Promise<ICostMngmtResponseJson>((resolve, reject) => {
resolve(MockCostMngmtHttpClient.jsonAzureMonitorCostsResponse3Months);
});
}
}

View File

@ -0,0 +1,105 @@
import { IDropdownOption } from "@fluentui/react";
import stringsCommon from "CommonDasboardWebPartStrings";
import moment from "moment";
const defaultDateFormat: string = "L";
//used for dropdown options in AppInsights TimePicker
enum TimeSpanAppInsights {
"PT1H" = "1 hour",
"PT6H" = "6 hours",
"PT12H" = "12 hours",
"P1D" = "1 day",
"P3D" = "3 days",
"P7D" = "7 days",
"P15D" = "15 days",
"P30D" = "30 days",
"P45D" = "45 days",
"P60D" = "60 days",
"P75D" = "75 days",
"P90D" = "90 days"
}
enum TimeSpanCost {
"MonthToDate" = "This month",//*this is the default
"BillingMonthToDate" = "Current billing period",
"TheLastBillingMonth"="Last invoice",
"TheLastMonth"="Last month",
"WeekToDate"="Last 7 days"
}
enum TimeSpanKusto{
"PT1H" = "1h",
"PT6H" = "6h",
"PT12H" = "12h",
"P1D" = "1d",
"P3D" = "3d",
"P7D" = "7d",
"P15D" = "15d",
"P30D" = "30d",
"P45D" = "45d",
"P60D" = "60d",
"P75D" = "75d",
"P90D" = "90d"
}
interface dateFormat {
datetime: string;
cultureName?: string;
format?: string;
}
export default class TimeHelper {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public static GetTimeOptions<T>(timeSpanOptions: any ): IDropdownOption<any>[] {
const options = Object.keys(timeSpanOptions).map((key) => {
return {
key: key,
text: timeSpanOptions[key as keyof T].toString(),
};
});
options.push({
key: "Custom",
text: stringsCommon.DatePicker_TimeSpanCustom,
});
return options;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public static get AppInsightsTimeOptions (): IDropdownOption<any>[] {
return TimeHelper.GetTimeOptions <TimeSpanAppInsights>(TimeSpanAppInsights);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public static get CostManagementTimeOptions(): IDropdownOption<any>[] {
return TimeHelper.GetTimeOptions<TimeSpanCost>(TimeSpanCost);
}
public static getFormattedDate = ({ datetime, cultureName, format }: dateFormat): string => {
if (cultureName) {
moment.locale(cultureName);
}
return moment(datetime).format(format ? format : defaultDateFormat);
};
public static getFormattedDateTime = ({ datetime, cultureName, format }: dateFormat): string => {
if (cultureName) {
moment.locale(cultureName);
}
return `${moment(datetime).format(format ? format : defaultDateFormat)} ${moment(datetime).format('LT')}`;
};
public static getQueryDateFormat = (datetime: string): string => {
return moment(datetime).format('YYYY-MM-DDT00:00:00.000Z');
}
public static getFirstDayOfWeek = (cultureName: string): number => {
moment.locale(cultureName);
return moment.localeData().firstDayOfWeek() || 0
}
}
export { TimeSpanCost, TimeSpanAppInsights, TimeSpanKusto };

View File

@ -0,0 +1,606 @@
import { ChoiceGroup, Dropdown, IChoiceGroupOption, IconButton, IDropdownOption, ITooltipProps, Label, Pivot, PivotItem, PrimaryButton, Stack, StackItem, TextField, Toggle, TooltipHost } from "@fluentui/react";
import * as stringsAppIns from "AppInsightsDasboardWebPartStrings";
import stringsCommon from "CommonDasboardWebPartStrings";
import * as stringsCost from "CostInsightsWebPartStrings";
import React from "react";
import { QueryPreset } from "../../common/ApiQueryHelper";
import { AppInsightsQueryLogsHelper } from "../../common/AppInsightsQueryHelper";
import { ThemedPalette } from "../../common/ColorsHelper";
import { dashboardStyles, stackTokens } from "../../common/ComponentStyles";
import CostHelper, { CostManagementScope } from "../../common/CostMngmtQueryHelper";
import { useId } from "@fluentui/react-hooks";
import moment from "moment";
import { AppInsightsEndpointType, ConfigType } from "../../common/CommonProps";
import { linkStyles } from "../../common/ComponentStyles";
import CostMngmtQueryHelper from "../../common/CostMngmtQueryHelper";
import { configChartStyles, configLayoutStyles, configListStyles } from "../../common/DashboardConfig";
import { ChartStyles, ListStyles } from "../../common/DashboardHelper";
import TimeHelper, { TimeSpanCost } from "../../common/TimeHelper";
import DatePickerMenu from "../DatePickerMenu/DatePickerMenu";
import SwatchColorPickerThemed from "../SwatchColorPickerThemed/SwatchColorPickerThemed";
import { IDashboardConfigurationAppInsProps } from "./IDashboardConfigurationAppInsProps";
import { IDashboardConfigurationCostProps } from "./IDashboardConfigurationCostProps";
const DashboardConfigurationCost: React.FunctionComponent<IDashboardConfigurationCostProps | IDashboardConfigurationAppInsProps> = (props) => {
//#region State
const tooltipIdApiKey = useId('tooltipIdApiKey');
const tooltipIdApiId = useId('tooltipIdApiId');
//AppInsights
const [showAppInsightsConfig, setShowAppInsightsConfig] = React.useState<boolean>(false);
const [AppId, setAppId] = React.useState<string>(props.appId);
const [AppKey, setAppKey] = React.useState<string>(props.appKey);
const [AppInsightsEndpoint, setAppInsightsEndpoint] = React.useState<string>('');
//CostManagement
const [showCostManagementConfig, setShowCostManagementConfig] = React.useState<boolean>(false);
const [scope, setScope] = React.useState<CostManagementScope>(props.scope);
const [subscriptionId, setSubscriptionId] = React.useState<string>(props.subscriptionId);
const [resourceGroupName, setResourceGroupName] = React.useState<string>(props.resourceGroupName);
const [managementGroupId, setManagementGroupId] = React.useState<string>(props.managementGroupId);
const [apiEndpoint, setApiEndpoint] = React.useState<string>("");
//Pivot
const [selectedTabKey, setSelectedTabKey] = React.useState<string>(props.pivotKey);
const [selectedPresetKey, setSelectedPresetKey] = React.useState<string | number>(props.preset || 100);
//Query
const [presets, setPresets] = React.useState<QueryPreset[]>([]);
const [presetInfo, setPresetInfo] = React.useState<QueryPreset>(null);
const [query, setQuery] = React.useState<string>(props.query);
const [queryLabel, setQueryLabel] = React.useState<string>("");
const [groupNameQuery, setGroupNameQuery] = React.useState<string>("");
const [dateSpan, setDateSpan] = React.useState<string>();
//Layout
const [showList, setShowList] = React.useState<boolean>(props.showList);
const [listStyle, setListStyle] = React.useState<ListStyles>(props.listStyle);
const [listPalette, setListPalette] = React.useState<ThemedPalette>(props.listPalette);
const [showChart, setShowChart] = React.useState<boolean>(props.showChart);
const [chartStyle, setChartStyle] = React.useState<ChartStyles>(props.chartStyle);
const [chartPalette, setChartPalette] = React.useState<ThemedPalette>(props.chartPalette);
const [layoutSettings, setLayoutSettings] = React.useState<number>(props.layoutSettings);
//#endregion
const setDateSpanFromJson = (jsonBody: string): void => {
if (jsonBody) {
const json = JSON.parse(jsonBody);
// userLoginName: props.userLoginName
if (json.timeframe && json.timeframe !== "Custom") {
setDateSpan(json.timeframe);
}
else if (json.timePeriod?.from && json.timePeriod?.to) {
const from = moment.utc(json.timePeriod.from).toDate();
const to = moment.utc(json.timePeriod.to).toDate();
setDateSpan(`${from.getTime()}-${to.getTime()}`);
}
}
else {
setDateSpan("MonthToDate");
}
}
//#region Effects
React.useEffect(() => {
const setUIConfiguration = (configType: ConfigType,
costConfig: {
scope: CostManagementScope,
subscriptionId?: string;
resourceGroupName?: string;
managementGroupId?: string;
},
appConfig: {
appId: string,
}): void => {
if (configType === ConfigType.CostManagement) {
setShowCostManagementConfig(true);
setQueryLabel(stringsCost.CostQueryLabel);
setGroupNameQuery(stringsCost.GroupNameCostQuery);
setApiEndpoint(
CostMngmtQueryHelper.GetAPIEndpoint(costConfig.scope, { subscriptionId: costConfig.subscriptionId, resourceGroupName: costConfig.resourceGroupName, managementGroupId: costConfig.managementGroupId })
);
}
else if (configType === ConfigType.ApplicationInsightsLogs) {
setShowAppInsightsConfig(true)
setQueryLabel(stringsAppIns.KustoQueryLabel);
setGroupNameQuery(stringsAppIns.GroupNameKustoQuery);
setAppInsightsEndpoint(AppInsightsEndpointType.query)
setApiEndpoint(
AppInsightsQueryLogsHelper.GetAPIEndpoint(appConfig.appId, AppInsightsEndpointType.query)
);
}
else if (configType === ConfigType.ApplicationInsightsMetrics) {
setShowAppInsightsConfig(true)
setQueryLabel(stringsAppIns.KustoQueryLabel);
setGroupNameQuery(stringsAppIns.GroupNameKustoQuery);
setAppInsightsEndpoint(AppInsightsEndpointType.metrics)
setApiEndpoint(
AppInsightsQueryLogsHelper.GetAPIEndpoint(appConfig.appId, AppInsightsEndpointType.metrics)
);
}
}
const setQueryConfiguration = (configType: ConfigType, preset: number, query: string): void => {
const getPreset = (configType: ConfigType): QueryPreset[] => {
switch (configType) {
case ConfigType.CostManagement:
return CostHelper.Presets;
case ConfigType.ApplicationInsightsLogs:
return AppInsightsQueryLogsHelper.Presets;
case ConfigType.ApplicationInsightsMetrics:
return [];
}
}
const presets = getPreset(configType);
if (presets.length > 0) {
setPresets(presets)
const querySet = presets.find(p => p.key === Number(preset));
setPresetInfo(querySet);
setQuery(preset === 100
? query
: querySet.query)
if (configType === ConfigType.CostManagement) {
const jsonBody = (preset === 100
? query
: querySet.query);
setDateSpanFromJson(jsonBody)
}
}
}
setUIConfiguration(props.configType,
{ scope: props.scope, subscriptionId: props.subscriptionId, resourceGroupName: props.resourceGroupName, managementGroupId: props.managementGroupId },
{ appId: props.appId }
);
setQueryConfiguration(props.configType, props.preset, props.query);
}, [
props.configType, props.preset, props.query,
props.scope, props.subscriptionId, props.resourceGroupName, props.managementGroupId,
props.appId
]);
React.useEffect(() => {
if (props.dateSelection) {
setDateSpan(props.dateSelection);
}
}, [props.dateSelection]);
//#endregion
//#region Pivot
const _applyChangeTab = (key: string): void => {
setSelectedTabKey(key);
props.onPivotItemChange(key);
}
const _onChangeTab = (item?: PivotItem): void => {
_applyChangeTab(item.props.itemKey)
}
//#endregion
//#region CostManagement Configuration
const _onChangeScope = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
setScope(Number(item.key));
setApiEndpoint(
CostMngmtQueryHelper.GetAPIEndpoint(Number(item.key), { subscriptionId: subscriptionId, managementGroupId: managementGroupId, resourceGroupName: resourceGroupName })
);
}
const _onChangeSubscriptionId = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setSubscriptionId(newValue.trim());
setApiEndpoint(
CostMngmtQueryHelper.GetAPIEndpoint(scope, { subscriptionId: newValue.trim() })
);
}
const _onChangeResourceGroupName = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setResourceGroupName(newValue.trim());
setApiEndpoint(
CostMngmtQueryHelper.GetAPIEndpoint(scope, { subscriptionId: subscriptionId, resourceGroupName: newValue.trim() })
);
}
const _onChangeManagementGroupId = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setManagementGroupId(newValue.trim());
setApiEndpoint(
CostMngmtQueryHelper.GetAPIEndpoint(scope, { managementGroupId: newValue.trim() })
);
}
const _applyCostManagementConfiguration = (): void => {
const config = {
scope: scope,
subscriptionId: subscriptionId,
resourceGroupName: resourceGroupName,
managementGroupId: managementGroupId
}
props.onConfigureCostManagementScope(config);
}
//#endregion
//#region ApplicationInsights Configuration
const _onChangeAppId = (ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setAppId(newValue.trim());
setApiEndpoint(
AppInsightsQueryLogsHelper.GetAPIEndpoint(newValue.trim(), AppInsightsEndpoint)
)
}
const _onChangeAppKey = (ev: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setAppKey(newValue.trim());
}
const _applyAppInsightsConfiguration = (): void => {
props.onConfigureAppInsights(AppId, AppKey); //save to WP properties
}
//#region Tooltips
const tooltipPropsAppId: ITooltipProps = {
onRenderContent: () => (
<div dangerouslySetInnerHTML={{ __html: stringsAppIns.HelpAppInsightsAppId }} />
),
};
const tooltipPropsAppKey: ITooltipProps = {
onRenderContent: () => (
<div dangerouslySetInnerHTML={{ __html: stringsAppIns.HelpAppInsightsAppKey }} />
),
};
//#endregion
//#endregion
//#region Query Configuration
const _onChangePreset = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
setSelectedPresetKey(item.key);
const querySet = presets.find(p => p.key === Number(item.key));
setPresetInfo(querySet);
setQuery(querySet.query);
if (props.configType === ConfigType.CostManagement) {
// setDateSpanFromJson(querySet.query)
setDateSpan("MonthToDate");
}
};
const _onDateSelectedCostManagement = (timeSpan: string): void => {
if (Object.keys(TimeSpanCost).includes(timeSpan)) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { type, timeframe, timePeriod, ...rest } = JSON.parse(query); //remove "timePeriod" property from json
const json = {
type,
timeframe: timeSpan,
...rest
}
setQuery(JSON.stringify(json, null, 2));
}
else {
const dates = timeSpan.split('-');
if (dates.length === 2) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { type, timeframe, timePeriod, ...rest } = JSON.parse(query); //remove "timeframe" property from json
const json = {
type,
timeframe: "Custom",
timePeriod: {
"from": moment.utc(Number(dates[0])).format('YYYY-MM-DDTHH:mm:ss+00:00'),
"to": moment.utc(Number(dates[1])).format('YYYY-MM-DDTHH:mm:ss+00:00')
},
...rest
}
setQuery(JSON.stringify(json, null, 2));
}
}
setDateSpan(timeSpan);
}
const _onDateSelectedAppInsights = (timeSpan: string): void => {
setDateSpan(timeSpan)
}
const _onChangeQueryAppInsights = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setQuery(newValue || '');
};
const _onChangeQueryCostManagement = (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string): void => {
setQuery(newValue || '');
if(newValue!==""){
setDateSpanFromJson(newValue)
}
}
const _applyQueryConfiguration = (): void => {
if (query === presetInfo.query) {
props.onConfigureQuery(presetInfo.key,
{
query: query,
dateSelection: dateSpan,
})
}
else {
props.onConfigureQuery(100,
{
query: query,
dateSelection: dateSpan,
})
}
}
//#endregion
//#region Layouts
const _onChangeShowList = (event: React.MouseEvent<HTMLElement>, checked?: boolean): void => {
setShowList(checked);
props.onConfigureListSettings(checked, listStyle, listPalette);
}
const _onChangeShowChart = (event: React.MouseEvent<HTMLElement>, checked?: boolean): void => {
setShowChart(checked);
props.onConfigureChartSettings(checked, chartStyle, chartPalette);
}
const _onChangeLayoutSettings = (event?: React.FormEvent<HTMLInputElement | HTMLElement>, option?: IChoiceGroupOption): void => {
setLayoutSettings(Number(option.key));
props.onConfigureLayoutSettings(Number(option.key));
}
//#endregion
//#region List Configuration
const _onChangeListStyle = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption): void => {
setListStyle(Number(option.key));
props.onConfigureListSettings(showList, Number(option.key), listPalette);
}
const _onChangeListPalette = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption): void => {
setListPalette(Number(option.key));
props.onConfigureListSettings(showList, listStyle, Number(option.key));
}
//#endregion
//#region Chart Configuration
const _onChangeChartStyle = (event?: React.FormEvent<HTMLInputElement | HTMLElement>, option?: IChoiceGroupOption): void => {
setChartStyle(Number(option.key));
props.onConfigureChartSettings(showChart, Number(option.key), chartPalette);
}
const _onChangeChartPalette = (event?: React.FormEvent<HTMLInputElement | HTMLElement>, option?: IChoiceGroupOption): void => {
setChartPalette(Number(option.key));
props.onConfigureChartSettings(showChart, chartStyle, Number(option.key));
}
//#endregion
return <>
<Pivot aria-label="Configuration" selectedKey={selectedTabKey} onLinkClick={_onChangeTab} styles={dashboardStyles.pivot} >
<PivotItem
headerText={stringsCommon.GroupNameConnection}
itemIcon="PlugConnected"
itemKey="0"
>
{showCostManagementConfig &&
<Stack tokens={stackTokens}>
<Dropdown
label={stringsCost.ScopeLabel}
selectedKey={scope}
options={CostHelper.Scopes}
onChange={_onChangeScope}
/>
{(scope === CostManagementScope.Subscription || scope === CostManagementScope.ResourceGroup) &&
<TextField
label={stringsCost.SubIdLabel}
value={subscriptionId}
hidden={scope !== CostManagementScope.Subscription}
required={scope !== CostManagementScope.Subscription}
onChange={_onChangeSubscriptionId}
/>
}
{scope === CostManagementScope.ResourceGroup &&
<TextField
label={stringsCost.ResourceGroupLabel}
value={resourceGroupName}
hidden={scope !== CostManagementScope.ResourceGroup}
required={scope === CostManagementScope.ResourceGroup}
onChange={_onChangeResourceGroupName}
/>
}
{scope === CostManagementScope.ManagementGroup &&
<TextField
label={stringsCost.ManagementGroupLabel}
value={managementGroupId}
hidden={scope !== CostManagementScope.ManagementGroup}
required={scope === CostManagementScope.ManagementGroup}
onChange={_onChangeManagementGroupId}
/>
}
<Label styles={linkStyles}>{apiEndpoint}</Label>
<PrimaryButton
text={stringsCommon.ApplyBtnLabel}
onClick={_applyCostManagementConfiguration}
styles={dashboardStyles.applyBtn} />
</Stack>
}
{showAppInsightsConfig &&
<Stack tokens={stackTokens}>
<Stack horizontal tokens={stackTokens}>
<Label required>{stringsAppIns.AppIdLabel}</Label>
<TooltipHost
tooltipProps={tooltipPropsAppId}
id={tooltipIdApiId}
>
<IconButton iconProps={dashboardStyles.helpIcon} aria-describedby={tooltipIdApiId} />
</TooltipHost>
</Stack>
<TextField
value={AppId}
onChange={_onChangeAppId}
/>
{props.isDevMode &&
<>
<Stack horizontal tokens={stackTokens}>
<Label required>{stringsAppIns.AppKeyLabel}</Label>
<TooltipHost
tooltipProps={tooltipPropsAppKey}
id={tooltipIdApiKey}
>
<IconButton iconProps={dashboardStyles.helpIcon} aria-describedby={tooltipIdApiKey} />
</TooltipHost>
</Stack>
<TextField
value={AppKey}
onChange={_onChangeAppKey}
type="password"
canRevealPassword
/>
</>
}
<Label styles={linkStyles}>{apiEndpoint}</Label>
<PrimaryButton
text={stringsCommon.ApplyBtnLabel}
onClick={_applyAppInsightsConfiguration}
styles={dashboardStyles.applyBtn} />
</Stack>
}
</PivotItem>
{/* Query */}
<PivotItem
headerText={groupNameQuery}
itemIcon="AnalyticsQuery" //CodeEdit
itemKey="1"
>
<Stack tokens={stackTokens} >
<Dropdown
label={queryLabel}
selectedKey={selectedPresetKey}
options={presets}
onChange={_onChangePreset}
/>
{showCostManagementConfig &&
<>
<DatePickerMenu
onDateSelected={_onDateSelectedCostManagement}
timeSpanMenus={TimeHelper.CostManagementTimeOptions}
cultureName={props.cultureName}
initialValue={dateSpan} />
<TextField
label={presetInfo?.description ?? ''}
key={presetInfo?.key}
value={query}
onChange={_onChangeQueryCostManagement}
multiline={true}
autoAdjustHeight
spellCheck={false}
/>
</>
}
{showAppInsightsConfig &&
<>
<DatePickerMenu
onDateSelected={_onDateSelectedAppInsights}
timeSpanMenus={TimeHelper.AppInsightsTimeOptions}
cultureName={props.cultureName}
initialValue={dateSpan} />
<TextField
label={presetInfo?.description ?? ''}
key={presetInfo?.key}
value={query}
onChange={_onChangeQueryAppInsights}
multiline={true}
autoAdjustHeight
spellCheck={false}
/>
</>
}
<Label styles={linkStyles}>{apiEndpoint}</Label>
<PrimaryButton
text={stringsCommon.ApplyBtnLabel}
onClick={_applyQueryConfiguration}
disabled={!query}
styles={dashboardStyles.applyBtn}
/>
</Stack>
</PivotItem>
{/* Layout */}
<PivotItem
headerText={stringsCommon.GroupNameLook}
itemIcon="DoubleColumnEdit"
itemKey="2"
>
<Stack >
<Toggle
label={stringsCommon.LookShowList}
inlineLabel
checked={showList}
onChange={_onChangeShowList}
/>
<Toggle
label={stringsCommon.LookShowChart}
inlineLabel
checked={showChart}
onChange={_onChangeShowChart}
/>
<StackItem hidden={!showList || !showChart}>
<ChoiceGroup
label={stringsCommon.LookLayout}
options={configLayoutStyles}
selectedKey={layoutSettings.toString()}
onChange={_onChangeLayoutSettings}
/>
</StackItem>
</Stack>
</PivotItem>
{/* List */}
<PivotItem
headerText={stringsCommon.GroupNameLookList}
itemIcon="NumberedListText"
itemKey="3"
>
<Stack>
<ChoiceGroup
label={stringsCommon.LookListStyle}
options={configListStyles}
selectedKey={listStyle.toString()}
onChange={_onChangeListStyle}
/>
{listStyle === ListStyles.heatmap &&
<SwatchColorPickerThemed
themePalette={listPalette.toString()}
onChangeColorPalette={_onChangeListPalette}
configThemePalette={[
ThemedPalette.ThemeMonochromatic,
ThemedPalette.AccentYellow,
ThemedPalette.AccentOrange,
ThemedPalette.AccentRed,
ThemedPalette.AccentMagenta,
ThemedPalette.AccentPurple,
ThemedPalette.AccentBlue,
ThemedPalette.AccentTeal,
ThemedPalette.AccentGreen,
]}
/>
}
</Stack>
</PivotItem>
{/* Chart */}
<PivotItem
headerText={stringsCommon.GroupNameLookChart}
itemIcon="BarChart4"
itemKey="4"
>
<ChoiceGroup
label={stringsCommon.LookChartStyle}
options={configChartStyles}
selectedKey={chartStyle.toString()}
onChange={_onChangeChartStyle}
/>
<SwatchColorPickerThemed
themePalette={chartPalette.toString()}
onChangeColorPalette={_onChangeChartPalette}
configThemePalette={[
ThemedPalette.ThemeAccents,
ThemedPalette.ThemeMonochromatic,
ThemedPalette.AccentYellow,
ThemedPalette.AccentOrange,
ThemedPalette.AccentRed,
ThemedPalette.AccentMagenta,
ThemedPalette.AccentPurple,
ThemedPalette.AccentBlue,
ThemedPalette.AccentTeal,
ThemedPalette.AccentGreen,
]}
/>
</PivotItem>
</Pivot>
</>
}
export default DashboardConfigurationCost;

View File

@ -0,0 +1,24 @@
import { ThemedPalette } from "../../common/ColorsHelper";
import { ConfigType, IAppInsightsQuery, IAppInsightsWebPartProps } from "../../common/CommonProps";
import { ChartStyles, LayoutStyles, ListStyles } from "../../common/DashboardHelper";
export interface IDashboardConfigurationAppInsProps extends IAppInsightsWebPartProps {
configType: ConfigType, // ApplicationInsights,CostManagement
//CostManagement props
scope?: never,
subscriptionId?: never,
resourceGroupName?: never,
managementGroupId?: never
endpointType?: never;
onConfigureCostManagementScope? : never;
width:number;
cultureName: string;
onPivotItemChange: (key: string) => void;
onConfigureAppInsights: (appId: string, appKey: string) => void;
onConfigureQuery: (preset: number, config: IAppInsightsQuery) => void;
onConfigureListSettings: (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette) => void;
onConfigureChartSettings: (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette) => void,
onConfigureLayoutSettings: (lookLayout: LayoutStyles) => void;
}

View File

@ -0,0 +1,23 @@
import { ThemedPalette } from "../../common/ColorsHelper";
import { ConfigType, ICostManagementConfig, ICostManagementQuery, ICostManagementWebPartProps } from "../../common/CommonProps";
import { ChartStyles, LayoutStyles, ListStyles } from "../../common/DashboardHelper";
export interface IDashboardConfigurationCostProps extends ICostManagementWebPartProps {
configType: ConfigType,
isDevMode?: never;
appId?: never;
appKey?: never;
// dateSelection?: never;
onConfigureAppInsights?: never;
width:number;
cultureName: string;
onConfigureCostManagementScope: (config: ICostManagementConfig) => void;
onConfigureQuery: (preset: number, config: ICostManagementQuery) => void;
onPivotItemChange: (key: string) => void;
onConfigureListSettings: (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette) => void;
onConfigureChartSettings: (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette) => void,
onConfigureLayoutSettings: (lookLayout: LayoutStyles) => void;
}

View File

@ -0,0 +1,53 @@
@import '~@fluentui/react/dist/sass/References.scss';
.datePickerCallout {
max-width: 500px;
padding: 20px 24px;
div[class^="dateTimePicker_"] {
>div[class^="container_"] {
flex-direction: row;
>div {
margin-top: 0px !important;
}
div[class^="labelCell_"] {
min-width: 5px;
}
div[class^="time_"] {
width: 150px;
}
}
}
}
.datePickerRow,
.datePickerDropDown {
display: flex;
padding: 2px 0px;
margin: 0px;
>div:first-child {
min-width: 150px;
i {
padding-top: 2px;
padding-right: 0px;
}
}
span,
div {
line-height: 23px;
height: 25px;
}
}
div[role="gridcell"]:has(> .heatmapCell) {
padding:0;
>.heatmapCell{
padding: 8px 12px;
}
}

View File

@ -0,0 +1,110 @@
import { addDays, Callout, DayOfWeek, DefaultButton, defaultDatePickerStrings, MessageBar, MessageBarType, PrimaryButton, Stack } from "@fluentui/react";
import { DateConvention, DateTimePicker, TimeConvention } from '@pnp/spfx-controls-react/';
import stringsCommon from "CommonDasboardWebPartStrings";
import moment from "moment";
import React from "react";
import { stackTokens } from "../../common/ComponentStyles";
import TimeHelper from "../../common/TimeHelper";
import styles from "./CommonControl.module.scss";
export interface IDatePickerCalloutProps {
dropDownId: string;
cultureName: string;
onDateSelected: (startDateTime: Date, endDateTime: Date) => void;
onCancel: () => void;
}
const today: Date = new Date(Date.now());
const startMaxDate: Date = addDays(today, -1); // moment(startDateTime).startOf('day').toDate().toUTCString(),
const minDate: Date = addDays(today, -90);
const DatePickerCallout: React.FunctionComponent<IDatePickerCalloutProps> = (props) => {
const firstDayOfWeek: DayOfWeek = TimeHelper.getFirstDayOfWeek(props.cultureName);
const [startDateTime, setStartDateTime] = React.useState<Date>(moment(startMaxDate).startOf('day').toDate());
const [endDateTime, setEndDateTime] = React.useState<Date>(moment(today).endOf('day').toDate());
const [isDateSpanErr, setDateSpanErr] = React.useState<boolean>(false);
React.useEffect((): void => {
if (startDateTime !== null && endDateTime !== null) {
if (startDateTime >= endDateTime) {
setDateSpanErr(true);
}
else {
setDateSpanErr(false);
}
}
}, [startDateTime, endDateTime]);
const handleStartChange = (dateTime: Date): void => {
setStartDateTime(dateTime);
}
const handleEndChange = (dateTime: Date): void => {
setEndDateTime(dateTime);
}
const handleButtonSave=():void=>{
props.onDateSelected(startDateTime, endDateTime);
}
return <Callout
target={`#${props.dropDownId}`}
className={styles.datePickerCallout}
>
<Stack tokens={stackTokens} >
{isDateSpanErr &&
<MessageBar messageBarType={MessageBarType.error}>{stringsCommon.DatePicker_Error}</MessageBar>
}
<DateTimePicker
label={stringsCommon.DatePicker_StartDate}
dateConvention={DateConvention.DateTime}
timeConvention={TimeConvention.Hours24}
firstDayOfWeek={firstDayOfWeek}
minDate={minDate}
maxDate={startMaxDate}
value={startDateTime}
allowTextInput={true}
formatDate={(date?: Date) => {
return TimeHelper.getFormattedDate({
datetime: date.toUTCString(),
cultureName: props.cultureName,
});
}}
onChange={handleStartChange}
strings={{ ...defaultDatePickerStrings, timeSeparator: ':' }}
/>
<DateTimePicker
label={stringsCommon.DatePicker_EndDate}
dateConvention={DateConvention.DateTime}
timeConvention={TimeConvention.Hours24}
firstDayOfWeek={firstDayOfWeek}
minDate={minDate}
maxDate={today}
value={endDateTime}
allowTextInput={true}
formatDate={(date?: Date) => {
return TimeHelper.getFormattedDate({
datetime: date.toUTCString(),
cultureName: props.cultureName,
});
}}
onChange={handleEndChange}
strings={{ ...defaultDatePickerStrings, timeSeparator: ':' }}
/>
<Stack className={styles.datePickerRow} horizontal={true} tokens={stackTokens} horizontalAlign="end">
<PrimaryButton
text={stringsCommon.DatePicker_BtnSave}
disabled={isDateSpanErr}
onClick={handleButtonSave}
/>
<DefaultButton
text={stringsCommon.DatePicker_BtnCancel}
onClick={props.onCancel}
/>
</Stack>
</Stack>
</Callout>
}
export default DatePickerCallout;

View File

@ -0,0 +1,115 @@
import { Dropdown, IDropdownOption, Stack, Text } from "@fluentui/react";
import { useId } from "@fluentui/react-hooks";
import stringsCommon from "CommonDasboardWebPartStrings";
import * as React from "react";
import { datePickerStyles, stackTokens } from "../../common/ComponentStyles";
import TimeHelper from "../../common/TimeHelper";
import styles from "./CommonControl.module.scss";
import DatePickerCallout from "./DatePickerCallout";
import { IDatePickerMenuProps } from "./IDatePickerMenuProps";
const DatePickerMenu: React.FunctionComponent<IDatePickerMenuProps> = (props) => {
const dropDownId = useId("callout-button");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [timespanMenus, setTimeSpanMenus] = React.useState<IDropdownOption<any>[]>(props.timeSpanMenus);
const [selTimeSpan, setSelTimeSpan] = React.useState<string>("");
const [prevTimeSpan, setPrevTimeSpan] = React.useState<string>("");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _getDateSpanOption = (startDateTime: Date, endDateTime: Date, key: string): IDropdownOption<any> => {
const start = TimeHelper.getFormattedDateTime({
datetime: startDateTime.toUTCString(),
cultureName: props.cultureName,
});
const end = TimeHelper.getFormattedDateTime({
datetime: endDateTime.toUTCString(),
cultureName: props.cultureName,
});
return {
text: `${start} - ${end}`,
key: key
};
}
React.useEffect((): void => {
if (props.initialValue) {
const tsMenus = timespanMenus;
const initDateSpanKey = tsMenus.find(o => o.key === props.initialValue);
if (initDateSpanKey !== undefined) {
setSelTimeSpan(props.initialValue);
}
else {
const dates = props.initialValue.split('-');
if (dates.length === 2) {
const tsMenusOption = _getDateSpanOption(
new Date(Number(dates[0])),
new Date(Number(dates[1])),
props.initialValue);
tsMenus.push(tsMenusOption);
setTimeSpanMenus(tsMenus);
setSelTimeSpan(props.initialValue);
}
}
}
}, [props.initialValue]);
const _onDateSelected = (startDateTime: Date, endDateTime: Date): void => {
//startDateTime, endDateTime = local time
const newTimeSpanKey = `${startDateTime.getTime()}-${endDateTime.getTime()}`;
if (timespanMenus.find(o => o.key === newTimeSpanKey) === undefined) {
const tsMenusOption = _getDateSpanOption(startDateTime, endDateTime, newTimeSpanKey);
timespanMenus.push(tsMenusOption);
setTimeSpanMenus(timespanMenus);
}
setSelTimeSpan(newTimeSpanKey);
props.onDateSelected(newTimeSpanKey);
}
const _onDateCancelled = (): void => {
setSelTimeSpan(prevTimeSpan);
props.onDateSelected(prevTimeSpan);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleTimeSpanMenuClick = (event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption<any>, index?: number): void => {
const selectedKey = option.key.toString();
if (selectedKey === "Custom"){
setPrevTimeSpan(selTimeSpan);
setSelTimeSpan(selectedKey);
}
else{
setSelTimeSpan(selectedKey);
props.onDateSelected(selectedKey);
}
};
return (
<Stack
horizontal={true}
styles={datePickerStyles.stack}
tokens={stackTokens}
>
<Text styles={datePickerStyles.text}>{stringsCommon.DatePicker_TimeSpan}</Text>
<Dropdown
id={dropDownId}
className={styles.datePickerDropDown}
dropdownWidth="auto"
options={timespanMenus}
selectedKey={selTimeSpan}
onChange={handleTimeSpanMenuClick}
/>
{selTimeSpan === "Custom"
&& <DatePickerCallout
dropDownId={dropDownId}
cultureName={props.cultureName}
onDateSelected={_onDateSelected}
onCancel={_onDateCancelled}
/>
}
</Stack>
);
};
export default DatePickerMenu;

View File

@ -0,0 +1,8 @@
import { IDropdownOption } from "@fluentui/react";
export interface IDatePickerMenuProps {
onDateSelected: (dateSelection: string) => void;
timeSpanMenus: IDropdownOption[];
initialValue: string;
cultureName: string;
}

View File

@ -0,0 +1,8 @@
div[role="gridcell"]:has(> .heatmapCell) {
padding:0;
>.heatmapCell{
padding: 8px 12px;
}
}

View File

@ -0,0 +1,160 @@
import { DetailsListLayoutMode, FontWeights, IColumn, SelectionMode, ShimmeredDetailsList } from "@fluentui/react";
import { cloneDeep } from "@microsoft/sp-lodash-subset";
import * as React from 'react';
import ApiHelper from "../../common/ApiHelper";
import ColorsHelper, { ThemedPalette } from "../../common/ColorsHelper";
import { getColorRGBA, heatmapStyles } from "../../common/ComponentStyles";
import styles from "./Heatmap.module.scss";
import { IHeatmapDetailsListProps } from "./IHeatmapDetailsListProps";
interface DataRange {
min: number,
max: number
}
const HeatmapDetailsList: React.FunctionComponent<IHeatmapDetailsListProps> = (props) => {
//#region State
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [items, setItems] = React.useState<any[]>(null);
const [listCols, setListCols] = React.useState<IColumn[]>([]);
const [firstColKey, setFirstColKey] = React.useState<string>();
const [firstColHeader, setFirstColHeader] = React.useState<boolean>();
//#endregion
//#region methods
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _renderNumericalItemColumn = (item: any, index: number, column: IColumn, dataRange: DataRange, colorBckg: string): JSX.Element => {
const isHeaderCol = (firstColHeader && firstColKey === column.key);
const fieldContent = item[column.key];
//calculate color opacity for heatmap cell background
const opacity = ((fieldContent - dataRange.min) / (dataRange.max - dataRange.min)).toFixed(4);
const cellCol = getColorRGBA(colorBckg, opacity)
const txtColor= ColorsHelper.GetContrastColor(cellCol);
return <div
className={styles.heatmapCell}
style={isHeaderCol
? { fontWeight: FontWeights.bold }
: { backgroundColor: cellCol, color: txtColor }}
>{fieldContent!== 0 && fieldContent < 0.001
? "<0.001"
: Number(fieldContent.toFixed(3))
}</div>;
}
const _shouldSkipFirstCol = (dataTypes: Map<string, string>): boolean => {
return ApiHelper.GetColByType(dataTypes, "string").length > 0
}
const _getColumns = (columns: IColumn[], numericalCols: string[], width: number, dataRange: DataRange, colorBckg: string): IColumn[] => {
if (columns.length > 0) {
const heatmapCols = cloneDeep(columns);
const colWidth = (width) / heatmapCols.length;
const minWidth = colWidth - 20; //padding
heatmapCols.forEach((column: IColumn) => {
column.minWidth = minWidth;
column.maxWidth = colWidth;
});
//Set rendering for numerical columns ONLY
const numericCols = heatmapCols.filter((col) => {
return numericalCols.includes(col.key);
});
numericCols.forEach((column: IColumn) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
column.onRender = (item: any, index: number, column: IColumn) => {
return _renderNumericalItemColumn(item, index, column, dataRange, colorBckg)
}
});
return heatmapCols;
}
else {
return columns;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _getMinMaxNumber = (items: any[], dataTypes: Map<string, string>, skipFirstCol: boolean): DataRange => {
if (items.length > 0 && dataTypes.size > 0) {
const columnsNumber = ApiHelper.GetColByTypes(dataTypes, ApiHelper.NumericTypes);
const props = (skipFirstCol && Object.keys(dataTypes)[0] === columnsNumber[0])
? columnsNumber.slice(1)
: columnsNumber;
if (props.length > 0) {
const min = items.reduce(function (min, curRow) {
const rMmin = props.reduce(function (max, prop) {
return curRow[prop] < min ? curRow[prop] : max;
}, curRow[props[0]]);
return rMmin < min ? rMmin : min;
}, items[0][props[0]]);
const max = items.reduce(function (max, curRow) {
const rMax = props.reduce(function (max, prop) {
return curRow[prop] > max ? curRow[prop] : max;
}, curRow[props[0]]);
return rMax > max ? rMax : max;
}, items[0][props[0]]);
return {
min: Number(min.toFixed(4)),
max: Number(max.toFixed(4))
}
}
}
return null;
}
const _getFirstColKey = (columns: IColumn[], skipFirstCol: boolean): string => {
return (columns.length > 0)
? skipFirstCol ? columns[0].key : ''
: '';
}
//#endregion
//#region Effects
React.useEffect((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setHeatmapConfiguration = (items: any[], columns: IColumn[], dataTypes: Map<string, string>, listPalette: ThemedPalette): void => {
if (items && columns && dataTypes) {
try {
const skipFirstCol = _shouldSkipFirstCol(dataTypes);
const dataRange = _getMinMaxNumber(items, dataTypes, skipFirstCol);
const color = ColorsHelper.GetThemeMonochromaticColors(listPalette as ThemedPalette, 2).Colors[0]; //can't use 1 becasue PaletteGenerator divides by 0
const numericalCols = ApiHelper.GetColByTypes(dataTypes, ApiHelper.NumericTypes);
setFirstColHeader(skipFirstCol);
setListCols(
_getColumns(columns, numericalCols, heatmapStyles.minWidth, dataRange, color)
);
setFirstColKey(
_getFirstColKey(columns, skipFirstCol)
)
setItems(items);
}
catch (err) {
console.log(err);
}
}
}
setHeatmapConfiguration(props.items, props.columns, props.dataTypes, props.listPalette)
}, [props.items, props.columns, props.dataTypes, props.listPalette]);
//#endregion
return (
<ShimmeredDetailsList
enableShimmer={!items}
items={items || []}
columns={listCols}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
compact={true}
/>
)
}
export default HeatmapDetailsList;

View File

@ -0,0 +1,11 @@
import { IColumn } from "@fluentui/react";
import { ThemedPalette } from "../../common/ColorsHelper";
export interface IHeatmapDetailsListProps {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
items: any[];
columns: IColumn[];
dataTypes: Map<string, string>;
listPalette: ThemedPalette;
showTotalColumnName?:string;
}

View File

@ -0,0 +1,25 @@
import { TimeUnit } from "chart.js";
import { ThemedPalette } from "../../common/ColorsHelper";
import { ChartStyles } from "../../common/DashboardHelper";
export interface IInsightsChartProps {
chartType?: ChartStyles;
chartPalette: ThemedPalette;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
items: any[];
dataTypes: Map<string, string>;
}
export interface DataTypesInfo extends ColumnsInfo {
isStacked: boolean;
hasTimeAxis: boolean;
isSupported: boolean;
timeGranularity: TimeUnit;
errorMsg?:string;
}
export interface ColumnsInfo {
colNumber: string[];
colDateTime: string[];
colString: string[];
}

View File

@ -0,0 +1,3 @@
.chart {
background-color: transparent !important;
}

View File

@ -0,0 +1,105 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MessageBar, MessageBarType, ThemeProvider } from "@fluentui/react";
import { ChartControl, ChartType } from "@pnp/spfx-controls-react";
import { ChartData, ChartOptions, TimeUnit } from "chart.js";
import stringsCommon from "CommonDasboardWebPartStrings";
import React from "react";
import ChartHelper from "../../common/ChartHelper";
import { ThemedPalette } from "../../common/ColorsHelper";
import { chartTheme } from "../../common/ComponentStyles";
import { ChartStyles } from "../../common/DashboardHelper";
import { ColumnsInfo, IInsightsChartProps } from "./IInsightsChartProps";
import styles from "./InsightsChart.module.scss";
const InsightsChart: React.FunctionComponent<IInsightsChartProps> = (props) => {
const [timetamp, setTimetamp] = React.useState(Date.now());
const [items, setItems] = React.useState<any[]>(props.items);
const [hasTimeAxis, setHasTimeAxis] = React.useState<boolean>(false);
const [timeGranularity, setTimeGranularity] = React.useState<TimeUnit>();
const [isHorizontal, setIsHorizontal] = React.useState<boolean>(false);
const [isStacked, setIsStacked] = React.useState<boolean>(false);
const [columnsInfo, setColumnsInfo] = React.useState<ColumnsInfo>(null);
const [chartType, setChartType] = React.useState<ChartType>();
const [chartData, setChartData] = React.useState<ChartData>(null);
const [chartOptions, setChartOptions] = React.useState<ChartOptions>(null);
const [chartPalette, setChartPalette] = React.useState<ThemedPalette>(null);
const [fillChart, setFillChart] = React.useState<boolean>(false);
const [messageBarTxt, setMessageBarTxt] = React.useState<string>("");
const [messageBarType, setMessageBarType] = React.useState<MessageBarType>(MessageBarType.info);
React.useEffect((): void => {
setItems([])
setMessageBarTxt("");
setChartPalette(props.chartPalette);
if (props.dataTypes && props.items.length > 0) {
const dataTypesInfo = ChartHelper.GetDataInfo(props.items, props.dataTypes, props.chartType);
//is supported? at least one numerical column
if (!dataTypesInfo.isSupported) {
setMessageBarTxt(`${stringsCommon.Msg_FailedVisErr} ${dataTypesInfo.errorMsg}`)
setMessageBarType(MessageBarType.warning);
setChartData(null);
setChartOptions(null);
}
else {
setColumnsInfo(dataTypesInfo as ColumnsInfo);
setHasTimeAxis(dataTypesInfo.hasTimeAxis);
setTimeGranularity(dataTypesInfo.timeGranularity)
setIsStacked(dataTypesInfo.isStacked);
setChartType(
ChartHelper.GetChartType(props.chartType)
);
setFillChart(
props.chartType === ChartStyles.linechart
? false
: true);
setIsHorizontal(
props.chartType === ChartStyles.barchart
? true
: false
)
setItems(props.items)
}
}
}, [props.dataTypes, props.chartType, props.chartPalette, props.items]);
//Set Chart Data
React.useEffect((): void => {
if (items?.length > 0 && columnsInfo) {
const data = ChartHelper.GetChartData(items, hasTimeAxis, isHorizontal, columnsInfo, chartType, fillChart, chartPalette);
setChartData(data);
const chartOptions = ChartHelper.GetChartOptions(chartType, hasTimeAxis, timeGranularity, isStacked || data.datasets.length>1);
setChartOptions(chartOptions);
//refresh chart
setTimetamp(Date.now());
}
}, [items, hasTimeAxis, timeGranularity, isHorizontal, isStacked, columnsInfo, chartType, fillChart]);
return (
<ThemeProvider theme={chartTheme} >
{messageBarTxt &&
<MessageBar messageBarType={messageBarType} >{messageBarTxt}</MessageBar>
}
{chartType && chartData && chartOptions &&
<ChartControl
key={timetamp}
type={chartType}
data={chartData}
options={chartOptions}
useTheme={true}
className={styles.chart}
/>
}
</ThemeProvider>
)
}
export default InsightsChart;

View File

@ -0,0 +1,10 @@
import AppInsightsHelper, { AppInsightsHelperSSO } from "../../common/AppInsightsHelper";
import { CacheExpiration, IDashboardContextProps, ILayoutConfig } from "../../common/CommonProps";
import CostManagementHelper from "../../common/CostMngmtHelper";
export interface IInsightsDashboardProps extends ILayoutConfig, IDashboardContextProps {
helper: AppInsightsHelper | AppInsightsHelperSSO | CostManagementHelper ;
query: string;
cacheExpiration: CacheExpiration;
dateSpan?: string;
}

View File

@ -0,0 +1,188 @@
import { buildColumns, IColumn, IStackItemStyles, MessageBar, MessageBarType, SelectionMode, Shimmer, ShimmeredDetailsList, Stack, StackItem, ThemeProvider } from '@fluentui/react';
import stringsCommon from 'CommonDasboardWebPartStrings';
import * as React from 'react';
import ApiHelper, { IResponseJson } from '../../common/ApiHelper';
import AppInsightsHelper, { AppInsightsHelperSSO } from '../../common/AppInsightsHelper';
import { shimmerStyleChart, stackTokens, transparentTheme } from '../../common/ComponentStyles';
import CostMngmtHelper from '../../common/CostMngmtHelper';
import DashboardHelper, { LayoutStyles, ListStyles } from '../../common/DashboardHelper';
import TimeHelper from '../../common/TimeHelper';
import HeatmapDetailsList from '../HeatmapDetailsList/HeatmapDetailsList';
import InsightsChart from '../InsightsChart/InsightsChart';
import { IInsightsDashboardProps } from "./IInsightsDashboardProps";
const InsightsDashboard: React.FunctionComponent<IInsightsDashboardProps> = (props) => {
//#region State
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [items, setItems] = React.useState<any[]>(null);
const [dataTypes, setDataTypes] = React.useState<Map<string, string>>(null)
const [listCols, setListCols] = React.useState<IColumn[]>([]);
const [messageBarTxt, setMessageBarTxt] = React.useState<string>("");
const [messageBarType, setMessageBarType] = React.useState<MessageBarType>(MessageBarType.info);
const [stackItemStylesList, setStackItemStylesList] = React.useState<Partial<IStackItemStyles>>({});
const [stackItemStylesChart, setStackItemStylesChart] = React.useState<Partial<IStackItemStyles>>({});
//#endregion
//#region Effects
React.useEffect(() => {
const setLayout = (showList: boolean, showChart: boolean, layoutSettings: LayoutStyles, width: number): void => {
if (showList && showChart) {
const styles = DashboardHelper.GetStackItemStyle(layoutSettings, width)
setStackItemStylesList(styles.list);
setStackItemStylesChart(styles.chart);
}
else {
const styleDefault = DashboardHelper.GetStackItemStyleFull();
setStackItemStylesList(styleDefault);
setStackItemStylesChart(styleDefault);
}
}
setLayout(props.showList, props.showChart, props.layoutSettings, props.width);
}, [props.showList, props.showChart, props.layoutSettings]);
React.useEffect((): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _buildColumns = (response: any[], colInfo: Map<string, string>): IColumn[] => {
const columns: IColumn[] = buildColumns(response);
//datetime
let _colsByType = ApiHelper.GetColByType(colInfo, 'datetime');
columns
.filter((col: IColumn) => { return _colsByType.includes(col.name) })
.forEach((col: IColumn) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
col.onRender = (item?: any, index?: number, column?: IColumn) => {
return TimeHelper.getFormattedDateTime({
datetime: item[column.name],
cultureName: props.cultureName
})
}
});
//real
_colsByType = ApiHelper.GetColByTypes(colInfo, ['real']);
columns
.filter((col: IColumn) => { return _colsByType.includes(col.name) })
.forEach((col: IColumn) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
col.onRender = (item?: any, index?: number, column?: IColumn) => {
return Number(item[column.name]).toFixed(3);
}
});
//Number
_colsByType = ApiHelper.GetColByTypes(colInfo, ['Number']);
columns
.filter((col: IColumn) => { return _colsByType.includes(col.name) })
.forEach((col: IColumn) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
col.onRender = (item?: any, index?: number, column?: IColumn) => {
const val = Number(item[column.name])
return (val!==0 && val < 0.001)
? "<0.001"
: val.toFixed(3)
}
});
columns.forEach((col: IColumn) => {
col.isResizable = true;
})
return columns;
}
const getQueryResults = (helper: AppInsightsHelper | AppInsightsHelperSSO | CostMngmtHelper, query: string, dateSpan?: string): void => {
setItems(null);
setDataTypes(null);
setMessageBarTxt("");
if (helper && query && dateSpan !== 'Custom') {
helper.GetAPIResponse({ query: query, dateSelection: dateSpan})
.then((response: IResponseJson) => {
if (response.error) {
const errMsg = (response.error.code === 'PathNotFoundError')
? stringsCommon.Msg_FailedConfig
: response.error.message || response.error.innererror?.message;
setMessageBarTxt(errMsg);
setMessageBarType(MessageBarType.error);
}
else if (response.tables.length === 0) {
setMessageBarTxt(stringsCommon.Query_NoResults);
setMessageBarType(MessageBarType.info);
}
else {
setItems(response.tables);
setDataTypes(response.columns);
setListCols(
_buildColumns(response.tables, response.columns)
);
}
})
.catch((error: Error) => {
setMessageBarTxt(error.message);
setMessageBarType(MessageBarType.error);
});
}
}
getQueryResults(props.helper, props.query, props.dateSpan);
}, [props.helper, props.dateSpan, props.query, props.cacheExpiration]);
//#endregion
return <Stack tokens={stackTokens} >
{messageBarTxt &&
<MessageBar
messageBarType={messageBarType}
dismissButtonAriaLabel="Close"
>{messageBarTxt}
</MessageBar>
}
{!messageBarTxt &&
<Stack horizontal wrap tokens={stackTokens}>
{props.showList &&
<StackItem styles={stackItemStylesList}>
<ThemeProvider theme={transparentTheme}>
{(props.listStyle === ListStyles.list
? <ShimmeredDetailsList
items={items || []}
columns={listCols}
enableShimmer={!items}
selectionMode={SelectionMode.none}
compact={true}
ariaLabelForShimmer="Content is being fetched"
ariaLabelForGrid="Item details"
/>
: <HeatmapDetailsList
items={items || []}
columns={listCols}
dataTypes={dataTypes}
listPalette={props.listPalette}
/>
)}
</ThemeProvider>
</StackItem>
}
{props.showChart &&
<StackItem styles={stackItemStylesChart}>
<Shimmer
isDataLoaded={items !== null}
styles={shimmerStyleChart}
ariaLabel="Loading content">
<InsightsChart
items={items || []}
dataTypes={dataTypes}
chartType={props.chartStyle}
chartPalette={props.chartPalette}
/>
</Shimmer>
</StackItem>
}
</Stack>
}
</Stack>
}
export default InsightsDashboard;

View File

@ -0,0 +1,8 @@
import { IChoiceGroupOption } from "@fluentui/react";
import { ThemedPalette } from "../../common/ColorsHelper";
export interface ISwatchColorPickerThemedProps {
configThemePalette: ThemedPalette[];
themePalette: string
onChangeColorPalette: (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption) => void;
}

View File

@ -0,0 +1,73 @@
import { ChoiceGroup, IChoiceGroupOption, IChoiceGroupOptionProps, IColorCellProps, SwatchColorPicker } from "@fluentui/react";
import { useId } from "@fluentui/react-hooks";
import React from "react";
import ColorsHelper, { ThemedPalette } from "../../common/ColorsHelper";
import { colorPickerStyles, disabledPickerStyle } from "../../common/ComponentStyles";
import { ISwatchColorPickerThemedProps } from "./ISwatchColorPickerThemedProps";
const SwatchColorPickerThemed: React.FunctionComponent<ISwatchColorPickerThemedProps> = (props) => {
const baseId = useId('colorpicker');
const [colorOptions, setColorOptions] = React.useState<IChoiceGroupOption[]>([]);
const [selectedColor, setSelectedColor] = React.useState<string>();
const getColorCells = (themeColors: string[]): IColorCellProps[] => {
return themeColors.map((color, index) => {
return {
id: `${index}`,
label: color,
color: color,
styles: disabledPickerStyle,
};
});
}
const _onRenderField = (props: IChoiceGroupOption & IChoiceGroupOptionProps, render: (props?: IChoiceGroupOption & IChoiceGroupOptionProps) => JSX.Element, colorCells: IColorCellProps[]): JSX.Element => {
return (<>
{render(props)}
<SwatchColorPicker
columnCount={5}
cellHeight={15}
cellWidth={15}
cellMargin={2}
cellShape={'square'}
colorCells={colorCells}
aria-labelledby={`${baseId}-circle`}
styles={disabledPickerStyle}
/>
</>);
}
React.useEffect(() => {
if (props.configThemePalette) {
const len = 5;
const colorOptions: IChoiceGroupOption[] = props.configThemePalette.map((theme) => {
const colorInfo = ColorsHelper.GetThemeMonochromaticColors(theme as ThemedPalette, len);
return {
key: colorInfo.Id,
text: colorInfo.Name,
onRenderField: (props, render) => {
return _onRenderField(props, render, getColorCells(colorInfo.Colors));
},
}
});
setColorOptions(colorOptions);
}
}, [props.configThemePalette]);
React.useEffect(() => {
if (props.themePalette) {
setSelectedColor(props.themePalette);
}
}, [props.themePalette]);
return <ChoiceGroup
options={colorOptions}
styles={colorPickerStyles}
selectedKey={selectedColor}
onChange={props.onChangeColorPalette}
defaultSelectedKey={props.themePalette}
/>
}
export default SwatchColorPickerThemed;

View File

@ -0,0 +1,61 @@
// eslint-disable-next-line no-undef
define([], function() {
return {
PropertyPaneDescription: "Use the WebPart Configuration Dashboard to configure the settings",//-
GroupNameConnection: "API Configuration",//-
GroupNameLook: "Layout", //-
GroupNameLookList: "Results", //-
GroupNameLookChart: "Chart", //-
LookShowTimePicker: "Show time picker in view mode",//-
LookShowList: "Show results table", //-
LookShowChart: "Show chart", //-
LookLayout:"Component layout within page column", //-
LookListStyle:"List style", //-
LookListList:"List", //-
LookListHeatmap:"Heatmap", //-
LookChartColors:"Chart colors", //-
LookChartStyle:"Chart style", //-
lookChartLine: "Line chart", //-
lookChartArea: "Area chart", //-
lookChartBar: "Bar chart", //-
lookChartColumn: "Column chart", //-
lookChartPie: "Pie chart", //-
paletteCol1:"Colorful 1", //-
paletteCol2:"Colorful 2", //-
paletteCol3:"Colorful 3", //-
paletteCol4:"Colorful 4", //-
paletteMono1:"Monochromatic 1", //-
paletteMono2:"Monochromatic 2", //-
paletteMono3:"Monochromatic 3", //-
paletteMono4:"Monochromatic 4", //-
paletteMono5:"Monochromatic 5", //-
paletteMono6:"Monochromatic 6", //-
paletteMono7:"Monochromatic 7", //-
Config_Desc_ReadMode: 'Please open the web part in edit mode to configure the settings.',//-
ApplyBtnLabel: 'Apply',//-
ConfigBtnLabel:'Configure',//-
DatePicker_TimeSpan: 'Time range:', //-
DatePicker_StartDate:"Start Date", //-
DatePicker_EndDate:"End Date", //-
DatePicker_TimeSpanCustom:"Custom", //-
DatePicker_Error:"Start time must be before end time.", //-
DatePicker_BtnSave:"Save", //-
DatePicker_BtnCancel:"Cancel", //-
Query_NoResults:"No results found from the specified time range",
Msg_FailedConfig:"Please ensure that component configuration is correct",
Msg_FailedVisErr: "Failed to create visualization",
Msg_FailedVisErrPie:"as Pie Chart requires EXACTLY ONE numerical column (int, long, decimal or real).",
Msg_FailedVisErrOneNumerical: "as you are missing a column of one of the following types: int, long, decimal or real."
}
});

View File

@ -0,0 +1,64 @@
declare interface ICommonDasboardWebPartStrings {
PropertyPaneDescription: string;
GroupNameConnection: string;
GroupNameLook: string;
GroupNameLookList: string;
GroupNameLookChart:string;
LookShowTimePicker: string;
LookLayout: string;
LookShowList: string;
LookShowChart:string;
LookListStyle: string;
LookListList: string;
LookListHeatmap: string;
LookChartColors: string;
LookChartStyle: string;
lookChartLine: string;
lookChartArea: string;
lookChartBar: string;
lookChartColumn: string;
lookChartPie: string;
paletteCol1:string;
paletteCol2:string;
paletteCol3:string;
paletteCol4:string;
paletteMono1:string;
paletteMono2:string;
paletteMono3:string;
paletteMono4:string;
paletteMono5:string;
paletteMono6:string;
paletteMono7:string;
Config_Desc_ReadMode: string;
ApplyBtnLabel: string;
ConfigBtnLabel: string;
DatePicker_TimeSpan: string;
DatePicker_StartDate: string;
DatePicker_EndDate: string;
DatePicker_TimeSpanCustom: string;
DatePicker_Error: string;
DatePicker_BtnSave: string;
DatePicker_BtnCancel: string;
Query_NoResults: string;
Msg_FailedConfig:string;
Msg_FailedVisErr: string;
Msg_FailedVisErrPie:string;
Msg_FailedVisErrOneNumerical: string;
}
declare module 'CommonDasboardWebPartStrings' {
const stringsCommon: ICommonDasboardWebPartStrings;
export = stringsCommon;
}

View File

@ -0,0 +1,51 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "7bbd40d0-805c-4b5d-8d6a-0abd65a09474",
"alias": "ApplicationInsightsLogsWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": [
"SharePointWebPart",
"TeamsTab",
"SharePointFullPage"
],
"supportsThemeVariants": true,
"preconfiguredEntries": [
{
// 4aca9e90-eff5-4fa1-bac7-728f5f157b66 "Business and intelligence"
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": {
"default": "Advanced"
},
"title": {
"default": "Application Insights Logs"
},
"description": {
"default": "Dashboard displaying Application Insights logs"
},
// "officeFabricIconFontName": "BIDashboard",
"iconImageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAmCAYAAACoPemuAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAe6SURBVFhH7Vd7cFTVGb/nnrubfWRXApnaghWJ1jBgMGDi8CgEqhJBIB0ejaAWlFEUaGkrdDo4dGit1hYZtYKUwSi1UKoWJpg2JIJaRBJgQxJKtAEJMImEh3ls1iSb3Xvvuf19J7sZsnmZ5M/6m/n2nHvuuef7fY/znbPKN+gnWKQdFH5bVMle9n3OGtbMFfS8+L0Ts4OmWGgKkW0pimuk172j8MKVnyQP9fhVxhzxNv5pnMbfSRri3vnryaOr5+0tYjd7XeqW+1JNuSAwaGJrPzrNXpyRAv2KsvrgqZk1X7U+YwprGg1ATM4Yh9LX86surx6T6A1g2C4sS9FUpthUNXhDnG3rm7PvWkff/2j/CfWdrLulcSr9DBQgwgrOX5X9R/NP/q62OViom5IULW72ZDW8JoSlGG2GcF5rDa3N2lf8j23lF0YRqcV5PslpUMRKr/pZxfJ7rYW5x5+rC4aeCRqmyZhC4aB1uZzUPYizhrnkWN0Q1oIjNXX/phd75qaLZfkl6oCJPZTn04oezhBPFpY9HRZivSkUE57oi1AsiKANoje2hW+es7doFw3unJ0mBkRsCdy9e266MW3Px65LzW3rYbEC60nJQHPWBqPI0w/B+w/TwICI/e39MpnsI9yOraZlDQWbaPgGAxWbhmK7/fniM4n9XuyRf5aoyqtPWGs/qhgRNMSSyPBgSREYbYo2w3SdvNp4X78XNCxLfoOykAlv2dElb/UZQunijka23YksFagmC/pNrPyqP1pnxoLY104q1C2aSolOIL30HCuaZAdi9NAFWY//gsYlaQvKnQ6H8vaW35tris6xVybfRt8qS/9VUvVlazgJ6ohoTwbSTuUjva6cA+evrBo9zFONMTeNQ7rVTYACS4v0OzD/yXVs3583kXL6uBMaKz+L9BSlLhgOSh/0DpiFSmpZompFZmjM3uKUvPIL9cqzS0wUVaajxrDrFsFhoAR1oWSMTOzMesPmbeqzTz8lNmx+LQUG/QHrtqB1CiHOnb1Ys+7drS/okanKg++dqAqEjSQs0JvHyECGMNbGcT4Rlb0G5+gef0h3wJNBvCPHyAhcB+IkOnnsiK9MEj3iK/8OmllkjAmrhng9yp1jkt/E2Kn09a9w3/NrTJeNn2oK6QhlJ9tiQS9N1LnhaEqz9/vGJThtO3RhfdCiG3Q0tc+KAY12spTyKdLq1MeBhqJuIRIyyWXSJ99+q6zsyK+DnHwfGe8FNN8AucQ20zh9KRDy3ZrgvjPepll0mANhCKUNiU4jWLeopxBIjfjh+OnkVacekkRu8jhLUOxp6e7CEQuaQ+SGKUxUV9a1VN8yxD3BbdOwA2XJIZAB8kxzaLy4J2IS12uL9m1f+WV328xUn52zT+Vg38QIUXJDYM/Fs/XN1RHPETkiRdVH1XB8YxcX9kqsO9gDDRYOcBnOG12OTXSvAqu+whlFhJy4AeTOV9Y1f5GU4B4Xb28nh5RTPXbt0B+n33Gw38QsfI16JIm8NjP1LSxUjJCTwo4d2weiniNyFyrrmy9/LyF+LIUVNtaO8Dgeo0n9JkbYMHm0tfxAqfx2uNs1A6b64DWq6pTI/QmrF9PPnG1oCQxz2idgl05/IeOOGhRvPiBihJxZEwRqGd80Y2yo2TC+j3vLcTiTEpk2Du2w3sJL5El3G0rHUF2I3O2Z48v2z5/0OS4J/C8PpJlqRvbjPCqRyd1CblPg4he1fPqDT/ApC5fzbx/Nt5YeKOMfZk8NTxw+7B6nxrdjSghao2tFy0BUiKyB97QclTGHg6sVpiXm41mZt6+Y/3VOGs3r0NcJIHkPmkMQ1FehJng9bNzo28c9t27laTkhBssKytSd94+XHlqQe+w2O+dvBUL6TVD8XRzIHUrITdRH6OkK/h+UhS1/n5u+E0Va/HBfsZo7f1KHlxlITIv06TsH5BgkFfIxBLwE93rilXn3ZqSXVvx3WcXZqltsmtam60bc+LHJl179zS9X0sJr9x9Rzxgay1swSVr8VGGps6Y5NHWU27YE97Zk/J0LJtg1R6tp5YYYy9/9QFoFzSPEkiJQEh5u73ZgOeRkezcCFBiP2wVDWTboJ0ZGCfWQVdRJCTdYLy7KEve/e1Qt2HXY2pY5gc7C9yPSBSk5H7CkBJeKpBdvzLqrSz4SseigAaHkpW0fE2L89aE/XIrihxAx2n00l54lcE+QbcGiKeKnh06x6qUzYAdTa1vDMpgOzhR/2FS+5dDYjS67tWtOukBeSO92ByIWTfhedyjUyvRof+rSssvX6vjGl7a3p1HFMfNPP1tB/R4V94XrycR4qV+w1q96zNj48xUmxNgIUpt37BrMetJjAwOpbVdtvZSzOyvObhuBVKQQ2xDCvSsfWXQte/Wv+JUv68lzEoff3tEll3oC7croh+R2Cs2PIVQWymhM7sr4eGXxvMyJn5SU7zldeW6UzaaZumHw8WOSP8M9bWnB4aO+UCiMqwEC0H6VmZqX8/In1Bkoes2rvgAKlmmajpaWoFLvb9Ib/QG9sSmgNDQFgj9YvMILo6dA0iB3Q1IhX1vfoIgREE2h4mTTJDiHKKhzTXD1o3hNXvNBjkM+hFCdpALeZ/4NmpgMHP0ghHTTpUiiJcVUfgiUd4Q2iJz+Df6PoCj/A5joSyRL3M9pAAAAAElFTkSuQmCC",
"fullPageAppIconImageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFYAAABLCAMAAADdwICAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAA8UExURVy0y0usxnjB1VGvyInJ2me5z4TG2G280WK3zVaxyn7E1p+rsj9XZW+BjJPF1IrD0m23zGy2y4/E0wAAAFHDhvEAAAAUdFJOU/////////////////////////8AT0/nEQAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAfRJREFUWEft2NtWwyAQheHS9JDak9r3f1cH2FAOMzA0Vm/y35hU8i1WSGzi5vFCG0NtacP+nHb+w6xxdm8tKrBULY+yE6SMpexe0hgbZmrLWWMOfohvhN0B8JWsmfwo1wB7xOGoYo3x42x6dsaxIYY1cenU7AlHxjjWfPjBarZSeTacByWbXgKIZ+Hq2AOOSRNY7+pYHJElsU5Usc9bK0li3XRVLMbniay9LTQsO1mZtbexguXWi5JZOg0KFmPL/p6dFewWY8sarFGw/IItZjGyqsUe38NOXVa4vNqsv4NbSSu2kC2/FGLLWOlCcKxYlwVSt4wVZ3vCALacPYewT4nn1rvFt3woZy+hKz5oXAlNt8vmjzJ5sttl5TWjRHcZK7nzQlZwiysBaMY21szGugq2M13OPf0Cy7g7DVuvSFHllncZ0JztTrd0q+cEoAUr/iWP5S5ta9j+dDPXvpuo2P50E9eJKpZ7ai6LrjtAxzLP+FVw3XAtK/81f+ZcpGUVy5a6anZsvnpWcX4xkBpgn9c7n/zOC1Rg2ydijzGuMVZeuRm/R6Ms/5VZoC+wNve/mtgRn6bJ7Bmbl0vyMBK73T+/qO8b9os2OJSiPWwp2E4rS60stbLUP7N4VUlfVlop2Ss23ShFK0u9wmKLcgTXylJvYR+PH/0CMcPIb3DQAAAAAElFTkSuQmCC",
"properties": {
"preset": 100,
"dateSelection": "P7D",
"query": "",
"cacheDuration": "FifteenMinutes",
"showList": true,
"listStyle": 1,
"listPalette": 2,
"showChart": true,
"chartStyle": 1,
"chartPalette": 1,
"layoutSettings": 1,
"showTimePicker": true
}
}
]
}

View File

@ -0,0 +1,139 @@
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration, IPropertyPaneDropdownOption, PropertyPaneDropdown, PropertyPaneToggle
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as ReactDom from 'react-dom';
import { ConsoleListener, Logger } from '@pnp/logging';
import PnPTelemetry from "@pnp/telemetry-js";
import strings from 'AppInsightsDasboardWebPartStrings';
import * as React from 'react';
import { ThemedPalette } from '../../common/ColorsHelper';
import { CacheExpiration, IAppInsightsQuery, IAppInsightsWebPartProps } from '../../common/CommonProps';
import { ChartStyles, LayoutStyles, ListStyles } from '../../common/DashboardHelper';
import ApplicationInsightsLogs from './components/ApplicationInsightsLogs';
import { IApplicationInsightsLogsProps } from './components/IApplicationInsightsLogsProps';
const telemetry = PnPTelemetry.getInstance();
telemetry.optOut();
const LOG_SOURCE: string = 'Application Insights Logs WebPart';
export default class ApplicationInsightsLogsWebPart extends BaseClientSideWebPart<IAppInsightsWebPartProps> {
public onInit(): Promise<void> {
const _setLogger = (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.subscribe(new (ConsoleListener as any)());
//default is 2 - Warning
if (this.properties.logLevel && this.properties.logLevel in [0, 1, 2, 3, 99]) {
Logger.activeLogLevel = this.properties.logLevel;
}
Logger.write(`${LOG_SOURCE} ${this.manifest.version} activated`);
Logger.write(`${LOG_SOURCE} Initialized with properties:`);
Logger.write(`${LOG_SOURCE} ${JSON.stringify(this.properties, undefined, 2)}`);
}
_setLogger();
return Promise.resolve();
}
public render(): void {
const element: React.ReactElement<IApplicationInsightsLogsProps> = React.createElement(ApplicationInsightsLogs, {
...this.properties,
width: this.width,
userLoginName: this.context.pageContext.user.loginName,
httpClient: this.context.httpClient,
aadHttpClientFactory: this.context.aadHttpClientFactory,
cultureName: this.context.pageContext.legacyPageContext.currentCultureName,
DisplayMode: this.displayMode,
onPivotItemChange: this._onPivotItemChange,
onConfigureAppInsights: this._onConfigureAppInsights,
onConfigureKustoQuery: this._onConfigureKustoQuery,
onConfigureListSettings: this._onConfigureListSettings,
onConfigureChartSettings: this._onConfigureChartSettings,
onConfigureTimePicker: this._onConfigureTimePicker,
onConfigureLayoutSettings: this._onConfigureLayoutSettings,
});
ReactDom.render(element, this.domElement);
}
//#region WebPart Properties
public _onPivotItemChange = (key: string): void => {
this.properties.pivotKey = key
}
public _onConfigureAppInsights = (appId: string, appKey: string): void => {
this.properties.appId = appId;
this.properties.appKey = appKey;
}
public _onConfigureKustoQuery = (preset: number, config: IAppInsightsQuery): void => {
this.properties.preset = preset;
this.properties.query = config.query;
this.properties.dateSelection = config.dateSelection;
}
public _onConfigureTimePicker = (showTimePicker: boolean): void => {
this.properties.showTimePicker = showTimePicker;
}
public _onConfigureListSettings = (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette): void => {
this.properties.showList = showList;
this.properties.listStyle = listStyle;
this.properties.listPalette = listPalette;
};
public _onConfigureChartSettings = (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette): void => {
this.properties.showChart = showChart;
this.properties.chartStyle = chartStyle;
this.properties.chartPalette = chartPalette;
}
public _onConfigureLayoutSettings = (layout: LayoutStyles): void => {
this.properties.layoutSettings = layout;
}
//#endregion
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse(this.manifest.version);
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
const cachingOptions: IPropertyPaneDropdownOption[] = Object.keys(CacheExpiration).map((value: string) => {
return {
key: value,
text: CacheExpiration[value as keyof typeof CacheExpiration]
};
});
console.log(this.properties.cacheDuration)
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.DevGroupName,
groupFields: [
PropertyPaneToggle('isDevMode', {
label: strings.IsDevModeLabel,
onText: strings.IsDevModeOnText,
offText: strings.IsDevModeOffText,
checked: this.properties.isDevMode
}),
PropertyPaneDropdown('cacheDuration', {
label: strings.CacheDurationLabel,
options: cachingOptions,
selectedKey: this.properties.cacheDuration
}),
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,195 @@
import { Stack } from "@fluentui/react";
import { DisplayMode } from "@microsoft/sp-core-library";
import { Placeholder } from "@pnp/spfx-controls-react";
import strings from "AppInsightsDasboardWebPartStrings";
import stringsCommon from "CommonDasboardWebPartStrings";
import React from "react";
import AppInsightsHelper, { AppInsightsHelperSSO } from "../../../common/AppInsightsHelper";
import { AppInsightsQueryLogsHelper } from "../../../common/AppInsightsQueryHelper";
import { ThemedPalette } from "../../../common/ColorsHelper";
import { AppInsightsEndpointType, CacheExpiration, ConfigType, IAppInsightsQuery, IDashboardContextProps } from "../../../common/CommonProps";
import { stackStylesMain, stackTokens } from "../../../common/ComponentStyles";
import { ChartStyles, LayoutStyles, ListStyles } from "../../../common/DashboardHelper";
import DashboardConfiguration from "../../../components/DashboardConfiguration/DashboardConfiguration";
import InsightsDashboard from "../../../components/InsightsDashboard/InsightsDashboard";
import { IApplicationInsightsLogsProps } from "./IApplicationInsightsLogsProps";
const ApplicationInsightsDashboard: React.FunctionComponent<IApplicationInsightsLogsProps> = (props) => {
//#region State
const [helper, setHelper] = React.useState<AppInsightsHelper | AppInsightsHelperSSO>(null);
const [isConfigValid, setIsConfigValid] = React.useState<boolean>(false);
const [kustoQuery, setKustoQuery] = React.useState<string>(props.query);
const [expiry, setExpiry] = React.useState<CacheExpiration>(props.cacheDuration);// ?? moment().endOf('day').toDate());
const [showList, setShowList] = React.useState<boolean>(props.showList);
const [listStyle, setListStyle] = React.useState<number>(props.listStyle);
const [listPalette, setListPalette] = React.useState<ThemedPalette>(props.listPalette);
const [showChart, setShowChart] = React.useState<boolean>(props.showChart);
const [chartStyle, setChartStyle] = React.useState<number>(props.chartStyle);
const [chartPalette, setChartPalette] = React.useState<ThemedPalette>(props.chartPalette);
const [layoutSettings, setLayoutSettings] = React.useState<number>(props.layoutSettings);
const [dateSpan, setDateSpan] = React.useState<string>(props.dateSelection);
//#endregion
//#region Methods
const configureAppInsightsHelper = (isConfigValid: boolean, appId: string, appKey?: string): void => {
if (isConfigValid && props.isDevMode) {
const helper = new AppInsightsHelper(
{
appId: appId,
appKey: appKey,
endpoint: AppInsightsEndpointType.query,
},
{
cacheDuration: props.cacheDuration,
userLoginName: props.userLoginName,
},
props.httpClient);
setHelper(helper);
}
else if (isConfigValid && !props.isDevMode) {
const helper = new AppInsightsHelperSSO(
{
appId: appId,
aadHttpClientFactory: props.aadHttpClientFactory,
endpoint: AppInsightsEndpointType.query,
},
{
cacheDuration: props.cacheDuration,
userLoginName: props.userLoginName,
});
setHelper(helper);
}
else {
setHelper(null);
}
}
//#endregion
//#region Effects
React.useEffect(() => {
const initializeSettings = (isDevMode: boolean, appId: string, appKey: string): void => {
const isValid = AppInsightsQueryLogsHelper.IsConfigValid(isDevMode, appId, appKey);
setIsConfigValid(isValid);
configureAppInsightsHelper(isValid, appId, appKey);
}
initializeSettings(props.isDevMode, props.appId, props.appKey);
}, [props.appId, props.appKey, props.isDevMode]);
React.useEffect(() => {
setExpiry(props.cacheDuration);
}, [props.cacheDuration]);
React.useEffect(() => {
if (props.preset !== 100) {
setKustoQuery(AppInsightsQueryLogsHelper.GetQueryById(Number(props.preset)).query);
}
}, [props.preset]);
//#endregion
//#region Events
const _onChangeTab = (key: string): void => {
props.onPivotItemChange(key);
}
const _onConfigureAppInsights = (appId: string, appKey: string): void => {
const isValid = AppInsightsQueryLogsHelper.IsConfigValid(props.isDevMode, props.appId, props.appKey);
setIsConfigValid(isValid);
configureAppInsightsHelper(isValid, appId, appKey);
props.onConfigureAppInsights(appId, appKey); //save to WP properties
}
const _onConfigureQuery = (preset: number, config: IAppInsightsQuery): void => {
setKustoQuery(config.query);
setDateSpan(config.dateSelection);
const chartInfo = AppInsightsQueryLogsHelper.GetChartConfig(config.query);
if (chartInfo.isSupported) {
setChartStyle(chartInfo.chartStyle);
}
//save to WP properties
if (preset === 100) {
props.onConfigureKustoQuery(preset, config)
}
else {
props.onConfigureKustoQuery(preset, { ...config, query: "" })
}
}
const _onConfigureListSettings = (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette): void => {
setShowList(showList);
setListStyle(listStyle);
setListPalette(listPalette);
props.onConfigureListSettings(showList, listStyle, listPalette);
}
const _onConfigureChartSettings = (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette): void => {
setShowChart(showChart);
setChartStyle(chartStyle);
setChartPalette(chartPalette)
props.onConfigureChartSettings(showChart, chartStyle, chartPalette);
}
const _onConfigureLayoutSettings = (layout: LayoutStyles): void => {
setLayoutSettings(layout);
props.onConfigureLayoutSettings(layout);
}
//#endregion
return (
<Stack tokens={stackTokens} styles={stackStylesMain}>
{/* Edit mode */}
{props.DisplayMode === DisplayMode.Edit &&
<DashboardConfiguration
{...props}
dateSelection={dateSpan}
configType={ConfigType.ApplicationInsightsLogs}
onPivotItemChange={_onChangeTab}
onConfigureAppInsights={_onConfigureAppInsights}
onConfigureQuery={_onConfigureQuery}
onConfigureListSettings={_onConfigureListSettings}
onConfigureChartSettings={_onConfigureChartSettings}
onConfigureLayoutSettings={_onConfigureLayoutSettings}
/>
}
{/* Read mode, needs config */}
{props.DisplayMode === DisplayMode.Read && (!isConfigValid || !kustoQuery) &&
<Placeholder iconName='Edit'
iconText={strings.Config_IconText}
description={stringsCommon.Config_Desc_ReadMode}
buttonLabel={stringsCommon.ConfigBtnLabel}
hideButton={props.DisplayMode === DisplayMode.Read}
/>
}
{isConfigValid && kustoQuery && (
<>
{/* {props.isDevMode &&
<MessageBar messageBarType={MessageBarType.severeWarning}>{strings.Msg_AuthWarning}</MessageBar>
} */}
<InsightsDashboard
{...props as IDashboardContextProps} //has all props not only the ones defined in IDashboardContextProps
helper={helper}
dateSpan={dateSpan}
query={kustoQuery}
cacheExpiration={expiry}
showList={showList}
listStyle={listStyle}
listPalette={listPalette}
showChart={showChart}
chartStyle={chartStyle}
chartPalette={chartPalette}
layoutSettings={layoutSettings}
/>
</>
)}
</Stack>
)
}
export default ApplicationInsightsDashboard;

View File

@ -0,0 +1,15 @@
import { ThemedPalette } from "../../../common/ColorsHelper";
import { IAppInsightsQuery, IAppInsightsWebPartProps, IDashboardContextProps } from "../../../common/CommonProps";
import { ChartStyles, LayoutStyles, ListStyles } from "../../../common/DashboardHelper";
export interface IApplicationInsightsLogsProps extends IAppInsightsWebPartProps, IDashboardContextProps {
onPivotItemChange: (key: string) => void;
onConfigureAppInsights: (appId: string, appKey: string) => void;
onConfigureKustoQuery: (preset: number, config: IAppInsightsQuery) => void;
onConfigureTimePicker: (showTimePicker: boolean) => void;
onConfigureListSettings: (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette) => void;
onConfigureChartSettings?: (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette) => void,
onConfigureLayoutSettings: (lookLayout: LayoutStyles) => void;
}

View File

@ -0,0 +1,27 @@
// eslint-disable-next-line no-undef
define([], function() {
return {
PropertyPaneDescription: 'Please use WebPart Dashboard to configure the properties',
DevGroupName: "Developer Settings",
IsDevModeLabel: "Enable authentication with ApiKey and AppId (not recommended for production)",
IsDevModeOnText: "Yes, I know what I am doing, I am not in production",
IsDevModeOffText: "No, I want to use AAD authentication",
GroupNameAppInsights: "Application Insights",//-
GroupNameKustoQuery:"Kusto Query",//-
AppIdLabel: "Application ID", //-
AppKeyLabel: "Application Key", //-
KustoQueryLabel:"Kusto query",//-
KustoQueryDocs:"Application Insights overview",//-
KustoQueryRef:"KQL quick reference",//-
AIAnalyticsDemo:"Application Insights demo data",//-
Config_IconText: 'App Insights Dashboard Configuration', //-
CacheDurationLabel:'Cache duration',
HelpAppInsightsAppId: "<ul style='margin:10px;padding:0'><li>1. Application Insights instance / API Access </li ><li>2. Copy <b>Application ID</b></li></ul >", //-
HelpAppInsightsAppKey: "<ul style='margin:10px;padding:0'><li>1. Application Insights instance / API Access / <b>Create API key</b></li ><li>2. Choose <b>Read telemetry</b></li></ul>", //-
Msg_AuthWarning:"You are currently authenticating using AppId and AppKey. This is OK to quickly explore the API in a non-production environment. Storing secrets in WebPart properties is NOT secure, please switch to AAD authentication soon =)",
}
});

View File

@ -0,0 +1,32 @@
declare interface IAppInsightsDasboardWebPartStrings {
PropertyPaneDescription:string
DevGroupName:string;
IsDevModeLabel:string;
IsDevModeOnText:string;
IsDevModeOffText:string;
GroupNameAppInsights: string;
GroupNameKustoQuery: string;
AppIdLabel: string;
AppKeyLabel: string;
KustoQueryLabel: string;
KustoQueryDocs: string;
KustoQueryRef: string;
AIAnalyticsDemo:string;
Config_IconText: string;
CacheDurationLabel: string;
HelpAppInsightsAppId: string;
HelpAppInsightsAppKey: string;
Msg_AuthWarning:string;
}
declare module 'AppInsightsDasboardWebPartStrings' {
const strings: IAppInsightsDasboardWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,52 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "7691e546-a4b6-457c-9018-a152a6e3e321",
"alias": "CostInsightsWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": [
"SharePointWebPart",
"TeamsTab",
"SharePointFullPage"
],
"supportsThemeVariants": true,
"preconfiguredEntries": [
{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": {
"default": "Advanced"
},
"title": {
"default": "Cost Insights"
},
"description": {
"default": "Dashboard displaying Cost Insights"
},
// "officeFabricIconFontName": "Savings",
"iconImageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAmCAYAAACoPemuAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAnZSURBVFhH7Vd5VFTXGf/efTPMsIw6SFgUEFTEBTAqKGgjYkldkxpbDq5BTWIUNakx2qiJS9S0LlXQmjY1NWqqYpajpx4ldQmCIKISVBJQlmEZ9mVgBoZZ33v97mNQJoIJ6jn9o/m988697977vve733a/B7/gf40mvZo5kR3H2h5Ba6gaeSrn9WOJaRHC57fmW68UJSy1TYnILP2S2Lp2YGztM8HRm3NIXFgST/uCIDh9eSd+ZaO+YEel9juJyaoT8HNMb7k3+CrHZU3wW7pvoNvkLxiGERYlKdn3o5OFwW7h4rsUz4TYjbKjZNancVC1DXgk5JyuOhh3t/qrt+pb7wearFpwdnDnAtynslpDGZRq0gWWYRlCfMHNZUzS/FGbPnB19i+icj7JfJ19ecQ63qvXEOGpiJU332Z8Nz0PsB9QGwB3qs5Mz685m6hqvDJYb2kAlnHgrZyBmTh4PTOy/3zQm+rg3A+roLY1n1c16YDjCRmgDG4d7xd7/JWg9btQeyoqJzk/kX1iYtW6AobujPYbWkvCLxXueKdMk/GKzlglwQ9wLCPFhhAzp4cXBq6Dkd4LocVYBd/k/wHKNHlQ1WLE3XC8mQOikPUBP2VIeYhX1ObfhWxJwheNT23Kc3kbd5dprr1brbtLP4RakvLIllDBvMABJaaQeUKgx0wMhHIoaUyBCl0rtFkAWHEVCBwu5HiQKB3dYbhn5N2YkE17n4jYjouDycYXi/gT2Ys2FDVc2mGwNAlS1pFngCECCAy2YOVN4OTgBiM8Z4OHIhhwHl2fQJtZA9kVFyCj9CtRFourqdppgwQFK2pwlPevoctQ/Sm0mevFtkaXO8zKG8GBdeLwke0gxQkWcJa5w9RhuyBswDLo3ycMHB1cUXP9YZDbZJg3eg8sDksECXFAUqI30CjGkGCITMLwtysvC09EjBCJ2PLAoS8QKryT5pEYb4FgrzmoqRDcRAOkFf8Zvr4dB1/kzIfLhQlQ0ZyHptShRnuhuR+mBkoSL+JAGdrG7FCgKmMupGWyyVcySPKVdHIpI4u9j2O2aUT7LlEkNZ2t3w76TBgJ9HHyRS1wYLRoobAuGdsmaDE1oE8ehISr8+Bf2R+AztggOmOXMmz9B6ioqWOGDBwg/GZiBDdt0gR+2qRf8dETxnGBOFav0fykT7Yv4MHKGVEbVsxhbhDquxQUck/QGg2oKQEJNoOjlIj+1R3siNU2NDLenu6CrqV1WFVt/bSq2rroypq66Oq6+mk45vucq6ugqslFaY/hhx+j0VitzcGokyNFHoK8YuCloL/Db4N3wZShi8HfNRiDA2cEqqmuZbU7iw37jyRRotzF9KyV/0nLjDdbLNQpQeHsDJHhY1bh3F/PX7xDwO1Huu8Eup5G4P36c5jZAyHQfYYYjb3k/dHvfCDI80WwYnDcKDsNp3N3oCAaN5ScvUg7janKK8W2rlFjvldcCnlFJda8whIr+hcds9I51KK4pnvQDxBRa1eLd2JCXQv3as9iBN/DQNDiOIYMb4WJg16FcL8YMKFU0oVJ7YjJHKRiK5VIGLlMBo54y+UysY9j7XPS9jWPh4A6QJPiVapJhZTC7fC3a3FwIH0B5FSeRyIsWNAHR3hEYcqgifhRA9gRo2boaG03I2A8i+PY77zmcRCjDNf1wkpCIfMAg4VDp9djmiiCkzmbQKOvQHIEXGRKDAIXkRjdSGfYEespUJgdS1FLGIlO0r4wdfgemBX8D4gashl4pg+aDJfit/1cQ0AmcRa11mJqxDTS2kXKoNmxx3i4Ozx2MNU/3CkVThgptJpq8VxUo0Y8wbv3OFg89jNYMm43LA0/gBk/AdycfcQEm1J0GAMBaXRKpygPjSTwPSZGkyc9Byk8FMOdeXRkegZ31h49GTJK9kFW6QHMXZXg6tgPQr1fxqiMxhQihdyab+HQ9WVQUHcTZFjgIA9xs3jxqFmmj6OH7WzpARiQwgv+a7C3BSYHvHcWdzulVJPmauEMlDQSBCyrCU1ncEv9KaQUnwS5tB9qbgg0G2qxXCoEjaEKnV9Ak1JSaAGG4fGZOjHrpfCD6IClx3usMSvHsdmXBjLrEldLfJVjTr4amhQ0qv+CLUpH/1qkzVoFE2pO4KgPAchB3VyL2V8Jkwa9BmG+s6EVqwtKRi6h8wzt8marQNC8bKjPSylzR28Lnx2yYYEkMvYN8ceBJQSadS20TzPeI+iw07Z3lpttXRG422pstpY1fXc8R30ioaDuwgydWY1yOE5v5vDLQCIGxGCdHwzuLv5wVfU53K+7ieU1x5uwfHN2cGZGuEUUTBw4b/+kQYs/Q3ltI/YAkaSeOtSZiNin/ig+UbQbnxKwXs64EVFcVjEWzdRmsVoZD7e+0ulR45Md5Y6qAcrRtG6fea3wRFRew8l3G9oKpxdr7lEJXKrqCFapSqZCmw/lTXfpDwfa2oEN9oywDnkubOv80bv3oXw9wBI48/2f2FlB6zmqsY30bQRW4MTFxcnxjFTCGm1j7UCmTnK5+cLV66vyi0rmUu0ZjSYYNtgf8LD/PT6qUu+ck0QdmcGPD5iXgs8p2eqkNTwcXVFQn+WfW5UFxQ1zOerYmBqIp8LfOLJf9Kk3xn2cQIj09gLYgwn4NTZ25Bbe1dlHVA71se22+yO8N7AsOx2zfHvYPYDooKBr0bc2aVugWauzNGl1Vl2rnvoLFsm4qzZ3gd8H/LncTaLzjPGZ85f1k8+HTglcvma0d6ReJlGwngofMjVwWe6yiE+i3ow4tIiS8t0O5H5dBrN8/D85JNXhMeIh3mFK2jrg3YZ+0Usc+RFYdEQJS78rEIkEf8JYMXZEs+N/B21gRvCHoryjtxZiVcNosLsXU0rG3rQYv+EekwzThr51mZqNXQskfcUpiPCL5QPfn0BfsQMlJjp/J6D9H/i6HehgR4ZG8u0DNly7dYeNXfmeeLzQ0ikudA33fXUqcyx7NXqIJAuX4H0am7chMW0ueXviST5id6z4blfocR7rDhtWLLGLVoogr0hKnbuuOksuFh5kfJTDYOrQeN6zV8CDP+7u8DTExGgl6M0x8X9c2FfZO5jnhTYcd/Ryd/th6+o3j/V9fjJpxPIpfOgyLNIILFk5Vli0M6CTnrtHjxPsj8ESFiqqa+OLStVri8vUm/FeV15VvZDONd7+locWFQ/mSgH0av7wzg9/FimKZ2JKrHS1DlYpjVATOraszWCsVVfWRJ749zdbdXp9KzqZgEGjiBgV/DWmlwMffXyYbIhf8lhzPrXGKDA5YRGKlsWDU2zxMC5WV/hfz8mNvJKZPSP1evbMqzdyIlXqylF0fWb23YcJvBs8E2KPxDDlCIzZNkzzXEdgGGztL/h/AcB/AaeyUv2tClRVAAAAAElFTkSuQmCC",
"fullPageAppIconImageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFQAAABJCAMAAACU/fG2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAHsUExURdLlsafOYpzITr/bj/n89ePuzZXEQX63FIe8J8jhn/P46pPCPNzswbXVf4K5HaTMWuz03om+LIS5HbLUefr899zsxJLCPIW8I57JUajOZI2/MGSqB2esGMXfp+304KPLW5DBN9bpv93tzNvsyKvQanu2E1ikAVejAHy3ONrrx7LTd9DlsW+vDZHDWO/256XMXmGnBVymCKvRf4K5G6HLWHq0Ep7JVb/cktToumytC3e0MNXov67ScIC4GLzbjMzkq16mA4zAUOrz38Pdl4W7IXayEKbPePT575rHS7HUd7XWfGirCcfhorfZkoS8RJnFSNHnta7ThcXgqMLel6PNc5XETdrsyLfYkdPovbPVi43AUsvjp5PDPWutCsXfnNnqw3GxF4m9KcnjrqrSf4i+S+3v8M/V2Ofq7Lral7fAxT9XZZ+rsrnak3CwJ2KpEMLeo365PdbpwpHDWWesCIS7IlqkAXWzLs3ksLnZh6bQedDluIG6QIy+MJrHZp7Kbd/uz6rQaoe9SOXw1+fy11ymA5bFX3GyKM/lt7XWj7rZh4G4HqHMcKTKaH21FX22E4m2PnKwDtLktJDANmOqBrrZl8PKz/P09cPelIS7IYeWn/n78q3Rd1dseJbGYMrir2yvIG+BjJOhqdvf4gAAAK+713oAAACkdFJOU/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8ANiMo3gAAAAlwSFlzAAAOwwAADsMBx2+oZAAAA6xJREFUWEft1/db00Acx3EQNIBb0SpWxVTFBVqL4sA9gIoIUhEcuFcRiltAxb333qL3j3r3vc9lHJYnOf3Jh/cPPEl7eT300kuTHGZaTu6IvHxsa5miI0dZvIJC7PozQ4tyBSkaPQYveTNCx44DKRo/Aa+6GaCFE8GhSZOL8Y4qNDplKqzItOklcmtGdCbeRCHRWbOlY1mlc2w7NldszZtfVrZgIQZQodD8Re5kLrZ5sVK+taRMVF6BQbwwaGGB9EQRYdr2Ur65jNCy+HJnaoOjzmRSiRihlZa1Qpo8Z2qDorNWQlNVCXNVwrJWgxStWUuDg6H51etgOSXW2/YGMaUbAco2bebDA6FbtkroT22DpopvrwmE6p9cVFJbl0wm62oTO4C5rakJgObB8bS0nk4TL7azAZZbeQB0FySnSCNEWVMcmCoeAPV9lXgR+t572g3MyQDdIKn6ZLKZL1VRCpgqPFpLTqyWdva0iJ292gSER/n3k1ctd5Y1tLbt0+fUAJUnXl713CXqKzy6n9ADtH0Qipbpf9pO2/4l6mQ6p3ZVZPASVYVHp0vUPlRVeRiIXnj0iLySUkePHR906nk+9MRJ1Sm8ItJQqw6irOX04MXvQ8+kVR14RaSj8vrsqQ2WkwlqVWN5qo4BUxmhVkJjtRkwQ3mlc8+2grTt09CQMSqWaGdKuVFwMnOUlmhXRqLdhKnMUblE4+cIPU87KmNULdE2Qv2X6fBoSWWyvvGIdQGARP/yP20npP7iJXl8p/z4l+UeCo2WyKV/RZ6aBnn6tZ++8B//KjH8YpLpyfTKzZZOaCg8mnBuJFQt/hkNhA66mdAuKEf9X1L9ZuLP6FhYbpXN8HiZ46Dc+gKgRddgua2IXk/1ZDI9N7r9p53q6g+AsqKb+t1pll9R6tZt/61kFpSxO9q83uUH39vd29QlHU/3H/DhwVA+zjsHYoleFxOq35p1PZSD6S8aAmXs0WOQFi1RuZL8V+cnNXJocJQVPX0mzed8iUbJ9K15ut2nQqCMTXhB6EtByMXkLiU8mFChUMZeveboG4F0i5vIJvJ40bcYQGVH33Wo3uNt6sNH8SzK60yl1PdePJF4y45+wmY67b2zYOzzF/2mxJ1MlIMD0+mvAVHGKr5Bo7yTiUxQxvr7ILrPo97MUMa+/xCk58nZmynKit/23X/iecb3ZowO1TCKhtHs6IDqJ44bsoAottLpARw3ZP81+gvX7o6OX0D0DFB31BkgesMo+mcoY78BGSj0zSLJGioAAAAASUVORK5CYII=",
"properties": {
"scope": 1,
"preset": 100,
"dateSelection": "MonthToDate",
"query": "",
"cacheDuration": "OneDay",
"endpointType": 1,
"showList": true,
"listStyle": 1,
"listPalette": 2,
"showChart": true,
"chartStyle": 1,
"chartPalette": 1,
"layoutSettings": 1,
"showTimePicker": true
}
}
]
}

View File

@ -0,0 +1,121 @@
import { Version } from '@microsoft/sp-core-library';
import { IPropertyPaneConfiguration, PropertyPaneLabel } from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { ConsoleListener, Logger } from '@pnp/logging';
import PnPTelemetry from "@pnp/telemetry-js";
import stringsCommon from 'CommonDasboardWebPartStrings';
import React from 'react';
import * as ReactDom from 'react-dom';
import { ThemedPalette } from '../../common/ColorsHelper';
import { ICostManagementConfig, ICostManagementQuery, ICostManagementWebPartProps } from '../../common/CommonProps';
import { ChartStyles, LayoutStyles, ListStyles } from '../../common/DashboardHelper';
import CostInsightsDashboard from './components/CostInsightsDashboard';
import { ICostInsightsDashboardProps } from './components/ICostInsightsDashboardProps';
const telemetry = PnPTelemetry.getInstance();
telemetry.optOut();
const LOG_SOURCE: string = 'Cost Insights WebPart';
export default class CostInsightsWebPart extends BaseClientSideWebPart<ICostManagementWebPartProps> {
public onInit(): Promise<void> {
const _setLogger = (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.subscribe(new (ConsoleListener as any)());
//default is 2 - Warning
if (this.properties.logLevel && this.properties.logLevel in [0, 1, 2, 3, 99]) {
Logger.activeLogLevel = this.properties.logLevel;
}
Logger.write(`${LOG_SOURCE} ${this.manifest.version} activated`);
Logger.write(`${LOG_SOURCE} Initialized with properties:`);
Logger.write(`${LOG_SOURCE} ${JSON.stringify(this.properties, undefined, 2)}`);
}
_setLogger();
return Promise.resolve();
}
public render(): void {
const element: React.ReactElement<ICostInsightsDashboardProps> = React.createElement(
CostInsightsDashboard,
{
...this.properties,
width: this.width,
userLoginName: this.context.pageContext.user.loginName,
httpClient: this.context.httpClient,
aadHttpClientFactory: this.context.aadHttpClientFactory,
cultureName: this.context.pageContext.legacyPageContext.currentCultureName,
DisplayMode: this.displayMode,
onPivotItemChange: this._onPivotItemChange,
onConfigureCostManagementScope: this._onConfigureCostManagementScope,
onConfigureCostQuery: this._onConfigureCostQuery,
onConfigureListSettings: this._onConfigureListSettings,
onConfigureChartSettings: this._onConfigureChartSettings,
onConfigureTimePicker: this._onConfigureTimePicker,
onConfigureLayoutSettings: this._onConfigureLayoutSettings,
}
);
ReactDom.render(element, this.domElement);
}
public _onPivotItemChange = (key: string): void => {
this.properties.pivotKey = key
}
public _onConfigureCostManagementScope = (config: ICostManagementConfig): void => {
this.properties.scope = config.scope;
this.properties.subscriptionId = config.subscriptionId;
this.properties.resourceGroupName = config.resourceGroupName;
this.properties.managementGroupId = config.managementGroupId;
}
public _onConfigureCostQuery = (preset: number, config: ICostManagementQuery): void => {
this.properties.query = config.query;
this.properties.preset = preset;
this.properties.dateSelection = config.dateSelection;
}
public _onConfigureTimePicker = (showTimePicker: boolean): void => {
this.properties.showTimePicker = showTimePicker;
}
public _onConfigureListSettings = (showList: boolean, listStyle: ListStyles): void => {
this.properties.showList = showList;
this.properties.listStyle = listStyle;
};
public _onConfigureChartSettings = (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette): void => {
this.properties.showChart = showChart;
this.properties.chartStyle = chartStyle;
this.properties.chartPalette = chartPalette;
}
public _onConfigureLayoutSettings = (layout: LayoutStyles): void => {
this.properties.layoutSettings = layout;
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse(this.manifest.version);
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: ""
},
groups: [
{
groupFields: [
PropertyPaneLabel('description', { text: stringsCommon.PropertyPaneDescription }),
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,34 @@
@import '~@fluentui/react/dist/sass/References.scss';
.costInsights {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.welcome {
text-align: center;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,170 @@
import { Stack } from '@fluentui/react';
import { DisplayMode } from '@microsoft/sp-core-library';
import { AadHttpClientFactory } from '@microsoft/sp-http';
import { Placeholder } from '@pnp/spfx-controls-react';
import stringsCommon from 'CommonDasboardWebPartStrings';
import strings from 'CostInsightsWebPartStrings';
import * as React from 'react';
import { ThemedPalette } from '../../../common/ColorsHelper';
import { CacheExpiration, ConfigType, ICostManagementConfig, ICostManagementQuery, IDashboardContextProps } from '../../../common/CommonProps';
import { stackStylesMain, stackTokens } from '../../../common/ComponentStyles';
import CostMngmtHelper from '../../../common/CostMngmtHelper';
import { default as CostHelper, default as CostMngmtQueryHelper } from '../../../common/CostMngmtQueryHelper';
import { ChartStyles, LayoutStyles, ListStyles } from '../../../common/DashboardHelper';
import DashboardConfiguration from '../../../components/DashboardConfiguration/DashboardConfiguration';
import InsightsDashboard from '../../../components/InsightsDashboard/InsightsDashboard';
import { ICostInsightsDashboardProps } from './ICostInsightsDashboardProps';
const CostInsightsDashboard: React.FunctionComponent<ICostInsightsDashboardProps> = (props) => {
//#region State
const [helper, setHelper] = React.useState<CostMngmtHelper>(null); //if helper change doesn't trigger refresh (it's an object), use key instead
const [isConfigValid, setIsConfigValid] = React.useState<boolean>(false);
const [costQuery, setCostQuery] = React.useState<string>(props.query);
const [expiry] = React.useState<CacheExpiration>(props.cacheDuration);// ?? moment().endOf('day').toDate());
const [showList, setShowList] = React.useState<boolean>(props.showList);
const [listStyle, setListStyle] = React.useState<number>(props.listStyle);
const [listPalette, setListPalette] = React.useState<ThemedPalette>(props.listPalette);
const [showChart, setShowChart] = React.useState<boolean>(props.showChart);
const [chartStyle, setChartStyle] = React.useState<number>(props.chartStyle);
const [chartPalette, setChartPalette] = React.useState<ThemedPalette>(props.chartPalette);
const [layoutSettings, setLayoutSettings] = React.useState<number>(props.layoutSettings);
//#endregion
//#region Methods
const configureCostManagementHelper = (config: ICostManagementConfig, aadHttpClientFactory: AadHttpClientFactory): void => {
if (config) {
setHelper(
new CostMngmtHelper(config,
{
cacheDuration: props.cacheDuration?? CacheExpiration.OneDay,
userLoginName: props.userLoginName,
},
aadHttpClientFactory)
);
}
else {
setHelper(null);
}
}
//#endregion
//#region Effects
React.useEffect(() => {
const config = {
scope: props.scope,
subscriptionId: props.subscriptionId,
resourceGroupName: props.resourceGroupName,
managementGroupId: props.managementGroupId
}
const isValid = CostMngmtQueryHelper.IsConfigValid(config);
setIsConfigValid(isValid);
configureCostManagementHelper(
isValid
? config
: null,
props.aadHttpClientFactory
);
}, [props.scope, props.subscriptionId, props.resourceGroupName, props.managementGroupId]);
React.useEffect(() => {
if (props.preset !== 100) {
setCostQuery(CostHelper.GetQueryById(Number(props.preset)).query);
}
}, [props.preset]);
//#endregion
//#region Events
const _onChangeTab = (key: string): void => {
props.onPivotItemChange(key);
}
const _onConfigureCostManagementScope = (config: ICostManagementConfig): void => {
const isValid = CostMngmtQueryHelper.IsConfigValid(config);
setIsConfigValid(isValid);
configureCostManagementHelper(
isValid
? config
: null,
props.aadHttpClientFactory);
props.onConfigureCostManagementScope(config); //save to WP Properties
}
const _onConfigureCostQuery = (preset: number, config: ICostManagementQuery): void => {
setCostQuery(config.query);
if (preset === 100) {
props.onConfigureCostQuery(preset, config) //save to WP properties
}
else {
props.onConfigureCostQuery(preset, { ...config, query: "" }) //save to WP properties
}
}
const _onConfigureListSettings = (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette): void => {
setShowList(showList);
setListStyle(listStyle);
setListPalette(listPalette)
props.onConfigureListSettings(showList, listStyle, listPalette);
}
const _onConfigureChartSettings = (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette): void => {
setShowChart(showChart);
setChartStyle(chartStyle);
setChartPalette(chartPalette)
props.onConfigureChartSettings(showChart, chartStyle, chartPalette);
}
const _onConfigureLayoutSettings = (layout: LayoutStyles): void => {
setLayoutSettings(layout);
props.onConfigureLayoutSettings(layout);
}
//#endregion
return (
<Stack tokens={stackTokens} styles={stackStylesMain}>
{/* Edit mode */}
{props.DisplayMode === DisplayMode.Edit &&
<DashboardConfiguration
{...props}
configType={ConfigType.CostManagement}
onPivotItemChange={_onChangeTab}
onConfigureCostManagementScope={_onConfigureCostManagementScope}
onConfigureQuery={_onConfigureCostQuery}
onConfigureListSettings={_onConfigureListSettings}
onConfigureChartSettings={_onConfigureChartSettings}
onConfigureLayoutSettings={_onConfigureLayoutSettings}
/>
}
{/* Read mode, needs config */}
{props.DisplayMode === DisplayMode.Read && (!isConfigValid || !costQuery) &&
<Placeholder iconName='Edit'
iconText={strings.Config_IconText}
description={stringsCommon.Config_Desc_ReadMode}
buttonLabel={stringsCommon.ConfigBtnLabel}
hideButton={props.DisplayMode === DisplayMode.Read}
/>
}
{isConfigValid && costQuery && (
<InsightsDashboard
{...props as IDashboardContextProps} //has all props not only the ones defined in IDashboardContextProps
helper={helper}
query={costQuery}
cacheExpiration={expiry}
showList={showList}
listStyle={listStyle}
listPalette={listPalette}
showChart={showChart}
chartStyle={chartStyle}
chartPalette={chartPalette}
layoutSettings={layoutSettings}
/>
)}
</Stack>
);
}
export default CostInsightsDashboard;

View File

@ -0,0 +1,14 @@
import { ThemedPalette } from "../../../common/ColorsHelper";
import { ICostManagementConfig, ICostManagementQuery, ICostManagementWebPartProps, IDashboardContextProps } from "../../../common/CommonProps";
import { ChartStyles, LayoutStyles, ListStyles } from "../../../common/DashboardHelper";
export interface ICostInsightsDashboardProps extends ICostManagementWebPartProps, IDashboardContextProps {
onPivotItemChange: (key: string) => void;
onConfigureCostManagementScope: (config: ICostManagementConfig) => void;
onConfigureCostQuery: (preset: number, config: ICostManagementQuery) => void;
onConfigureTimePicker: (showTimePicker: boolean) => void;
onConfigureListSettings: (showList: boolean, listStyle: ListStyles, listPalette: ThemedPalette) => void;
onConfigureChartSettings?: (showChart: boolean, chartStyle: ChartStyles, chartPalette: ThemedPalette) => void,
onConfigureLayoutSettings: (lookLayout: LayoutStyles) => void;
}

View File

@ -0,0 +1,17 @@
// eslint-disable-next-line no-undef
define([], function() {
return {
GroupNameCostInsights: "Cost Insights",//-
GroupNameCostQuery: "Cost Query",//-
ScopeLabel: "Scope", //-
SubIdLabel: "Subscription Id", //-
ResourceGroupLabel: "Resource Group Name", //-
ManagementGroupLabel: "Management Group Id", //-
CostQueryLabel: "Json body",//-
CostQueryDocs: "Cost Management API overview",//-
Config_IconText: 'Cost Insights Dashboard Configuration', //-
}
});

View File

@ -0,0 +1,18 @@
declare interface ICostInsightsWebPartStrings {
GroupNameCostInsights: string;
GroupNameCostQuery: string;
ScopeLabel: string;
SubIdLabel: string;
ResourceGroupLabel: string;
ManagementGroupLabel: string;
CostQueryLabel: string;
CostQueryDocs: string;
Config_IconText: string;
}
declare module 'CostInsightsWebPartStrings' {
const strings: ICostInsightsWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Some files were not shown because too many files have changed in this diff Show More