Merge pull request #4019 from NishkalankBezawada/main

This commit is contained in:
Hugo Bernier 2023-09-12 22:09:15 -04:00 committed by GitHub
commit d48968c539
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 68099 additions and 0 deletions

View File

@ -0,0 +1,354 @@
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': [
'off',
{
'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': 'off',
// 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': 'off',
// 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': [
'off',
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 'off',
// 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-case-declarations':'off',
'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-empty-function' : 'off',
'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': 'off',
// 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': 'off',
// 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': 'off',
// 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': 'off',
// 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: {}
}
]
};

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,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-manage-hublevel-list-subscriptions",
"libraryId": "e2c0325f-7b70-4738-b4cf-568be2bdf627",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-manage-hublevel-list-subscriptions",
"solutionShortDescription": "react-manage-hublevel-list-subscriptions description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,88 @@
# Subscription Manager
## Summary
This sample web part demonstrates managing the list subscriptions (sharepoint webhooks) and action to renew the webhook expiration date using Rest calls. The webpart is to be added at Hubsite level or the sites associated to the hubsite, on selection of the site, it will list out the lists available. On list/library selection, the available subscriptions is displayed. Depending upon the expiry date of the subscription, 'Renew subscription' action can be performed. The subscription (webhook expiry renewal date) renewal date is set to 179 days, as the default days are 180.
# Subscription Manager
![](./assets/SubscriptionsDashboard.gif)
# Configuring subscription manager webpart
![](./assets/ConfiguringWebpart.gif)
# Renewing webhook subscriptions
![](./assets/RenewingSubscriptions.gif)
# Configuration error while adding the webpart to Non-Hub related sites
![](./assets/ConfiguringWebpart-NonHubrelatedSite.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 requires access to lists and libraries to perform renewing the webhook subscription
## References
*[Get Subscription](https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/lists/get-subscription)
*[Update Subscription](https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/lists/update-subscription)
## 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-manage-hublevel-subscriptions) then unzip it)
- From your command line, change your current directory to the directory containing this sample (`react-manage-hublevel-subscriptions`, 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|September 9, 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-manage-hublevel-subscriptions%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-manage-hublevel-subscriptions) 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-manage-hublevel-subscriptions&template=bug-report.yml&sample=react-manage-hublevel-subscriptions&authors=@NishkalankBezawada&title=react-manage-hublevel-subscriptions%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-manage-hublevel-subscriptions&template=question.yml&sample=react-manage-hublevel-subscriptions&authors=@NishkalankBezawada&title=react-manage-hublevel-subscriptions%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-manage-hublevel-subscriptions&template=suggestion.yml&sample=react-manage-hublevel-subscriptions&authors=@NishkalankBezawada&title=react-manage-hublevel-subscriptions%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-manage-hublevel-subscriptions" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 MiB

View File

@ -0,0 +1,81 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-manage-hublevel-subscriptions",
"source": "pnp",
"title": "React-Manage-Subscriptions",
"shortDescription": "This sample web part demonstrates managing the list subscriptions (sharepoint webhooks) and action to renew the webhook expiration date using Rest calls.",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-manage-hublevel-subscriptions",
"longDescription": [
"This sample web part demonstrates managing the list subscriptions (sharepoint webhooks) and action to renew the webhook expiration date using Rest calls. The webpart is to be added at Hubsite level or the sites associated to the hubsite, on selection of the site, it will list out the lists available. On list/library selection, the available subscriptions is displayed. Depending upon the expiry date of the subscription, 'Renew subscription' action can be performed. The subscription (webhook expiry renewal date) renewal date is set to 179 days, as the default days are 180. "
],
"creationDateTime": "2023-09-01",
"updateDateTime": "2023-09-01",
"products": [
"SharePoint",
"WebHooks",
"Subscriptions",
"Update Subscriptions",
"Get Subscriptions"
],
"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-manage-hublevel-subscriptions/assets/SubscriptionsDashboard.gif",
"alt": "Subscription Manager"
},
{
"type": "image",
"order": 101,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-manage-hublevel-subscriptions/assets/ConfiguringWebpart.gif",
"alt": "Configuring subscription manager webpart"
},
{
"type": "image",
"order": 102,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-manage-hublevel-subscriptions/assets/RenewingSubscriptions.gif",
"alt": "Renewing webhook subscriptions"
},
{
"type": "image",
"order": 103,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-manage-hublevel-subscriptions/assets/ConfiguringWebpart-NonHubrelatedSite.gif",
"alt": "Configuration error while adding the webpart to Non-Hub related sites"
}
],
"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"
},
{
"name": "Get Subscription",
"description": "Get SharePoint webhook subscriptions",
"url": "https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/lists/get-subscription"
},
{
"name": "Update Subscription",
"description": "Update SharePoint webhook subscriptions",
"url": "https://learn.microsoft.com/en-us/sharepoint/dev/apis/webhooks/lists/update-subscription"
}
]
}
]

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"react-manage-hublevel-list-subscriptions-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/reactManageHublevelSubscriptions/ReactManageHublevelSubscriptionsWebPart.js",
"manifest": "./src/webparts/reactManageHublevelSubscriptions/ReactManageHublevelSubscriptionsWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ReactManageHublevelSubscriptionsWebPartStrings": "lib/webparts/reactManageHublevelSubscriptions/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-manage-hublevel-list-subscriptions",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,40 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-manage-hublevel-list-subscriptions-client-side-solution",
"id": "e2c0325f-7b70-4738-b4cf-568be2bdf627",
"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"
},
"metadata": {
"shortDescription": {
"default": "react-manage-hublevel-list-subscriptions description"
},
"longDescription": {
"default": "react-manage-hublevel-list-subscriptions description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-manage-hublevel-list-subscriptions Feature",
"description": "The feature that activates elements of the react-manage-hublevel-list-subscriptions solution.",
"id": "668cceeb-581c-4f11-b14d-2510726c7f2a",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-manage-hublevel-list-subscriptions.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://{tenantDomain}/_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 -->"
}

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,48 @@
{
"name": "react-manage-hublevel-list-subscriptions",
"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": {
"@fluentui/react": "^7.199.1",
"@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/graph": "^3.17.0",
"@pnp/logging": "^3.17.0",
"@pnp/queryable": "^3.17.0",
"@pnp/sp": "^3.17.0",
"@pnp/spfx-controls-react": "^3.15.0",
"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,39 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
// import pnp, pnp logging system, and any other selective imports needed
import { spfi, SPFI, SPFx } from "@pnp/sp";
import { GraphFI, graphfi, SPFx as graphSPFx } from "@pnp/graph";
import { LogLevel, PnPLogging } from "@pnp/logging";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/items/get-all";
import "@pnp/sp/items/list";
import "@pnp/sp/fields";
import "@pnp/sp/views";
import "@pnp/sp/attachments";
import "@pnp/sp/site-users/web";
import "@pnp/sp/files";
import "@pnp/sp/folders";
import "@pnp/sp/hubsites";
import "@pnp/sp/batching";
//eslint-disable-next-line no-var
var _sp: SPFI;
//eslint-disable-next-line no-var
var _graph: GraphFI;
export const getSP = (context?: WebPartContext): SPFI => {
//eslint-disable-next-line eqeqeq
if (context != null) {
_sp = spfi().using(SPFx(context)).using(PnPLogging(LogLevel.Warning));
}
return _sp;
};
export const getGraph = (context?: WebPartContext): GraphFI => {
if(!!context){
_graph = graphfi().using(graphSPFx(context)).using(PnPLogging(LogLevel.Warning));
}
return _graph;
}

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,19 @@
export default class HubSiteMapper{
public OriginalPath : string;
public Title : string;
public SiteId : string;
public Url : string;
/**
* Constructor
*
* @param {object} searchResults
*/
constructor(searchResults:any){
this.SiteId = searchResults.SiteId;
this.Title = searchResults.Title;
this.Url = searchResults.Url;
this.OriginalPath = this.OriginalPath
}
}

View File

@ -0,0 +1,23 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "dd98f5af-57c7-47fc-ac58-a754206f7cf2",
"alias": "ReactManageHublevelSubscriptionsWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "react-manage-hublevel-list-subscriptions" },
"description": { "default": "react-manage-hublevel-list-subscriptions description" },
"officeFabricIconFontName": "AzureServiceEndpoint",
"properties": {
"description": "react-manage-hublevel-list-subscriptions",
"WebpartTitle": "Subscriptions Manager"
}
}]
}

View File

@ -0,0 +1,74 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { getSP } from '../../Config/pnpConfig';
import * as strings from 'ReactManageHublevelSubscriptionsWebPartStrings';
import ReactManageHublevelSubscriptions from './components/ParentComponent/ManageHublevelSubscriptions';
import { IManageHublevelSubscriptionsProps } from './components/ParentComponent/IManageHublevelSubscriptions';
export interface IManageHublevelSubscriptionsWebPartProps {
WebpartTitle: string;
}
export default class ReactManageHublevelSubscriptionsWebPart extends BaseClientSideWebPart<IManageHublevelSubscriptionsWebPartProps> {
public render(): void {
const element: React.ReactElement<IManageHublevelSubscriptionsProps> = React.createElement(
ReactManageHublevelSubscriptions,
{
_context : this.context,
setWebPartTitle : (value: string) => {
this.properties.WebpartTitle = value;
},
displayMode: this.displayMode,
webpartTitle: this.properties.WebpartTitle
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
super.onInit();
getSP(this.context);
return Promise.resolve();
}
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.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,48 @@
import { SPHttpClient } from "@microsoft/sp-http";
import { WebPartContext } from "@microsoft/sp-webpart-base";
export class RestService{
public async GetMethod(context:WebPartContext, endPoint:string, headers:Headers){
try{
const response = await context.spHttpClient.get(endPoint, SPHttpClient.configurations.v1,{
headers: headers
});
if (!response || !response.ok) {
throw new Error(`Something went wrong when executing GetMethod at Rest Service. Status='${response.status}'`);
}
if(response.ok){
const results = await response.json();
return results;
}else {
throw new Error(response.statusText);
}
}catch (error) {
console.error("[Rest Service - GetMethod()]", error, "React Manage Hublevel subscriptions");
throw error;
}
}
//Update-Patch Method Implementation
public async PatchMethod(context:WebPartContext, endPoint:string, headers:Headers, body:any){
try{
const response = await context.spHttpClient.fetch(endPoint, SPHttpClient.configurations.v1,{
method: "PATCH",
body:JSON.stringify(body),
headers: headers
});
if (!response || !response.ok) {
throw new Error(`Something went wrong when executing PatchMethod at Rest Service. Status='${response.status}'`);
}
if(response.ok){
//If the subscription is found and successfully updated, a 204 No Content response is returned.
return response.status;
}else {
throw new Error(response.statusText);
}
}
catch (error) {
console.error("[Error at Patch Method-RestService]", error, "React Manage Hublevel subscriptions");
throw error;
}
}
}

View File

@ -0,0 +1,174 @@
import { SPHttpClient } from "@microsoft/sp-http";
import { cloneDeep } from "@microsoft/sp-lodash-subset";
import { WebPartContext } from "@microsoft/sp-webpart-base";
interface ISearchResults{
queryKeywords: string,
refinementResults: any[],
relevantResults : any[],
secondaryResults: any[],
promotedResults : any[],
totalRows: 0
}
export class SearchService{
public async getCachedSearchResults(context: WebPartContext, query:any): Promise<any> {
let results:ISearchResults= {
queryKeywords: query.Querytext,
refinementResults: [],
relevantResults : [],
secondaryResults: [],
promotedResults:[],
totalRows: 0
};
const searchEndpoint = `${context.pageContext.web.absoluteUrl}/_api/search/postquery`;
try{
const response = await context.spHttpClient.post(searchEndpoint, SPHttpClient.configurations.v1, {
body: this.getRequestPayload(query),
headers: {
'accept': 'application/json;odata=nometadata',
'content-type': 'application/json;odata=verbose',
'odata-version': '3.0',
'X-ClientService-ClientTag': 'NonISV|PnP|ModernSearch',
'UserAgent': 'NonISV|PnP|ModernSearch'
}
});
if (!response || !response.ok) {
throw new Error(`Something went wrong when executing search query. Status='${response.status}'`);
}
if(response.ok){
const recentSearchData: any = await response.json();
if (!recentSearchData || !recentSearchData.PrimaryQueryResult?.RelevantResults?.Table?.Rows) {
throw new Error(`Cannot read JSON result`);
}
if(recentSearchData.PrimaryQueryResult){
let refinementResults: any[] = [];
const resultRows = recentSearchData.PrimaryQueryResult.RelevantResults?.Table?.Rows;
let refinementResultsRows = recentSearchData.PrimaryQueryResult.RefinementResults;
const refinementRows: any = refinementResultsRows ? refinementResultsRows.Refiners : [];
let searchResults : any[] = this.getSearchResults(resultRows);
refinementRows.forEach((refiner:any) => {
let values: any[] = [];
refiner.Entries.forEach((item:any) => {
values.push({
count: parseInt(item.RefinementCount, 10),
name: item.RefinementValue.replace("string;#", ""),
value: item.RefinementToken
} as any);
});
refinementResults.push({
filterName: refiner.Name,
values: values
});
});
results.relevantResults = searchResults;
results.refinementResults = refinementResults;
results.totalRows = recentSearchData.PrimaryQueryResult.RelevantResults.TotalRows;
}
if(recentSearchData.SecondaryQueryResults){
const secondaryQueryResults = recentSearchData.SecondaryQueryResults;
if (Array.isArray(secondaryQueryResults) && secondaryQueryResults.length > 0){
let promotedResults: any[] = [];
let secondaryResults: any[] = [];
secondaryQueryResults.forEach((e) => {
// Best bets are mapped through the "SpecialTermResults" https://msdn.microsoft.com/en-us/library/dd907265(v=office.12).aspx
if (e.SpecialTermResults) {
// Casting as pnpjs has an incorrect mapping of SpecialTermResults
(e.SpecialTermResults).Results.forEach((result:any) => {
promotedResults.push({
title: result.Title,
url: result.Url,
description: result.Description
} as any);
});
}
// Secondary/Query Rule results are mapped through SecondaryQueryResults.RelevantResults
if (e.RelevantResults) {
const secondaryResultItems = this.getSearchResults(e.RelevantResults.Table.Rows);
const secondaryResultBlock: any = {
title: e.RelevantResults.ResultTitle,
results: secondaryResultItems
};
// Only keep secondary result blocks which have items
if (secondaryResultBlock.results.length > 0) {
secondaryResults.push(secondaryResultBlock);
}
}
});
results.promotedResults = promotedResults;
results.secondaryResults = secondaryResults;
}
}
return results;
} else {
throw new Error(response.statusText);
}
}catch (error) {
console.error("[SharePointSearchService.search()]", error, "Manage-hublevel-list-subscriptions");
throw error;
}
}
private fixArrProp(prop: any): { results: any[] } {
if (typeof prop === "undefined") {
return ({ results: [] });
}
return { results: Array.isArray(prop) ? prop : [prop] };
}
private getRequestPayload(searchQuery: any): string {
let queryPayload: any = cloneDeep(searchQuery);
queryPayload.HitHighlightedProperties = this.fixArrProp(queryPayload.HitHighlightedProperties);
queryPayload.Properties = this.fixArrProp(queryPayload.Properties);
queryPayload.RefinementFilters = this.fixArrProp(queryPayload.RefinementFilters);
queryPayload.ReorderingRules = this.fixArrProp(queryPayload.ReorderingRules);
queryPayload.SelectProperties = this.fixArrProp(queryPayload.SelectProperties);
queryPayload.SortList = this.fixArrProp(queryPayload.SortList);
const postBody = {
request: {
'__metadata': {
'type': 'Microsoft.Office.Server.Search.REST.SearchRequest'
},
...queryPayload
}
};
return JSON.stringify(postBody);
}
private getSearchResults(resultRows: any): any[] {
// Map search results
let searchResults: any[] = resultRows.map((elt:any) => {
let result: any = {};
elt.Cells.map((item:any) => {
if (item.Key === "HtmlFileType" && item.Value) {
result["FileType"] = item.Value;
}
else if (!result[item.Key]) {
result[item.Key] = item.Value;
}
});
return result;
});
return searchResults;
}
}

View File

@ -0,0 +1,209 @@
import { SubscriptionModel } from "../ParentComponent/IManageHublevelSubscriptions";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import * as React from 'react';
import {
MessageBar, MessageBarType,/*, IconButton,
IIconProps, Label, TooltipHost,*/
DetailsList, DetailsListLayoutMode, SelectionMode,
IColumn, mergeStyles, Spinner, /*
ProgressIndicator,ITooltipHostStyles,*/ Link
} from 'office-ui-fabric-react';
import { RestService } from '../../Services/RestService';
interface SubscriptionDashboardProps{
subscriptions:SubscriptionModel[];
selectedListID:string|number;
_context: WebPartContext;
selectedSite:string|number;
restService : RestService;
parentCallBack?: (childData:any) => void;
}
interface SubscriptionDashboardState{
subscriptions?:SubscriptionModel[];
columns: IColumn[];
selectedListID:string|number;
renewedMessage ? : string;
renewedMessageBarType? : MessageBarType;
showRenewedMessage ? : boolean;
showSpinner? : boolean;
}
export default class SubscriptionDashboard extends React.Component<SubscriptionDashboardProps, SubscriptionDashboardState> {
constructor(props:any) {
super(props);
this._renderItemColumn = this._renderItemColumn.bind(this);
const columns : IColumn[] = [
{
key: 'id',
name: 'Subscription ID',
fieldName: 'id',
minWidth: 210,
maxWidth: 300,
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: 'expirationDateTime',
name: 'Expiration Date',
fieldName: 'expirationDateTime',
minWidth: 150,
maxWidth: 175,
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,
}
];
this.state = {
columns : columns,
subscriptions: this.props.subscriptions,
selectedListID:this.props.selectedListID,
showRenewedMessage : false,
showSpinner: false
}
}
public componentDidUpdate(prevProps: Readonly<SubscriptionDashboardProps>, prevState: Readonly<SubscriptionDashboardState>, snapshot?: any): void {
prevProps.subscriptions !== this.props.subscriptions && this.setState({subscriptions:this.props.subscriptions, showRenewedMessage:false});
prevProps.selectedListID !== this.props.selectedListID && this.setState({selectedListID:this.props.selectedListID, showRenewedMessage:false});
prevState.showSpinner !== this.state.showSpinner && this.setState({subscriptions:this.props.subscriptions,selectedListID:this.props.selectedListID, showRenewedMessage:false});
if(prevState.showRenewedMessage !== this.state.showRenewedMessage){
this.setState({subscriptions:this.props.subscriptions,selectedListID:this.props.selectedListID, showRenewedMessage:false});
this.props.parentCallBack && this.props.parentCallBack(true);
}
}
public render(){
const {subscriptions, columns, showRenewedMessage, renewedMessage, renewedMessageBarType, showSpinner} = this.state;
return (
<React.Fragment>
{showRenewedMessage &&
<MessageBar messageBarType={renewedMessageBarType}>
{renewedMessage}
</MessageBar>
}
{showSpinner ? (<Spinner label="Please wait..." ariaLive="assertive" labelPosition="bottom" />) :
<div>
<h4 style={{ paddingTop: '5px' }}>Subscriptions</h4>
<DetailsList
items={subscriptions?subscriptions:[]}
columns={columns}
onRenderItemColumn={this._renderItemColumn}
selectionMode={SelectionMode.none}
setKey="none"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
/>
</div>
}
</React.Fragment>
);
}
public onButtonClick = async (item: any): Promise<void> => {
this.setState({showSpinner:true});
const renewSubscriptionEndpoint = this.props.selectedSite+`/_api/web/lists('${this.props.selectedListID}')/subscriptions('${item.id}')`;
const renewSubscriptionRequestHeaders: Headers = new Headers();
renewSubscriptionRequestHeaders.append('Content-Type', 'application/json');
const payload = {
expirationDateTime: this.getNewSubscriptionDate(),
notificationUrl: item.notificationUrl,
};
const renewResults = await this.props.restService.PatchMethod(this.props._context, renewSubscriptionEndpoint, renewSubscriptionRequestHeaders, payload);
if(renewResults == 204){
this.setState({showRenewedMessage:true,renewedMessageBarType:MessageBarType.success, renewedMessage:"Subcription renewed", showSpinner:false});
} else{
this.setState({showRenewedMessage:true,renewedMessageBarType:MessageBarType.error, renewedMessage:"Something went wrong, please try after sometime.", showSpinner:false});
}
}
public _onColumnClick = (ev: React.MouseEvent<HTMLElement>, column: IColumn): void => {
const { columns, subscriptions } = 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(subscriptions?subscriptions:[], currColumn.fieldName!, currColumn.isSortedDescending); // eslint-disable-line @typescript-eslint/no-non-null-assertion
this.setState({
columns: newColumns,
subscriptions: 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 isCallBack() {
this.props.parentCallBack? this.props.children(true) : "";
}
public _renderItemColumn(item : SubscriptionModel, index: number, column: IColumn) {
const fieldContent = item[column.fieldName as keyof SubscriptionModel] as string;
let fieldColor = "green";
let showLink : boolean = false;
switch (column.fieldName) {
case 'expirationDateTime':
const parsedDate = new Date(fieldContent);
const formattedDate = parsedDate.toISOString().substring(0, 10);
let isExpired :boolean = false;
const currentDate = new Date();
const parsedFormattedDate = new Date(formattedDate);
parsedFormattedDate < currentDate ? isExpired = true : isExpired
isExpired ? fieldColor = "red" : fieldColor;
isExpired ? showLink = true : showLink;
return (
showLink ?
(<div>
<span data-selection-disabled={true} className={mergeStyles({ color: fieldColor, height: '100%', display: 'block' })}>
{formattedDate}
</span>
<div>
<Link onClick={()=> this.onButtonClick(item) }>Renew Subscription</Link>
</div>
</div> ):
(
<span data-selection-disabled={true} className={mergeStyles({ color: fieldColor, height: '100%', display: 'block' })}>
{formattedDate}
</span>
)
);
default:
return <span>{fieldContent}</span>;
}
}
public getNewSubscriptionDate(){
const currentDate = new Date();
// Add 179 days
currentDate.setDate(currentDate.getDate() + 179);
const formattedDate = currentDate.toISOString();
return formattedDate;
}
}

View File

@ -0,0 +1,34 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import {IDropdownOption} from '@fluentui/react';
import { DisplayMode } from '@microsoft/sp-core-library';
import {MessageBarType} from 'office-ui-fabric-react';
export interface IManageHublevelSubscriptionsProps {
_context: WebPartContext;
displayMode: DisplayMode;
webpartTitle: string;
setWebPartTitle: (value: string) => void;
}
export interface SubscriptionModel{
id:string;
clientState:string;
expirationDateTime:string;
notificationUrl:string;
resource:string;
}
export interface IManageHublevelSubscriptionsState{
dropDownSiteOptions?: IDropdownOption[];
dropDownListOptions?: IDropdownOption[];
selectedSite ?: IDropdownOption;
selectedList?: IDropdownOption;
isListsToBeLoaded?:boolean;
showTable?:boolean;
subscriptions ? : SubscriptionModel[];
callBackFromDashboard?:any;
showMessage?:boolean;
Message ? : string;
MessageBarType? : MessageBarType;
showRenewedMessage ? : boolean;
}

View File

@ -0,0 +1,22 @@
@import '~@fluentui/react/dist/sass/References.scss';
.reactManageHublevelSubscriptions {
.container{
width:100%;
.webpartTitle{
display: flex;
color: rgb(0 0 0);
}
.sectionContainer {
display: flex;
align-items: center;
}
.dropdownSites {
margin-right: 10px;
}
.dropdownLists {
margin-left: 10px;
}
}
}

View File

@ -0,0 +1,218 @@
import * as React from 'react';
import styles from './ManageHublevelSubscriptions.module.scss';
import {Dropdown, IDropdownOption} from '@fluentui/react';
import { IManageHublevelSubscriptionsProps,
IManageHublevelSubscriptionsState,
SubscriptionModel }
from './IManageHublevelSubscriptions';
import {
Spinner
} from 'office-ui-fabric-react';
import { SearchService } from '../../Services/SearchService';
import { RestService } from '../../Services/RestService';
import HubSiteMapper from '../../Mapper/HubSiteMapper';
import SubscriptionDashboard from '../DashboardComponent/SubscriptionDashboard';
import { WebPartTitle } from '@pnp/spfx-controls-react';
import {MessageBar, MessageBarType} from 'office-ui-fabric-react';
export default class ReactManageHublevelSubscriptions
extends React.Component<IManageHublevelSubscriptionsProps, IManageHublevelSubscriptionsState> {
public sites : IDropdownOption[];
public lists : IDropdownOption[];
public subscriptions : SubscriptionModel[];
public selectedSite: IDropdownOption;
public selectedList: IDropdownOption;
public hubSiteID: string = "";
private searchService: SearchService;
private restService : RestService;
private sitesAssociated: HubSiteMapper[];
constructor(props:any) {
super(props);
this.hubSiteID = this.props._context.pageContext.legacyPageContext.departmentId;
this.searchService = new SearchService();
this.restService = new RestService();
this.sites = [];
this.lists = [];
this.subscriptions = [];
this.state={
isListsToBeLoaded : true,
dropDownListOptions : [],
dropDownSiteOptions: [],
showTable: false,
showMessage:false
}
}
public async componentDidMount() {
this.sites = await this.getAssociatedHubSites(this.hubSiteID);
if(this.sites.length === 0){
this.setState({
showMessage:true,
MessageBarType:MessageBarType.severeWarning,
Message:"This site is not associated to any hubsite, or is not a hubsite. Please configure this webpart in a site which is associated to hubsite or a Hubsite itself."
});
} else{
this.setState({
dropDownSiteOptions : this.sites
});
}
}
public async componentDidUpdate(prevProps: Readonly<IManageHublevelSubscriptionsProps>, prevState: IManageHublevelSubscriptionsState, snapshot?: any){
const { isListsToBeLoaded, showTable} = this.state;
if(prevState.isListsToBeLoaded !== isListsToBeLoaded){
this.lists = await this.populateListDropDown(this.selectedSite.key);
this.setState({dropDownListOptions:this.lists});
}
if(prevState.showTable !== showTable){
this.subscriptions = await this.getSubscriptions(this.selectedSite.key, this.selectedList.key);
this.setState({showTable:false, subscriptions:this.subscriptions});
}
}
public render() {
const { dropDownListOptions, dropDownSiteOptions, selectedList, selectedSite, showTable, showMessage, Message, MessageBarType } = this.state;
const {displayMode, webpartTitle, setWebPartTitle} = this.props;
return (
<React.Fragment>
<div className={styles.reactManageHublevelSubscriptions}>
{showMessage ?
<MessageBar messageBarType={MessageBarType}>
{Message}
</MessageBar>
:
<div className={styles.container}>
<div className={styles.webpartTitle}>
<WebPartTitle
displayMode={displayMode}
title={webpartTitle}
updateProperty={setWebPartTitle}
/>
</div>
<section className={styles.sectionContainer}>
{!showMessage &&
<Dropdown
className={styles.dropdownSites}
placeholder="Select sites from associated hub..."
selectedKey={selectedSite? selectedSite.key : undefined}
label="Select sites"
options={dropDownSiteOptions? dropDownSiteOptions : []}
onChange={this.onChange}
/>
}
{this.lists.length > 0 &&
<Dropdown
className={styles.dropdownLists}
placeholder="Select list..."
selectedKey={selectedList? selectedList.key : undefined}
label={`Select list from ${selectedSite ? selectedSite.text : ''}`}
options={dropDownListOptions ? dropDownListOptions : []}
onChange={this.onChangeList}
/>
}
</section>
{showTable ? (<Spinner label="Loading subcriptions..." ariaLive="assertive" labelPosition="bottom" />) :
<div>
{this.subscriptions?.length > 0 &&
<SubscriptionDashboard
subscriptions= {this.state.subscriptions?this.state.subscriptions:[]}
selectedListID={ selectedList ? selectedList.key : ""}
_context={this.props._context}
selectedSite={selectedSite? selectedSite.key : ""}
restService={this.restService}
parentCallBack={this.callbackFunctionNewForm}
/>
}
</div>
}
</div>
}
</div>
</React.Fragment>
);
}
public callbackFunctionNewForm = (childData:any) => {
this.setState({ showTable:true });
}
public onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
this.selectedSite = item;
this.setState({isListsToBeLoaded:false, selectedSite : this.selectedSite});
};
public onChangeList = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
this.selectedList = item;
this.setState({isListsToBeLoaded:true, showTable:true, selectedList: this.selectedList});
}
public async getAssociatedHubSites(hubsiteID : string):Promise<any>{
const dropdownSites :IDropdownOption[]= [];
let query = {};
//Query to get sites associated to Hubsite
const queryTemplate: string = `{searchTerms}contentclass:STS_Site AND NOT WebTemplate:SPSPERS AND NOT SiteId:{${hubsiteID}} AND (DepartmentId:{${hubsiteID}} OR DepartmentId:${hubsiteID})`;
if(hubsiteID !== undefined){
query =
{
QueryTemplate: queryTemplate,
RowLimit: 20,
SelectProperties: ['Title','Url','OriginalPath','Author','Path','SiteName','contentclass'], //Will only use Title & Url for Dropdown
TrimDuplicates: false
};
}
const results = await this.searchService.getCachedSearchResults(this.props._context, query);
//This mapping is unnecessary for now, but may be useful later
this.sitesAssociated = results.relevantResults.map((i: any) => new HubSiteMapper(i));
this.sitesAssociated.forEach((site) => {
dropdownSites.push({key: site.Url, text : site.Title});
});
return dropdownSites;
}
public async populateListDropDown(selectedSite : string| number):Promise<any>{
const dropdownLists :IDropdownOption[]= [];
//Will fetch both lists and libraries apart from site collection app catalog
const listEndpoint = selectedSite+'/_api/web/lists?$filter=Hidden eq false and BaseTemplate ne 336'; // and BaseType ne 1
const listRequestHeaders: Headers = new Headers();
listRequestHeaders.append('accept', 'application/json;odata=verbose');
listRequestHeaders.append('content-type', 'application/json;odata=verbose');
listRequestHeaders.append('odata-version', '3.0');
const listResults = await this.restService.GetMethod(this.props._context, listEndpoint, listRequestHeaders);
listResults.d.results.forEach((list:any) => {
dropdownLists.push({key:list.Id, text:list.Title});
});
return dropdownLists;
}
public async getSubscriptions(selectedSite : string| number, selectedListID: string| number):Promise<SubscriptionModel[]>{
const subscriptions : SubscriptionModel[] = [];
const subscriptionEndpoint = selectedSite+`/_api/web/lists('${selectedListID}')/subscriptions`;
const subscriptionRequestHeaders: Headers = new Headers();
subscriptionRequestHeaders.append('accept', 'application/json;odata=verbose');
subscriptionRequestHeaders.append('content-type', 'application/json;odata=verbose');
subscriptionRequestHeaders.append('odata-version', '3.0');
const subcriptionResults = await this.restService.GetMethod(this.props._context, subscriptionEndpoint, subscriptionRequestHeaders);
subcriptionResults.d.results.forEach((subscription:any) =>{
subscriptions.push({
clientState:subscription.clientState,
expirationDateTime:subscription.expirationDateTime,
notificationUrl:subscription.notificationUrl,
id:subscription.id,
resource:subscription.resource
});
});
return subscriptions;
}
}

View File

@ -0,0 +1,15 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field",
"AppLocalEnvironmentSharePoint": "The app is running on your local environment as SharePoint web part",
"AppLocalEnvironmentTeams": "The app is running on your local environment as Microsoft Teams app",
"AppLocalEnvironmentOffice": "The app is running on your local environment in office.com",
"AppLocalEnvironmentOutlook": "The app is running on your local environment in Outlook",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams",
"AppOfficeEnvironment": "The app is running in office.com",
"AppOutlookEnvironment": "The app is running in Outlook"
}
});

View File

@ -0,0 +1,18 @@
declare interface IReactManageHublevelSubscriptionsWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module 'ReactManageHublevelSubscriptionsWebPartStrings' {
const strings: IReactManageHublevelSubscriptionsWebPartStrings;
export = strings;
}

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"
]
}