stapel-hubspot 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stapel_hubspot-0.1.0/CONFIG.MD +3 -0
- stapel_hubspot-0.1.0/LICENSE +21 -0
- stapel_hubspot-0.1.0/MODULE.md +10 -0
- stapel_hubspot-0.1.0/PKG-INFO +59 -0
- stapel_hubspot-0.1.0/README.md +24 -0
- stapel_hubspot-0.1.0/__init__.py +25 -0
- stapel_hubspot-0.1.0/apps.py +15 -0
- stapel_hubspot-0.1.0/conf.py +8 -0
- stapel_hubspot-0.1.0/conftest.py +58 -0
- stapel_hubspot-0.1.0/dto.py +11 -0
- stapel_hubspot-0.1.0/llms.txt +9 -0
- stapel_hubspot-0.1.0/presenters.py +5 -0
- stapel_hubspot-0.1.0/py.typed +0 -0
- stapel_hubspot-0.1.0/pyproject.toml +81 -0
- stapel_hubspot-0.1.0/serializers.py +13 -0
- stapel_hubspot-0.1.0/setup.cfg +4 -0
- stapel_hubspot-0.1.0/stapel_hubspot.egg-info/PKG-INFO +59 -0
- stapel_hubspot-0.1.0/stapel_hubspot.egg-info/SOURCES.txt +47 -0
- stapel_hubspot-0.1.0/stapel_hubspot.egg-info/dependency_links.txt +1 -0
- stapel_hubspot-0.1.0/stapel_hubspot.egg-info/requires.txt +10 -0
- stapel_hubspot-0.1.0/stapel_hubspot.egg-info/top_level.txt +1 -0
- stapel_hubspot-0.1.0/stpl_hubspot_crm.py +156 -0
- stapel_hubspot-0.1.0/stpl_hubspot_html.py +73 -0
- stapel_hubspot-0.1.0/stpl_hubspot_provider.py +49 -0
- stapel_hubspot-0.1.0/stpl_hubspot_records.py +54 -0
- stapel_hubspot-0.1.0/tests/test_module_names.py +23 -0
- stapel_hubspot-0.1.0/tests/test_public_api.py +32 -0
- stapel_hubspot-0.1.0/tests/test_stpl_hubspot.py +87 -0
- stapel_hubspot-0.1.0/urls.py +4 -0
- stapel_hubspot-0.1.0/urls_v1.py +8 -0
- stapel_hubspot-0.1.0/views.py +28 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stapel contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# MODULE.md — stapel-hubspot
|
|
2
|
+
|
|
3
|
+
## Provider `hubspot`
|
|
4
|
+
Fields: `access_token` (secret); `portal_id`, `ui_domain` are filled by a check. Run a check once so links are matched to the account.
|
|
5
|
+
|
|
6
|
+
## HTTP
|
|
7
|
+
`POST /hubspot/api/v1/connections/<id>/record` `{link}` — needs permission to use.
|
|
8
|
+
|
|
9
|
+
## Unverified against a live account
|
|
10
|
+
The note association type ids (contact 202, company 190, deal 214) follow HubSpot's documentation and have not been read back from a real portal.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stapel-hubspot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: HubSpot for Stapel: notes on CRM records from Markdown, connection provider
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/usestapel/stapel-hubspot
|
|
7
|
+
Project-URL: Repository, https://github.com/usestapel/stapel-hubspot
|
|
8
|
+
Project-URL: Documentation, https://github.com/usestapel/stapel-hubspot#readme
|
|
9
|
+
Project-URL: Changelog, https://github.com/usestapel/stapel-hubspot/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/usestapel/stapel-hubspot/issues
|
|
11
|
+
Keywords: django,stapel,hubspot
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: stapel-core<1.0,>=0.99.5
|
|
27
|
+
Requires-Dist: stapel-integrations-core<1.0,>=0.1.0
|
|
28
|
+
Requires-Dist: drf-spectacular>=0.27
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: pytest-django; extra == "test"
|
|
33
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# stapel-hubspot
|
|
37
|
+
|
|
38
|
+
HubSpot for Stapel: attach notes written in Markdown to contacts, companies and deals, with a `hubspot` connection provider.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install stapel-hubspot
|
|
44
|
+
```
|
|
45
|
+
Add `stapel_integrations_core` and `stapel_hubspot` to `INSTALLED_APPS`, mount `path("hubspot/", include("stapel_hubspot.urls"))`.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from stapel_hubspot import HubSpotClient, StapelHubSpotIntegration, new_marker, parse_record_link
|
|
51
|
+
|
|
52
|
+
hubspot = StapelHubSpotIntegration(HubSpotClient(access_token))
|
|
53
|
+
ref = parse_record_link("https://app.hubspot.com/contacts/123/deal/456")
|
|
54
|
+
note_id = hubspot.create_note(ref, "## Summary\n- next step agreed", marker=new_marker("export:42"))
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
58
|
+
|
|
59
|
+
MIT licensed.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# stapel-hubspot
|
|
2
|
+
|
|
3
|
+
HubSpot for Stapel: attach notes written in Markdown to contacts, companies and deals, with a `hubspot` connection provider.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install stapel-hubspot
|
|
9
|
+
```
|
|
10
|
+
Add `stapel_integrations_core` and `stapel_hubspot` to `INSTALLED_APPS`, mount `path("hubspot/", include("stapel_hubspot.urls"))`.
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from stapel_hubspot import HubSpotClient, StapelHubSpotIntegration, new_marker, parse_record_link
|
|
16
|
+
|
|
17
|
+
hubspot = StapelHubSpotIntegration(HubSpotClient(access_token))
|
|
18
|
+
ref = parse_record_link("https://app.hubspot.com/contacts/123/deal/456")
|
|
19
|
+
note_id = hubspot.create_note(ref, "## Summary\n- next step agreed", marker=new_marker("export:42"))
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
23
|
+
|
|
24
|
+
MIT licensed.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""stapel-hubspot — HubSpot notes from the Stapel framework (lazy exports)."""
|
|
2
|
+
|
|
3
|
+
_LAZY_EXPORTS = {
|
|
4
|
+
"StapelHubSpotIntegration": ".stpl_hubspot_crm",
|
|
5
|
+
"HubSpotClient": ".stpl_hubspot_crm",
|
|
6
|
+
"new_marker": ".stpl_hubspot_crm",
|
|
7
|
+
"parse_record_link": ".stpl_hubspot_records",
|
|
8
|
+
"RecordRef": ".stpl_hubspot_records",
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
__all__ = sorted(_LAZY_EXPORTS)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def __getattr__(name):
|
|
15
|
+
if name in _LAZY_EXPORTS:
|
|
16
|
+
from importlib import import_module
|
|
17
|
+
|
|
18
|
+
value = getattr(import_module(_LAZY_EXPORTS[name], __name__), name)
|
|
19
|
+
globals()[name] = value
|
|
20
|
+
return value
|
|
21
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def __dir__():
|
|
25
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class HubSpotAppConfig(AppConfig):
|
|
5
|
+
name = "stapel_hubspot"
|
|
6
|
+
label = "hubspot"
|
|
7
|
+
verbose_name = "HubSpot"
|
|
8
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
9
|
+
|
|
10
|
+
def ready(self):
|
|
11
|
+
from stapel_integrations_core.stpl_integrations_providers import register_provider
|
|
12
|
+
|
|
13
|
+
from .stpl_hubspot_provider import HubSpotProvider
|
|
14
|
+
|
|
15
|
+
register_provider(HubSpotProvider())
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
def pytest_configure(config):
|
|
2
|
+
from django.conf import settings
|
|
3
|
+
if not settings.configured:
|
|
4
|
+
settings.configure(
|
|
5
|
+
SECRET_KEY="test-secret-key-not-for-production",
|
|
6
|
+
INSTALLED_APPS=[
|
|
7
|
+
"django.contrib.contenttypes",
|
|
8
|
+
"django.contrib.auth",
|
|
9
|
+
"django.contrib.sessions",
|
|
10
|
+
"django.contrib.admin",
|
|
11
|
+
"django.contrib.messages",
|
|
12
|
+
"stapel_core.django.users",
|
|
13
|
+
"rest_framework",
|
|
14
|
+
"stapel_integrations_core",
|
|
15
|
+
"stapel_hubspot",
|
|
16
|
+
],
|
|
17
|
+
AUTH_USER_MODEL="users.User",
|
|
18
|
+
DATABASES={
|
|
19
|
+
"default": {
|
|
20
|
+
"ENGINE": "django.db.backends.sqlite3",
|
|
21
|
+
"NAME": ":memory:",
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
|
|
25
|
+
USE_TZ=True,
|
|
26
|
+
ROOT_URLCONF="stapel_hubspot.tests.urls",
|
|
27
|
+
CACHES={
|
|
28
|
+
"default": {
|
|
29
|
+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
# Synchronous in-process comm with schema validation ON, so the
|
|
33
|
+
# committed contracts in schemas/ are enforced by the tests.
|
|
34
|
+
STAPEL_BUS_BACKEND="stapel_core.bus.backends.memory.MemoryBus",
|
|
35
|
+
STAPEL_COMM={
|
|
36
|
+
"OUTBOX_ENABLED": False,
|
|
37
|
+
"ACTION_TRANSPORT": "inprocess",
|
|
38
|
+
"VALIDATE_SCHEMAS": True,
|
|
39
|
+
},
|
|
40
|
+
MIGRATION_MODULES={
|
|
41
|
+
"users": None,
|
|
42
|
+
"integrations": None, "hubspot": None,
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
import django
|
|
46
|
+
django.setup()
|
|
47
|
+
|
|
48
|
+
from stapel_core.comm.schemas import autoload_schemas
|
|
49
|
+
autoload_schemas()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
import pytest # noqa: E402
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@pytest.fixture
|
|
56
|
+
def api_client():
|
|
57
|
+
from rest_framework.test import APIClient
|
|
58
|
+
return APIClient()
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# stapel-hubspot
|
|
2
|
+
|
|
3
|
+
> HubSpot for Stapel: attach notes written in Markdown to contacts, companies and deals, with a `hubspot` connection provider.
|
|
4
|
+
|
|
5
|
+
## Rules
|
|
6
|
+
- Show `get_record(ref).name` to the user before writing.
|
|
7
|
+
- Always pass a marker. After `UnknownOutcome` call `find_notes(marker)` (search lags about a minute) before sending again.
|
|
8
|
+
- `update_note` is safe to repeat; `create_note` is not.
|
|
9
|
+
- Pass the connection's `portal_id` to `parse_record_link` so a link of another account is refused.
|
|
File without changes
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "stapel-hubspot"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "HubSpot for Stapel: notes on CRM records from Markdown, connection provider"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
keywords = ["django", "stapel", "hubspot"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Framework :: Django",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"stapel-core>=0.99.5,<1.0",
|
|
28
|
+
"stapel-integrations-core>=0.1.0,<1.0",
|
|
29
|
+
"drf-spectacular>=0.27",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/usestapel/stapel-hubspot"
|
|
34
|
+
Repository = "https://github.com/usestapel/stapel-hubspot"
|
|
35
|
+
Documentation = "https://github.com/usestapel/stapel-hubspot#readme"
|
|
36
|
+
Changelog = "https://github.com/usestapel/stapel-hubspot/blob/main/CHANGELOG.md"
|
|
37
|
+
Issues = "https://github.com/usestapel/stapel-hubspot/issues"
|
|
38
|
+
|
|
39
|
+
[project.optional-dependencies]
|
|
40
|
+
all = []
|
|
41
|
+
# ONE declaration of what the TEST SUITE needs, as opposed to what the package
|
|
42
|
+
# needs. CI installs exactly this (`pip install -e ".[test]"`), so a sibling a
|
|
43
|
+
# test imports and this list does not name is a red release on a clean runner —
|
|
44
|
+
# the class that killed three of them in one night on 2026-08-24. The gate over
|
|
45
|
+
# this list is `stapel-sibling-lint` (SIB001-006), wired into CI below; the
|
|
46
|
+
# skip-vs-fail half of the contract is `tests/siblings.py`.
|
|
47
|
+
test = [
|
|
48
|
+
"pytest",
|
|
49
|
+
"pytest-django",
|
|
50
|
+
"pytest-cov",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.setuptools]
|
|
54
|
+
package-dir = {"stapel_hubspot" = "."}
|
|
55
|
+
packages = ["stapel_hubspot"]
|
|
56
|
+
|
|
57
|
+
[tool.setuptools.package-data]
|
|
58
|
+
# The contract documents ship IN THE WHEEL: that is what makes
|
|
59
|
+
# `stapel-catalog --from-installed` possible, i.e. what turns catalog
|
|
60
|
+
# freshness from somebody's discipline into a property of the lockfile.
|
|
61
|
+
# A module that keeps them repo-only publishes code an agent cannot read.
|
|
62
|
+
stapel_hubspot = ["py.typed", "llms.txt", "MODULE.md", "docs/capabilities.json", "docs/flows.json", "docs/errors.json", "CONFIG.MD"]
|
|
63
|
+
|
|
64
|
+
[tool.ruff]
|
|
65
|
+
target-version = "py311"
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint]
|
|
68
|
+
# Single source for the git hooks and CI (they pass the same flags on the CLI).
|
|
69
|
+
select = ["E", "F", "W"]
|
|
70
|
+
ignore = ["E501"]
|
|
71
|
+
|
|
72
|
+
[tool.pytest.ini_options]
|
|
73
|
+
django_find_project = false
|
|
74
|
+
addopts = "--tb=short -q --import-mode=importlib"
|
|
75
|
+
|
|
76
|
+
[tool.coverage.run]
|
|
77
|
+
omit = [
|
|
78
|
+
"*/tests/*",
|
|
79
|
+
"*/conftest.py",
|
|
80
|
+
"*/migrations/*",
|
|
81
|
+
]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from rest_framework import serializers
|
|
2
|
+
from stapel_core.django.api.serializers import StapelDataclassSerializer
|
|
3
|
+
|
|
4
|
+
from .dto import HubSpotRecordDTO
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class HubSpotRecordSerializer(StapelDataclassSerializer):
|
|
8
|
+
class Meta:
|
|
9
|
+
dataclass = HubSpotRecordDTO
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class RecordLinkSerializer(serializers.Serializer):
|
|
13
|
+
link = serializers.CharField(max_length=2048)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stapel-hubspot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: HubSpot for Stapel: notes on CRM records from Markdown, connection provider
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/usestapel/stapel-hubspot
|
|
7
|
+
Project-URL: Repository, https://github.com/usestapel/stapel-hubspot
|
|
8
|
+
Project-URL: Documentation, https://github.com/usestapel/stapel-hubspot#readme
|
|
9
|
+
Project-URL: Changelog, https://github.com/usestapel/stapel-hubspot/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/usestapel/stapel-hubspot/issues
|
|
11
|
+
Keywords: django,stapel,hubspot
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: Django
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: stapel-core<1.0,>=0.99.5
|
|
27
|
+
Requires-Dist: stapel-integrations-core<1.0,>=0.1.0
|
|
28
|
+
Requires-Dist: drf-spectacular>=0.27
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: pytest-django; extra == "test"
|
|
33
|
+
Requires-Dist: pytest-cov; extra == "test"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# stapel-hubspot
|
|
37
|
+
|
|
38
|
+
HubSpot for Stapel: attach notes written in Markdown to contacts, companies and deals, with a `hubspot` connection provider.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install stapel-hubspot
|
|
44
|
+
```
|
|
45
|
+
Add `stapel_integrations_core` and `stapel_hubspot` to `INSTALLED_APPS`, mount `path("hubspot/", include("stapel_hubspot.urls"))`.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from stapel_hubspot import HubSpotClient, StapelHubSpotIntegration, new_marker, parse_record_link
|
|
51
|
+
|
|
52
|
+
hubspot = StapelHubSpotIntegration(HubSpotClient(access_token))
|
|
53
|
+
ref = parse_record_link("https://app.hubspot.com/contacts/123/deal/456")
|
|
54
|
+
note_id = hubspot.create_note(ref, "## Summary\n- next step agreed", marker=new_marker("export:42"))
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
See `MODULE.md` for the contract, `CONFIG.MD` for settings, `llms.txt` for agents.
|
|
58
|
+
|
|
59
|
+
MIT licensed.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
CONFIG.MD
|
|
2
|
+
LICENSE
|
|
3
|
+
MODULE.md
|
|
4
|
+
README.md
|
|
5
|
+
__init__.py
|
|
6
|
+
apps.py
|
|
7
|
+
conf.py
|
|
8
|
+
conftest.py
|
|
9
|
+
dto.py
|
|
10
|
+
llms.txt
|
|
11
|
+
presenters.py
|
|
12
|
+
py.typed
|
|
13
|
+
pyproject.toml
|
|
14
|
+
serializers.py
|
|
15
|
+
stpl_hubspot_crm.py
|
|
16
|
+
stpl_hubspot_html.py
|
|
17
|
+
stpl_hubspot_provider.py
|
|
18
|
+
stpl_hubspot_records.py
|
|
19
|
+
urls.py
|
|
20
|
+
urls_v1.py
|
|
21
|
+
views.py
|
|
22
|
+
./CONFIG.MD
|
|
23
|
+
./MODULE.md
|
|
24
|
+
./__init__.py
|
|
25
|
+
./apps.py
|
|
26
|
+
./conf.py
|
|
27
|
+
./conftest.py
|
|
28
|
+
./dto.py
|
|
29
|
+
./llms.txt
|
|
30
|
+
./presenters.py
|
|
31
|
+
./py.typed
|
|
32
|
+
./serializers.py
|
|
33
|
+
./stpl_hubspot_crm.py
|
|
34
|
+
./stpl_hubspot_html.py
|
|
35
|
+
./stpl_hubspot_provider.py
|
|
36
|
+
./stpl_hubspot_records.py
|
|
37
|
+
./urls.py
|
|
38
|
+
./urls_v1.py
|
|
39
|
+
./views.py
|
|
40
|
+
stapel_hubspot.egg-info/PKG-INFO
|
|
41
|
+
stapel_hubspot.egg-info/SOURCES.txt
|
|
42
|
+
stapel_hubspot.egg-info/dependency_links.txt
|
|
43
|
+
stapel_hubspot.egg-info/requires.txt
|
|
44
|
+
stapel_hubspot.egg-info/top_level.txt
|
|
45
|
+
tests/test_module_names.py
|
|
46
|
+
tests/test_public_api.py
|
|
47
|
+
tests/test_stpl_hubspot.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
stapel_hubspot
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""``StapelHubSpotIntegration`` — notes on HubSpot contacts, companies and deals.
|
|
2
|
+
|
|
3
|
+
HubSpot has no idempotency key. Every note therefore carries a *marker*; after
|
|
4
|
+
an :class:`UnknownOutcome` search for it before sending again::
|
|
5
|
+
|
|
6
|
+
marker = new_marker("export:42")
|
|
7
|
+
record = parse_record_link(pasted_url)
|
|
8
|
+
try:
|
|
9
|
+
note_id = hubspot.create_note(record, "## Summary\\n…", marker=marker)
|
|
10
|
+
except UnknownOutcome:
|
|
11
|
+
found = hubspot.find_notes(marker) # search lags about a minute
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Optional
|
|
21
|
+
|
|
22
|
+
from stapel_integrations_core.stpl_integrations_net import (
|
|
23
|
+
ApiClient,
|
|
24
|
+
RejectedError,
|
|
25
|
+
UnknownOutcome,
|
|
26
|
+
path_segment,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
from .stpl_hubspot_html import markdown_to_note_html
|
|
30
|
+
from .stpl_hubspot_records import OBJECTS, RecordRef
|
|
31
|
+
|
|
32
|
+
API_HOST = "api.hubapi.com"
|
|
33
|
+
#: HubSpot's limit on a note body.
|
|
34
|
+
NOTE_LIMIT = 65536
|
|
35
|
+
_MARKER = re.compile(r"^stplref[0-9a-f]{20}$")
|
|
36
|
+
_NAME_PROPERTIES = {"contact": "firstname,lastname", "company": "name,domain", "deal": "dealname"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class HubSpotClient(ApiClient):
|
|
40
|
+
"""The API host is fixed: a token is never sent anywhere else."""
|
|
41
|
+
|
|
42
|
+
user_agent = "stapel-hubspot"
|
|
43
|
+
|
|
44
|
+
def __init__(self, access_token: str, **kwargs) -> None:
|
|
45
|
+
token = (access_token or "").strip()
|
|
46
|
+
if not token or any(ord(c) <= 0x20 or ord(c) >= 0x7F for c in token):
|
|
47
|
+
raise RejectedError("the access token is empty or malformed")
|
|
48
|
+
super().__init__(
|
|
49
|
+
API_HOST, headers={"Authorization": f"Bearer {token}"}, secrets=(token,), **kwargs)
|
|
50
|
+
|
|
51
|
+
def error_detail(self, body: bytes) -> str:
|
|
52
|
+
text = body.decode("utf-8", "replace").strip()
|
|
53
|
+
try:
|
|
54
|
+
return str(json.loads(text).get("message") or text)
|
|
55
|
+
except (ValueError, AttributeError):
|
|
56
|
+
return text
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Account:
|
|
61
|
+
portal_id: str
|
|
62
|
+
ui_domain: str
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Record:
|
|
67
|
+
ref: RecordRef
|
|
68
|
+
name: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def new_marker(seed: str) -> str:
|
|
72
|
+
"""One searchable word; the same *seed* gives the same marker."""
|
|
73
|
+
return "stplref" + hashlib.sha256(seed.encode()).hexdigest()[:20]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def note_body(markdown: str, marker: str = "") -> str:
|
|
77
|
+
html = markdown_to_note_html(markdown)
|
|
78
|
+
if marker:
|
|
79
|
+
if not _MARKER.match(marker):
|
|
80
|
+
raise RejectedError("use new_marker() to make a marker")
|
|
81
|
+
html += f"<p>Ref {marker}</p>"
|
|
82
|
+
if len(html) > NOTE_LIMIT:
|
|
83
|
+
raise RejectedError(f"the note is longer than HubSpot's {NOTE_LIMIT} characters")
|
|
84
|
+
return html
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class StapelHubSpotIntegration:
|
|
88
|
+
def __init__(self, client: HubSpotClient) -> None:
|
|
89
|
+
self.client = client
|
|
90
|
+
|
|
91
|
+
def account(self) -> Account:
|
|
92
|
+
"""The account behind the token — the harmless credential check."""
|
|
93
|
+
data = self.client.get("/account-info/v3/details") or {}
|
|
94
|
+
return Account(str(data.get("portalId", "")), data.get("uiDomain", "app.hubspot.com"))
|
|
95
|
+
|
|
96
|
+
def get_record(self, ref: RecordRef) -> Record:
|
|
97
|
+
"""Show the user what they are about to write to."""
|
|
98
|
+
plural = OBJECTS[ref.object_type][0]
|
|
99
|
+
data = self.client.get(
|
|
100
|
+
f"/crm/v3/objects/{plural}/{path_segment(ref.record_id)}",
|
|
101
|
+
{"properties": _NAME_PROPERTIES[ref.object_type]},
|
|
102
|
+
) or {}
|
|
103
|
+
values = data.get("properties") or {}
|
|
104
|
+
if ref.object_type == "contact":
|
|
105
|
+
name = " ".join(filter(None, [values.get("firstname"), values.get("lastname")]))
|
|
106
|
+
else:
|
|
107
|
+
name = values.get("name" if ref.object_type == "company" else "dealname") or ""
|
|
108
|
+
return Record(ref, name or f"{ref.object_type.title()} {ref.record_id}")
|
|
109
|
+
|
|
110
|
+
def create_note(self, ref: RecordRef, markdown: str, *, marker: str = "",
|
|
111
|
+
timestamp_ms: Optional[int] = None) -> str:
|
|
112
|
+
"""Create a note attached to a record, in one request. Returns its id."""
|
|
113
|
+
data = self.client.post("/crm/v3/objects/notes", {
|
|
114
|
+
"properties": {
|
|
115
|
+
"hs_timestamp": str(timestamp_ms or int(time.time() * 1000)),
|
|
116
|
+
"hs_note_body": note_body(markdown, marker),
|
|
117
|
+
},
|
|
118
|
+
"associations": [{
|
|
119
|
+
"to": {"id": ref.record_id},
|
|
120
|
+
"types": [{
|
|
121
|
+
"associationCategory": "HUBSPOT_DEFINED",
|
|
122
|
+
"associationTypeId": OBJECTS[ref.object_type][2],
|
|
123
|
+
}],
|
|
124
|
+
}],
|
|
125
|
+
})
|
|
126
|
+
note_id = (data or {}).get("id")
|
|
127
|
+
if not note_id:
|
|
128
|
+
raise UnknownOutcome("HubSpot accepted the note but returned no id")
|
|
129
|
+
return str(note_id)
|
|
130
|
+
|
|
131
|
+
def update_note(self, note_id: str, markdown: str, *, marker: str = "") -> None:
|
|
132
|
+
"""Replace the body; the note keeps its date. Safe to repeat."""
|
|
133
|
+
self.client.patch(
|
|
134
|
+
f"/crm/v3/objects/notes/{path_segment(note_id)}",
|
|
135
|
+
{"properties": {"hs_note_body": note_body(markdown, marker)}},
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def find_notes(self, marker: str) -> list:
|
|
139
|
+
"""Ids of the notes that carry *marker*. New notes take a minute to appear."""
|
|
140
|
+
if not _MARKER.match(marker):
|
|
141
|
+
raise RejectedError("use new_marker() to make a marker")
|
|
142
|
+
data = self.client.post(
|
|
143
|
+
"/crm/v3/objects/notes/search",
|
|
144
|
+
{"query": marker, "limit": 10, "properties": ["hs_note_body"]},
|
|
145
|
+
read_only=True,
|
|
146
|
+
) or {}
|
|
147
|
+
return [
|
|
148
|
+
str(hit["id"]) for hit in data.get("results") or []
|
|
149
|
+
if marker in ((hit.get("properties") or {}).get("hs_note_body") or "")
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
__all__ = [
|
|
154
|
+
"API_HOST", "Account", "HubSpotClient", "NOTE_LIMIT", "Record",
|
|
155
|
+
"StapelHubSpotIntegration", "new_marker", "note_body",
|
|
156
|
+
]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Markdown to the small HTML a HubSpot note body accepts.
|
|
2
|
+
|
|
3
|
+
All text is escaped; the only tags are the ones written here, and the only
|
|
4
|
+
attribute is the ``href`` of a web or mail link.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from html import escape
|
|
10
|
+
|
|
11
|
+
from stapel_integrations_core import stpl_integrations_markdown as md
|
|
12
|
+
|
|
13
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _text(value: str) -> str:
|
|
17
|
+
return escape(_CONTROL.sub(" ", value), quote=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _inline(nodes: list) -> str:
|
|
21
|
+
out = []
|
|
22
|
+
for node in nodes:
|
|
23
|
+
if node[0] == "break":
|
|
24
|
+
out.append("<br>")
|
|
25
|
+
continue
|
|
26
|
+
_, value, marks = node
|
|
27
|
+
html = _text(value)
|
|
28
|
+
for mark in reversed(tuple(dict.fromkeys(marks))):
|
|
29
|
+
if isinstance(mark, tuple):
|
|
30
|
+
html = f'<a href="{escape(mark[1], quote=True)}">{html}</a>'
|
|
31
|
+
else:
|
|
32
|
+
tag = {"strong": "strong", "em": "em", "code": "code", "strike": "s"}[mark]
|
|
33
|
+
html = f"<{tag}>{html}</{tag}>"
|
|
34
|
+
out.append(html)
|
|
35
|
+
return "".join(out)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _list(kind: str, items: list) -> str:
|
|
39
|
+
tag = "ol" if kind == "ordered" else "ul"
|
|
40
|
+
body = "".join(
|
|
41
|
+
"<li>"
|
|
42
|
+
+ (("[x] " if done else "[ ] ") if kind == "task" else "")
|
|
43
|
+
+ _inline(inline)
|
|
44
|
+
+ "".join(_list(c[1], c[2]) for c in children)
|
|
45
|
+
+ "</li>"
|
|
46
|
+
for inline, done, children in items
|
|
47
|
+
)
|
|
48
|
+
return f"<{tag}>{body}</{tag}>"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _block(block: tuple) -> str:
|
|
52
|
+
kind = block[0]
|
|
53
|
+
if kind == "heading":
|
|
54
|
+
return f"<p><strong>{_inline(block[2])}</strong></p>"
|
|
55
|
+
if kind == "paragraph":
|
|
56
|
+
return f"<p>{_inline(block[1])}</p>"
|
|
57
|
+
if kind == "list":
|
|
58
|
+
return _list(block[1], block[2])
|
|
59
|
+
if kind == "code":
|
|
60
|
+
return f"<pre>{_text(block[2])}</pre>"
|
|
61
|
+
if kind == "quote":
|
|
62
|
+
return f"<blockquote>{''.join(_block(b) for b in block[1])}</blockquote>"
|
|
63
|
+
if kind == "rule":
|
|
64
|
+
return "<hr>"
|
|
65
|
+
_, header, rows = block
|
|
66
|
+
return "".join(f"<p>{' | '.join(_inline(c) for c in row)}</p>" for row in [header, *rows])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def markdown_to_note_html(markdown: str) -> str:
|
|
70
|
+
return "".join(_block(b) for b in md.parse(markdown))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
__all__ = ["markdown_to_note_html"]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""The ``hubspot`` provider: one connection is one HubSpot account."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from stapel_integrations_core.stpl_integrations_net import IntegrationError
|
|
5
|
+
from stapel_integrations_core.stpl_integrations_providers import (
|
|
6
|
+
CheckResult,
|
|
7
|
+
Field,
|
|
8
|
+
IntegrationProvider,
|
|
9
|
+
InvalidField,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from .stpl_hubspot_crm import HubSpotClient, StapelHubSpotIntegration
|
|
13
|
+
|
|
14
|
+
SLUG = "hubspot"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HubSpotProvider(IntegrationProvider):
|
|
18
|
+
slug = SLUG
|
|
19
|
+
title = "HubSpot"
|
|
20
|
+
fields = (
|
|
21
|
+
Field("access_token", "secret", required=True, label="Access token",
|
|
22
|
+
help="A private app token with read access to contacts, companies and deals "
|
|
23
|
+
"and write access to contacts.", max_length=512),
|
|
24
|
+
Field("portal_id", read_only=True, label="Account ID"),
|
|
25
|
+
Field("ui_domain", read_only=True, label="Account domain"),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
def clean(self, config: dict, secrets: dict) -> tuple:
|
|
29
|
+
try:
|
|
30
|
+
HubSpotClient(secrets.get("access_token", ""))
|
|
31
|
+
except IntegrationError as exc:
|
|
32
|
+
raise InvalidField("access_token", exc.detail) from exc
|
|
33
|
+
return config, secrets
|
|
34
|
+
|
|
35
|
+
def client(self, secrets: dict) -> HubSpotClient:
|
|
36
|
+
return HubSpotClient(secrets["access_token"])
|
|
37
|
+
|
|
38
|
+
def build(self, config: dict, secrets: dict) -> StapelHubSpotIntegration:
|
|
39
|
+
return StapelHubSpotIntegration(self.client(secrets))
|
|
40
|
+
|
|
41
|
+
def check(self, config: dict, secrets: dict) -> CheckResult:
|
|
42
|
+
account = self.build(config, secrets).account()
|
|
43
|
+
return CheckResult(
|
|
44
|
+
ok=bool(account.portal_id), errors={"hubspot": ""},
|
|
45
|
+
config={"portal_id": account.portal_id, "ui_domain": account.ui_domain},
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
__all__ = ["HubSpotProvider", "SLUG"]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""A pasted HubSpot record link to ``(portal, object type, id)``.
|
|
2
|
+
|
|
3
|
+
The link is only parsed, never fetched.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
|
|
11
|
+
from stapel_integrations_core.stpl_integrations_net import RejectedError
|
|
12
|
+
|
|
13
|
+
#: object type -> (REST plural, record-URL code, HubSpot-defined note association id)
|
|
14
|
+
OBJECTS = {
|
|
15
|
+
"contact": ("contacts", "0-1", 202),
|
|
16
|
+
"company": ("companies", "0-2", 190),
|
|
17
|
+
"deal": ("deals", "0-3", 214),
|
|
18
|
+
}
|
|
19
|
+
_BY_CODE = {code: name for name, (_, code, _id) in OBJECTS.items()}
|
|
20
|
+
_HOST = re.compile(r"^app(-[a-z]{2,3}[0-9]{1,2})?\.hubspot\.com$")
|
|
21
|
+
_NAMED = re.compile(r"^/contacts/(\d{1,20})/(contact|company|deal)/(\d{1,20})(?:/|$)")
|
|
22
|
+
_CODED = re.compile(r"^/contacts/(\d{1,20})/record/(0-[123])/(\d{1,20})(?:/|$)")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class RecordRef:
|
|
27
|
+
object_type: str
|
|
28
|
+
record_id: str
|
|
29
|
+
portal_id: str = ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_record_link(link: str, *, portal_id: str = "") -> RecordRef:
|
|
33
|
+
"""A contact, company or deal link; with *portal_id*, only of that account."""
|
|
34
|
+
try:
|
|
35
|
+
parts = urlsplit((link or "").strip())
|
|
36
|
+
except ValueError as exc:
|
|
37
|
+
raise RejectedError("this is not a HubSpot record link") from exc
|
|
38
|
+
if parts.scheme != "https" or not _HOST.match(parts.netloc.lower()):
|
|
39
|
+
raise RejectedError("paste the address of a HubSpot record (app.hubspot.com)")
|
|
40
|
+
named = _NAMED.match(parts.path)
|
|
41
|
+
coded = _CODED.match(parts.path)
|
|
42
|
+
if named:
|
|
43
|
+
portal, object_type, record_id = named.groups()
|
|
44
|
+
elif coded:
|
|
45
|
+
portal, code, record_id = coded.groups()
|
|
46
|
+
object_type = _BY_CODE[code]
|
|
47
|
+
else:
|
|
48
|
+
raise RejectedError("only contact, company and deal links are supported")
|
|
49
|
+
if portal_id and portal != str(portal_id):
|
|
50
|
+
raise RejectedError("this link belongs to another HubSpot account")
|
|
51
|
+
return RecordRef(object_type, record_id, portal)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = ["OBJECTS", "RecordRef", "parse_record_link"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Our own modules are named ``stpl_<library>_<module>``.
|
|
2
|
+
|
|
3
|
+
The package has a flat layout: with the repository root on ``sys.path`` a
|
|
4
|
+
module called ``markdown`` or ``http`` would shadow the real one. Only the
|
|
5
|
+
names Django and the Stapel tools look for stay bare.
|
|
6
|
+
"""
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
CONVENTIONAL = {
|
|
10
|
+
"__init__", "actions", "admin", "apps", "checks", "conf", "conftest", "dto", "errors",
|
|
11
|
+
"functions", "gdpr", "models", "presenters", "serializers", "services", "urls", "urls_v1",
|
|
12
|
+
"views", "_capabilities", "_codegen", "_codegen_settings", "codegen_urls",
|
|
13
|
+
}
|
|
14
|
+
PREFIX = "stpl_hubspot_"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_every_other_module_is_prefixed():
|
|
18
|
+
root = Path(__file__).resolve().parent.parent
|
|
19
|
+
bare = sorted(
|
|
20
|
+
p.stem for p in root.glob("*.py")
|
|
21
|
+
if p.stem not in CONVENTIONAL and not p.stem.startswith(PREFIX)
|
|
22
|
+
)
|
|
23
|
+
assert bare == []
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Package-level public API (PEP 562 lazy exports) and import hygiene."""
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import stapel_hubspot
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestLazyExports:
|
|
10
|
+
def test_all_names_resolve(self):
|
|
11
|
+
for name in stapel_hubspot.__all__:
|
|
12
|
+
assert getattr(stapel_hubspot, name) is not None
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TestImportWithoutDjangoSettings:
|
|
16
|
+
def test_package_import_is_django_free(self):
|
|
17
|
+
"""`import stapel_hubspot` must not import Django nor require settings."""
|
|
18
|
+
env = {k: v for k, v in os.environ.items() if k != "DJANGO_SETTINGS_MODULE"}
|
|
19
|
+
code = (
|
|
20
|
+
"import sys\n"
|
|
21
|
+
"import stapel_hubspot\n"
|
|
22
|
+
'polluted = [m for m in sys.modules if m == "django" or m.startswith("django.")]\n'
|
|
23
|
+
'assert not polluted, f"django imported at package import time: {polluted}"\n'
|
|
24
|
+
)
|
|
25
|
+
result = subprocess.run(
|
|
26
|
+
[sys.executable, "-c", code],
|
|
27
|
+
capture_output=True,
|
|
28
|
+
text=True,
|
|
29
|
+
env=env,
|
|
30
|
+
cwd=os.path.dirname(sys.executable),
|
|
31
|
+
)
|
|
32
|
+
assert result.returncode == 0, result.stderr
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from stapel_hubspot import HubSpotClient, RecordRef, StapelHubSpotIntegration, new_marker, parse_record_link
|
|
4
|
+
from stapel_hubspot.stpl_hubspot_html import markdown_to_note_html
|
|
5
|
+
from stapel_integrations_core.stpl_integrations_net import (
|
|
6
|
+
AuthError, RejectedError, TransportFailure, UnknownOutcome,
|
|
7
|
+
)
|
|
8
|
+
from stapel_integrations_core.stpl_integrations_testing import FakeTransport
|
|
9
|
+
|
|
10
|
+
TOKEN = "pat-eu1-SECRET-000000000000"
|
|
11
|
+
NOTES = "/crm/v3/objects/notes"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def transport():
|
|
16
|
+
return FakeTransport()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.fixture
|
|
20
|
+
def hubspot(transport):
|
|
21
|
+
return StapelHubSpotIntegration(HubSpotClient(TOKEN, transport=transport, sleep=lambda _s: None))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.mark.parametrize("link,kind", [
|
|
25
|
+
("https://app.hubspot.com/contacts/123/contact/55?x=1", "contact"),
|
|
26
|
+
("https://app-eu1.hubspot.com/contacts/123/record/0-2/55/", "company"),
|
|
27
|
+
("https://app.hubspot.com/contacts/123/record/0-3/55", "deal"),
|
|
28
|
+
])
|
|
29
|
+
def test_record_links(link, kind):
|
|
30
|
+
assert parse_record_link(link, portal_id="123") == RecordRef(kind, "55", "123")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.mark.parametrize("link", [
|
|
34
|
+
"http://app.hubspot.com/contacts/1/contact/2", "https://evil.example/contacts/1/contact/2",
|
|
35
|
+
"https://app.hubspot.com.evil.example/contacts/1/contact/2",
|
|
36
|
+
"https://u@app.hubspot.com/contacts/1/contact/2",
|
|
37
|
+
"https://app.hubspot.com/contacts/1/record/0-5/2", "https://app.hubspot.com/contacts/1/contact/",
|
|
38
|
+
"https://app.hubspot.com/contacts/999/contact/2",
|
|
39
|
+
])
|
|
40
|
+
def test_bad_record_links(link):
|
|
41
|
+
with pytest.raises(RejectedError):
|
|
42
|
+
parse_record_link(link, portal_id="1")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_note_is_one_request_with_association_and_marker(hubspot, transport):
|
|
46
|
+
transport.on("POST", NOTES, (201, {"id": "9"}))
|
|
47
|
+
marker = new_marker("export:1")
|
|
48
|
+
assert hubspot.create_note(RecordRef("deal", "55"), "**ok** <script>", marker=marker, timestamp_ms=5) == "9"
|
|
49
|
+
sent = transport.calls[0]["json"]
|
|
50
|
+
assert sent["properties"] == {
|
|
51
|
+
"hs_timestamp": "5",
|
|
52
|
+
"hs_note_body": f"<p><strong>ok</strong> <script></p><p>Ref {marker}</p>"}
|
|
53
|
+
assert sent["associations"][0]["types"][0]["associationTypeId"] == 214
|
|
54
|
+
assert transport.calls[0]["host"] == "api.hubapi.com" and len(transport.calls) == 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.mark.parametrize("answer", [(500, {}), (202, {}), TransportFailure("x", sent=True)])
|
|
58
|
+
def test_unconfirmed_note_is_unknown_and_not_retried(hubspot, transport, answer):
|
|
59
|
+
transport.on("POST", NOTES, answer)
|
|
60
|
+
with pytest.raises(UnknownOutcome):
|
|
61
|
+
hubspot.create_note(RecordRef("contact", "1"), "x")
|
|
62
|
+
assert len(transport.calls) == 1
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_find_notes_trusts_only_the_marker(hubspot, transport):
|
|
66
|
+
marker = new_marker("export:2")
|
|
67
|
+
transport.on("POST", NOTES + "/search", (503, {}), {"results": [
|
|
68
|
+
{"id": "1", "properties": {"hs_note_body": f"<p>Ref {marker}</p>"}},
|
|
69
|
+
{"id": "2", "properties": {"hs_note_body": "unrelated"}}]})
|
|
70
|
+
assert hubspot.find_notes(marker) == ["1"] and len(transport.calls) == 2
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_token_never_leaks(hubspot, transport):
|
|
74
|
+
transport.on("GET", "/account-info/v3/details", (401, {"message": f"bad {TOKEN}"}))
|
|
75
|
+
with pytest.raises(AuthError) as caught:
|
|
76
|
+
hubspot.account()
|
|
77
|
+
assert "SECRET" not in caught.value.detail + repr(hubspot.client)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_oversized_note_is_refused_before_sending(hubspot, transport):
|
|
81
|
+
with pytest.raises(RejectedError):
|
|
82
|
+
hubspot.create_note(RecordRef("contact", "1"), "&" * 20000)
|
|
83
|
+
assert transport.calls == []
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_dangerous_link_in_note():
|
|
87
|
+
assert "<a " not in markdown_to_note_html("[x](javascript:alert(1))")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Check a pasted record link and show which record it is."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from drf_spectacular.utils import extend_schema
|
|
5
|
+
from stapel_integrations_core import services
|
|
6
|
+
from stapel_integrations_core.views import IntegrationAPIView, maps_errors
|
|
7
|
+
|
|
8
|
+
from .presenters import present_record
|
|
9
|
+
from .serializers import HubSpotRecordSerializer, RecordLinkSerializer
|
|
10
|
+
from .stpl_hubspot_provider import SLUG
|
|
11
|
+
from .stpl_hubspot_records import parse_record_link
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@extend_schema(tags=["HubSpot"])
|
|
15
|
+
class RecordLookupView(IntegrationAPIView):
|
|
16
|
+
provider_slug = SLUG
|
|
17
|
+
request_serializer_class = RecordLinkSerializer
|
|
18
|
+
response_serializer_class = HubSpotRecordSerializer
|
|
19
|
+
|
|
20
|
+
@extend_schema(request=RecordLinkSerializer, responses={200: HubSpotRecordSerializer})
|
|
21
|
+
@maps_errors
|
|
22
|
+
def post(self, request, connection_id): # noqa: R007 — settings CRUD and pickers, no user flow of their own
|
|
23
|
+
row = services.get_connection(request.user, connection_id, services.USE, provider=SLUG)
|
|
24
|
+
body = self.get_request_serializer_class()(data=request.data)
|
|
25
|
+
body.is_valid(raise_exception=True)
|
|
26
|
+
ref = parse_record_link(body.validated_data["link"], portal_id=row.config.get("portal_id", ""))
|
|
27
|
+
record = services.open_integration(row).get_record(ref)
|
|
28
|
+
return self.serialized_response(present_record(record))
|