Merge pull request #4002 from NishkalankBezawada/react-flow-dashboard

This commit is contained in:
Hugo Bernier 2023-08-09 23:43:25 -04:00 committed by GitHub
commit 7966ddb5e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 69915 additions and 0 deletions

View File

@ -0,0 +1,354 @@
const { off } = require('gulp');
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': [
0,
{
'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': 0,
// 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/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': 0,
// 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: {}
}
]
};

39
samples/react-flow-dashboard/.gitignore vendored Normal file
View File

@ -0,0 +1,39 @@
# 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
# .CER Certificates
*.cer
# .PEM Certificates
*.pem

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": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "16.18.1",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.9.1"
},
"version": "1.17.4",
"libraryName": "react-flow-dashboard",
"libraryId": "a55dc82b-3833-4250-9563-c6ab960ec7ae",
"environment": "spo",
"packageManager": "npm",
"solutionName": "React-Flow-Dashboard",
"solutionShortDescription": "React-Flow-Dashboard description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,90 @@
# Flow Dashboard
## Summary
This web part demonstrates displaying the list of flows and perform some basic actions on the flow.
# Flow Dashboard
![](./assets/Dashboard.gif)
# Flow run history
![](./assets/Flowrunhistory.gif)
# Enabling stopped or suspended flows
![](./assets/Enablingflows.gif)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
![SPFx 1.17.4](https://img.shields.io/badge/SPFx-1.17.4-green.svg)
![Node.js v16 | v14](https://img.shields.io/badge/Node.js-v16%20%7C%20v14-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 (with permissions)](https://img.shields.io/badge/Hosted%20Workbench-Compatible-yellow.svg "Requires API permissions")
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Prerequisites
This web part uses *Microsoft Graph* API and *Microsoft Flow Service* API. You need to approve the API request after deploying the package.
- Microsoft Graph
- `User.ReadBasic.All`
- Microsoft Flow Service
- `Flows.Read.All`
If the problem still persists,
- go to `App Registrations`
- find `SharePoint Online Client Extensibility Web Application Principal`
- make sure you have added the above permission levels
![](./assets/APIPermissions.png)
## Minimal Path to Awesome
- Clone this repository (or [download this solution as a .ZIP file](https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-flow-dashboard) then unzip it)
- From your command line, change your current directory to the directory containing this sample (`react-flow-dashboard`, located under `samples`)
- in the command-line run:
- `npm install`
- `gulp serve`
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit https://aka.ms/spfx-devcontainer for further instructions.
## Contributors
* [Nishkalank Bezawada](https://github.com/NishkalankBezawada)
## Version history
Version|Date|Comments
-------|----|--------
1.0|August 3, 2023|Initial release
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-flow-dashboard%22) to see if anybody else is having the same issues.
You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-flow-dashboard) and see what the community is saying.
If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-flow-dashboard&template=bug-report.yml&sample=react-flow-dashboard&authors=@NishkalankBezawada&title=react-flow-dashboard%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-flow-dashboard&template=question.yml&sample=react-flow-dashboard&authors=@NishkalankBezawada&title=react-flow-dashboard%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-flow-dashboard&template=suggestion.yml&sample=react-flow-dashboard&authors=@NishkalankBezawada&title=react-flow-dashboard%20-%20).
## 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.**
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/react-flow-dashboard" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 MiB

View File

@ -0,0 +1,60 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-flow-dashboard",
"source": "pnp",
"title": "Flow Dashboard",
"shortDescription": "This web part demonstrates displaying the list of flows in different environments, ability to re-enable flows which are stopped or suspended, and the flow run history of the selected flow.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-flow-dashboard",
"longDescription": [
"This web part demonstrates displaying the list of flows in different environments, ability to re-enable flows which are stopped or suspended, and the flow run history of the selected flow."
],
"creationDateTime": "2023-08-03",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.17.4"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-flow-dashboard/assets/Dashboard.gif",
"alt": "Web Part Preview"
},
{
"type": "image",
"order": 101,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-flow-dashboard/assets/Flowrunhistory.gif",
"alt": "Flow run history preview"
},
{
"type": "image",
"order": 102,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-flow-dashboard/assets/Enablingflows.gif",
"alt": "Enabling flows Preview"
}
],
"authors": [
{
"gitHubAccount": "NishkalankBezawada",
"pictureUrl": "https://github.com/NishkalankBezawada.png",
"name": "NIshkalank Bezawada"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"react-flow-dashboard-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/reactFlowDashboard/ReactFlowDashboardWebPart.js",
"manifest": "./src/webparts/reactFlowDashboard/ReactFlowDashboardWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ReactFlowDashboardWebPartStrings": "lib/webparts/reactFlowDashboard/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/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": "react-flow-dashboard",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,50 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-flow-dashboard-client-side-solution",
"id": "a55dc82b-3833-4250-9563-c6ab960ec7ae",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "Nishkalank Bezawada",
"websiteUrl": "https://github.com/NishkalankBezawada",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.17.4"
},
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "User.ReadBasic.All"
},
{
"resource": "Microsoft Flow Service",
"scope": "Flows.Read.All"
}
],
"metadata": {
"shortDescription": {
"default": "React-Flow-Dashboard description"
},
"longDescription": {
"default": "React-Flow-Dashboard description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-flow-dashboard Feature",
"description": "The feature that activates elements of the react-flow-dashboard solution.",
"id": "6302f19a-1bd1-4021-8c94-6fe9ce9f3410",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-flow-dashboard.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/15/workbench.aspx?debugManifestsFile=https://localhost:4321/temp/manifests.js&loadSPFX=true"
}

View File

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

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'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
{
"name": "react-flow-dashboard",
"version": "0.0.1",
"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": {
"@microsoft/sp-component-base": "1.17.4",
"@microsoft/sp-core-library": "1.17.4",
"@microsoft/sp-lodash-subset": "1.17.4",
"@microsoft/sp-office-ui-fabric-core": "1.17.4",
"@microsoft/sp-property-pane": "1.17.4",
"@microsoft/sp-webpart-base": "1.17.4",
"@pnp/spfx-controls-react": "^3.15.0",
"@pnp/spfx-property-controls": "^3.14.0",
"jwt-decode": "^3.1.2",
"office-ui-fabric-react": "^7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.17.4",
"@microsoft/eslint-plugin-spfx": "1.17.4",
"@microsoft/rush-stack-compiler-4.5": "0.5.0",
"@microsoft/sp-build-web": "1.17.4",
"@microsoft/sp-module-interfaces": "1.17.4",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "194724cf-7350-42d0-9bab-b14ff7987022",
"alias": "ReactFlowDashboardWebPart",
"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", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "react-flow-dashboard" },
"description": { "default": "react-flow-dashboard description" },
"officeFabricIconFontName": "PowerAutomateLogo",
"properties": {
"description": "react-flow-dashboard"
}
}]
}

View File

@ -0,0 +1,96 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import { IPropertyPaneConfiguration } from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'ReactFlowDashboardWebPartStrings';
import ReactFlowDashboard from '../reactFlowDashboard/components/Dashboard/ReactFlowDashboard';
import { IReactFlowDashboardProps } from './components/Dashboard/IReactFlowDashboardProps';
import { PropertyFieldMultiSelect } from '@pnp/spfx-property-controls';
import FlowService from './services/FlowService';
import GraphService from './services/GraphService';
import { AadTokenProvider } from '@microsoft/sp-http';
export interface IReactFlowDashboardWebPartProps {
WebpartTitle: string;
environments: string[];
}
export default class ReactFlowDashboardWebPart extends BaseClientSideWebPart<IReactFlowDashboardWebPartProps> {
private flowService: FlowService;
private graphService: GraphService;
private environments: string[];
private provider : AadTokenProvider;
public render(): void {
const element: React.ReactElement<IReactFlowDashboardProps> = React.createElement(
ReactFlowDashboard,
{
displayMode: this.displayMode,
flowService : this.flowService,
graphService : this.graphService,
provider : this.provider,
context : this.context,
webpartTitle: this.properties.WebpartTitle,
environments: this.properties.environments,
setWebPartTitle : (value: string) => {
this.properties.WebpartTitle = value;
}
}
);
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
this.flowService = await FlowService.create(this.context);
this.graphService = await GraphService.create(this.context);
this.environments = await this.flowService.getEnvironments().then((values) => values.map((value) => value.name));
this.provider = await this.context.aadTokenProviderFactory.getTokenProvider();
if (!this.properties.environments) {
this.properties.environments = this.environments;
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.Groupdescription,
groupFields: [
PropertyFieldMultiSelect(
'environments',
{
key: 'environments',
label: strings.EnvironmentLabel,
options: this.environments.map((value) => ({
key: value,
text: value
})),
selectedKeys: this.properties.environments
}
)
]
}
]
}
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,35 @@
import { DisplayMode } from '@microsoft/sp-core-library';
import FlowService from '../../services/FlowService';
import { WebPartContext } from "@microsoft/sp-webpart-base";
import GraphService from '../../services/GraphService';
import { AadTokenProvider } from '@microsoft/sp-http';
export interface IReactFlowDashboardProps {
displayMode: DisplayMode;
flowService: FlowService;
graphService: GraphService;
provider : AadTokenProvider;
context : WebPartContext;
webpartTitle: string;
environments: string[];
setWebPartTitle: (value: string) => void;
}
export interface Items{
id: string;
environment : string;
flowName : string;
flowDisplayName : string;
flowState : string;
flowAuthor : string;
flowTriggerUrl : string;
}
export interface IFlow {
name: string;
id: string;
type: string;
properties: any;
}

View File

@ -0,0 +1,20 @@
import { IColumn,IGroup } from 'office-ui-fabric-react';
import {MessageBarType } from 'office-ui-fabric-react';
import { Items } from './IReactFlowDashboardProps';
import { IFlow } from './IReactFlowDashboardProps';
import { IFlowRun } from '../RunHistory/IReactFlowRunHistoryProps';
export interface IReactFlowDashboardState{
flowItems : Items[];
columns: IColumn[];
isLoaded : boolean;
groups : IGroup[];
flowEnabled? : boolean;
flowEnabledMessage ? : string;
flowEnabledMessageBarType? : MessageBarType;
showFlowEnabledMessage ? : boolean;
isSynced ? : boolean;
syncedTime? :string;
runhistoryItems? : IFlow[];
flowrunItems? : IFlowRun[];
openPanel : boolean;
}

View File

@ -0,0 +1,31 @@
@import '~@fluentui/react/dist/sass/References.scss';
.reactFlowDashboard {
width: 100%;
.notifications{
margin: 0 0 20px 0;
}
.syncbtn{
padding-left: 33em;
padding-top: 1em;
display : flex;
}
.refresh{
padding-left: 34em;
}
}
.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,326 @@
import * as React from 'react';
import styles from './ReactFlowDashboard.module.scss';
import * as strings from 'ReactFlowDashboardWebPartStrings';
import { IReactFlowDashboardProps , Items} from './IReactFlowDashboardProps';
import { IReactFlowDashboardState } from './IReactFlowDashboardState';
import { IFlowRun } from '../RunHistory/IReactFlowRunHistoryProps';
import { WebPartTitle } from '@pnp/spfx-controls-react';
import {
MessageBar, MessageBarType, IconButton,
IIconProps, Label, TooltipHost,
DetailsList, DetailsListLayoutMode, SelectionMode,
IColumn, mergeStyles, Spinner,
ProgressIndicator,ITooltipHostStyles, Link
} from 'office-ui-fabric-react';
import FlowService from '../../services/FlowService';
import GraphService from '../../services/GraphService';
import { AadTokenProvider } from '@microsoft/sp-http-base';
import FlowRunHistoryPanel from '../RunHistory/index';
const emojiIcon: IIconProps = { iconName: 'Sync' };
const calloutProps = { gapSpace: 0 };
const hostStyles: Partial<ITooltipHostStyles> = { root: { display: 'inline-block' } };
export default class ReactFlowDashboard extends React.Component<IReactFlowDashboardProps, IReactFlowDashboardState> {
private _flowService: FlowService;
constructor(props: IReactFlowDashboardProps | Readonly<IReactFlowDashboardProps>){
super(props);
this._renderItemColumn = this._renderItemColumn.bind(this);
this._flowService = this.props.flowService;
const columns : IColumn[] = [
{
key: 'id',
name: 'Display name',
fieldName: 'flowDisplayName',
minWidth: 100,
maxWidth: 125,
isRowHeader: true,
isResizable: true,
isSorted: true,
isSortedDescending: true,
sortAscendingAriaLabel: 'Sorted A to Z',
sortDescendingAriaLabel: 'Sorted Z to A',
onColumnClick: this._onColumnClick,
data: 'string',
isPadded: true,
},
{
key: 'id',
name: 'Author',
fieldName: 'flowAuthor',
minWidth: 100,
maxWidth: 125,
isRowHeader: true,
isResizable: true,
isSorted: false,
isSortedDescending: false,
sortAscendingAriaLabel: 'Sorted A to Z',
sortDescendingAriaLabel: 'Sorted Z to A',
onColumnClick: this._onColumnClick,
data: 'string',
isPadded: true,
},
{
key: 'id',
name: 'Name',
fieldName: 'flowName',
minWidth: 50,
maxWidth: 125,
isRowHeader: true,
isResizable: true,
isSorted: false,
isSortedDescending: false,
sortAscendingAriaLabel: 'Sorted A to Z',
sortDescendingAriaLabel: 'Sorted Z to A',
onColumnClick: this._onColumnClick,
data: 'string',
isPadded: true,
},
{
key: 'id',
name: 'Status',
fieldName: 'flowState',
minWidth: 50,
maxWidth: 70,
isResizable: true,
isSorted: false,
isSortedDescending: false,
onColumnClick: this._onColumnClick,
data: 'sting',
isPadded: true,
},
{
key: 'id',
name: 'Run history',
fieldName: 'flowHistory',
minWidth: 70,
maxWidth: 100,
isResizable: true,
isSorted: false,
isSortedDescending: false,
onColumnClick: this._onColumnClick,
data: 'sting',
isPadded: true,
}
];
this.state = {
flowItems : [],
columns : columns,
isLoaded : true,
groups: [],
showFlowEnabledMessage : false,
isSynced : true,
openPanel: false
};
}
public async componentDidMount(){
const {environments, flowService, graphService, provider} = this.props;
await this.loadFlowDetails(environments, flowService, graphService, provider);
}
public async componentDidUpdate(prevProps: Readonly<IReactFlowDashboardProps>, prevState: IReactFlowDashboardState, snapshot?: any){
const { environments,flowService, graphService, provider} = this.props;
prevProps.environments !== environments && await this.loadFlowDetails(environments, flowService, graphService, provider);
prevState.isSynced !== this.state.isSynced && ! this.state.isSynced && await this.loadFlowDetails(environments, flowService, graphService, provider);
}
public async loadFlowDetails(environments: string[], flowService:FlowService, graphService:GraphService, provider: AadTokenProvider){
const data : Items[] = await flowService.getFlowDetails(environments, flowService, graphService, provider);
const timeNow = new Date().toLocaleString();
const group = this.getGroupInfo(data);
this.setState({flowItems : data, isLoaded : data.length > 0 ? false : true, groups : group,isSynced:true, syncedTime:timeNow});
}
public getGroupInfo(data:Items[]){
const groupsMap: { [environment: string]: number } = {}; // To keep track of environment and its count
const groups: { key: string, name: string, startIndex: number, count: number }[] = [];
data.forEach((item, index) => {
const environment = item.environment;
if (groupsMap[environment] === undefined) {
// If the environment is not in the groupsMap, create a new entry
groupsMap[environment] = groups.length;
groups.push({
key: environment,
name: environment,
startIndex: index,
count: 1
});
} else {
// If the environment is already in the groupsMap, increment the count
const groupIndex = groupsMap[environment];
groups[groupIndex].count++;
}
});
return groups;
}
public onButtonClick = async (item: any): Promise<void> => {
this.setState({flowEnabled : true});
const response = await this._flowService.restartFlow(item.environment, item.flowName);
if (response && response.success) {
console.log('Flow restarted successfully.');
this.setState(
{
flowEnabled : false,
flowEnabledMessage : `Flow restarted successfully ${response.data} .`,
flowEnabledMessageBarType:MessageBarType.success,
showFlowEnabledMessage : true
}
);
} else {
console.error('Flow restart failed.');
console.error('Error message:', response?.error || 'Unknown error');
this.setState(
{
flowEnabled : false,
flowEnabledMessage : `Flow restarted successfully ${response?.error} .`,
flowEnabledMessageBarType:MessageBarType.error,
showFlowEnabledMessage : true
}
);
}
};
public getFlowRunHistory = async (item: any): Promise<void> => {
const response = await this._flowService.fetchFlowRunHistory(item.environment, item.flowName);
const flowRunHistory : IFlowRun[] = [];
response.length > 0 && response.forEach(e => {
flowRunHistory.push({
runName : e.name,
startTime : e.properties.startTime,
endTime : e.properties.endTime,
status : e.properties.status,
triggername : e.properties.trigger.name
});
});
this.setState({runhistoryItems:response ? response : [], flowrunItems:flowRunHistory, openPanel:true});
}
public _onSync(){
this.setState({isSynced:false, showFlowEnabledMessage : false});
}
public render(): React.ReactElement<IReactFlowDashboardProps> {
const {environments, displayMode, webpartTitle, setWebPartTitle} = this.props;
const {flowItems, columns, isLoaded, groups, flowEnabled, showFlowEnabledMessage, flowEnabledMessageBarType, flowEnabledMessage, syncedTime, flowrunItems, openPanel} = this.state;
const flowEnabledStatus : JSX.Element = flowEnabled ? <div className={styles.notifications}><ProgressIndicator label="Restarting flow" /></div> : <div/>;
const _showFlowEnabledMessage : JSX.Element = showFlowEnabledMessage ? <div className={styles.notifications}><MessageBar messageBarType={flowEnabledMessageBarType}>{flowEnabledMessage}<IconButton className={styles.refresh} iconProps={emojiIcon} title="Refresh" ariaLabel="Refresh" disabled={false} checked={false} onClick={this._onSync.bind(this)}/></MessageBar></div> : <div/>;
const showFlowHistory : JSX.Element = openPanel ? <div><FlowRunHistoryPanel items={flowrunItems|| []} isOpen={openPanel} onDismiss={e => this.setState({flowrunItems:[], openPanel:false})}/> </div>: <div/>
return (
<div className={styles.reactFlowDashboard}>
{
environments.length ?
(
<React.Fragment>
{flowEnabledStatus}
{_showFlowEnabledMessage}
{showFlowHistory}
<WebPartTitle
displayMode={displayMode}
title={webpartTitle}
updateProperty={setWebPartTitle} />
<div className={styles.syncbtn}>
<Label>Last Updated : {syncedTime}</Label>
<TooltipHost
content="Refresh"
id={"SyncToolTipID"}
calloutProps={calloutProps}
styles={hostStyles}
>
<IconButton iconProps={emojiIcon} title="Refresh" ariaLabel="Refresh" disabled={false} checked={false} onClick={this._onSync.bind(this)}/>
</TooltipHost>
</div>
{isLoaded ? (<Spinner label="Loading" ariaLive="assertive" labelPosition="bottom" />) : (
<DetailsList
items={flowItems}
groups={groups}
columns={columns}
onRenderItemColumn={this._renderItemColumn}
selectionMode={SelectionMode.none}
setKey="none"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
/>
)}
</React.Fragment>
) :
(
<MessageBar messageBarType={MessageBarType.error}>
{strings.EnvironmentEmptyError}
</MessageBar>
)
}
</div>
);
}
private _onColumnClick = (ev: React.MouseEvent<HTMLElement>, column: IColumn): void => {
const { columns, flowItems } = this.state;
const newColumns: IColumn[] = columns.slice();
const currColumn: IColumn = newColumns.filter(currCol => column.key === currCol.key)[0];
newColumns.forEach((newCol: IColumn) => {
if (newCol === currColumn) {
currColumn.isSortedDescending = !currColumn.isSortedDescending;
currColumn.isSorted = true;
} else {
newCol.isSorted = false;
newCol.isSortedDescending = true;
}
});
const newItems = this._copyAndSort(flowItems, currColumn.fieldName!, currColumn.isSortedDescending); // eslint-disable-line @typescript-eslint/no-non-null-assertion
this.setState({
columns: newColumns,
flowItems: newItems
});
}
private _copyAndSort<T>(items: T[], columnKey: string, isSortedDescending?: boolean): T[] {
const key = columnKey as keyof T;
return items.slice(0).sort((a: T, b: T) => ((isSortedDescending ? a[key] < b[key] : a[key] > b[key]) ? 1 : -1));
}
public _renderItemColumn(item : Items, index: number, column: IColumn) {
const fieldContent = item[column.fieldName as keyof Items] as string;
let fieldColor = "green";
let showLink : boolean = false;
switch (column.fieldName) {
case 'flowState':
fieldContent.toLocaleLowerCase() === "stopped" || fieldContent.toLocaleLowerCase() === "suspended" ? fieldColor = "red": fieldColor;
fieldContent.toLocaleLowerCase() === "stopped" || fieldContent.toLocaleLowerCase() === "suspended" ? showLink = true: showLink;
return (
showLink ?
(<div>
<span data-selection-disabled={true} className={mergeStyles({ color: fieldColor, height: '100%', display: 'block' })}>
{fieldContent}
</span>
<div>
<Link onClick={()=> this.onButtonClick(item) }>Restart flow</Link>
</div>
</div> ):
(
<span data-selection-disabled={true} className={mergeStyles({ color: fieldColor, height: '100%', display: 'block' })}>
{fieldContent}
</span>
)
);
case 'flowHistory':
return(
<div>
<Link onClick={()=> this.getFlowRunHistory(item) }>Get flow run history</Link>
</div>
);
default:
return <span>{fieldContent}</span>;
}
}
}

View File

@ -0,0 +1,14 @@
export interface IFlowRun {
runName: string;
startTime: string;
endTime: string;
status: string;
triggername : string;
}
export interface IReactFlowRunHistoryProps {
items : IFlowRun[];
isOpen: boolean;
onDismiss: (e: any) => void;
}

View File

@ -0,0 +1,40 @@
import * as React from 'react';
import { Panel, PanelType } from 'office-ui-fabric-react';
import { IReactFlowRunHistoryProps } from './IReactFlowRunHistoryProps';
export default class FlowRunHistoryPanel extends React.Component<IReactFlowRunHistoryProps>{
constructor(props: IReactFlowRunHistoryProps) {
super(props);
}
public render(): React.ReactElement<IReactFlowRunHistoryProps>{
const {items, isOpen} = this.props;
return(
<Panel
type={PanelType.medium}
onDismiss={(ev)=> this.props.onDismiss(ev)}
isOpen={isOpen}
headerText="Flow Run History"
isBlocking={false}
>
<div>
{items.map((i) => (
<div key={i.runName}>
<p>Run ID: {i.runName}</p>
<p>Start Time: {i.startTime}</p>
<p>End Time: {i.endTime}</p>
<p>Status: {i.status}</p>
<p>Trigger: {i.triggername}</p>
<hr />
</div>
))}
</div>
</Panel>
)
}
public _onPanelDismiss(ev:any){
this.props.onDismiss(ev);
}
}

View File

@ -0,0 +1,8 @@
define([], function() {
return {
"PropertyPaneDescription": "Flow Dashboard",
"Groupdescription" : "Select environment from the dropdown",
"EnvironmentLabel": "Environment",
"EnvironmentEmptyError": "The environment is not selected. Please edit the web part and select the environment.",
}
});

View File

@ -0,0 +1,11 @@
declare interface IReactFlowDashboardWebPartStrings {
PropertyPaneDescription: string;
Groupdescription: string;
EnvironmentLabel: string;
EnvironmentEmptyError: string;
}
declare module 'ReactFlowDashboardWebPartStrings' {
const strings: IReactFlowDashboardWebPartStrings;
export = strings;
}

View File

@ -0,0 +1,150 @@
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { AadHttpClient, IHttpClientOptions } from '@microsoft/sp-http';
import GraphService from './GraphService';
import { AadTokenProvider } from '@microsoft/sp-http-base';
import { Items } from '../components/Dashboard/IReactFlowDashboardProps';
interface IEnvironment {
name: string;
location: string;
id: string;
type: string;
properties: any;
}
interface IFlow {
name: string;
id: string;
type: string;
properties: any;
}
export default class FlowService {
private static readonly endpoint: string = 'https://service.flow.microsoft.com';
private static readonly graphEndPoint : string = "https://graph.microsoft.com/";
public static async create(context: WebPartContext): Promise<FlowService> {
return new FlowService(await context.aadHttpClientFactory.getClient(FlowService.endpoint));
}
private aadHttpClient: AadHttpClient;
private constructor(aadHttpClient: AadHttpClient) {
this.aadHttpClient = aadHttpClient;
}
public async getEnvironments(): Promise<IEnvironment[]> {
const response = await this.aadHttpClient.get(
'https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments' +
'?api-version=2016-11-01',
AadHttpClient.configurations.v1);
const json = await response.json();
if (json.error) {
throw new Error(json.error);
}
return json.value as IEnvironment[];
}
public async getFlows(environment: string): Promise<IFlow[]> {
const response = await this.aadHttpClient.get(
`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments/${environment}/flows` +
'?api-version=2016-11-01',
AadHttpClient.configurations.v1);
const json = await response.json();
if (json.error) {
throw new Error(json.error);
}
return json.value as IFlow[];
}
public async getFlow(id: string): Promise<IFlow> {
const response = await this.aadHttpClient.get(
`https://api.flow.microsoft.com/${id}` +
'?api-version=2016-11-01',
AadHttpClient.configurations.v1);
const json = await response.json();
if (json.error) {
throw new Error(json.error);
}
return json as IFlow;
}
public async getFlowDetails(environments: string[], flowService:FlowService, graphService:GraphService, provider: AadTokenProvider):Promise<Items[]>{
const token: any = await provider.getToken(FlowService.graphEndPoint);
const data : any[] = []; // eslint-disable-next-line @typescript-eslint/no-explicit-any
for(const environment of environments){
const flows = await flowService.getFlows(environment);
await Promise.all(flows.map(async (item) => {
const flow = await flowService.getFlow(item.id);
const author = await graphService.getUser(flow.properties.creator.objectId, token);
data.push({
id: item.id,
environment : flow.properties.environment.name,
flowName : flow.name,
flowDisplayName: flow.properties.displayName,
flowState : flow.properties.state,
flowAuthor : author.displayName,
flowTriggerUrl : flow.properties.flowTriggerUri ? flow.properties.flowTriggerUri : `https://flow.microsoft.com/manage/environments/${flow.properties.environment.name}/flows/${flow.name}/details`,
});
}));
}
return data;
}
public async restartFlow(environment: string, flowName: string) {
const requestHeaders: Headers = new Headers();
requestHeaders.append('accept', 'application/json');
const httpClientOptions: IHttpClientOptions = {
headers: requestHeaders
};
try {
const response = await this.aadHttpClient.post(
`https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments/${environment}/flows/${flowName}` +
'/start?api-version=2016-11-01',
AadHttpClient.configurations.v1,
httpClientOptions
);
// Check if the response status indicates success (2xx status codes)
if (response.ok) {
try {
// Try to parse the JSON response
if(response.status >= 200 && response.status < 300){
return { success: true, data: response.status };
}
} catch (jsonError) {
// If parsing as JSON fails, handle non-JSON response here
const textResponse = await response.text();
console.warn('Non-JSON response:', textResponse);
return { success: false, error: 'Non-JSON response received' };
}
} else {
// If the response status is not in the 2xx range, throw an error or handle it accordingly.
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
} catch (error) {
// Handle any exceptions that may occur during the request or parsing the response.
console.error(error);
return { success: false, error: error.message };
}
}
public async fetchFlowRunHistory(environment : string, flowId:string): Promise<any[]>{
const fetchFlowRunHistoryEndpoint = `https://api.flow.microsoft.com/providers/Microsoft.ProcessSimple/environments/${environment}/flows/${flowId}/runs?api-version=2016-11-01`;
const requestHeaders: Headers = new Headers();
requestHeaders.append('accept', 'application/json;odata.metadata=none');
const httpClientOptions: IHttpClientOptions = {
headers: requestHeaders
};
const response= await this.aadHttpClient.get(fetchFlowRunHistoryEndpoint, AadHttpClient.configurations.v1,httpClientOptions);
const flowRunsData = await response.json();
return flowRunsData.value as IFlow[];
}
}

View File

@ -0,0 +1,41 @@
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { AadHttpClient } from '@microsoft/sp-http';
interface IUser {
id: string;
displayName: string;
}
export default class GraphService {
private static readonly endpoint: string = 'https://graph.microsoft.com';
public static async create(context: WebPartContext): Promise<GraphService> {
return new GraphService(await context.aadHttpClientFactory.getClient(GraphService.endpoint));
}
private httpClient: AadHttpClient;
private constructor(httpClient: AadHttpClient) {
this.httpClient = httpClient;
}
public async getUser(id: string, token : any): Promise<IUser> {
const response = await this.httpClient.get(
`https://graph.microsoft.com/v1.0/users/${id}`,
AadHttpClient.configurations.v1,
{
headers: {
authorization: `Bearer ${token}`,
accept: "application/json"
},
}
);
const json = await response.json();
if (json.error) {
throw new Error(json.error);
}
return json as IUser;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

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