django-shopify-kit 0.1.0__py3-none-any.whl
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.
- django_shopify_kit-0.1.0.dist-info/METADATA +183 -0
- django_shopify_kit-0.1.0.dist-info/RECORD +16 -0
- django_shopify_kit-0.1.0.dist-info/WHEEL +5 -0
- django_shopify_kit-0.1.0.dist-info/top_level.txt +1 -0
- shopify_kit/__init__.py +0 -0
- shopify_kit/apps.py +34 -0
- shopify_kit/checks.py +48 -0
- shopify_kit/event_bus.py +114 -0
- shopify_kit/events.py +43 -0
- shopify_kit/handlers.py +47 -0
- shopify_kit/legacy_tasks.py +63 -0
- shopify_kit/models.py +94 -0
- shopify_kit/referrals.py +44 -0
- shopify_kit/services/__init__.py +0 -0
- shopify_kit/services/crm.py +54 -0
- shopify_kit/tasks.py +48 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django_shopify_kit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Event bus, shop lifecycle events and CRM wiring for Django apps built on django_shopify_app
|
|
5
|
+
Author: Santiago Fernandez
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Framework :: Django
|
|
8
|
+
Classifier: Framework :: Django :: 5.2
|
|
9
|
+
Classifier: Framework :: Django :: 6.0
|
|
10
|
+
Classifier: Framework :: Django :: 6.1
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Requires-Dist: Django<7,>=5.2
|
|
20
|
+
Requires-Dist: django_shopify_app[celery]>=2.20.0
|
|
21
|
+
Requires-Dist: django-crm-events
|
|
22
|
+
Requires-Dist: requests>=2.25
|
|
23
|
+
|
|
24
|
+
# django-shopify-kit
|
|
25
|
+
|
|
26
|
+
The layer between [django_shopify_app](https://pypi.org/project/django_shopify_app/) and your Shopify app: an event bus, shop lifecycle events, and handlers that send those events to your CRM.
|
|
27
|
+
|
|
28
|
+
- **`shopify_kit.event_bus`**: emit events from model methods; handlers run after the transaction commits.
|
|
29
|
+
- **`ShopKitMixin`** for your shop model: emits `ShopInstalled`, `ShopUserLoggedIn`, `ShopUninstalled` and `ShopSaved`, and has the CRM methods.
|
|
30
|
+
- **Handlers**, registered at startup, that store the shop's GID and send installs, logins, uninstalls and plan price changes to the CRM through Celery.
|
|
31
|
+
|
|
32
|
+
## Requirements
|
|
33
|
+
|
|
34
|
+
- Python 3.10+ and Django 5.2 through 6.1
|
|
35
|
+
- django_shopify_app 2.20.0+ with its `celery` extra, and `SHOPIFY_SHOP_MODEL` set
|
|
36
|
+
- Celery
|
|
37
|
+
- [django-crm-events](https://pypi.org/project/django-crm-events/), configured with its own settings
|
|
38
|
+
- Optional: django_shopify_pricing, for the plan price handler
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install django-shopify-kit
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Add the app:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
INSTALLED_APPS = [
|
|
50
|
+
# ...
|
|
51
|
+
"shopify_app",
|
|
52
|
+
"shopify_kit",
|
|
53
|
+
"shops",
|
|
54
|
+
]
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
List `ShopKitMixin` before `ShopBase` in your shop model, and subclass `ShopUserBase` for the shop's users:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from shopify_app.models import ShopBase, ShopUserBase
|
|
61
|
+
from shopify_kit.models import ShopKitMixin
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Shop(ShopKitMixin, ShopBase):
|
|
65
|
+
...
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class User(ShopUserBase):
|
|
69
|
+
...
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Then run `makemigrations` and `migrate`. `ShopKitMixin` includes django_shopify_app's `ShopLifecycleMixin`, which adds `status`, `installed_at` and `uninstalled_at`. `manage.py check` reports a shop model without the mixin (`shopify_kit.E001`) or with `ShopBase` listed first (`shopify_kit.E002`).
|
|
73
|
+
|
|
74
|
+
## Events
|
|
75
|
+
|
|
76
|
+
`ShopKitMixin` overrides four methods of the shop model and emits an event from each:
|
|
77
|
+
|
|
78
|
+
| Method | Event | When |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| `installed(request=None)` | `ShopInstalled(shop, request)` | Once per install. django_shopify_app calls `installed()` for every token it acquires; only the call that claims the install emits |
|
|
81
|
+
| `on_user_login(user_data, request=None)` | `ShopUserLoggedIn(shop, user, user_data, request)` | A staff user opened the app. The user is stored first, through `shop.users` |
|
|
82
|
+
| `uninstall()` | `ShopUninstalled(shop)` | After the shop's credentials are cleared |
|
|
83
|
+
| `save()` | `ShopSaved(shop)` | Every save |
|
|
84
|
+
|
|
85
|
+
Register your own handlers from an `AppConfig.ready()`:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from django.apps import AppConfig
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class OrdersConfig(AppConfig):
|
|
92
|
+
name = "orders"
|
|
93
|
+
|
|
94
|
+
def ready(self) -> None:
|
|
95
|
+
from shopify_kit.event_bus import register_handler
|
|
96
|
+
from shopify_kit.events import ShopInstalled
|
|
97
|
+
|
|
98
|
+
from .handlers import import_orders
|
|
99
|
+
|
|
100
|
+
register_handler(ShopInstalled, import_orders)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- Handlers run from `transaction.on_commit`, so a Celery task a handler queues sees the committed data. Outside a transaction they run right away.
|
|
104
|
+
- `register_handler` takes the event class, not its dotted name, and raises once startup is over: request threads read the registry without a lock.
|
|
105
|
+
|
|
106
|
+
### Emitting your own events
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from dataclasses import dataclass
|
|
110
|
+
|
|
111
|
+
from django.utils.decorators import method_decorator
|
|
112
|
+
from shopify_kit.event_bus import Event, use_event_bus
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@dataclass
|
|
116
|
+
class RewardRedeemed(Event):
|
|
117
|
+
reward: "Reward"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Reward(models.Model):
|
|
121
|
+
@method_decorator(use_event_bus)
|
|
122
|
+
def redeem(self, *, events: list[Event]) -> None:
|
|
123
|
+
...
|
|
124
|
+
events.append(RewardRedeemed(reward=self))
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`use_event_bus` passes the method a new `events` list and dispatches what it appends once the method returns. Keep `events` keyword-only and without a default.
|
|
128
|
+
|
|
129
|
+
## What the package does on each event
|
|
130
|
+
|
|
131
|
+
| Event | Handler |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `ShopInstalled` | Stores the shop's GID (`shop.ensure_shopify_gid()`), sends the install to the CRM, and reports it to the partners service |
|
|
134
|
+
| `ShopUserLoggedIn` | Sends the login to the CRM |
|
|
135
|
+
| `ShopUninstalled` | Sends the uninstall to the CRM |
|
|
136
|
+
| django_shopify_pricing's `subscription_price_changed` | Sends the new price to the CRM. Connected only when `shopify_pricing` is installed |
|
|
137
|
+
|
|
138
|
+
The CRM calls and the GID run in Celery tasks (`shopify_kit.tasks`). The CRM methods on the mixin (`crm_on_install()`, `crm_on_login()`, `crm_on_uninstall()`, `crm_on_billing_plan_change()`) read the shop's name, email, phone and country from the GraphQL Admin API. If Shopify refuses the request, they send the shop's domain alone.
|
|
139
|
+
|
|
140
|
+
### Partners service
|
|
141
|
+
|
|
142
|
+
An install is posted to a partners service, with the merchant's IP for referral tracking, when all three settings are set:
|
|
143
|
+
|
|
144
|
+
| Setting | Description |
|
|
145
|
+
|---|---|
|
|
146
|
+
| `SHOPIFY_KIT_PARTNERS_URL` | The endpoint that receives the install |
|
|
147
|
+
| `SHOPIFY_KIT_PARTNERS_API_KEY` | Its API key |
|
|
148
|
+
| `SHOPIFY_KIT_PARTNERS_APP_ID` | The app's ID in the partners service |
|
|
149
|
+
|
|
150
|
+
Without them nothing is sent. The call has a timeout, and an error is logged, never raised.
|
|
151
|
+
|
|
152
|
+
## The uninstall webhook
|
|
153
|
+
|
|
154
|
+
Queue django_shopify_app's task from your webhook callback; it calls `shop.uninstall()`, which emits `ShopUninstalled`:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from shopify_app.tasks import uninstall_shop
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def webhook_entry(shopify_domain, topic, data, attributes=None):
|
|
161
|
+
if topic == "app/uninstalled":
|
|
162
|
+
uninstall_shop.delay(shopify_domain)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Moving an app that has its own copies
|
|
166
|
+
|
|
167
|
+
An app cloned from django-shopify-app-base before this package has the same tasks under `shops.tasks.*`. During the deploy that moves it, tasks queued under those names would be dropped. List the old names for that one release:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
CELERY_IMPORTS = ["shopify_kit.legacy_tasks"]
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Development
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
python -m venv .venv
|
|
177
|
+
.venv/bin/pip install -e . pytest pytest-django
|
|
178
|
+
.venv/bin/pytest
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Releasing
|
|
182
|
+
|
|
183
|
+
Bump `version` in `pyproject.toml`, add the entry to `CHANGES.txt` and push to `main`. Once the tests pass, `.github/workflows/release.yml` publishes that version to PyPI and tags a GitHub release. PyPI never accepts the same version twice, so a bad release is fixed with a new version.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
shopify_kit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
shopify_kit/apps.py,sha256=ENa9OYuWOqJY3phSsdZ8JcdwFiLZc4-atXYawAibE6o,1380
|
|
3
|
+
shopify_kit/checks.py,sha256=Zns5ffjLV-ZvDJ2pfGYwApbIZfRUBEMQrgbWX5HpqSk,1664
|
|
4
|
+
shopify_kit/event_bus.py,sha256=Ia-l5Xyuegy2XoVS6AdNsprB7mBUzxckKEkSS_TiYqk,3856
|
|
5
|
+
shopify_kit/events.py,sha256=1M6dFDJqNtPGeIWQ4Bx4QHjF9F9JoOwJPyZPnkD65Dg,1010
|
|
6
|
+
shopify_kit/handlers.py,sha256=eavtkQb7B7jxmbjveUgaGavjjpkPtnZN997Fdzl-XoM,1543
|
|
7
|
+
shopify_kit/legacy_tasks.py,sha256=Nubh383r_B2hsO62MSiyjOvEGrA1NtMihjwFNQ3dxCk,2359
|
|
8
|
+
shopify_kit/models.py,sha256=UzWmoWYNVqvtLr7Q4NSI74IgJrc1Ic2UjZY_2Yy7sAE,3548
|
|
9
|
+
shopify_kit/referrals.py,sha256=rvgY66jEkF58fjoCpq9E17h-OUIiPG5k9AAVG0Cq01c,1442
|
|
10
|
+
shopify_kit/tasks.py,sha256=W5O5ZzXgLApksOEY8dgrboVUcza-mLHtyYQkLjZ0VLA,1351
|
|
11
|
+
shopify_kit/services/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
shopify_kit/services/crm.py,sha256=L0PhnRUfdsO7EZ9UMIFJ8_dMoVc4K27Ma1qRLuokyeA,1542
|
|
13
|
+
django_shopify_kit-0.1.0.dist-info/METADATA,sha256=gi_QdZYT1hQRqGDygY298IR4kT_uz12T57FqIuBKfsM,6896
|
|
14
|
+
django_shopify_kit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
django_shopify_kit-0.1.0.dist-info/top_level.txt,sha256=HQNz7YzWR09v5R5SiY8PLA--xgbWdc965SAvHAZ3N-E,12
|
|
16
|
+
django_shopify_kit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
shopify_kit
|
shopify_kit/__init__.py
ADDED
|
File without changes
|
shopify_kit/apps.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from django.apps import AppConfig, apps
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ShopifyKitConfig(AppConfig):
|
|
5
|
+
"""Django app for the event bus, the shop events and their CRM handlers."""
|
|
6
|
+
|
|
7
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
8
|
+
name = "shopify_kit"
|
|
9
|
+
verbose_name = "Shopify kit"
|
|
10
|
+
|
|
11
|
+
def ready(self) -> None:
|
|
12
|
+
"""Register the system checks and the package's shop event handlers."""
|
|
13
|
+
from . import checks # noqa: F401 (registers the checks)
|
|
14
|
+
from .event_bus import register_handler
|
|
15
|
+
from .events import ShopInstalled, ShopUninstalled, ShopUserLoggedIn
|
|
16
|
+
from .handlers import (
|
|
17
|
+
handle_shop_installed,
|
|
18
|
+
handle_shop_uninstalled,
|
|
19
|
+
handle_shop_user_logged_in,
|
|
20
|
+
handle_subscription_price_changed,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
register_handler(ShopInstalled, handle_shop_installed)
|
|
24
|
+
register_handler(ShopUserLoggedIn, handle_shop_user_logged_in)
|
|
25
|
+
register_handler(ShopUninstalled, handle_shop_uninstalled)
|
|
26
|
+
|
|
27
|
+
# django_shopify_pricing is optional: apps on the Billing API don't have it.
|
|
28
|
+
if apps.is_installed("shopify_pricing"):
|
|
29
|
+
from shopify_pricing.signals import subscription_price_changed
|
|
30
|
+
|
|
31
|
+
subscription_price_changed.connect(
|
|
32
|
+
handle_subscription_price_changed,
|
|
33
|
+
dispatch_uid="shopify_kit.handle_subscription_price_changed",
|
|
34
|
+
)
|
shopify_kit/checks.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""System checks for the shop model.
|
|
2
|
+
|
|
3
|
+
Registered in ``ShopifyKitConfig.ready()``; ``manage.py check``, ``runserver`` and
|
|
4
|
+
``migrate`` run them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from django.apps import apps
|
|
10
|
+
from django.conf import settings
|
|
11
|
+
from django.core.checks import CheckMessage, Error, register
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@register()
|
|
15
|
+
def check_shop_model(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:
|
|
16
|
+
"""E001: the shop model lacks ``ShopKitMixin``. E002: it comes after ``ShopBase``."""
|
|
17
|
+
from shopify_app.models import ShopBase
|
|
18
|
+
|
|
19
|
+
from .models import ShopKitMixin
|
|
20
|
+
|
|
21
|
+
shop_model_path = getattr(settings, "SHOPIFY_SHOP_MODEL", None)
|
|
22
|
+
if not shop_model_path:
|
|
23
|
+
# django_shopify_app's own checks report a missing SHOPIFY_SHOP_MODEL.
|
|
24
|
+
return []
|
|
25
|
+
mro = _mro(apps.get_model(shop_model_path))
|
|
26
|
+
if ShopKitMixin not in mro:
|
|
27
|
+
return [
|
|
28
|
+
Error(
|
|
29
|
+
f"{shop_model_path} doesn't inherit shopify_kit.models.ShopKitMixin.",
|
|
30
|
+
hint="Add ShopKitMixin to the shop model's bases, before ShopBase.",
|
|
31
|
+
id="shopify_kit.E001",
|
|
32
|
+
)
|
|
33
|
+
]
|
|
34
|
+
if mro.index(ShopKitMixin) > mro.index(ShopBase):
|
|
35
|
+
return [
|
|
36
|
+
Error(
|
|
37
|
+
f"{shop_model_path} lists ShopBase before ShopKitMixin, so ShopBase's "
|
|
38
|
+
"installed(), on_user_login() and CRM methods win.",
|
|
39
|
+
hint="List ShopKitMixin before ShopBase in the shop model's bases.",
|
|
40
|
+
id="shopify_kit.E002",
|
|
41
|
+
)
|
|
42
|
+
]
|
|
43
|
+
return []
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _mro(model: type) -> tuple[type, ...]:
|
|
47
|
+
"""Return the classes ``model`` inherits from, in method resolution order."""
|
|
48
|
+
return model.__mro__
|
shopify_kit/event_bus.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""An in-process event bus whose handlers run after the transaction commits.
|
|
2
|
+
|
|
3
|
+
A method decorated with ``use_event_bus`` receives an ``events`` list, appends
|
|
4
|
+
``Event`` instances to it, and the bus dispatches them to the handlers registered for
|
|
5
|
+
their class::
|
|
6
|
+
|
|
7
|
+
class Shop(ShopBase):
|
|
8
|
+
@method_decorator(use_event_bus)
|
|
9
|
+
def uninstall(self, *, events: list[Event]) -> None:
|
|
10
|
+
...
|
|
11
|
+
events.append(ShopUninstalled(shop=self))
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from django.apps import apps
|
|
19
|
+
from django.db import transaction
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Event:
|
|
25
|
+
"""Base class of every event; subclasses are usually dataclasses."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Written only during startup, so request threads read it without a lock.
|
|
29
|
+
_HANDLERS: dict[type[Event], list[Callable[[Event], None]]] = {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register_handler(
|
|
33
|
+
event_class: type[Event], handler: Callable[[Event], None]
|
|
34
|
+
) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Register a handler for an event class.
|
|
37
|
+
|
|
38
|
+
Call it from an app's AppConfig.ready(). Once the app registry is ready it
|
|
39
|
+
raises RuntimeError: requests run in several threads of one process and read
|
|
40
|
+
the registry without a lock, so it must not change after startup. Several
|
|
41
|
+
handlers can listen to the same event, and registering the same handler twice
|
|
42
|
+
has no effect.
|
|
43
|
+
|
|
44
|
+
It takes the event class rather than its dotted name, so renaming or moving
|
|
45
|
+
an event fails at startup instead of silently dropping its handlers.
|
|
46
|
+
|
|
47
|
+
Example:
|
|
48
|
+
# myapp/apps.py
|
|
49
|
+
class MyAppConfig(AppConfig):
|
|
50
|
+
def ready(self):
|
|
51
|
+
from shopify_kit.event_bus import register_handler
|
|
52
|
+
from shopify_kit.events import ShopInstalled
|
|
53
|
+
from .handlers import on_shop_installed
|
|
54
|
+
|
|
55
|
+
register_handler(ShopInstalled, on_shop_installed)
|
|
56
|
+
"""
|
|
57
|
+
if not (isinstance(event_class, type) and issubclass(event_class, Event)):
|
|
58
|
+
raise TypeError(
|
|
59
|
+
f"register_handler expects an Event subclass, got {event_class!r}"
|
|
60
|
+
)
|
|
61
|
+
if apps.ready:
|
|
62
|
+
raise RuntimeError(
|
|
63
|
+
"register_handler() must be called from an AppConfig.ready(), "
|
|
64
|
+
f"not after startup (registering {handler!r} for {event_class.__name__})"
|
|
65
|
+
)
|
|
66
|
+
handlers = _HANDLERS.setdefault(event_class, [])
|
|
67
|
+
if handler not in handlers:
|
|
68
|
+
handlers.append(handler)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def handle_events(events: list[Event]) -> None:
|
|
72
|
+
"""
|
|
73
|
+
Handle events after the current transaction commits.
|
|
74
|
+
|
|
75
|
+
Uses transaction.on_commit() to ensure that any Celery tasks
|
|
76
|
+
dispatched by event handlers only run after the database state
|
|
77
|
+
is consistent and visible to other connections.
|
|
78
|
+
|
|
79
|
+
If called outside a transaction, handlers execute immediately.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def _dispatch_events() -> None:
|
|
83
|
+
"""Call each event's handlers, in the order the events were emitted."""
|
|
84
|
+
for event in events:
|
|
85
|
+
handlers = _HANDLERS.get(type(event), [])
|
|
86
|
+
logger.debug(
|
|
87
|
+
"Dispatching event %s to %d handlers",
|
|
88
|
+
type(event).__name__,
|
|
89
|
+
len(handlers),
|
|
90
|
+
)
|
|
91
|
+
for handler in handlers:
|
|
92
|
+
handler(event)
|
|
93
|
+
|
|
94
|
+
transaction.on_commit(_dispatch_events)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def use_event_bus(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
98
|
+
"""Pass ``func`` a new ``events`` list and dispatch what it appends to it.
|
|
99
|
+
|
|
100
|
+
The events are handed to ``handle_events`` once ``func`` returns; nothing is
|
|
101
|
+
dispatched when it raises. On a method, apply it with ``method_decorator``.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
105
|
+
"""Call ``func`` with ``events`` and dispatch them afterwards."""
|
|
106
|
+
kwargs["events"] = []
|
|
107
|
+
|
|
108
|
+
result = func(*args, **kwargs)
|
|
109
|
+
|
|
110
|
+
handle_events(kwargs["events"])
|
|
111
|
+
|
|
112
|
+
return result
|
|
113
|
+
|
|
114
|
+
return wrapper
|
shopify_kit/events.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""The shop events ``ShopKitMixin`` emits. Register handlers for them from an
|
|
2
|
+
``AppConfig.ready()`` with ``shopify_kit.event_bus.register_handler``."""
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from .event_bus import Event
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from django.http import HttpRequest
|
|
11
|
+
from shopify_app.models import ShopBase, ShopUserBase
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ShopInstalled(Event):
|
|
16
|
+
"""The app was installed on the shop. Emitted once per install."""
|
|
17
|
+
|
|
18
|
+
shop: "ShopBase"
|
|
19
|
+
request: "HttpRequest | None"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ShopSaved(Event):
|
|
24
|
+
"""The shop was saved."""
|
|
25
|
+
|
|
26
|
+
shop: "ShopBase"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class ShopUninstalled(Event):
|
|
31
|
+
"""The app was uninstalled from the shop; its credentials are cleared."""
|
|
32
|
+
|
|
33
|
+
shop: "ShopBase"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class ShopUserLoggedIn(Event):
|
|
38
|
+
"""A Shopify staff user opened the app. ``user_data`` is what Shopify sent."""
|
|
39
|
+
|
|
40
|
+
shop: "ShopBase"
|
|
41
|
+
user: "ShopUserBase"
|
|
42
|
+
user_data: dict[str, Any]
|
|
43
|
+
request: "HttpRequest | None"
|
shopify_kit/handlers.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""What the package does on each shop event. ``ShopifyKitConfig.ready()`` registers
|
|
2
|
+
these; an app adds its own handlers for the same events from its own ``ready()``."""
|
|
3
|
+
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from .referrals import report_install_to_partners
|
|
8
|
+
from .tasks import (
|
|
9
|
+
crm_on_billing_plan_change,
|
|
10
|
+
crm_on_install,
|
|
11
|
+
crm_on_login,
|
|
12
|
+
crm_on_uninstall,
|
|
13
|
+
ensure_shop_gid,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from shopify_app.models import ShopBase
|
|
18
|
+
|
|
19
|
+
from .events import ShopInstalled, ShopUninstalled, ShopUserLoggedIn
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def handle_shop_installed(event: "ShopInstalled") -> None:
|
|
23
|
+
"""Store the shop's GID, send the install to the CRM and report it to partners."""
|
|
24
|
+
ensure_shop_gid.delay(event.shop.id)
|
|
25
|
+
crm_on_install.delay(event.shop.id)
|
|
26
|
+
report_install_to_partners(event.shop, event.request)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def handle_shop_user_logged_in(event: "ShopUserLoggedIn") -> None:
|
|
30
|
+
"""Send the login to the CRM."""
|
|
31
|
+
crm_on_login.delay(event.shop.id, event.user_data)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def handle_shop_uninstalled(event: "ShopUninstalled") -> None:
|
|
35
|
+
"""Send the uninstall to the CRM."""
|
|
36
|
+
crm_on_uninstall.delay(event.shop.id)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def handle_subscription_price_changed(
|
|
40
|
+
sender: Any, shop: "ShopBase", price: Decimal, **kwargs: Any
|
|
41
|
+
) -> None:
|
|
42
|
+
"""Send the shop's new App Pricing base price to the CRM.
|
|
43
|
+
|
|
44
|
+
Receives django_shopify_pricing's ``subscription_price_changed``, which is sent
|
|
45
|
+
after the commit of a sync that changed the price.
|
|
46
|
+
"""
|
|
47
|
+
crm_on_billing_plan_change.delay(shop.id, float(price))
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""The names the tasks had while they lived in each app's ``shops`` package.
|
|
2
|
+
|
|
3
|
+
A deploy that moves an app to this package can leave tasks queued under the old
|
|
4
|
+
names, and a worker drops a task whose name it doesn't know. List this module in
|
|
5
|
+
``CELERY_IMPORTS`` for that one release, and remove it in the next::
|
|
6
|
+
|
|
7
|
+
CELERY_IMPORTS = ["shopify_kit.legacy_tasks"]
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from celery import shared_task
|
|
13
|
+
from shopify_app import tasks as shopify_app_tasks
|
|
14
|
+
|
|
15
|
+
from . import tasks
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@shared_task(name="shops.tasks.fetch_shopify_shop_data")
|
|
19
|
+
def fetch_shopify_shop_data(shop_id: int) -> None:
|
|
20
|
+
"""Old name of ``shopify_kit.tasks.ensure_shop_gid``."""
|
|
21
|
+
tasks.ensure_shop_gid(shop_id)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@shared_task(name="shops.tasks.crm_on_install_task")
|
|
25
|
+
def crm_on_install_task(shop_id: int) -> None:
|
|
26
|
+
"""Old name of ``shopify_kit.tasks.crm_on_install``."""
|
|
27
|
+
tasks.crm_on_install(shop_id)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@shared_task(name="shops.tasks.crm_on_login_task")
|
|
31
|
+
def crm_on_login_task(shop_id: int, user_data: dict[str, Any]) -> None:
|
|
32
|
+
"""Old name of ``shopify_kit.tasks.crm_on_login``."""
|
|
33
|
+
tasks.crm_on_login(shop_id, user_data)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@shared_task(name="shops.tasks.crm_on_uninstall_task")
|
|
37
|
+
def crm_on_uninstall_task(shop_id: int) -> None:
|
|
38
|
+
"""Old name of ``shopify_kit.tasks.crm_on_uninstall``."""
|
|
39
|
+
tasks.crm_on_uninstall(shop_id)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@shared_task(name="shops.tasks.crm_on_billing_plan_change_task")
|
|
43
|
+
def crm_on_billing_plan_change_task(shop_id: int, plan_price: float) -> None:
|
|
44
|
+
"""Old name of ``shopify_kit.tasks.crm_on_billing_plan_change``."""
|
|
45
|
+
tasks.crm_on_billing_plan_change(shop_id, plan_price)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@shared_task(name="shops.tasks.update_all_shops_status_task")
|
|
49
|
+
def update_all_shops_status_task(delay_between_tasks: float = 0) -> None:
|
|
50
|
+
"""Old name of ``shopify_app.tasks.update_all_shops_status``."""
|
|
51
|
+
shopify_app_tasks.update_all_shops_status(delay_between_tasks)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@shared_task(name="shops.tasks.update_shop_status_task")
|
|
55
|
+
def update_shop_status_task(shop_id: int) -> None:
|
|
56
|
+
"""Old name of ``shopify_app.tasks.update_shop_status``."""
|
|
57
|
+
shopify_app_tasks.update_shop_status(shop_id)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@shared_task(name="shops.webhooks.app.app_uninstalled")
|
|
61
|
+
def app_uninstalled(shopify_domain: str, data: dict[str, Any]) -> None:
|
|
62
|
+
"""Old name of ``shopify_app.tasks.uninstall_shop``; ``data`` is unused."""
|
|
63
|
+
shopify_app_tasks.uninstall_shop(shopify_domain)
|
shopify_kit/models.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, Any
|
|
2
|
+
|
|
3
|
+
from crm_events import on_billing_plan_change, on_install, on_login, on_uninstall
|
|
4
|
+
from django.utils.decorators import method_decorator
|
|
5
|
+
from shopify_app.models import ShopLifecycleMixin
|
|
6
|
+
from shopify_app.services.shop_users import record_user_login
|
|
7
|
+
|
|
8
|
+
from .event_bus import use_event_bus
|
|
9
|
+
from .events import ShopInstalled, ShopSaved, ShopUninstalled, ShopUserLoggedIn
|
|
10
|
+
from .services.crm import fetch_crm_shop_data
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from django.http import HttpRequest
|
|
14
|
+
|
|
15
|
+
from .event_bus import Event
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ShopKitMixin(ShopLifecycleMixin):
|
|
19
|
+
"""Shop lifecycle events and CRM calls for the app's shop model.
|
|
20
|
+
|
|
21
|
+
List it before ``ShopBase``, so its methods override ``ShopBase``'s::
|
|
22
|
+
|
|
23
|
+
class Shop(ShopKitMixin, ShopBase):
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
It includes django_shopify_app's ``ShopLifecycleMixin`` (``status``,
|
|
27
|
+
``installed_at``, ``uninstalled_at``). ``on_user_login`` needs a
|
|
28
|
+
``ShopUserBase`` subclass in the app, which provides ``shop.users``.
|
|
29
|
+
|
|
30
|
+
``use_event_bus`` supplies the ``events`` argument of each decorated method.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
class Meta:
|
|
34
|
+
abstract = True
|
|
35
|
+
|
|
36
|
+
@method_decorator(use_event_bus)
|
|
37
|
+
def save(self, *args: Any, events: "list[Event]", **kwargs: Any) -> None:
|
|
38
|
+
"""Save the shop and emit ``ShopSaved``."""
|
|
39
|
+
events.append(ShopSaved(self))
|
|
40
|
+
return super().save(*args, **kwargs)
|
|
41
|
+
|
|
42
|
+
@method_decorator(use_event_bus)
|
|
43
|
+
def installed(
|
|
44
|
+
self, *, events: "list[Event]", request: "HttpRequest | None" = None
|
|
45
|
+
) -> None:
|
|
46
|
+
"""Mark the shop installed and emit ``ShopInstalled``, once per install.
|
|
47
|
+
|
|
48
|
+
django_shopify_app calls this once per token it acquires, including through
|
|
49
|
+
``token_reacquired()`` for a shop that never uninstalled; ``claim_install()``
|
|
50
|
+
lets only the first call of an install through.
|
|
51
|
+
"""
|
|
52
|
+
if not self.claim_install():
|
|
53
|
+
return
|
|
54
|
+
events.append(ShopInstalled(shop=self, request=request))
|
|
55
|
+
|
|
56
|
+
@method_decorator(use_event_bus)
|
|
57
|
+
def on_user_login(
|
|
58
|
+
self,
|
|
59
|
+
user_data: dict[str, Any],
|
|
60
|
+
*,
|
|
61
|
+
events: "list[Event]",
|
|
62
|
+
request: "HttpRequest | None" = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Record the staff user who opened the app and emit ``ShopUserLoggedIn``."""
|
|
65
|
+
user = record_user_login(self, user_data)
|
|
66
|
+
events.append(
|
|
67
|
+
ShopUserLoggedIn(shop=self, user=user, user_data=user_data, request=request)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
@method_decorator(use_event_bus)
|
|
71
|
+
def uninstall(self, *, events: "list[Event]") -> None:
|
|
72
|
+
"""Clear the shop's credentials and emit ``ShopUninstalled``."""
|
|
73
|
+
super().uninstall()
|
|
74
|
+
events.append(ShopUninstalled(shop=self))
|
|
75
|
+
|
|
76
|
+
def get_crm_shop_data(self) -> dict[str, str]:
|
|
77
|
+
"""Return the shop's name, domain, email, phone and country for the CRM."""
|
|
78
|
+
return fetch_crm_shop_data(self)
|
|
79
|
+
|
|
80
|
+
def crm_on_install(self) -> None:
|
|
81
|
+
"""Send the install to the CRM."""
|
|
82
|
+
on_install(self.get_crm_shop_data())
|
|
83
|
+
|
|
84
|
+
def crm_on_login(self, user_data: dict[str, Any]) -> None:
|
|
85
|
+
"""Send a staff user's login to the CRM."""
|
|
86
|
+
on_login(self.get_crm_shop_data(), user_data)
|
|
87
|
+
|
|
88
|
+
def crm_on_uninstall(self, users: "list[Any] | None" = None) -> None:
|
|
89
|
+
"""Send the uninstall to the CRM."""
|
|
90
|
+
on_uninstall(self.get_crm_shop_data(), users or [])
|
|
91
|
+
|
|
92
|
+
def crm_on_billing_plan_change(self, plan_price: float) -> None:
|
|
93
|
+
"""Send the shop's new plan price to the CRM."""
|
|
94
|
+
on_billing_plan_change(self.get_crm_shop_data(), plan_price)
|
shopify_kit/referrals.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import TYPE_CHECKING
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from django.http import HttpRequest
|
|
9
|
+
from shopify_app.models import ShopBase
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
# (connect, read) seconds. The call runs in a request thread, and Gunicorn's gthread
|
|
14
|
+
# worker doesn't stop a thread that waits forever.
|
|
15
|
+
PARTNERS_TIMEOUT = (5, 10)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def report_install_to_partners(
|
|
19
|
+
shop: "ShopBase", request: "HttpRequest | None"
|
|
20
|
+
) -> None:
|
|
21
|
+
"""Report an install to the partners service, with the merchant's IP for referrals.
|
|
22
|
+
|
|
23
|
+
Does nothing unless SHOPIFY_KIT_PARTNERS_URL, SHOPIFY_KIT_PARTNERS_API_KEY and
|
|
24
|
+
SHOPIFY_KIT_PARTNERS_APP_ID are all set. Errors, timeouts included, are logged and
|
|
25
|
+
never raised, so they can't fail the install.
|
|
26
|
+
"""
|
|
27
|
+
url = getattr(settings, "SHOPIFY_KIT_PARTNERS_URL", None)
|
|
28
|
+
api_key = getattr(settings, "SHOPIFY_KIT_PARTNERS_API_KEY", None)
|
|
29
|
+
app_id = getattr(settings, "SHOPIFY_KIT_PARTNERS_APP_ID", None)
|
|
30
|
+
if not (url and api_key and app_id):
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
data = {
|
|
34
|
+
"app_id": app_id,
|
|
35
|
+
"api_key": api_key,
|
|
36
|
+
"customer_name": shop.shopify_domain,
|
|
37
|
+
"referred_ip_address": (
|
|
38
|
+
request.META.get("HTTP_X_FORWARDED_FOR") if request is not None else None
|
|
39
|
+
),
|
|
40
|
+
}
|
|
41
|
+
try:
|
|
42
|
+
requests.post(url, data, timeout=PARTNERS_TIMEOUT)
|
|
43
|
+
except Exception as e:
|
|
44
|
+
logger.error(e)
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
from shopify_app.exceptions import ShopifyRequestException
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from shopify_app.models import ShopBase
|
|
7
|
+
|
|
8
|
+
# Validated against the Admin API 2026-10 with the Shopify dev MCP.
|
|
9
|
+
CRM_SHOP_QUERY = """
|
|
10
|
+
query CrmShopData {
|
|
11
|
+
shop {
|
|
12
|
+
name
|
|
13
|
+
email
|
|
14
|
+
shopAddress {
|
|
15
|
+
phone
|
|
16
|
+
countryCodeV2
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def fetch_crm_shop_data(shop: "ShopBase") -> dict[str, str]:
|
|
24
|
+
"""Return the shop's name, domain, email, phone and country for the CRM.
|
|
25
|
+
|
|
26
|
+
Read from the GraphQL Admin API. When Shopify answers with an error status or
|
|
27
|
+
GraphQL errors, or the token can't be refreshed, only the domain is known: the
|
|
28
|
+
name falls back to it and the rest stay empty, so an uninstalled shop still
|
|
29
|
+
reaches the CRM. Never log the result: it carries the merchant's email and phone.
|
|
30
|
+
"""
|
|
31
|
+
data = {
|
|
32
|
+
"name": shop.shopify_domain,
|
|
33
|
+
"domain": shop.shopify_domain,
|
|
34
|
+
"email": "",
|
|
35
|
+
"phone": "",
|
|
36
|
+
"country": "",
|
|
37
|
+
}
|
|
38
|
+
try:
|
|
39
|
+
response = shop.graphql(query=CRM_SHOP_QUERY)
|
|
40
|
+
except ShopifyRequestException:
|
|
41
|
+
return data
|
|
42
|
+
if response.status_code != 200:
|
|
43
|
+
return data
|
|
44
|
+
body = response.json()
|
|
45
|
+
if body.get("errors"):
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
shop_data = body["data"]["shop"]
|
|
49
|
+
address = shop_data.get("shopAddress") or {}
|
|
50
|
+
data["name"] = shop_data["name"]
|
|
51
|
+
data["email"] = shop_data.get("email") or ""
|
|
52
|
+
data["phone"] = address.get("phone") or ""
|
|
53
|
+
data["country"] = address.get("countryCodeV2") or ""
|
|
54
|
+
return data
|
shopify_kit/tasks.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Celery tasks queued by the package's shop event handlers.
|
|
2
|
+
|
|
3
|
+
Each takes ``shop_id``, so ``shopify_app.sentry.tag_task_shop`` tags its events with
|
|
4
|
+
the shop.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from celery import shared_task
|
|
10
|
+
from shopify_app.utils import get_shop_model
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .models import ShopKitMixin
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _get_shop(shop_id: int) -> "ShopKitMixin":
|
|
17
|
+
"""Return the shop with that primary key."""
|
|
18
|
+
return get_shop_model()._default_manager.get(pk=shop_id)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@shared_task
|
|
22
|
+
def ensure_shop_gid(shop_id: int) -> None:
|
|
23
|
+
"""Store the shop's GID, which the Partner API takes, if it isn't stored yet."""
|
|
24
|
+
_get_shop(shop_id).ensure_shopify_gid()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@shared_task
|
|
28
|
+
def crm_on_install(shop_id: int) -> None:
|
|
29
|
+
"""Send the shop's install to the CRM."""
|
|
30
|
+
_get_shop(shop_id).crm_on_install()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@shared_task
|
|
34
|
+
def crm_on_login(shop_id: int, user_data: dict[str, Any]) -> None:
|
|
35
|
+
"""Send a staff user's login to the CRM."""
|
|
36
|
+
_get_shop(shop_id).crm_on_login(user_data)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@shared_task
|
|
40
|
+
def crm_on_uninstall(shop_id: int) -> None:
|
|
41
|
+
"""Send the shop's uninstall to the CRM."""
|
|
42
|
+
_get_shop(shop_id).crm_on_uninstall()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@shared_task
|
|
46
|
+
def crm_on_billing_plan_change(shop_id: int, plan_price: float) -> None:
|
|
47
|
+
"""Send the shop's new plan price to the CRM."""
|
|
48
|
+
_get_shop(shop_id).crm_on_billing_plan_change(plan_price)
|