From 278c3082ff5133339341e80d73127282257c5b87 Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Wed, 5 Aug 2026 16:49:23 +0100 Subject: [PATCH 01/95] slack connection --- config/forms-pro.php | 8 + lang/en/messages.php | 36 ++ lang/en/validation.php | 5 + package-lock.json | 389 ++++++++++++++++- package.json | 2 + .../connections/SlackConnection.vue | 268 ++++++++++++ .../connections/SlackSetupInstructions.vue | 76 ++++ resources/js/cp.js | 10 +- resources/svg/slack.svg | 6 + src/FormConnections/Slack.php | 75 ++++ src/FormConnections/Slack/MessageBuilder.php | 270 ++++++++++++ .../Slack/Rules/SlackChannel.php | 16 + .../Slack/SendSlackMessage.php | 40 ++ src/FormConnections/Slack/SlackClient.php | 90 ++++ .../Slack/SlackRequestException.php | 58 +++ .../CP/SlackChannelsController.php | 23 + .../CP/SlackConnectionController.php | 40 ++ src/ServiceProvider.php | 8 + tests/FakesRoles.php | 30 ++ .../Slack/SendSlackMessageTest.php | 401 ++++++++++++++++++ .../Slack/SlackChannelsTest.php | 136 ++++++ .../Slack/SlackConnectionTest.php | 125 ++++++ .../Slack/UpdateSlackConnectionTest.php | 177 ++++++++ tests/__fixtures__/dev-null/.gitkeep | 0 24 files changed, 2282 insertions(+), 7 deletions(-) create mode 100644 lang/en/messages.php create mode 100644 lang/en/validation.php create mode 100644 resources/js/components/connections/SlackConnection.vue create mode 100644 resources/js/components/connections/SlackSetupInstructions.vue create mode 100644 resources/svg/slack.svg create mode 100644 src/FormConnections/Slack.php create mode 100644 src/FormConnections/Slack/MessageBuilder.php create mode 100644 src/FormConnections/Slack/Rules/SlackChannel.php create mode 100644 src/FormConnections/Slack/SendSlackMessage.php create mode 100644 src/FormConnections/Slack/SlackClient.php create mode 100644 src/FormConnections/Slack/SlackRequestException.php create mode 100644 src/Http/Controllers/CP/SlackChannelsController.php create mode 100644 src/Http/Controllers/CP/SlackConnectionController.php create mode 100644 tests/FakesRoles.php create mode 100644 tests/FormConnections/Slack/SendSlackMessageTest.php create mode 100644 tests/FormConnections/Slack/SlackChannelsTest.php create mode 100644 tests/FormConnections/Slack/SlackConnectionTest.php create mode 100644 tests/FormConnections/Slack/UpdateSlackConnectionTest.php create mode 100644 tests/__fixtures__/dev-null/.gitkeep diff --git a/config/forms-pro.php b/config/forms-pro.php index 5b900a0..4da3e9f 100644 --- a/config/forms-pro.php +++ b/config/forms-pro.php @@ -22,4 +22,12 @@ ], + 'connections' => [ + + 'slack' => [ + 'token' => env('FORMS_PRO_SLACK_TOKEN'), + ], + + ], + ]; diff --git a/lang/en/messages.php b/lang/en/messages.php new file mode 100644 index 0000000..b43a41c --- /dev/null +++ b/lang/en/messages.php @@ -0,0 +1,36 @@ + 'Private channels only appear once the app has been invited to them.', + 'slack_connection_description' => 'Post submissions to a Slack channel.', + 'slack_connection_fields_instructions' => 'Leave empty to include every field.', + 'slack_connection_heading' => 'New :form submission', + 'slack_connection_delete_confirmation' => 'Are you sure you want to delete this Slack notification?', + 'slack_connection_include_fields_instructions' => 'Displays the submitted values as a table.', + 'slack_connection_link_to_submission_instructions' => 'Add a button linking to the submission in the Control Panel.', + 'slack_connection_unavailable' => 'Couldn\'t reach Slack.', + 'slack_connection_test_sent' => 'Test message sent.', + 'slack_connection_truncated' => 'This submission was too long to show in full.', + 'slack_connection_view_submission' => 'View submission', + + 'slack_error_account_inactive' => 'The Slack app has been deactivated in your workspace.', + 'slack_error_channel_not_found' => 'That channel no longer exists, or it\'s private and the app hasn\'t been invited to it.', + 'slack_error_invalid_auth' => 'Slack rejected your token. Check the FORMS_PRO_SLACK_TOKEN environment variable.', + 'slack_error_is_archived' => 'That channel has been archived.', + 'slack_error_missing_scope' => 'The Slack app is missing a required scope. Reinstall it with the scopes listed in the documentation.', + 'slack_error_missing_token' => 'No Slack token has been configured. Add one to your FORMS_PRO_SLACK_TOKEN environment variable.', + 'slack_error_not_in_channel' => 'The app isn\'t in that channel. Invite it with /invite, then try again.', + 'slack_error_ratelimited' => 'Slack is rate limiting us. Try again in a moment.', + 'slack_error_restricted_action' => 'The app isn\'t allowed to post in that channel.', + 'slack_error_token_revoked' => 'The Slack token has been revoked. Reinstall the app and update your FORMS_PRO_SLACK_TOKEN environment variable.', + 'slack_error_unknown' => 'Slack returned an error: :error', + + 'slack_setup_heading' => 'Connect your Slack workspace', + 'slack_setup_intro' => 'Slack needs to know about your site before it\'ll accept messages. You only need to do this once.', + 'slack_setup_create_app' => 'Create a Slack app in the workspace you\'d like submissions sent to.', + 'slack_setup_manifest_toggle' => 'Set it up by hand, or update an existing app', + 'slack_setup_manifest' => 'Paste this manifest into the app\'s "App Manifest" page.', + 'slack_setup_install' => 'Choose "Install to Workspace", select the workspace you\'d like to install it into, and click Allow.', + 'slack_setup_token' => 'Copy the Bot User OAuth Token from the app\'s "OAuth & Permissions" page into your site\'s :file file:', + 'slack_setup_developer' => 'This step needs access to the server, so you may need a developer to do it for you. Once :variable is set, reload this page.', +]; diff --git a/lang/en/validation.php b/lang/en/validation.php new file mode 100644 index 0000000..f3ce9c1 --- /dev/null +++ b/lang/en/validation.php @@ -0,0 +1,5 @@ + 'Choose a Slack channel.', +]; diff --git a/package-lock.json b/package-lock.json index cd9f94c..b24e6cb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,7 +6,9 @@ "": { "devDependencies": { "@statamic/cms": "file:./vendor/statamic/cms/resources/dist-package", + "axios": "^1.18.1", "laravel-vite-plugin": "^3.0.0", + "nanoid": "^5.1.6", "vite": "^8.0.0" } }, @@ -549,6 +551,66 @@ "license": "MIT", "peer": true }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.19.0.tgz", + "integrity": "sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -557,6 +619,34 @@ "license": "MIT", "peer": true }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -567,6 +657,21 @@ "node": ">=8" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/entities": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", @@ -581,6 +686,55 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", @@ -607,6 +761,44 @@ } } }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -622,6 +814,124 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/laravel-vite-plugin": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/laravel-vite-plugin/-/laravel-vite-plugin-3.1.0.tgz", @@ -921,10 +1231,50 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "version": "5.1.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz", + "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==", "dev": true, "funding": [ { @@ -934,10 +1284,10 @@ ], "license": "MIT", "bin": { - "nanoid": "bin/nanoid.cjs" + "nanoid": "bin/nanoid.js" }, "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + "node": "^18 || >=20" } }, "node_modules/picocolors": { @@ -989,6 +1339,35 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postcss/node_modules/nanoid": { + "version": "3.3.17", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz", + "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/rolldown": { "version": "1.0.0-rc.17", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.17.tgz", diff --git a/package.json b/package.json index 48b47a4..5d16c91 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ }, "devDependencies": { "@statamic/cms": "file:./vendor/statamic/cms/resources/dist-package", + "axios": "^1.18.1", "laravel-vite-plugin": "^3.0.0", + "nanoid": "^5.1.6", "vite": "^8.0.0" } } \ No newline at end of file diff --git a/resources/js/components/connections/SlackConnection.vue b/resources/js/components/connections/SlackConnection.vue new file mode 100644 index 0000000..b5d2283 --- /dev/null +++ b/resources/js/components/connections/SlackConnection.vue @@ -0,0 +1,268 @@ + + + diff --git a/resources/js/components/connections/SlackSetupInstructions.vue b/resources/js/components/connections/SlackSetupInstructions.vue new file mode 100644 index 0000000..c0ab7ed --- /dev/null +++ b/resources/js/components/connections/SlackSetupInstructions.vue @@ -0,0 +1,76 @@ + + + \ No newline at end of file diff --git a/resources/js/cp.js b/resources/js/cp.js index 2d28aa0..5303f4b 100644 --- a/resources/js/cp.js +++ b/resources/js/cp.js @@ -1,5 +1,11 @@ +import { registerIconSet } from '@statamic/cms/ui'; import AddressFieldtype from './components/fieldtypes/AddressFieldtype.vue'; +import SlackConnection from './components/connections/SlackConnection.vue'; + +registerIconSet('forms-pro', import.meta.glob('../svg/*.svg', { query: '?raw', import: 'default' })); Statamic.booting(() => { - Statamic.component('address-fieldtype', AddressFieldtype); -}); \ No newline at end of file + Statamic.$components.register('address-fieldtype', AddressFieldtype); + + Statamic.$components.register('slack-connection', SlackConnection); +}); diff --git a/resources/svg/slack.svg b/resources/svg/slack.svg new file mode 100644 index 0000000..2887980 --- /dev/null +++ b/resources/svg/slack.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/FormConnections/Slack.php b/src/FormConnections/Slack.php new file mode 100644 index 0000000..3a47fb6 --- /dev/null +++ b/src/FormConnections/Slack.php @@ -0,0 +1,75 @@ +connections()->get('slack', [])); + } + + public function finalized(Submission $submission): object|array + { + return collect($submission->form()->connections()->get('slack')) + ->reject(fn (array $config) => ($config['enabled'] ?? true) === false) + ->filter(fn (array $config) => ConnectionLogic::passes($config, $submission)) + ->map(fn (array $config) => new SendSlackMessage($submission, $submission->site(), $config)) + ->values() + ->all(); + } + + public function render(Form $form): VueComponent + { + return VueComponent::render('slack-connection', [ + 'action' => cp_route('forms.connect.slack.update', $form->handle()), + 'channelsUrl' => cp_route('forms.connect.slack.channels', $form->handle()), + 'testUrl' => cp_route('forms.connect.slack.test', $form->handle()), + 'configured' => app(SlackClient::class)->configured(), + 'fields' => $this->fields($form), + ]); + } + + private function fields(Form $form): array + { + return $form->formFields()->fields() + ->reject(fn ($field) => array_intersect($field->fieldtype()->categories(), ['information', 'structure'])) + ->map(fn ($field) => ['handle' => $field->handle(), 'display' => __($field->display())]) + ->values() + ->all(); + } + + public function routes(Router $router): void + { + $router->patch('/', [SlackConnectionController::class, 'update'])->name('update'); + $router->get('/channels', SlackChannelsController::class)->name('channels'); + $router->post('/test', SendTestSlackMessageController::class)->name('test'); + } +} diff --git a/src/FormConnections/Slack/MessageBuilder.php b/src/FormConnections/Slack/MessageBuilder.php new file mode 100644 index 0000000..9719f40 --- /dev/null +++ b/src/FormConnections/Slack/MessageBuilder.php @@ -0,0 +1,270 @@ + $this->config['channel'], + 'text' => $this->heading(), + 'blocks' => $this->blocks(), + 'unfurl_links' => false, + 'unfurl_media' => false, + ]; + } + + private function heading(): string + { + if ($heading = Arr::get($this->config, 'heading')) { + return (string) Antlers::parse(Parse::config($heading), $this->submission->toAugmentedArray()); + } + + return __('forms-pro::messages.slack_connection_heading', [ + 'form' => __($this->submission->form()->title()), + ]); + } + + private function blocks(): array + { + $fields = $this->fieldBlocks(); + $trailing = collect([$this->submissionBlock(), $this->contextBlock()])->filter(); + $available = self::BLOCK_LIMIT - $trailing->count() - 1; + + if ($fields->count() > $available) { + $fields = $fields->take($available - 1)->push($this->truncationBlock()); + } + + return collect([$this->headingBlock()])->merge($fields)->merge($trailing)->all(); + } + + private function headingBlock(): array + { + return [ + 'type' => 'header', + 'text' => [ + 'type' => 'plain_text', + 'text' => Str::limit($this->heading(), self::HEADING_LIMIT - 1, '…'), + 'emoji' => true, + ], + ]; + } + + private function fieldBlocks(): Collection + { + if (! Arr::get($this->config, 'include_fields', true)) { + return collect(); + } + + $blocks = collect(); + $short = collect(); + + foreach ($this->renderedFields() as $field) { + if ($this->isShort($field['text'])) { + $short->push($field); + + continue; + } + + $blocks = $blocks->merge($this->fieldsSections($short))->push($this->textSection($field)); + $short = collect(); + } + + return $blocks->merge($this->fieldsSections($short))->values(); + } + + private function renderedFields(): Collection + { + $selected = Arr::get($this->config, 'fields'); + $excluded = $this->submission->form()->formFields()->fields() + ->filter(fn ($field) => array_intersect($field->fieldtype()->categories(), ['information', 'structure'])) + ->keys(); + + return collect(Arr::except($this->submission->toAugmentedArray(), ['id', 'date', 'form'])) + ->filter(fn ($value) => $value instanceof Value) + ->reject(fn (Value $value, string $handle) => $excluded->contains($handle)) + ->when($selected, fn (Collection $fields) => $fields->only($selected)) + ->map(fn (Value $value) => [ + 'display' => $value->field()->display(), + 'text' => $this->renderValue($value), + ]) + ->reject(fn (array $field) => blank($field['text'])) + ->values(); + } + + private function renderValue(Value $value): string + { + $field = $value->field(); + $type = $field->type(); + $value = $value->value(); + + return match (true) { + $type === 'assets', $type === 'form_upload' && $field->get('store') => $this->renderAssets($value), + in_array($type, ['files', 'form_upload']) => $this->renderFilenames($value), + in_array($type, ['select', 'radio', 'checkboxes', 'dictionary']) => $this->renderOptions($value), + is_iterable($value) => $this->renderJson($value), + default => $this->escape((string) $value), + }; + } + + private function renderAssets(mixed $value): string + { + $assets = $value instanceof Asset ? collect([$value]) : collect($value?->get()); + + return $assets->map(fn (Asset $asset) => $this->renderAsset($asset))->implode(', '); + } + + private function renderAsset(Asset $asset): string + { + $filename = $this->escape($asset->basename()); + + return ($url = $asset->absoluteUrl()) ? "<{$url}|{$filename}>" : $filename; + } + + private function renderFilenames(mixed $value): string + { + return collect(Arr::wrap($value)) + ->map(fn ($file) => $this->escape(basename((string) $file))) + ->implode(', '); + } + + private function renderOptions(mixed $value): string + { + return collect(is_iterable($value) ? $value : [$value]) + ->map(fn ($option) => $this->escape($this->optionLabel($option))) + ->reject(fn (string $label) => $label === '') + ->implode(', '); + } + + private function optionLabel(mixed $option): string + { + $option = $option instanceof Arrayable ? $option->toArray() : $option; + + if (is_array($option)) { + return (string) (Arr::get($option, 'label') ?? Arr::get($option, 'value')); + } + + return (string) $option; + } + + private function renderJson(iterable $value): string + { + $json = json_encode(collect($value)->toArray(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + + return '`'.$this->escape($json).'`'; + } + + private function isShort(string $text): bool + { + return ! Str::contains($text, "\n") && Str::length($text) <= self::SHORT_VALUE_LENGTH; + } + + private function fieldsSections(Collection $fields): Collection + { + return $fields + ->chunk(self::FIELDS_PER_SECTION) + ->map(fn (Collection $chunk) => [ + 'type' => 'section', + 'fields' => $chunk + ->map(fn (array $field) => $this->mrkdwn($field, self::FIELD_TEXT_LIMIT)) + ->values() + ->all(), + ]) + ->values(); + } + + private function textSection(array $field): array + { + return [ + 'type' => 'section', + 'text' => $this->mrkdwn($field, self::SECTION_TEXT_LIMIT), + ]; + } + + private function mrkdwn(array $field, int $limit): array + { + $label = '*'.$this->escape(__($field['display']))."*\n"; + + return [ + 'type' => 'mrkdwn', + 'text' => Str::limit($label.$field['text'], $limit - 1, '…'), + ]; + } + + private function submissionBlock(): ?array + { + if (! Arr::get($this->config, 'link_to_submission', true)) { + return null; + } + + return [ + 'type' => 'actions', + 'elements' => [[ + 'type' => 'button', + 'text' => ['type' => 'plain_text', 'text' => __('forms-pro::messages.slack_connection_view_submission')], + 'url' => cp_route('forms.submissions.show', [$this->submission->form()->handle(), $this->submission->id()]), + ]], + ]; + } + + private function contextBlock(): array + { + $date = $this->submission->date(); + + return [ + 'type' => 'context', + 'elements' => [[ + 'type' => 'mrkdwn', + 'text' => collect([ + $this->escape(__($this->submission->form()->title())), + $this->site->handle(), + 'timestamp.'^{date_short_pretty} {time}|'.$date->toDayDateTimeString().'>', + ])->implode(' · '), + ]], + ]; + } + + private function truncationBlock(): array + { + return [ + 'type' => 'context', + 'elements' => [[ + 'type' => 'mrkdwn', + 'text' => '_'.__('forms-pro::messages.slack_connection_truncated').'_', + ]], + ]; + } + + private function escape(string $value): string + { + return str_replace(['&', '<', '>'], ['&', '<', '>'], $value); + } +} diff --git a/src/FormConnections/Slack/Rules/SlackChannel.php b/src/FormConnections/Slack/Rules/SlackChannel.php new file mode 100644 index 0000000..11941c1 --- /dev/null +++ b/src/FormConnections/Slack/Rules/SlackChannel.php @@ -0,0 +1,16 @@ +translate(); + } + } +} diff --git a/src/FormConnections/Slack/SendSlackMessage.php b/src/FormConnections/Slack/SendSlackMessage.php new file mode 100644 index 0000000..3bf093d --- /dev/null +++ b/src/FormConnections/Slack/SendSlackMessage.php @@ -0,0 +1,40 @@ +submission->form()->submission($this->submission->id()) ?? $this->submission; + + try { + $slack->postMessage(new MessageBuilder($submission, $this->site, $this->config)->build()); + } catch (SlackRequestException $e) { + if ($e->isRetryable()) { + $this->release($e->retryAfter()); + } else { + $this->fail($e); + } + } + } +} diff --git a/src/FormConnections/Slack/SlackClient.php b/src/FormConnections/Slack/SlackClient.php new file mode 100644 index 0000000..07e6994 --- /dev/null +++ b/src/FormConnections/Slack/SlackClient.php @@ -0,0 +1,90 @@ +token); + } + + public function postMessage(array $payload): array + { + try { + return $this->call('chat.postMessage', $payload); + } catch (SlackRequestException $e) { + if ($e->error() === 'not_in_channel') { + try { + $this->join($payload['channel']); + } catch (SlackRequestException) { + throw $e; + } + + return $this->call('chat.postMessage', $payload); + } + + throw $e; + } + } + + private function join(string $channel): void + { + $this->call('conversations.join', ['channel' => $channel]); + } + + public function channels(): Collection + { + $cursor = ''; + $channels = collect(); + + do { + $response = $this->call('conversations.list', [ + 'exclude_archived' => true, + 'types' => 'public_channel,private_channel', + 'limit' => 200, + 'cursor' => $cursor, + ]); + + $channels = $channels->merge($response['channels']); + $cursor = $response['response_metadata']['next_cursor'] ?? ''; + } while (filled($cursor)); + + return $channels + ->map(fn (array $channel) => [ + 'id' => $channel['id'], + 'name' => $channel['name'], + 'is_private' => $channel['is_private'] ?? false, + ]) + ->sortBy('name') + ->values(); + } + + private function call(string $method, array $payload): array + { + throw_unless($this->configured(), SlackRequestException::missingToken()); + + $response = Http::withToken($this->token) + ->asJson() + ->connectTimeout(5) + ->timeout(30) + ->post("https://slack.com/api/{$method}", $payload); + + if ($response->status() === 429) { + throw SlackRequestException::rateLimited((int) $response->header('Retry-After') ?: 30); + } + + $response->throw(); + + $body = $response->json(); + + throw_unless($body['ok'] ?? false, SlackRequestException::fromResponse($body)); + + return $body; + } +} diff --git a/src/FormConnections/Slack/SlackRequestException.php b/src/FormConnections/Slack/SlackRequestException.php new file mode 100644 index 0000000..8ed10b4 --- /dev/null +++ b/src/FormConnections/Slack/SlackRequestException.php @@ -0,0 +1,58 @@ +error; + } + + public function retryAfter(): int + { + return $this->retryAfter; + } + + public function isRetryable(): bool + { + return in_array($this->error, self::RETRYABLE); + } + + public function errorMessage(): string + { + $translation = __($key = "forms-pro::messages.slack_error_{$this->error}"); + + if ($translation !== $key) { + return $translation; + } + + return __('forms-pro::messages.slack_error_unknown', ['error' => $this->error]); + } +} diff --git a/src/Http/Controllers/CP/SlackChannelsController.php b/src/Http/Controllers/CP/SlackChannelsController.php new file mode 100644 index 0000000..944de90 --- /dev/null +++ b/src/Http/Controllers/CP/SlackChannelsController.php @@ -0,0 +1,23 @@ +addMinutes(5), fn () => $slack->channels()->all()); + } catch (SlackRequestException $e) { + return response()->json(['message' => $e->errorMessage()], 422); + } + + return ['channels' => $channels]; + } +} diff --git a/src/Http/Controllers/CP/SlackConnectionController.php b/src/Http/Controllers/CP/SlackConnectionController.php new file mode 100644 index 0000000..4f8d431 --- /dev/null +++ b/src/Http/Controllers/CP/SlackConnectionController.php @@ -0,0 +1,40 @@ +validate([ + 'configs' => ['present', 'array'], + 'configs.*' => ['array'], + 'configs.*.channel' => ['required', new SlackChannel], + 'configs.*.channel_name' => ['nullable', 'string'], + 'configs.*.message' => ['nullable', 'string', 'max:2000'], + 'configs.*.include_fields' => ['sometimes', 'boolean'], + 'configs.*.fields' => ['nullable', 'array'], + 'configs.*.fields.*' => ['string', Rule::in($form->formFields()->fields()->keys())], + 'configs.*.link_to_submission' => ['sometimes', 'boolean'], + ]); + + $configs = collect($request->configs) + ->map(fn (array $config) => Arr::removeNullValues(array_merge(Arr::except($config, '_id'), [ + 'enabled' => Arr::get($config, 'enabled') === false ? false : null, + 'include_fields' => Arr::get($config, 'include_fields') === false ? false : null, + 'link_to_submission' => Arr::get($config, 'link_to_submission') === false ? false : null, + 'conditions' => ConnectionLogic::normalize(Arr::get($config, 'conditions') ?? []), + ]))) + ->values() + ->all(); + + $form->connections($form->connections()->put('slack', $configs))->save(); + } +} diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php index efad59b..8f07621 100644 --- a/src/ServiceProvider.php +++ b/src/ServiceProvider.php @@ -2,6 +2,7 @@ namespace Statamic\FormsPro; +use Statamic\FormsPro\FormConnections\Slack\SlackClient; use Statamic\Providers\AddonServiceProvider; class ServiceProvider extends AddonServiceProvider @@ -32,5 +33,12 @@ public function bootAddon() $this->publishes([ $stubsSource => resource_path('views/vendor/forms-pro/forms'), ], 'forms-pro-fields'); + + $this->bootConnections(); + } + + private function bootConnections(): void + { + $this->app->bind(SlackClient::class, fn () => new SlackClient(config('forms-pro.connections.slack.token'))); } } diff --git a/tests/FakesRoles.php b/tests/FakesRoles.php new file mode 100644 index 0000000..961b62f --- /dev/null +++ b/tests/FakesRoles.php @@ -0,0 +1,30 @@ +map(fn ($permissions, $handle) => Role::make()->handle($handle)->addPermission($permissions)); + + $fake = new class($roles) extends RoleRepository + { + public function __construct(protected $roles) {} + + public function all(): Collection + { + return $this->roles; + } + }; + + app()->instance(RepositoryContract::class, $fake); + Role::swap($fake); + } +} diff --git a/tests/FormConnections/Slack/SendSlackMessageTest.php b/tests/FormConnections/Slack/SendSlackMessageTest.php new file mode 100644 index 0000000..6cc9af6 --- /dev/null +++ b/tests/FormConnections/Slack/SendSlackMessageTest.php @@ -0,0 +1,401 @@ + 'xoxb-token']); + } + + #[Test] + public function it_posts_the_message_to_slack() + { + Http::fake(['slack.com/*' => Http::response(['ok' => true])]); + + $this->send($this->form(), ['name' => 'Jack Black']); + + Http::assertSent(function (Request $request) { + return $request->url() === 'https://slack.com/api/chat.postMessage' + && $request->hasHeader('Authorization', 'Bearer xoxb-token') + && $request['channel'] === 'C0123ABCDEF' + && $request['unfurl_links'] === false; + }); + } + + #[Test] + public function it_includes_a_heading_with_the_form_title() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black']); + + $this->assertEquals('header', $blocks[0]['type']); + $this->assertEquals('New Contact Us submission', $blocks[0]['text']['text']); + } + + #[Test] + public function it_uses_the_configured_heading() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black'], [ + 'heading' => 'New enquiry from {{ name }}', + ]); + + $this->assertEquals('New enquiry from Jack Black', $blocks[0]['text']['text']); + } + + #[Test] + public function it_truncates_a_heading_to_slacks_limit() + { + $blocks = $this->blocksForForm($this->form(), ['name' => str_repeat('a', 300)], [ + 'heading' => 'New enquiry from {{ name }}', + ]); + + $this->assertEquals(150, mb_strlen($blocks[0]['text']['text'])); + $this->assertStringEndsWith('…', $blocks[0]['text']['text']); + } + + #[Test] + public function it_sets_a_plain_text_fallback() + { + Http::fake(['slack.com/*' => Http::response(['ok' => true])]); + + $this->send($this->form(), ['name' => 'Jack Black']); + + Http::assertSent(fn (Request $request) => $request['text'] === 'New Contact Us submission'); + } + + #[Test] + public function it_includes_all_fields_by_default() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black', 'email' => 'jack@example.com']); + + $this->assertEquals([ + ['type' => 'mrkdwn', 'text' => "*Name*\nJack Black"], + ['type' => 'mrkdwn', 'text' => "*Email*\njack@example.com"], + ], $blocks[1]['fields']); + } + + #[Test] + public function it_only_includes_the_selected_fields() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black', 'email' => 'jack@example.com'], [ + 'fields' => ['email'], + ]); + + $this->assertEquals([['type' => 'mrkdwn', 'text' => "*Email*\njack@example.com"]], $blocks[1]['fields']); + } + + #[Test] + public function it_omits_the_fields_when_they_arent_included() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black'], ['include_fields' => false]); + + $this->assertEquals(['header', 'actions', 'context'], collect($blocks)->pluck('type')->all()); + } + + #[Test] + public function it_excludes_information_fields() + { + $form = $this->form([ + ['handle' => 'about_you', 'field' => ['type' => 'heading', 'display' => 'About You']], + ['handle' => 'name', 'field' => ['type' => 'text']], + ]); + + $blocks = $this->blocksForForm($form, ['about_you' => 'About You', 'name' => 'Jack Black']); + + $this->assertEquals([['type' => 'mrkdwn', 'text' => "*Name*\nJack Black"]], $blocks[1]['fields']); + } + + #[Test] + public function it_skips_blank_values() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black', 'email' => null]); + + $this->assertEquals([['type' => 'mrkdwn', 'text' => "*Name*\nJack Black"]], $blocks[1]['fields']); + } + + #[Test] + public function it_puts_long_values_in_their_own_section() + { + $form = $this->form([ + ['handle' => 'name', 'field' => ['type' => 'text']], + ['handle' => 'message', 'field' => ['type' => 'textarea']], + ]); + + $blocks = $this->blocksForForm($form, ['name' => 'Jack Black', 'message' => "Hey there.\nLet's talk."]); + + $this->assertEquals([['type' => 'mrkdwn', 'text' => "*Name*\nJack Black"]], $blocks[1]['fields']); + $this->assertEquals(['type' => 'mrkdwn', 'text' => "*Message*\nHey there.\nLet's talk."], $blocks[2]['text']); + } + + #[Test] + #[DataProvider('optionFieldProvider')] + public function it_renders_option_labels($field, $value, $expected) + { + $form = $this->form([['handle' => 'choice', 'field' => $field]]); + + $blocks = $this->blocksForForm($form, ['choice' => $value]); + + $this->assertEquals("*Choice*\n{$expected}", $blocks[1]['fields'][0]['text']); + } + + public static function optionFieldProvider() + { + $options = ['sales' => 'Sales Enquiry', 'support' => 'Support Request']; + + return [ + 'select' => [['type' => 'select', 'options' => $options], 'sales', 'Sales Enquiry'], + 'select without a label' => [['type' => 'select', 'options' => ['sales' => null]], 'sales', 'sales'], + 'radio' => [['type' => 'radio', 'options' => $options], 'support', 'Support Request'], + 'multiple select' => [['type' => 'select', 'multiple' => true, 'options' => $options], ['sales', 'support'], 'Sales Enquiry, Support Request'], + 'checkboxes' => [['type' => 'checkboxes', 'options' => $options], ['sales'], 'Sales Enquiry'], + 'zero' => [['type' => 'radio', 'options' => ['0' => '0', '5' => '5']], '0', '0'], + ]; + } + + #[Test] + public function it_renders_stored_uploads_as_links() + { + Storage::fake('test', ['url' => 'http://localhost/assets']); + Storage::disk('test')->put('cv.pdf', ''); + AssetContainer::make('documents')->disk('test')->save(); + + $form = $this->form([['handle' => 'cv', 'field' => ['type' => 'form_upload', 'store' => true, 'container' => 'documents']]]); + + $blocks = $this->blocksForForm($form, ['cv' => ['cv.pdf']]); + + $this->assertEquals("*Cv*\n", $blocks[1]['fields'][0]['text']); + } + + #[Test] + public function it_renders_stored_uploads_in_a_private_container_as_filenames() + { + Storage::fake('test', ['url' => null]); + Storage::disk('test')->put('cv.pdf', ''); + AssetContainer::make('documents')->disk('test')->save(); + + $form = $this->form([['handle' => 'cv', 'field' => ['type' => 'form_upload', 'store' => true, 'container' => 'documents']]]); + + $blocks = $this->blocksForForm($form, ['cv' => ['cv.pdf']]); + + $this->assertEquals("*Cv*\ncv.pdf", $blocks[1]['fields'][0]['text']); + } + + #[Test] + public function it_renders_unstored_uploads_as_filenames() + { + $form = $this->form([['handle' => 'cv', 'field' => ['type' => 'form_upload']]]); + + $blocks = $this->blocksForForm($form, ['cv' => ['1785861616.23/cv/cv.pdf']]); + + $this->assertEquals("*Cv*\ncv.pdf", $blocks[1]['fields'][0]['text']); + } + + #[Test] + public function it_escapes_mrkdwn_characters() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack & ']); + + $this->assertEquals("*Name*\nJack & <Jill>", $blocks[1]['fields'][0]['text']); + } + + #[Test] + public function it_truncates_long_values() + { + $form = $this->form([['handle' => 'heading', 'field' => ['type' => 'textarea']]]); + + $blocks = $this->blocksForForm($form, ['heading' => str_repeat('a', 4000)]); + + $this->assertEquals(3000, mb_strlen($blocks[1]['text']['text'])); + $this->assertStringEndsWith('…', $blocks[1]['text']['text']); + } + + #[Test] + public function it_caps_the_number_of_blocks() + { + $fields = collect(range(1, 60)) + ->map(fn ($i) => ['handle' => "field_{$i}", 'field' => ['type' => 'textarea']]) + ->all(); + + $data = collect(range(1, 60))->mapWithKeys(fn ($i) => ["field_{$i}" => "line one\nline two"])->all(); + + $blocks = $this->blocksForForm($this->form($fields), $data); + + $this->assertCount(50, $blocks); + $this->assertEquals('context', $blocks[47]['type']); + $this->assertStringContainsString('too long', $blocks[47]['elements'][0]['text']); + } + + #[Test] + public function it_links_to_the_submission() + { + $submission = $this->submission($this->form(), ['name' => 'Jack Black']); + + $blocks = $this->blocksForSubmission($submission); + $button = collect($blocks)->firstWhere('type', 'actions')['elements'][0]; + + $this->assertEquals('View submission', $button['text']['text']); + $this->assertEquals(cp_route('forms.submissions.show', ['contact_us', $submission->id()]), $button['url']); + } + + #[Test] + public function it_omits_the_submission_link_when_disabled() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black'], ['link_to_submission' => false]); + + $this->assertNull(collect($blocks)->firstWhere('type', 'actions')); + } + + #[Test] + public function it_includes_a_context_footer() + { + $blocks = $this->blocksForForm($this->form(), ['name' => 'Jack Black']); + $context = collect($blocks)->last(); + + $this->assertEquals('context', $context['type']); + $this->assertStringStartsWith('Contact Us · default · Http::sequence() + ->push(['ok' => false, 'error' => 'not_in_channel']) + ->push(['ok' => true]), + 'slack.com/api/conversations.join' => Http::response(['ok' => true]), + ]); + + $this->send($this->form(), ['name' => 'Jack Black']); + + Http::assertSentCount(3); + Http::assertSent(fn (Request $request) => $request->url() === 'https://slack.com/api/conversations.join' && $request['channel'] === 'C0123ABCDEF'); + } + + #[Test] + public function it_releases_the_job_when_rate_limited() + { + Http::fake(['slack.com/*' => Http::response(['ok' => false, 'error' => 'ratelimited'], 429, ['Retry-After' => 42])]); + + $queueJob = Mockery::mock(Job::class); + $queueJob->shouldReceive('release')->once()->with(42); + + $this->job($this->form(), ['name' => 'Jack Black'])->setJob($queueJob)->handle(app(SlackClient::class)); + } + + #[Test] + public function it_throws_when_slack_is_unavailable() + { + Http::fake(['slack.com/*' => Http::response(null, 503)]); + + $this->expectException(RequestException::class); + + $this->send($this->form(), ['name' => 'Jack Black']); + } + + #[Test] + #[DataProvider('fatalErrorProvider')] + public function it_fails_without_retrying_on_fatal_errors($error) + { + Http::fake(['slack.com/*' => Http::response(['ok' => false, 'error' => $error])]); + + $queueJob = Mockery::mock(Job::class); + $queueJob->shouldReceive('fail')->once()->with(Mockery::on(fn (SlackRequestException $e) => $e->error() === $error)); + + $this->job($this->form(), ['name' => 'Jack Black'])->setJob($queueJob)->handle(app(SlackClient::class)); + + Http::assertSentCount(1); + } + + public static function fatalErrorProvider() + { + return [ + 'channel not found' => ['channel_not_found'], + 'invalid auth' => ['invalid_auth'], + 'archived channel' => ['is_archived'], + 'missing scope' => ['missing_scope'], + ]; + } + + #[Test] + public function it_doesnt_send_when_no_token_has_been_configured() + { + config(['forms-pro.connections.slack.token' => null]); + + Http::fake(); + + $queueJob = Mockery::mock(Job::class); + $queueJob->shouldReceive('fail')->once(); + + $this->job($this->form(), ['name' => 'Jack Black'])->setJob($queueJob)->handle(app(SlackClient::class)); + + Http::assertNothingSent(); + } + + private function form(?array $fields = null): FormContract + { + return tap(Form::make('contact_us')->title('Contact Us')->formFields([ + 'fields' => $fields ?? [ + ['handle' => 'name', 'field' => ['type' => 'text']], + ['handle' => 'email', 'field' => ['type' => 'text']], + ], + ]))->save(); + } + + private function submission(FormContract $form, array $data): Submission + { + return $form->makeSubmission()->data($data); + } + + private function config(array $overrides = []): array + { + return array_merge(['id' => 'abc', 'channel' => 'C0123ABCDEF', 'channel_name' => 'enquiries'], $overrides); + } + + private function job(FormContract $form, array $data = [], array $config = []): SendSlackMessage + { + return new SendSlackMessage($this->submission($form, $data), Site::default(), $this->config($config)); + } + + private function send(FormContract $form, array $data, array $config = []) + { + $this->job($form, $data, $config)->handle(app(SlackClient::class)); + } + + private function blocksForForm(FormContract $form, array $data, array $config = []): array + { + return $this->blocksForSubmission($this->submission($form, $data), $config); + } + + private function blocksForSubmission(Submission $submission, array $config = []): array + { + Http::fake(['slack.com/*' => Http::response(['ok' => true])]); + + new SendSlackMessage($submission, Site::default(), $this->config($config))->handle(app(SlackClient::class)); + + return Http::recorded()->first()[0]->data()['blocks']; + } +} diff --git a/tests/FormConnections/Slack/SlackChannelsTest.php b/tests/FormConnections/Slack/SlackChannelsTest.php new file mode 100644 index 0000000..0458b90 --- /dev/null +++ b/tests/FormConnections/Slack/SlackChannelsTest.php @@ -0,0 +1,136 @@ + 'xoxb-token']); + } + + #[Test] + public function it_denies_access_if_you_dont_have_permission() + { + Http::fake(); + + $this + ->actingAs($this->userWithoutPermission()) + ->channels($this->form()) + ->assertForbidden(); + + Http::assertNothingSent(); + } + + #[Test] + public function it_returns_the_channels() + { + Http::fake(['slack.com/*' => Http::response([ + 'ok' => true, + 'channels' => [ + ['id' => 'C0456DEFGHI', 'name' => 'general', 'is_private' => false], + ['id' => 'C0123ABCDEF', 'name' => 'enquiries', 'is_private' => true], + ], + ])]); + + $this + ->actingAs($this->userWithPermission()) + ->channels($this->form()) + ->assertOk() + ->assertExactJson(['channels' => [ + ['id' => 'C0123ABCDEF', 'name' => 'enquiries', 'is_private' => true], + ['id' => 'C0456DEFGHI', 'name' => 'general', 'is_private' => false], + ]]); + } + + #[Test] + public function it_follows_the_cursor_until_every_channel_has_been_fetched() + { + Http::fake(['slack.com/*' => Http::sequence() + ->push([ + 'ok' => true, + 'channels' => [['id' => 'C0123ABCDEF', 'name' => 'enquiries']], + 'response_metadata' => ['next_cursor' => 'page-two'], + ]) + ->push([ + 'ok' => true, + 'channels' => [['id' => 'C0456DEFGHI', 'name' => 'general']], + 'response_metadata' => ['next_cursor' => ''], + ]), + ]); + + $this + ->actingAs($this->userWithPermission()) + ->channels($this->form()) + ->assertOk() + ->assertJsonCount(2, 'channels'); + + Http::assertSentCount(2); + Http::assertSent(fn (Request $request) => $request['cursor'] === 'page-two'); + } + + #[Test] + public function it_caches_the_channels() + { + Http::fake(['slack.com/*' => Http::response(['ok' => true, 'channels' => []])]); + + $this->actingAs($this->userWithPermission()); + + $this->channels($form = $this->form())->assertOk(); + $this->channels($form)->assertOk(); + + Http::assertSentCount(1); + $this->assertNotNull(Cache::get('forms-pro.slack.channels')); + } + + #[Test] + public function it_returns_the_slack_error_when_the_token_is_invalid() + { + Http::fake(['slack.com/*' => Http::response(['ok' => false, 'error' => 'invalid_auth'])]); + + $this + ->actingAs($this->userWithPermission()) + ->channels($this->form()) + ->assertUnprocessable() + ->assertJson(['message' => 'Slack rejected your token. Check the FORMS_PRO_SLACK_TOKEN environment variable.']); + } + + private function form() + { + return tap(Form::make('test'))->save(); + } + + private function channels($form) + { + return $this->getJson(cp_route('forms.connect.slack.channels', $form->handle())); + } + + private function userWithoutPermission() + { + $this->setTestRoles(['test' => ['access cp']]); + + return tap(User::make()->assignRole('test'))->save(); + } + + private function userWithPermission() + { + $this->setTestRoles(['test' => ['access cp', 'edit forms']]); + + return tap(User::make()->assignRole('test'))->save(); + } +} diff --git a/tests/FormConnections/Slack/SlackConnectionTest.php b/tests/FormConnections/Slack/SlackConnectionTest.php new file mode 100644 index 0000000..a5f094b --- /dev/null +++ b/tests/FormConnections/Slack/SlackConnectionTest.php @@ -0,0 +1,125 @@ +connections(['slack' => [ + ['id' => 'abc', 'channel' => 'C0123ABCDEF'], + ['id' => 'def', 'channel' => 'C0456DEFGHI'], + ]]))->save(); + + $jobs = (new Slack)->finalized($form->makeSubmission()); + + $this->assertCount(2, $jobs); + $this->assertContainsOnlyInstancesOf(SendSlackMessage::class, $jobs); + $this->assertEquals('C0123ABCDEF', $jobs[0]->config['channel']); + $this->assertEquals('C0456DEFGHI', $jobs[1]->config['channel']); + } + + #[Test] + public function it_returns_no_jobs_when_the_form_has_no_slack_configs() + { + $form = tap(Form::make('test'))->save(); + + $this->assertEmpty((new Slack)->finalized($form->makeSubmission())); + } + + #[Test] + public function it_skips_disabled_configs() + { + $form = tap(Form::make('test')->connections(['slack' => [ + ['id' => 'abc', 'channel' => 'C0123ABCDEF', 'enabled' => false], + ['id' => 'def', 'channel' => 'C0456DEFGHI'], + ]]))->save(); + + $jobs = (new Slack)->finalized($form->makeSubmission()); + + $this->assertCount(1, $jobs); + $this->assertEquals('C0456DEFGHI', $jobs[0]->config['channel']); + } + + #[Test] + #[DataProvider('conditionsProvider')] + public function it_filters_configs_using_conditions($conditions, $value, $shouldDispatch) + { + $form = tap(Form::make('test')->formFields([ + 'fields' => [ + ['handle' => 'how_did_you_hear', 'field' => ['type' => 'text']], + ], + ])->connections(['slack' => [ + ['id' => 'abc', 'channel' => 'C0123ABCDEF', 'conditions' => $conditions], + ]]))->save(); + + $submission = $form->makeSubmission()->data(['how_did_you_hear' => $value]); + + $this->assertCount($shouldDispatch ? 1 : 0, (new Slack)->finalized($submission)); + } + + public static function conditionsProvider() + { + $conditions = [['field' => 'how_did_you_hear', 'operator' => 'equals', 'value' => 'friend', 'join' => 'and']]; + + return [ + 'no conditions' => [[], 'google', true], + 'matching conditions' => [$conditions, 'friend', true], + 'non-matching conditions' => [$conditions, 'google', false], + ]; + } + + #[Test] + public function it_counts_configs() + { + $form = tap(Form::make('test')->connections(['slack' => [ + ['id' => 'abc', 'channel' => 'C0123ABCDEF'], + ['id' => 'def', 'channel' => 'C0456DEFGHI'], + ]]))->save(); + + $this->assertEquals(2, (new Slack)->count($form)); + } + + #[Test] + public function it_renders_the_vue_component() + { + config(['forms-pro.connections.slack.token' => 'xoxb-token']); + + $form = tap(Form::make('test')->formFields([ + 'fields' => [ + ['handle' => 'name', 'field' => ['type' => 'text', 'display' => 'Full Name']], + ['handle' => 'about_you', 'field' => ['type' => 'heading', 'display' => 'About You']], + ], + ]))->save(); + + $component = (new Slack)->render($form)->toArray(); + + $this->assertEquals('slack-connection', $component['name']); + $this->assertEquals(cp_route('forms.connect.slack.update', 'test'), $component['props']['action']); + $this->assertEquals(cp_route('forms.connect.slack.channels', 'test'), $component['props']['channelsUrl']); + $this->assertEquals(cp_route('forms.connect.slack.test', 'test'), $component['props']['testUrl']); + $this->assertTrue($component['props']['configured']); + $this->assertEquals([['handle' => 'name', 'display' => 'Full Name']], $component['props']['fields']); + } + + #[Test] + public function it_reports_when_no_token_has_been_configured() + { + config(['forms-pro.connections.slack.token' => null]); + + $form = tap(Form::make('test'))->save(); + + $this->assertFalse((new Slack)->render($form)->toArray()['props']['configured']); + } +} diff --git a/tests/FormConnections/Slack/UpdateSlackConnectionTest.php b/tests/FormConnections/Slack/UpdateSlackConnectionTest.php new file mode 100644 index 0000000..d267bd0 --- /dev/null +++ b/tests/FormConnections/Slack/UpdateSlackConnectionTest.php @@ -0,0 +1,177 @@ +connections([ + 'slack' => [['id' => 'abc', 'channel' => 'C0123ABCDEF']], + ]))->save(); + + $this + ->from('/original') + ->actingAs($this->userWithoutPermission()) + ->update($form, ['configs' => []]) + ->assertRedirect('/original') + ->assertSessionHas('error'); + + $this->assertEquals([['id' => 'abc', 'channel' => 'C0123ABCDEF']], Form::find('test')->connections()->get('slack')); + } + + #[Test] + public function it_updates_the_slack_configs() + { + $form = tap(Form::make('test')->connections([ + 'webhook' => [['id' => 'abc', 'url' => 'https://example.com/hook']], + 'slack' => [['id' => 'def', 'channel' => 'C0123ABCDEF']], + ]))->save(); + + $this + ->actingAs($this->userWithPermission()) + ->update($form, ['configs' => [ + ['id' => 'def', 'channel' => 'C0456DEFGHI', 'channel_name' => 'general', 'enabled' => false], + ['id' => 'ghi', 'channel' => 'C0789JKLMNO', 'include_fields' => false, 'link_to_submission' => false], + ['id' => 'jkl', 'channel' => 'C0123ABCDEF', 'enabled' => true, 'include_fields' => true, 'link_to_submission' => true], + ]]) + ->assertOk(); + + $updated = Form::find('test'); + $this->assertEquals([ + ['id' => 'def', 'channel' => 'C0456DEFGHI', 'channel_name' => 'general', 'enabled' => false], + ['id' => 'ghi', 'channel' => 'C0789JKLMNO', 'include_fields' => false, 'link_to_submission' => false], + ['id' => 'jkl', 'channel' => 'C0123ABCDEF'], + ], $updated->connections()->get('slack')); + $this->assertEquals([['id' => 'abc', 'url' => 'https://example.com/hook']], $updated->connections()->get('webhook')); + } + + #[Test] + public function it_doesnt_persist_the_client_row_state() + { + $form = tap(Form::make('test'))->save(); + + $this + ->actingAs($this->userWithPermission()) + ->update($form, ['configs' => [['_id' => 'vue-row', 'id' => 'abc', 'channel' => 'C0123ABCDEF']]]) + ->assertOk(); + + $this->assertEquals([['id' => 'abc', 'channel' => 'C0123ABCDEF']], Form::find('test')->connections()->get('slack')); + } + + #[Test] + public function it_normalizes_the_conditions() + { + $form = tap(Form::make('test'))->save(); + + $this + ->actingAs($this->userWithPermission()) + ->update($form, ['configs' => [ + [ + 'id' => 'abc', + 'channel' => 'C0123ABCDEF', + 'conditions' => [ + ['_id' => 'vue-row', 'field' => 'name', 'operator' => 'equals', 'value' => 'Bob', 'join' => 'and'], + ['field' => null, 'operator' => 'equals', 'value' => 'incomplete', 'join' => 'and'], + ], + ], + ['id' => 'def', 'channel' => 'C0456DEFGHI', 'conditions' => []], + ]]) + ->assertOk(); + + $this->assertEquals([ + [ + 'id' => 'abc', + 'channel' => 'C0123ABCDEF', + 'conditions' => [['field' => 'name', 'operator' => 'equals', 'value' => 'Bob', 'join' => 'and']], + ], + ['id' => 'def', 'channel' => 'C0456DEFGHI'], + ], Form::find('test')->connections()->get('slack')); + } + + #[Test] + public function it_removes_null_values_from_configs() + { + $form = tap(Form::make('test'))->save(); + + $this + ->actingAs($this->userWithPermission()) + ->update($form, ['configs' => [[ + 'id' => 'abc', + 'channel' => 'C0123ABCDEF', + 'heading' => null, + 'enabled' => null, + ]]]) + ->assertOk(); + + $this->assertEquals([['id' => 'abc', 'channel' => 'C0123ABCDEF']], Form::find('test')->connections()->get('slack')); + } + + #[Test] + #[DataProvider('invalidPayloads')] + public function it_rejects_invalid_payloads($payload, $errors) + { + $form = tap(Form::make('test')->formFields([ + 'fields' => [['handle' => 'name', 'field' => ['type' => 'text']]], + ])->connections([ + 'slack' => [['id' => 'abc', 'channel' => 'C0123ABCDEF']], + ]))->save(); + + $this + ->actingAs($this->userWithPermission()) + ->updateJson($form, $payload) + ->assertUnprocessable() + ->assertJsonValidationErrors($errors); + + $this->assertEquals([['id' => 'abc', 'channel' => 'C0123ABCDEF']], Form::find('test')->connections()->get('slack')); + } + + public static function invalidPayloads() + { + return [ + 'missing configs' => [[], ['configs']], + 'configs not an array' => [['configs' => 'nope'], ['configs']], + 'config not an array' => [['configs' => ['nope']], ['configs.0']], + 'config without a channel' => [['configs' => [['enabled' => true]]], ['configs.0.channel']], + 'config with a channel name' => [['configs' => [['channel' => '#enquiries']]], ['configs.0.channel']], + 'config with a non-boolean include_fields' => [['configs' => [['channel' => 'C0123ABCDEF', 'include_fields' => 'nope']]], ['configs.0.include_fields']], + 'config with an unknown field' => [['configs' => [['channel' => 'C0123ABCDEF', 'fields' => ['nope']]]], ['configs.0.fields.0']], + ]; + } + + private function userWithoutPermission() + { + $this->setTestRoles(['test' => ['access cp']]); + + return tap(User::make()->assignRole('test'))->save(); + } + + private function userWithPermission() + { + $this->setTestRoles(['test' => ['access cp', 'edit forms']]); + + return tap(User::make()->assignRole('test'))->save(); + } + + private function update($form, $params = []) + { + return $this->patch(cp_route('forms.connect.slack.update', $form->handle()), $params); + } + + private function updateJson($form, $params = []) + { + return $this->patchJson(cp_route('forms.connect.slack.update', $form->handle()), $params); + } +} diff --git a/tests/__fixtures__/dev-null/.gitkeep b/tests/__fixtures__/dev-null/.gitkeep new file mode 100644 index 0000000..e69de29 From d1ed0fd68d199b762770f83c5c195cb36b1df77e Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Wed, 5 Aug 2026 17:26:17 +0100 Subject: [PATCH 02/95] refactor channels request and tweak authentication error messages --- lang/en/messages.php | 4 +- .../connections/SlackConnection.vue | 23 +-- src/FormConnections/Slack.php | 27 +++- .../CP/SlackChannelsController.php | 23 --- .../Slack/SlackChannelsTest.php | 136 ------------------ 5 files changed, 29 insertions(+), 184 deletions(-) delete mode 100644 src/Http/Controllers/CP/SlackChannelsController.php delete mode 100644 tests/FormConnections/Slack/SlackChannelsTest.php diff --git a/lang/en/messages.php b/lang/en/messages.php index b43a41c..5fa14e6 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -8,14 +8,14 @@ 'slack_connection_delete_confirmation' => 'Are you sure you want to delete this Slack notification?', 'slack_connection_include_fields_instructions' => 'Displays the submitted values as a table.', 'slack_connection_link_to_submission_instructions' => 'Add a button linking to the submission in the Control Panel.', - 'slack_connection_unavailable' => 'Couldn\'t reach Slack.', + 'slack_connection_unavailable' => 'Couldn\'t connect to Slack.', 'slack_connection_test_sent' => 'Test message sent.', 'slack_connection_truncated' => 'This submission was too long to show in full.', 'slack_connection_view_submission' => 'View submission', 'slack_error_account_inactive' => 'The Slack app has been deactivated in your workspace.', 'slack_error_channel_not_found' => 'That channel no longer exists, or it\'s private and the app hasn\'t been invited to it.', - 'slack_error_invalid_auth' => 'Slack rejected your token. Check the FORMS_PRO_SLACK_TOKEN environment variable.', + 'slack_error_invalid_auth' => 'Your token was rejected. Check the `FORMS_PRO_SLACK_TOKEN` environment variable.', 'slack_error_is_archived' => 'That channel has been archived.', 'slack_error_missing_scope' => 'The Slack app is missing a required scope. Reinstall it with the scopes listed in the documentation.', 'slack_error_missing_token' => 'No Slack token has been configured. Add one to your FORMS_PRO_SLACK_TOKEN environment variable.', diff --git a/resources/js/components/connections/SlackConnection.vue b/resources/js/components/connections/SlackConnection.vue index b5d2283..4aef2b4 100644 --- a/resources/js/components/connections/SlackConnection.vue +++ b/resources/js/components/connections/SlackConnection.vue @@ -11,20 +11,19 @@ const props = defineProps({ form: Object, config: { type: Array, default: () => [] }, action: String, - channelsUrl: String, testUrl: String, configured: Boolean, fields: { type: Array, default: () => [] }, + channels: { type: Array, default: () => [] }, + connectionError: String, }); const dirtyKey = 'slack-connection'; const errors = ref({}); -const channels = ref([]); const saving = ref(false); const testing = ref(null); const saveBinding = ref(null); -const connectionError = ref(null); const notifications = ref(props.config.map((notification) => ({ enabled: true, @@ -34,7 +33,7 @@ const notifications = ref(props.config.map((notification) => ({ conditions: (notification.conditions ?? []).map((condition) => ({ ...condition, _id: uniqid() })), }))); -const channelOptions = computed(() => channels.value.map((channel) => ({ ...channel, name: `#${channel.name}` }))); +const channelOptions = computed(() => props.channels.map((channel) => ({ ...channel, name: `#${channel.name}` }))); const selectedFields = (notification) => notification.fields ?? props.fields.map((field) => field.handle); @@ -65,7 +64,7 @@ const removeNotification = (notification) => const channelSelected = (notification, id) => { notification.channel = id; - notification.channel_name = channels.value.find((channel) => channel.id === id)?.name; + notification.channel_name = props.channels.find((channel) => channel.id === id)?.name; }; // TODO: Duplicated from ConnectionLogic.vue. Core doesn't export it, and its copy reads @@ -97,17 +96,6 @@ const conditionsSummary = (conditions) => { const error = (index, handle) => errors.value[`configs.${index}.${handle}`]?.[0]; const hasError = (index) => Object.keys(errors.value).some((key) => key.startsWith(`configs.${index}.`)); -const loadChannels = () => { - if (!props.configured) return; - - axios - .get(props.channelsUrl) - .then(({ data }) => (channels.value = data.channels)) - .catch((e) => (connectionError.value = e.response?.data?.message ?? __('Something went wrong'))); -}; - -const reload = () => window.location.reload(); - const save = () => { if (saving.value) return; @@ -134,8 +122,6 @@ const save = () => { watch(notifications, () => Statamic.$dirty.add(dirtyKey), { deep: true }); onMounted(() => { - loadChannels(); - saveBinding.value = keys.bindGlobal(['mod+s'], (e) => { e.preventDefault(); save(); @@ -160,7 +146,6 @@ onUnmounted(() => { -