lfs-gtm 1.0.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.
- lfs_gtm-1.0.0/.gitignore +54 -0
- lfs_gtm-1.0.0/LICENSE +21 -0
- lfs_gtm-1.0.0/PKG-INFO +161 -0
- lfs_gtm-1.0.0/README.md +149 -0
- lfs_gtm-1.0.0/pyproject.toml +35 -0
- lfs_gtm-1.0.0/src/lfs_gtm/__init__.py +1 -0
- lfs_gtm-1.0.0/src/lfs_gtm/apps.py +7 -0
- lfs_gtm-1.0.0/src/lfs_gtm/ga4_events.py +141 -0
- lfs_gtm-1.0.0/src/lfs_gtm/static/lfs_gtm/lfs_gtm_consent.js +82 -0
- lfs_gtm-1.0.0/src/lfs_gtm/templates/lfs_gtm/datalayer_event_script.html +11 -0
- lfs_gtm-1.0.0/src/lfs_gtm/templates/lfs_gtm/gtm_noscript.html +4 -0
- lfs_gtm-1.0.0/src/lfs_gtm/templates/lfs_gtm/gtm_script.html +25 -0
- lfs_gtm-1.0.0/src/lfs_gtm/templatetags/__init__.py +0 -0
- lfs_gtm-1.0.0/src/lfs_gtm/templatetags/lfs_gtm_tags.py +68 -0
- lfs_gtm-1.0.0/tests/test_ga4_events.py +136 -0
- lfs_gtm-1.0.0/tests/test_project/settings.py +44 -0
- lfs_gtm-1.0.0/tests/test_project/urls.py +3 -0
- lfs_gtm-1.0.0/tests/test_template_tags.py +98 -0
lfs_gtm-1.0.0/.gitignore
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
.Python
|
|
7
|
+
build/
|
|
8
|
+
develop-eggs/
|
|
9
|
+
dist/
|
|
10
|
+
downloads/
|
|
11
|
+
eggs/
|
|
12
|
+
.eggs/
|
|
13
|
+
lib/
|
|
14
|
+
lib64/
|
|
15
|
+
parts/
|
|
16
|
+
sdist/
|
|
17
|
+
var/
|
|
18
|
+
wheels/
|
|
19
|
+
*.egg-info/
|
|
20
|
+
.installed.cfg
|
|
21
|
+
*.egg
|
|
22
|
+
|
|
23
|
+
# Django
|
|
24
|
+
*.log
|
|
25
|
+
local_settings.py
|
|
26
|
+
db.sqlite3
|
|
27
|
+
db.sqlite3-journal
|
|
28
|
+
media
|
|
29
|
+
|
|
30
|
+
# Virtual Environment
|
|
31
|
+
venv/
|
|
32
|
+
env/
|
|
33
|
+
ENV/
|
|
34
|
+
|
|
35
|
+
# IDE
|
|
36
|
+
.idea/
|
|
37
|
+
.vscode/
|
|
38
|
+
*.swp
|
|
39
|
+
*.swo
|
|
40
|
+
|
|
41
|
+
# macOS
|
|
42
|
+
.DS_Store
|
|
43
|
+
.AppleDouble
|
|
44
|
+
.LSOverride
|
|
45
|
+
._*
|
|
46
|
+
|
|
47
|
+
# Pytest
|
|
48
|
+
.pytest_cache/
|
|
49
|
+
.coverage
|
|
50
|
+
htmlcov/
|
|
51
|
+
|
|
52
|
+
# npm
|
|
53
|
+
node_modules/
|
|
54
|
+
npm-debug.log
|
lfs_gtm-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kai Diefenbach
|
|
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.
|
lfs_gtm-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lfs-gtm
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Google Tag Manager and Consent Mode adapter for Django (pairs with lfs-cookie-consent)
|
|
5
|
+
Author-email: Kai Diefenbach <kai.diefenbach@iqpp.de>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: <3.14,>=3.8
|
|
9
|
+
Requires-Dist: django<6.0,>=3.2
|
|
10
|
+
Requires-Dist: lfs-cookie-consent<3,>=2.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# lfs-gtm
|
|
14
|
+
|
|
15
|
+
Google Tag Manager for [LFS](https://github.com/diefenbach/django-lfs) shops: loads the GTM container with Google
|
|
16
|
+
Consent Mode v2, applies the visitor's choice from [lfs-cookie-consent](https://github.com/diefenbach/lfs_cookie_consent),
|
|
17
|
+
and pushes the GA4 e-commerce events of the shop (`view_item_list`, `view_item`, `add_to_cart`, `begin_checkout`,
|
|
18
|
+
`purchase`) to the `dataLayer`.
|
|
19
|
+
|
|
20
|
+
What it does not do: the cookie banner (that is lfs-cookie-consent) and the configuration inside Google Tag Manager
|
|
21
|
+
(triggers, GA4 tags), which you set up in your GTM container (see [Set up the GTM container](#set-up-the-gtm-container)).
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install lfs-gtm
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
This installs lfs-cookie-consent as well: without a consent banner GTM never gets consent. Add both apps, `lfs_gtm`
|
|
30
|
+
after `lfs_cookie_consent`, and your container ID:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
INSTALLED_APPS = [
|
|
34
|
+
# ...
|
|
35
|
+
"lfs_cookie_consent",
|
|
36
|
+
"lfs_gtm",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
GTM_ID = "GTM-XXXXXXX"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Without `GTM_ID` none of the tags renders anything, so a shop can install the app and switch GTM on per environment.
|
|
43
|
+
|
|
44
|
+
With [lfs-theme](https://github.com/diefenbach/lfs-theme) that is all: the theme includes every tag below when
|
|
45
|
+
`lfs_gtm` is installed. With your own theme, add the tags as described in [Templates](#templates).
|
|
46
|
+
|
|
47
|
+
## How it works
|
|
48
|
+
|
|
49
|
+
LFS builds tracker-neutral snapshots of what the visitor sees or buys (no GA4 field names), for example
|
|
50
|
+
`lfs.cart.utils.cart_items_to_tracking_snapshot` and `lfs.order.utils.order_to_tracking_snapshot`, and hands them
|
|
51
|
+
to the templates. lfs-gtm turns a snapshot into a GA4 event (`lfs_gtm/ga4_events.py`) and renders a small script that
|
|
52
|
+
pushes it to the `dataLayer`. GTM then fires the GA4 tags you configured for these event names.
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
LFS view → snapshot in the template context → lfs-gtm tag → dataLayer.push → GTM trigger → GA4 tag
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
lfs-gtm itself does not import LFS; the shop's views and templates connect the two. Empty snapshots render nothing.
|
|
59
|
+
|
|
60
|
+
## Consent Mode
|
|
61
|
+
|
|
62
|
+
`{% gtm_script %}` defines `dataLayer` and `gtag()`, sets the Consent Mode defaults (analytics and advertising
|
|
63
|
+
`denied`, `wait_for_update: 500`) and loads the container.
|
|
64
|
+
|
|
65
|
+
`lfs_gtm/lfs_gtm_consent.js` listens to the browser event `lfs:consent-changed` that lfs-cookie-consent fires when a
|
|
66
|
+
visitor saves a choice, and on every page load once a choice is stored. It then
|
|
67
|
+
|
|
68
|
+
- calls `gtag('consent', 'update', {analytics_storage, ad_storage})`,
|
|
69
|
+
- pushes `analytics_consent_granted` / `analytics_consent_denied` and `advertising_consent_granted` /
|
|
70
|
+
`advertising_consent_denied` to the `dataLayer`,
|
|
71
|
+
- deletes the Google Analytics or Ads cookies of a category the visitor declined.
|
|
72
|
+
|
|
73
|
+
The event's `detail` carries `necessary`, `analytics` and `advertising` (booleans) and an optional `timestamp`.
|
|
74
|
+
|
|
75
|
+
## Templates
|
|
76
|
+
|
|
77
|
+
lfs-theme does this for you. In your own theme, the order in the base template matters: the consent adapter must
|
|
78
|
+
listen before lfs-cookie-consent fires its first `lfs:consent-changed`.
|
|
79
|
+
|
|
80
|
+
```django
|
|
81
|
+
{% load static lfs_cookie_consent_tags lfs_gtm_tags %}
|
|
82
|
+
<head>
|
|
83
|
+
{% gtm_script %}
|
|
84
|
+
<link rel="stylesheet" href="{% static 'lfs_cookie_consent/lfs_cookie_consent.css' %}">
|
|
85
|
+
</head>
|
|
86
|
+
<body>
|
|
87
|
+
{% gtm_noscript %}
|
|
88
|
+
{% cookie_banner %}
|
|
89
|
+
{% cookie_modal %}
|
|
90
|
+
...
|
|
91
|
+
<script defer src="{% static 'lfs_cookie_consent/lfs_cookie_consent.js' %}"></script>
|
|
92
|
+
<script defer src="{% static 'lfs_gtm/lfs_gtm_consent.js' %}"></script>
|
|
93
|
+
</body>
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The e-commerce events, each in the template LFS renders for that page:
|
|
97
|
+
|
|
98
|
+
| Template | Tag | GA4 event | Fires |
|
|
99
|
+
|---|---|---|---|
|
|
100
|
+
| `lfs/catalog/category_base.html` | `{% view_item_list_script item_list_tracking %}` | `view_item_list` | on a category page with products, per page of the list |
|
|
101
|
+
| `lfs/search/search_results.html` | `{% view_item_list_script item_list_tracking %}` | `view_item_list` | on search results with a search term |
|
|
102
|
+
| `lfs/catalog/product_base.html` | `{% view_item_script product_tracking %}` | `view_item` | when the product page loads, for the variant shown |
|
|
103
|
+
| `lfs/cart/cart.html` | `{% added_to_cart_script added_to_cart_tracking %}` | `add_to_cart` | once after a product was added to the cart |
|
|
104
|
+
| `lfs/checkout/new_addresses.html` | `{% begin_checkout_script begin_checkout_tracking %}` | `begin_checkout` | once when the checkout starts (GET of the address step) |
|
|
105
|
+
| `lfs/checkout/thank_you_page.html` | `{% purchase_script order_tracking %}` | `purchase` | once on the thank-you page after an order |
|
|
106
|
+
|
|
107
|
+
`add_to_cart`, `begin_checkout` and `purchase` fire once per action: LFS stores the snapshot in the session where the
|
|
108
|
+
action happens (adding to the cart, "Checkout", placing the order) and takes it out on the page that shows the
|
|
109
|
+
result, so reloading that page does not count the action again. `view_item` and `view_item_list` fire on every page
|
|
110
|
+
load.
|
|
111
|
+
|
|
112
|
+
Not covered: `page_view` (comes from the GA4 configuration in GTM), `view_cart`, and a new `view_item` when the
|
|
113
|
+
visitor switches the variant on the product page without reloading it.
|
|
114
|
+
|
|
115
|
+
`{% datalayer_push event "element-id" %}` pushes any event dict you build yourself.
|
|
116
|
+
|
|
117
|
+
## Events
|
|
118
|
+
|
|
119
|
+
The GA4 events follow Google's recommended e-commerce events:
|
|
120
|
+
|
|
121
|
+
| Event | `ecommerce` fields |
|
|
122
|
+
|---|---|
|
|
123
|
+
| `view_item_list` | `item_list_id`, `item_list_name`, `currency`, `value`, `items` |
|
|
124
|
+
| `view_item`, `add_to_cart`, `begin_checkout` | `currency`, `value`, `items` |
|
|
125
|
+
| `purchase` | `transaction_id`, `currency`, `value`, `tax`, `shipping`, `items` |
|
|
126
|
+
|
|
127
|
+
Each item has `item_id` (the SKU), `item_name`, `price` and `quantity`. For a category list `item_list_id` is the
|
|
128
|
+
category's slug and `item_list_name` its name; for search results they are `search` and the search term.
|
|
129
|
+
|
|
130
|
+
## Set up the GTM container
|
|
131
|
+
|
|
132
|
+
In Google Tag Manager, for each event name above:
|
|
133
|
+
|
|
134
|
+
1. A trigger of type *Custom Event* with exactly that event name.
|
|
135
|
+
2. A GA4 event tag that sends the `ecommerce` data of the push (`items`, `value`, `currency`, `transaction_id`, …).
|
|
136
|
+
3. Consent: let the tags respect Consent Mode; the `*_consent_*` events can serve as additional triggers.
|
|
137
|
+
|
|
138
|
+
Checklist: `GTM_ID` set · base template in the order above · a trigger and GA4 tag per event · consent settings in
|
|
139
|
+
GTM match the categories of the banner.
|
|
140
|
+
|
|
141
|
+
## Adding an event
|
|
142
|
+
|
|
143
|
+
1. In LFS (or your shop): build a tracker-neutral snapshot and put it into the template context, through the session
|
|
144
|
+
if it should fire once per action.
|
|
145
|
+
2. In `lfs_gtm/ga4_events.py`: a `build_ga4_<event>(snapshot)` that returns the GA4 payload, or `None`.
|
|
146
|
+
3. In `lfs_gtm/templatetags/lfs_gtm_tags.py`: a tag that calls it and renders `lfs_gtm/datalayer_event_script.html`.
|
|
147
|
+
4. In the template: load `lfs_gtm_tags` and use the tag.
|
|
148
|
+
|
|
149
|
+
## Development
|
|
150
|
+
|
|
151
|
+
```sh
|
|
152
|
+
uv sync --group test
|
|
153
|
+
uv run pytest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The tests of the snapshots and of where the events fire are in django-lfs (`lfs/catalog/tests/test_product_tracking.py`,
|
|
157
|
+
`lfs/catalog/tests/test_item_list_tracking.py`, `lfs/checkout/tests/test_begin_checkout_gtm.py`).
|
|
158
|
+
|
|
159
|
+
## License
|
|
160
|
+
|
|
161
|
+
MIT, see [LICENSE](LICENSE).
|
lfs_gtm-1.0.0/README.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# lfs-gtm
|
|
2
|
+
|
|
3
|
+
Google Tag Manager for [LFS](https://github.com/diefenbach/django-lfs) shops: loads the GTM container with Google
|
|
4
|
+
Consent Mode v2, applies the visitor's choice from [lfs-cookie-consent](https://github.com/diefenbach/lfs_cookie_consent),
|
|
5
|
+
and pushes the GA4 e-commerce events of the shop (`view_item_list`, `view_item`, `add_to_cart`, `begin_checkout`,
|
|
6
|
+
`purchase`) to the `dataLayer`.
|
|
7
|
+
|
|
8
|
+
What it does not do: the cookie banner (that is lfs-cookie-consent) and the configuration inside Google Tag Manager
|
|
9
|
+
(triggers, GA4 tags), which you set up in your GTM container (see [Set up the GTM container](#set-up-the-gtm-container)).
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pip install lfs-gtm
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
This installs lfs-cookie-consent as well: without a consent banner GTM never gets consent. Add both apps, `lfs_gtm`
|
|
18
|
+
after `lfs_cookie_consent`, and your container ID:
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
INSTALLED_APPS = [
|
|
22
|
+
# ...
|
|
23
|
+
"lfs_cookie_consent",
|
|
24
|
+
"lfs_gtm",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
GTM_ID = "GTM-XXXXXXX"
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Without `GTM_ID` none of the tags renders anything, so a shop can install the app and switch GTM on per environment.
|
|
31
|
+
|
|
32
|
+
With [lfs-theme](https://github.com/diefenbach/lfs-theme) that is all: the theme includes every tag below when
|
|
33
|
+
`lfs_gtm` is installed. With your own theme, add the tags as described in [Templates](#templates).
|
|
34
|
+
|
|
35
|
+
## How it works
|
|
36
|
+
|
|
37
|
+
LFS builds tracker-neutral snapshots of what the visitor sees or buys (no GA4 field names), for example
|
|
38
|
+
`lfs.cart.utils.cart_items_to_tracking_snapshot` and `lfs.order.utils.order_to_tracking_snapshot`, and hands them
|
|
39
|
+
to the templates. lfs-gtm turns a snapshot into a GA4 event (`lfs_gtm/ga4_events.py`) and renders a small script that
|
|
40
|
+
pushes it to the `dataLayer`. GTM then fires the GA4 tags you configured for these event names.
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
LFS view → snapshot in the template context → lfs-gtm tag → dataLayer.push → GTM trigger → GA4 tag
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
lfs-gtm itself does not import LFS; the shop's views and templates connect the two. Empty snapshots render nothing.
|
|
47
|
+
|
|
48
|
+
## Consent Mode
|
|
49
|
+
|
|
50
|
+
`{% gtm_script %}` defines `dataLayer` and `gtag()`, sets the Consent Mode defaults (analytics and advertising
|
|
51
|
+
`denied`, `wait_for_update: 500`) and loads the container.
|
|
52
|
+
|
|
53
|
+
`lfs_gtm/lfs_gtm_consent.js` listens to the browser event `lfs:consent-changed` that lfs-cookie-consent fires when a
|
|
54
|
+
visitor saves a choice, and on every page load once a choice is stored. It then
|
|
55
|
+
|
|
56
|
+
- calls `gtag('consent', 'update', {analytics_storage, ad_storage})`,
|
|
57
|
+
- pushes `analytics_consent_granted` / `analytics_consent_denied` and `advertising_consent_granted` /
|
|
58
|
+
`advertising_consent_denied` to the `dataLayer`,
|
|
59
|
+
- deletes the Google Analytics or Ads cookies of a category the visitor declined.
|
|
60
|
+
|
|
61
|
+
The event's `detail` carries `necessary`, `analytics` and `advertising` (booleans) and an optional `timestamp`.
|
|
62
|
+
|
|
63
|
+
## Templates
|
|
64
|
+
|
|
65
|
+
lfs-theme does this for you. In your own theme, the order in the base template matters: the consent adapter must
|
|
66
|
+
listen before lfs-cookie-consent fires its first `lfs:consent-changed`.
|
|
67
|
+
|
|
68
|
+
```django
|
|
69
|
+
{% load static lfs_cookie_consent_tags lfs_gtm_tags %}
|
|
70
|
+
<head>
|
|
71
|
+
{% gtm_script %}
|
|
72
|
+
<link rel="stylesheet" href="{% static 'lfs_cookie_consent/lfs_cookie_consent.css' %}">
|
|
73
|
+
</head>
|
|
74
|
+
<body>
|
|
75
|
+
{% gtm_noscript %}
|
|
76
|
+
{% cookie_banner %}
|
|
77
|
+
{% cookie_modal %}
|
|
78
|
+
...
|
|
79
|
+
<script defer src="{% static 'lfs_cookie_consent/lfs_cookie_consent.js' %}"></script>
|
|
80
|
+
<script defer src="{% static 'lfs_gtm/lfs_gtm_consent.js' %}"></script>
|
|
81
|
+
</body>
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The e-commerce events, each in the template LFS renders for that page:
|
|
85
|
+
|
|
86
|
+
| Template | Tag | GA4 event | Fires |
|
|
87
|
+
|---|---|---|---|
|
|
88
|
+
| `lfs/catalog/category_base.html` | `{% view_item_list_script item_list_tracking %}` | `view_item_list` | on a category page with products, per page of the list |
|
|
89
|
+
| `lfs/search/search_results.html` | `{% view_item_list_script item_list_tracking %}` | `view_item_list` | on search results with a search term |
|
|
90
|
+
| `lfs/catalog/product_base.html` | `{% view_item_script product_tracking %}` | `view_item` | when the product page loads, for the variant shown |
|
|
91
|
+
| `lfs/cart/cart.html` | `{% added_to_cart_script added_to_cart_tracking %}` | `add_to_cart` | once after a product was added to the cart |
|
|
92
|
+
| `lfs/checkout/new_addresses.html` | `{% begin_checkout_script begin_checkout_tracking %}` | `begin_checkout` | once when the checkout starts (GET of the address step) |
|
|
93
|
+
| `lfs/checkout/thank_you_page.html` | `{% purchase_script order_tracking %}` | `purchase` | once on the thank-you page after an order |
|
|
94
|
+
|
|
95
|
+
`add_to_cart`, `begin_checkout` and `purchase` fire once per action: LFS stores the snapshot in the session where the
|
|
96
|
+
action happens (adding to the cart, "Checkout", placing the order) and takes it out on the page that shows the
|
|
97
|
+
result, so reloading that page does not count the action again. `view_item` and `view_item_list` fire on every page
|
|
98
|
+
load.
|
|
99
|
+
|
|
100
|
+
Not covered: `page_view` (comes from the GA4 configuration in GTM), `view_cart`, and a new `view_item` when the
|
|
101
|
+
visitor switches the variant on the product page without reloading it.
|
|
102
|
+
|
|
103
|
+
`{% datalayer_push event "element-id" %}` pushes any event dict you build yourself.
|
|
104
|
+
|
|
105
|
+
## Events
|
|
106
|
+
|
|
107
|
+
The GA4 events follow Google's recommended e-commerce events:
|
|
108
|
+
|
|
109
|
+
| Event | `ecommerce` fields |
|
|
110
|
+
|---|---|
|
|
111
|
+
| `view_item_list` | `item_list_id`, `item_list_name`, `currency`, `value`, `items` |
|
|
112
|
+
| `view_item`, `add_to_cart`, `begin_checkout` | `currency`, `value`, `items` |
|
|
113
|
+
| `purchase` | `transaction_id`, `currency`, `value`, `tax`, `shipping`, `items` |
|
|
114
|
+
|
|
115
|
+
Each item has `item_id` (the SKU), `item_name`, `price` and `quantity`. For a category list `item_list_id` is the
|
|
116
|
+
category's slug and `item_list_name` its name; for search results they are `search` and the search term.
|
|
117
|
+
|
|
118
|
+
## Set up the GTM container
|
|
119
|
+
|
|
120
|
+
In Google Tag Manager, for each event name above:
|
|
121
|
+
|
|
122
|
+
1. A trigger of type *Custom Event* with exactly that event name.
|
|
123
|
+
2. A GA4 event tag that sends the `ecommerce` data of the push (`items`, `value`, `currency`, `transaction_id`, …).
|
|
124
|
+
3. Consent: let the tags respect Consent Mode; the `*_consent_*` events can serve as additional triggers.
|
|
125
|
+
|
|
126
|
+
Checklist: `GTM_ID` set · base template in the order above · a trigger and GA4 tag per event · consent settings in
|
|
127
|
+
GTM match the categories of the banner.
|
|
128
|
+
|
|
129
|
+
## Adding an event
|
|
130
|
+
|
|
131
|
+
1. In LFS (or your shop): build a tracker-neutral snapshot and put it into the template context, through the session
|
|
132
|
+
if it should fire once per action.
|
|
133
|
+
2. In `lfs_gtm/ga4_events.py`: a `build_ga4_<event>(snapshot)` that returns the GA4 payload, or `None`.
|
|
134
|
+
3. In `lfs_gtm/templatetags/lfs_gtm_tags.py`: a tag that calls it and renders `lfs_gtm/datalayer_event_script.html`.
|
|
135
|
+
4. In the template: load `lfs_gtm_tags` and use the tag.
|
|
136
|
+
|
|
137
|
+
## Development
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
uv sync --group test
|
|
141
|
+
uv run pytest
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The tests of the snapshots and of where the events fire are in django-lfs (`lfs/catalog/tests/test_product_tracking.py`,
|
|
145
|
+
`lfs/catalog/tests/test_item_list_tracking.py`, `lfs/checkout/tests/test_begin_checkout_gtm.py`).
|
|
146
|
+
|
|
147
|
+
## License
|
|
148
|
+
|
|
149
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "lfs-gtm"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Google Tag Manager and Consent Mode adapter for Django (pairs with lfs-cookie-consent)"
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Kai Diefenbach", email = "kai.diefenbach@iqpp.de" }
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
requires-python = ">=3.8,<3.14"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"Django>=3.2,<6.0",
|
|
14
|
+
# Without a consent banner GTM never gets consent, so it comes along.
|
|
15
|
+
"lfs-cookie-consent>=2.0,<3",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[build-system]
|
|
19
|
+
requires = ["hatchling>=1.27"]
|
|
20
|
+
build-backend = "hatchling.build"
|
|
21
|
+
|
|
22
|
+
[dependency-groups]
|
|
23
|
+
test = [
|
|
24
|
+
"pytest>=7.0.0",
|
|
25
|
+
"pytest-django>=4.11.1",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[tool.pytest.ini_options]
|
|
29
|
+
DJANGO_SETTINGS_MODULE = "tests.test_project.settings"
|
|
30
|
+
pythonpath = [".", "src"]
|
|
31
|
+
|
|
32
|
+
# Only what belongs to the package: the local notes (recaps/, todos/) and caches stay out of the sdist.
|
|
33
|
+
[tool.hatch.build.targets.sdist]
|
|
34
|
+
include = ["src/lfs_gtm", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
35
|
+
exclude = ["__pycache__", "*.pyc"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Google Tag Manager integration for Django (Consent Mode + dataLayer helpers)."""
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Map tracker-neutral shop snapshots to GA4 dataLayer event payloads."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def build_ga4_add_to_cart(snapshot):
|
|
5
|
+
"""
|
|
6
|
+
Convert a cart tracking snapshot from LFS into a GA4 add_to_cart event dict.
|
|
7
|
+
"""
|
|
8
|
+
if not snapshot or not snapshot.get("line_items"):
|
|
9
|
+
return None
|
|
10
|
+
|
|
11
|
+
items = [
|
|
12
|
+
{
|
|
13
|
+
"item_id": line["sku"],
|
|
14
|
+
"item_name": line["name"],
|
|
15
|
+
"price": line["price"],
|
|
16
|
+
"quantity": line["quantity"],
|
|
17
|
+
}
|
|
18
|
+
for line in snapshot.get("line_items", [])
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
"event": "add_to_cart",
|
|
23
|
+
"ecommerce": {
|
|
24
|
+
"currency": snapshot.get("currency", "EUR"),
|
|
25
|
+
"value": snapshot["value"],
|
|
26
|
+
"items": items,
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_ga4_view_item(snapshot):
|
|
32
|
+
"""
|
|
33
|
+
Convert a product tracking snapshot from LFS into a GA4 view_item event dict.
|
|
34
|
+
"""
|
|
35
|
+
if not snapshot or not snapshot.get("line_items"):
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
items = [
|
|
39
|
+
{
|
|
40
|
+
"item_id": line["sku"],
|
|
41
|
+
"item_name": line["name"],
|
|
42
|
+
"price": line["price"],
|
|
43
|
+
"quantity": line["quantity"],
|
|
44
|
+
}
|
|
45
|
+
for line in snapshot.get("line_items", [])
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
"event": "view_item",
|
|
50
|
+
"ecommerce": {
|
|
51
|
+
"currency": snapshot.get("currency", "EUR"),
|
|
52
|
+
"value": snapshot["value"],
|
|
53
|
+
"items": items,
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_ga4_view_item_list(snapshot):
|
|
59
|
+
"""
|
|
60
|
+
Convert an item list tracking snapshot from LFS into a GA4 view_item_list event dict.
|
|
61
|
+
"""
|
|
62
|
+
if not snapshot or not snapshot.get("line_items"):
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
items = [
|
|
66
|
+
{
|
|
67
|
+
"item_id": line["sku"],
|
|
68
|
+
"item_name": line["name"],
|
|
69
|
+
"price": line["price"],
|
|
70
|
+
"quantity": line["quantity"],
|
|
71
|
+
}
|
|
72
|
+
for line in snapshot.get("line_items", [])
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
"event": "view_item_list",
|
|
77
|
+
"ecommerce": {
|
|
78
|
+
"item_list_id": snapshot["list_id"],
|
|
79
|
+
"item_list_name": snapshot["list_name"],
|
|
80
|
+
"currency": snapshot.get("currency", "EUR"),
|
|
81
|
+
"value": snapshot["value"],
|
|
82
|
+
"items": items,
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def build_ga4_begin_checkout(snapshot):
|
|
88
|
+
"""
|
|
89
|
+
Convert a cart tracking snapshot from LFS into a GA4 begin_checkout event dict.
|
|
90
|
+
"""
|
|
91
|
+
if not snapshot or not snapshot.get("line_items"):
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
items = [
|
|
95
|
+
{
|
|
96
|
+
"item_id": line["sku"],
|
|
97
|
+
"item_name": line["name"],
|
|
98
|
+
"price": line["price"],
|
|
99
|
+
"quantity": line["quantity"],
|
|
100
|
+
}
|
|
101
|
+
for line in snapshot.get("line_items", [])
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
"event": "begin_checkout",
|
|
106
|
+
"ecommerce": {
|
|
107
|
+
"currency": snapshot.get("currency", "EUR"),
|
|
108
|
+
"value": snapshot["value"],
|
|
109
|
+
"items": items,
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def build_ga4_purchase(snapshot):
|
|
115
|
+
"""
|
|
116
|
+
Convert an order tracking snapshot from LFS into a GA4 purchase event dict.
|
|
117
|
+
"""
|
|
118
|
+
if not snapshot or not snapshot.get("order_id"):
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
items = [
|
|
122
|
+
{
|
|
123
|
+
"item_id": line["sku"],
|
|
124
|
+
"item_name": line["name"],
|
|
125
|
+
"price": line["price"],
|
|
126
|
+
"quantity": line["quantity"],
|
|
127
|
+
}
|
|
128
|
+
for line in snapshot.get("line_items", [])
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
"event": "purchase",
|
|
133
|
+
"ecommerce": {
|
|
134
|
+
"transaction_id": snapshot["order_id"],
|
|
135
|
+
"value": snapshot["value"],
|
|
136
|
+
"tax": snapshot["tax"],
|
|
137
|
+
"shipping": snapshot["shipping"],
|
|
138
|
+
"currency": snapshot.get("currency", "EUR"),
|
|
139
|
+
"items": items,
|
|
140
|
+
},
|
|
141
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Listens for lfs:consent-changed from lfs_cookie_consent and applies
|
|
3
|
+
* Google Consent Mode v2, GTM dataLayer events, and Google cookie cleanup.
|
|
4
|
+
* Register listener synchronously (do not defer inside DOMContentLoaded).
|
|
5
|
+
*/
|
|
6
|
+
(function () {
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
function deleteGACookies() {
|
|
10
|
+
const allCookies = document.cookie.split(';').map(c => c.trim().split('=')[0]);
|
|
11
|
+
const prefixes = ['_ga', '_gid', '_gat', '_gat_gtag', '_gat_UA', '__utma', '__utmb', '__utmc', '__utmz', '__utmt'];
|
|
12
|
+
const domain = window.location.hostname.replace(/^www\./, '');
|
|
13
|
+
const paths = ['/', window.location.pathname];
|
|
14
|
+
const domains = [undefined, domain, '.' + domain];
|
|
15
|
+
|
|
16
|
+
const gaCookies = allCookies.filter(name =>
|
|
17
|
+
prefixes.some(prefix => name.startsWith(prefix))
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
gaCookies.forEach(name => {
|
|
21
|
+
paths.forEach(path => {
|
|
22
|
+
domains.forEach(d => {
|
|
23
|
+
let cookieString = `${name}=; Max-Age=0; path=${path};`;
|
|
24
|
+
if (d) cookieString += ` domain=${d};`;
|
|
25
|
+
document.cookie = cookieString;
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function deleteAdsCookies() {
|
|
32
|
+
const allCookies = document.cookie.split(';').map(c => c.trim().split('=')[0]);
|
|
33
|
+
const prefixes = ['_gcl_', '_gclid', '_gcl_aw', '_gcl_dc', '_gcl_gb', '_gcl_ha', '_gcl_hb', '_gcl_hc', '_gcl_hd', '_gcl_he', '_gcl_hf', '_gcl_hg', '_gcl_hh', '_gcl_hi', '_gcl_hj', '_gcl_hk', '_gcl_hl', '_gcl_hm', '_gcl_hn', '_gcl_ho', '_gcl_hp', '_gcl_hq', '_gcl_hr', '_gcl_hs', '_gcl_ht', '_gcl_hu', '_gcl_hv', '_gcl_hw', '_gcl_hx', '_gcl_hy', '_gcl_hz', 'IDE', 'test_cookie', 'NID', '1P_JAR', 'CONSENT', 'DV'];
|
|
34
|
+
const domain = window.location.hostname.replace(/^www\./, '');
|
|
35
|
+
const paths = ['/', window.location.pathname];
|
|
36
|
+
const domains = [undefined, domain, '.' + domain];
|
|
37
|
+
|
|
38
|
+
const adsCookies = allCookies.filter(name =>
|
|
39
|
+
prefixes.some(prefix => name.startsWith(prefix))
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
adsCookies.forEach(name => {
|
|
43
|
+
paths.forEach(path => {
|
|
44
|
+
domains.forEach(d => {
|
|
45
|
+
let cookieString = `${name}=; Max-Age=0; path=${path};`;
|
|
46
|
+
if (d) cookieString += ` domain=${d};`;
|
|
47
|
+
document.cookie = cookieString;
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function applyConsentDetail(detail) {
|
|
54
|
+
if (!detail || typeof detail.analytics !== 'boolean' || typeof detail.advertising !== 'boolean') {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (typeof gtag === 'function') {
|
|
59
|
+
gtag('consent', 'update', {
|
|
60
|
+
analytics_storage: detail.analytics ? 'granted' : 'denied',
|
|
61
|
+
ad_storage: detail.advertising ? 'granted' : 'denied',
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
window.dataLayer = window.dataLayer || [];
|
|
66
|
+
const analyticsEvent = detail.analytics ? 'analytics_consent_granted' : 'analytics_consent_denied';
|
|
67
|
+
const advertisingEvent = detail.advertising ? 'advertising_consent_granted' : 'advertising_consent_denied';
|
|
68
|
+
window.dataLayer.push({ event: analyticsEvent });
|
|
69
|
+
window.dataLayer.push({ event: advertisingEvent });
|
|
70
|
+
|
|
71
|
+
if (!detail.analytics) {
|
|
72
|
+
deleteGACookies();
|
|
73
|
+
}
|
|
74
|
+
if (!detail.advertising) {
|
|
75
|
+
deleteAdsCookies();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
document.addEventListener('lfs:consent-changed', function (e) {
|
|
80
|
+
applyConsentDetail(e.detail);
|
|
81
|
+
});
|
|
82
|
+
})();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{% if event and gtm_id %}
|
|
2
|
+
{{ event|json_script:element_id }}
|
|
3
|
+
<script>
|
|
4
|
+
(function () {
|
|
5
|
+
var el = document.getElementById('{{ element_id }}');
|
|
6
|
+
if (!el) return;
|
|
7
|
+
window.dataLayer = window.dataLayer || [];
|
|
8
|
+
dataLayer.push(JSON.parse(el.textContent));
|
|
9
|
+
})();
|
|
10
|
+
</script>
|
|
11
|
+
{% endif %}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{# GTM Head Script (Consent Mode V2 ready) #}
|
|
2
|
+
{% if gtm_id %}
|
|
3
|
+
<script>
|
|
4
|
+
// Define the dataLayer
|
|
5
|
+
window.dataLayer = window.dataLayer || [];
|
|
6
|
+
function gtag(){dataLayer.push(arguments);}
|
|
7
|
+
|
|
8
|
+
// By default all cookies are denied
|
|
9
|
+
gtag('consent', 'default', {
|
|
10
|
+
'ad_storage': 'denied',
|
|
11
|
+
'analytics_storage': 'denied',
|
|
12
|
+
'functionality_storage': 'granted',
|
|
13
|
+
'personalization_storage': 'denied',
|
|
14
|
+
'security_storage': 'granted',
|
|
15
|
+
'wait_for_update': 500
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// GTM Config
|
|
19
|
+
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
|
|
20
|
+
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
|
|
21
|
+
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
|
|
22
|
+
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
|
|
23
|
+
})(window,document,'script','dataLayer','{{ gtm_id }}');
|
|
24
|
+
</script>
|
|
25
|
+
{% endif %}
|
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
from django import template
|
|
2
|
+
from django.conf import settings
|
|
3
|
+
from django.template.loader import render_to_string
|
|
4
|
+
|
|
5
|
+
from lfs_gtm.ga4_events import (
|
|
6
|
+
build_ga4_add_to_cart,
|
|
7
|
+
build_ga4_begin_checkout,
|
|
8
|
+
build_ga4_purchase,
|
|
9
|
+
build_ga4_view_item,
|
|
10
|
+
build_ga4_view_item_list,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
register = template.Library()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@register.simple_tag
|
|
17
|
+
def gtm_script(gtm_id=None):
|
|
18
|
+
gtm_id = gtm_id or getattr(settings, "GTM_ID", None)
|
|
19
|
+
return render_to_string("lfs_gtm/gtm_script.html", {"gtm_id": gtm_id})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@register.simple_tag
|
|
23
|
+
def gtm_noscript(gtm_id=None):
|
|
24
|
+
gtm_id = gtm_id or getattr(settings, "GTM_ID", None)
|
|
25
|
+
return render_to_string("lfs_gtm/gtm_noscript.html", {"gtm_id": gtm_id})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@register.simple_tag(takes_context=True)
|
|
29
|
+
def datalayer_push(context, event=None, element_id="datalayer-event"):
|
|
30
|
+
gtm_id = getattr(settings, "GTM_ID", None)
|
|
31
|
+
return render_to_string(
|
|
32
|
+
"lfs_gtm/datalayer_event_script.html",
|
|
33
|
+
{
|
|
34
|
+
"event": event,
|
|
35
|
+
"gtm_id": gtm_id,
|
|
36
|
+
"element_id": element_id,
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@register.simple_tag(takes_context=True)
|
|
42
|
+
def added_to_cart_script(context, snapshot=None):
|
|
43
|
+
event = build_ga4_add_to_cart(snapshot)
|
|
44
|
+
return datalayer_push(context, event=event, element_id="added-to-cart-event")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@register.simple_tag(takes_context=True)
|
|
48
|
+
def view_item_script(context, snapshot=None):
|
|
49
|
+
event = build_ga4_view_item(snapshot)
|
|
50
|
+
return datalayer_push(context, event=event, element_id="view-item-event")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@register.simple_tag(takes_context=True)
|
|
54
|
+
def view_item_list_script(context, snapshot=None):
|
|
55
|
+
event = build_ga4_view_item_list(snapshot)
|
|
56
|
+
return datalayer_push(context, event=event, element_id="view-item-list-event")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@register.simple_tag(takes_context=True)
|
|
60
|
+
def begin_checkout_script(context, snapshot=None):
|
|
61
|
+
event = build_ga4_begin_checkout(snapshot)
|
|
62
|
+
return datalayer_push(context, event=event, element_id="begin-checkout-event")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@register.simple_tag(takes_context=True)
|
|
66
|
+
def purchase_script(context, snapshot=None):
|
|
67
|
+
event = build_ga4_purchase(snapshot)
|
|
68
|
+
return datalayer_push(context, event=event, element_id="purchase-event")
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
from lfs_gtm.ga4_events import (
|
|
2
|
+
build_ga4_add_to_cart,
|
|
3
|
+
build_ga4_begin_checkout,
|
|
4
|
+
build_ga4_purchase,
|
|
5
|
+
build_ga4_view_item,
|
|
6
|
+
build_ga4_view_item_list,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_build_ga4_add_to_cart_maps_snapshot():
|
|
11
|
+
snapshot = {
|
|
12
|
+
"currency": "EUR",
|
|
13
|
+
"value": 22.0,
|
|
14
|
+
"line_items": [
|
|
15
|
+
{"sku": "sku-1", "name": "Product 1", "price": 11.0, "quantity": 2},
|
|
16
|
+
],
|
|
17
|
+
}
|
|
18
|
+
event = build_ga4_add_to_cart(snapshot)
|
|
19
|
+
|
|
20
|
+
assert event["event"] == "add_to_cart"
|
|
21
|
+
assert event["ecommerce"]["currency"] == "EUR"
|
|
22
|
+
assert event["ecommerce"]["value"] == 22.0
|
|
23
|
+
assert len(event["ecommerce"]["items"]) == 1
|
|
24
|
+
assert event["ecommerce"]["items"][0]["item_id"] == "sku-1"
|
|
25
|
+
assert event["ecommerce"]["items"][0]["item_name"] == "Product 1"
|
|
26
|
+
assert event["ecommerce"]["items"][0]["price"] == 11.0
|
|
27
|
+
assert event["ecommerce"]["items"][0]["quantity"] == 2
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_build_ga4_view_item_list_maps_snapshot():
|
|
31
|
+
snapshot = {
|
|
32
|
+
"list_id": "category-1",
|
|
33
|
+
"list_name": "Category 1",
|
|
34
|
+
"currency": "EUR",
|
|
35
|
+
"value": 30.0,
|
|
36
|
+
"line_items": [
|
|
37
|
+
{"sku": "sku-1", "name": "Product 1", "price": 10.0, "quantity": 1},
|
|
38
|
+
{"sku": "sku-2", "name": "Product 2", "price": 20.0, "quantity": 1},
|
|
39
|
+
],
|
|
40
|
+
}
|
|
41
|
+
event = build_ga4_view_item_list(snapshot)
|
|
42
|
+
|
|
43
|
+
assert event["event"] == "view_item_list"
|
|
44
|
+
assert event["ecommerce"]["item_list_id"] == "category-1"
|
|
45
|
+
assert event["ecommerce"]["item_list_name"] == "Category 1"
|
|
46
|
+
assert event["ecommerce"]["value"] == 30.0
|
|
47
|
+
assert len(event["ecommerce"]["items"]) == 2
|
|
48
|
+
assert event["ecommerce"]["items"][0]["item_id"] == "sku-1"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_build_ga4_view_item_list_returns_none_for_empty_snapshot():
|
|
52
|
+
assert build_ga4_view_item_list(None) is None
|
|
53
|
+
assert build_ga4_view_item_list({"list_id": "x", "list_name": "y", "line_items": []}) is None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_build_ga4_begin_checkout_maps_snapshot():
|
|
57
|
+
snapshot = {
|
|
58
|
+
"currency": "EUR",
|
|
59
|
+
"value": 22.0,
|
|
60
|
+
"line_items": [
|
|
61
|
+
{"sku": "sku-1", "name": "Product 1", "price": 11.0, "quantity": 2},
|
|
62
|
+
],
|
|
63
|
+
}
|
|
64
|
+
event = build_ga4_begin_checkout(snapshot)
|
|
65
|
+
|
|
66
|
+
assert event["event"] == "begin_checkout"
|
|
67
|
+
assert event["ecommerce"]["currency"] == "EUR"
|
|
68
|
+
assert event["ecommerce"]["value"] == 22.0
|
|
69
|
+
assert len(event["ecommerce"]["items"]) == 1
|
|
70
|
+
assert event["ecommerce"]["items"][0]["item_id"] == "sku-1"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_build_ga4_begin_checkout_returns_none_for_empty_snapshot():
|
|
74
|
+
assert build_ga4_begin_checkout(None) is None
|
|
75
|
+
assert build_ga4_begin_checkout({"currency": "EUR", "value": 0, "line_items": []}) is None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_build_ga4_add_to_cart_returns_none_for_empty_snapshot():
|
|
79
|
+
assert build_ga4_add_to_cart(None) is None
|
|
80
|
+
assert build_ga4_add_to_cart({"currency": "EUR", "value": 0, "line_items": []}) is None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_build_ga4_purchase_maps_snapshot():
|
|
84
|
+
snapshot = {
|
|
85
|
+
"order_id": "ORD-42",
|
|
86
|
+
"currency": "EUR",
|
|
87
|
+
"value": 9.8,
|
|
88
|
+
"tax": 1.56,
|
|
89
|
+
"shipping": 1.0,
|
|
90
|
+
"line_items": [
|
|
91
|
+
{"sku": "sku-1", "name": "Product 1", "price": 1.1, "quantity": 2},
|
|
92
|
+
],
|
|
93
|
+
}
|
|
94
|
+
event = build_ga4_purchase(snapshot)
|
|
95
|
+
|
|
96
|
+
assert event["event"] == "purchase"
|
|
97
|
+
assert event["ecommerce"]["transaction_id"] == "ORD-42"
|
|
98
|
+
assert event["ecommerce"]["value"] == 9.8
|
|
99
|
+
assert event["ecommerce"]["tax"] == 1.56
|
|
100
|
+
assert event["ecommerce"]["shipping"] == 1.0
|
|
101
|
+
assert event["ecommerce"]["currency"] == "EUR"
|
|
102
|
+
assert len(event["ecommerce"]["items"]) == 1
|
|
103
|
+
assert event["ecommerce"]["items"][0]["item_id"] == "sku-1"
|
|
104
|
+
assert event["ecommerce"]["items"][0]["item_name"] == "Product 1"
|
|
105
|
+
assert event["ecommerce"]["items"][0]["price"] == 1.1
|
|
106
|
+
assert event["ecommerce"]["items"][0]["quantity"] == 2
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_build_ga4_purchase_returns_none_for_empty_snapshot():
|
|
110
|
+
assert build_ga4_purchase(None) is None
|
|
111
|
+
assert build_ga4_purchase({}) is None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_build_ga4_view_item_maps_snapshot():
|
|
115
|
+
snapshot = {
|
|
116
|
+
"currency": "EUR",
|
|
117
|
+
"value": 11.0,
|
|
118
|
+
"line_items": [
|
|
119
|
+
{"sku": "sku-1", "name": "Product 1", "price": 11.0, "quantity": 1},
|
|
120
|
+
],
|
|
121
|
+
}
|
|
122
|
+
event = build_ga4_view_item(snapshot)
|
|
123
|
+
|
|
124
|
+
assert event["event"] == "view_item"
|
|
125
|
+
assert event["ecommerce"]["currency"] == "EUR"
|
|
126
|
+
assert event["ecommerce"]["value"] == 11.0
|
|
127
|
+
assert len(event["ecommerce"]["items"]) == 1
|
|
128
|
+
assert event["ecommerce"]["items"][0]["item_id"] == "sku-1"
|
|
129
|
+
assert event["ecommerce"]["items"][0]["item_name"] == "Product 1"
|
|
130
|
+
assert event["ecommerce"]["items"][0]["price"] == 11.0
|
|
131
|
+
assert event["ecommerce"]["items"][0]["quantity"] == 1
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_build_ga4_view_item_returns_none_for_empty_snapshot():
|
|
135
|
+
assert build_ga4_view_item(None) is None
|
|
136
|
+
assert build_ga4_view_item({"currency": "EUR", "value": 0, "line_items": []}) is None
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
SECRET_KEY = "test"
|
|
2
|
+
DEBUG = True
|
|
3
|
+
ALLOWED_HOSTS = ["*"]
|
|
4
|
+
INSTALLED_APPS = [
|
|
5
|
+
"django.contrib.contenttypes",
|
|
6
|
+
"django.contrib.auth",
|
|
7
|
+
"django.contrib.sessions",
|
|
8
|
+
"django.contrib.messages",
|
|
9
|
+
"django.contrib.staticfiles",
|
|
10
|
+
"lfs_gtm",
|
|
11
|
+
]
|
|
12
|
+
MIDDLEWARE = [
|
|
13
|
+
"django.middleware.security.SecurityMiddleware",
|
|
14
|
+
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
15
|
+
"django.middleware.common.CommonMiddleware",
|
|
16
|
+
"django.middleware.csrf.CsrfViewMiddleware",
|
|
17
|
+
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
|
18
|
+
"django.contrib.messages.middleware.MessageMiddleware",
|
|
19
|
+
]
|
|
20
|
+
ROOT_URLCONF = "tests.test_project.urls"
|
|
21
|
+
TEMPLATES = [
|
|
22
|
+
{
|
|
23
|
+
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
|
24
|
+
"DIRS": [],
|
|
25
|
+
"APP_DIRS": True,
|
|
26
|
+
"OPTIONS": {
|
|
27
|
+
"context_processors": [
|
|
28
|
+
"django.template.context_processors.debug",
|
|
29
|
+
"django.template.context_processors.request",
|
|
30
|
+
"django.contrib.auth.context_processors.auth",
|
|
31
|
+
"django.contrib.messages.context_processors.messages",
|
|
32
|
+
],
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
]
|
|
36
|
+
STATIC_URL = "/static/"
|
|
37
|
+
DATABASES = {
|
|
38
|
+
"default": {
|
|
39
|
+
"ENGINE": "django.db.backends.sqlite3",
|
|
40
|
+
"NAME": ":memory:",
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
USE_TZ = True
|
|
44
|
+
GTM_ID = "GTM-UNITTEST"
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from django.template import Context, Template
|
|
3
|
+
from django.test import override_settings
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@pytest.mark.django_db
|
|
7
|
+
def test_gtm_script_renders_when_gtm_id_set():
|
|
8
|
+
tpl = Template("{% load lfs_gtm_tags %}{% gtm_script %}")
|
|
9
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
10
|
+
html = tpl.render(Context())
|
|
11
|
+
assert "GTM-UNITTEST" in html
|
|
12
|
+
assert "googletagmanager.com/gtm.js" in html
|
|
13
|
+
assert "consent" in html
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.mark.django_db
|
|
17
|
+
def test_gtm_script_empty_without_gtm_id():
|
|
18
|
+
tpl = Template("{% load lfs_gtm_tags %}{% gtm_script %}")
|
|
19
|
+
with override_settings(GTM_ID=None):
|
|
20
|
+
html = tpl.render(Context())
|
|
21
|
+
assert html.strip() == ""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@pytest.mark.django_db
|
|
25
|
+
def test_added_to_cart_script_renders_from_snapshot():
|
|
26
|
+
tpl = Template("{% load lfs_gtm_tags %}{% added_to_cart_script snapshot %}")
|
|
27
|
+
snapshot = {
|
|
28
|
+
"currency": "EUR",
|
|
29
|
+
"value": 10.0,
|
|
30
|
+
"line_items": [{"sku": "sku-1", "name": "Product 1", "price": 10.0, "quantity": 1}],
|
|
31
|
+
}
|
|
32
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
33
|
+
html = tpl.render(Context({"snapshot": snapshot}))
|
|
34
|
+
assert 'id="added-to-cart-event"' in html
|
|
35
|
+
assert "add_to_cart" in html
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@pytest.mark.django_db
|
|
39
|
+
def test_begin_checkout_script_renders_from_snapshot():
|
|
40
|
+
tpl = Template("{% load lfs_gtm_tags %}{% begin_checkout_script snapshot %}")
|
|
41
|
+
snapshot = {
|
|
42
|
+
"currency": "EUR",
|
|
43
|
+
"value": 10.0,
|
|
44
|
+
"line_items": [{"sku": "sku-1", "name": "Product 1", "price": 10.0, "quantity": 1}],
|
|
45
|
+
}
|
|
46
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
47
|
+
html = tpl.render(Context({"snapshot": snapshot}))
|
|
48
|
+
assert 'id="begin-checkout-event"' in html
|
|
49
|
+
assert "begin_checkout" in html
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@pytest.mark.django_db
|
|
53
|
+
def test_view_item_list_script_renders_from_snapshot():
|
|
54
|
+
tpl = Template("{% load lfs_gtm_tags %}{% view_item_list_script snapshot %}")
|
|
55
|
+
snapshot = {
|
|
56
|
+
"list_id": "category-1",
|
|
57
|
+
"list_name": "Category 1",
|
|
58
|
+
"currency": "EUR",
|
|
59
|
+
"value": 10.0,
|
|
60
|
+
"line_items": [{"sku": "sku-1", "name": "Product 1", "price": 10.0, "quantity": 1}],
|
|
61
|
+
}
|
|
62
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
63
|
+
html = tpl.render(Context({"snapshot": snapshot}))
|
|
64
|
+
assert 'id="view-item-list-event"' in html
|
|
65
|
+
assert "view_item_list" in html
|
|
66
|
+
assert "category-1" in html
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@pytest.mark.django_db
|
|
70
|
+
def test_view_item_script_renders_from_snapshot():
|
|
71
|
+
tpl = Template("{% load lfs_gtm_tags %}{% view_item_script snapshot %}")
|
|
72
|
+
snapshot = {
|
|
73
|
+
"currency": "EUR",
|
|
74
|
+
"value": 10.0,
|
|
75
|
+
"line_items": [{"sku": "sku-1", "name": "Product 1", "price": 10.0, "quantity": 1}],
|
|
76
|
+
}
|
|
77
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
78
|
+
html = tpl.render(Context({"snapshot": snapshot}))
|
|
79
|
+
assert 'id="view-item-event"' in html
|
|
80
|
+
assert "view_item" in html
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.mark.django_db
|
|
84
|
+
def test_purchase_script_renders_from_snapshot():
|
|
85
|
+
tpl = Template("{% load lfs_gtm_tags %}{% purchase_script snapshot %}")
|
|
86
|
+
snapshot = {
|
|
87
|
+
"order_id": "ORD-1",
|
|
88
|
+
"currency": "EUR",
|
|
89
|
+
"value": 10.0,
|
|
90
|
+
"tax": 1.0,
|
|
91
|
+
"shipping": 1.0,
|
|
92
|
+
"line_items": [{"sku": "s1", "name": "P", "price": 5.0, "quantity": 1}],
|
|
93
|
+
}
|
|
94
|
+
with override_settings(GTM_ID="GTM-UNITTEST"):
|
|
95
|
+
html = tpl.render(Context({"snapshot": snapshot}))
|
|
96
|
+
assert 'id="purchase-event"' in html
|
|
97
|
+
assert "purchase" in html
|
|
98
|
+
assert "ORD-1" in html
|