Metadata-Version: 2.4
Name: digital-analytics-toolkit
Version: 0.1.2
Summary: Toolkit for Google Analytics, Google Tag Manager, and BigQuery workflows
Author: Isha Panchal, Kris Dsouza
Maintainer-email: Isha Panchal <hacker.knight177@gmail.com>, Kris Dsouza <kris.dsouza64@gmail.com>
License-Expression: LicenseRef-Proprietary
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas
Requires-Dist: numpy
Requires-Dist: google-auth
Requires-Dist: google-analytics-data
Requires-Dist: google-analytics-admin
Requires-Dist: google-api-python-client
Requires-Dist: gspread
Requires-Dist: google-cloud-bigquery
Requires-Dist: db-dtypes
Dynamic: license-file

# 🚀 Digital Analytics Toolkit

### A Python toolkit for Google Analytics 4, Google Tag Manager, and BigQuery workflows

**Digital Analytics Toolkit** is a Python library designed to streamline GA4 reporting, GA4 administration, audience management, GTM container inspection, and BigQuery querying through reusable Python functions and clients.

---

## 📦 Installation

Install the latest release from PyPI:

```bash
pip install digital-analytics-toolkit
```

For future upgrade:

```bash
pip install --upgrade digital-analytics-toolkit
```

---

## 🔐 Authentication

Digital Analytics Toolkit supports **Service Account Key JSON files** and **Google OAuth2 Credentials**.

1. Create a Service Account in the [Google Cloud Console](https://console.cloud.google.com/).
2. Enable necessary APIs:
   - Google Analytics Data API
   - Google Analytics Admin API
   - Google Tag Manager API
   - BigQuery API
3. Download the JSON key file and share your GA4 property / GTM account access with the service account email.

---

## 🧩 Features & Module Usage

The toolkit is organized into 4 primary functional areas:

1. [GA4 Free-Form & Funnel Reporting](#1-ga4-reporting)
2. [GA4 Admin & Audience Management](#2-ga4-admin--audiences)
3. [Google Tag Manager (GTM) Operations](#3-google-tag-manager-gtm)
4. [BigQuery Integration](#4-bigquery-integration)

---

### 1. GA4 Reporting

#### 📊 Free-Form Reports (`free_form_report_GA4`)
Run custom GA4 reports specifying metrics, dimensions, date ranges, and optional dimension/metric filters.

```python
from digital_analytics_toolkit import free_form_report_GA4, dimension_filter_generation

# Initialize client
report_client = free_form_report_GA4(
    service_account_file="path/to/service_account.json",
    property_id="123456789"
)

# Optional: Generate dimension filter
dim_filter = dimension_filter_generation(
    operator="CONTAINS",
    value="Organic",
    dimension_name="sessionDefaultChannelGroup"
)

# Generate report
df = report_client.free_form_report(
    start_date="30daysAgo",
    end_date="today",
    metrics=["activeUsers", "eventCount", "conversions"],
    dimensions=["date", "sessionDefaultChannelGroup"],
    dimension_filter=dim_filter
)

print(df.head())
```

#### 🏆 Multi-Step Funnel Reports (`Funnel_Reports`)
Generate multi-step funnel analysis with support for breakdown dimensions based on funnel step definitions configured in Google Sheets.

```python
from digital_analytics_toolkit import Funnel_Reports

funnel = Funnel_Reports(
    reporting_client="path/to/service_account.json",
    prop_id="123456789"
)

# Run funnel report using steps defined in a Google Sheet
response = funnel.funnel_report(
    startDate="2024-01-01",
    endDate="2024-01-31",
    file_n="My_Funnel_Steps_Sheet_Name",
    breakdown="deviceCategory",
    breakdown_limit="5"
)
```

#### 📜 Dimension & Metric Metadata (`get_dimension_metric`)
Fetch all available custom & standard dimensions/metrics for a GA4 property and export to CSV.

```python
from digital_analytics_toolkit import utils

utils.get_dimension_metric(
    service_account_file="path/to/service_account.json",
    property_id="123456789",
    file_name="ga4_dimensions_metrics"
)
```

---

### 2. GA4 Admin & Audiences

#### 🏢 Accounts & Property Discovery
Discover accounts, properties, key events (conversions), and BigQuery links. The GA4 Admin helpers also cover property settings, data streams, custom dimensions, audience listing, and Measurement Protocol secrets.

```python
from google.oauth2 import service_account
from digital_analytics_toolkit import (
    get_ga4_accounts_list,
    get_ga4_properties_list,
    get_ga4_property_keyEvents,
    get_ga4_property_bq_link
)

creds = service_account.Credentials.from_service_account_file(
    "path/to/service_account.json",
    scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)

# List accounts & properties
accounts_df = get_ga4_accounts_list(creds)
properties_df = get_ga4_properties_list(creds, account_id="12345678")

# Key events & BigQuery export status
key_events_df = get_ga4_property_keyEvents(creds, property_id="123456789")
bq_links_df = get_ga4_property_bq_link(creds, property_id="123456789")
```

#### ⚙️ Property Settings & Data Streams
Inspect data retention, Google Signals, and data streams. Each function returns a pandas DataFrame.

```python
from digital_analytics_toolkit import (
    get_data_retension_settings,
    get_google_signals_status,
    list_data_streams,
)

retention_df = get_data_retension_settings(creds, property_id="123456789")
signals_df = get_google_signals_status(creds, property_id="123456789")
streams_df = list_data_streams(creds, property_id="123456789")
```

| Function | Returns (columns) |
|---|---|
| `get_data_retension_settings` | `event_data_retention`, `reset_user_data_on_new_activity`, `user_data_retention` |
| `get_google_signals_status` | `status`, `consent` |
| `list_data_streams` | `name`, `stream_id`, `type`, `display_name`, `create_time`, `update_time`, `measurement_id`, `firebase_app_id`, `default_uri` |

> The function name `get_data_retension_settings` is spelled as it appears in the code.

#### 🧮 Custom Dimensions & Audience Listing
Create and list custom dimensions, and list existing audiences.

```python
from digital_analytics_toolkit import (
    custom_dimension_creation,
    list_custom_dimensions,
    list_ga4_audiences,
)

# Creating requires the analytics.edit scope
custom_dimension_creation(
    creds,
    ga4_property_id="123456789",
    dimension_name="plan_type",   # used as both parameter name and display name
    type="EVENT",                 # EVENT, USER or ITEM
    description="Subscription plan of the user",
)

dimensions_df = list_custom_dimensions(creds, ga4_property_id="123456789")  # dimension_name, type, description
audiences_df = list_ga4_audiences(creds, ga4_property_id="123456789")       # audience_name, description, creation_date
```

#### 🔑 Measurement Protocol Secrets
List and create Measurement Protocol secrets for a data stream.

```python
from digital_analytics_toolkit import list_mp_secrets, create_mp_secret

secrets_df = list_mp_secrets(creds, ga4_property_id="123456789", data_stream_id="987654321")

# Requires analytics.edit scope. Returns the secret value, or None (with a
# UserWarning) if a secret with the same display name already exists.
secret_value = create_mp_secret(
    creds, "123456789", "987654321", display_name="Server-side hits"
)
```

> ⚠️ `secret_value` is a live credential. Avoid printing, logging, or exporting it.

#### 🎯 Audience Creation (`GA4AudienceClient`)
Programmatically construct and create GA4 audiences using a simplified dictionary condition language.

```python
from digital_analytics_toolkit import GA4AudienceClient

client = GA4AudienceClient(credentials_path="path/to/service_account.json")

audience = client.create_audience(
    property_id="123456789",
    display_name="High Intent Purchasers",
    description="Users with > 3 sessions who completed a purchase",
    membership_duration_days=30,
    scope="ACROSS_ALL_SESSIONS",
    include_conditions=[
        {"type": "event", "event_name": "purchase"},
        {"type": "numeric", "field_name": "sessionCount", "operation": "GREATER_THAN", "value": 3}
    ]
)
print(f"Created audience: {audience.name}")
```

---

### 3. Google Tag Manager (GTM)

Inspect accounts, containers, workspaces, tags, triggers, variables, built-in variables, and custom templates, and manage cleanup, versions, and publishing.

```python
from google.oauth2 import service_account
from digital_analytics_toolkit import (
    get_accounts,
    get_containers,
    get_workspaces,
    get_tags,
    get_triggers,
    get_variables,
    get_built_in_variables,
    get_custom_templates
)

creds = service_account.Credentials.from_service_account_file(
    "path/to/service_account.json",
    scopes=["https://www.googleapis.com/auth/tagmanager.readonly"]
)

# List accounts & containers
gtm_accounts = get_accounts(creds)
containers_df = get_containers(creds, account_id="123456")

# Inspect workspace assets
workspace_id = get_workspaces(creds, account_id="123456", container_id="987654")
tags = get_tags(creds, account_id="123456", container_id="987654", workspace_id=workspace_id)
triggers = get_triggers(creds, account_id="123456", container_id="987654", workspace_id=workspace_id)
variables = get_variables(creds, account_id="123456", container_id="987654", workspace_id=workspace_id)
```

#### 🧹 Cleanup, Versioning & Publishing
Delete workspace assets, create container versions, and publish. These require edit/publish scopes (e.g. `tagmanager.edit.containers`, `tagmanager.edit.containerversions`, `tagmanager.publish`).

```python
from digital_analytics_toolkit import (
    get_container_type,
    delete_tags,
    delete_triggers,
    delete_templates,
    create_version,
    publish_version,
    publish_workspace,
)

container_type = get_container_type(creds, "123456", "987654")

# Accept a single ID or a list; return {"deleted": [...], "failed": [{"id": ..., "error": ...}]}
result = delete_tags(creds, "123456", "987654", workspace_id, tag_ids=["11", "12"])
delete_triggers(creds, "123456", "987654", workspace_id, trigger_ids="21")
delete_templates(creds, "123456", "987654", workspace_id, template_ids="31")

# Snapshot the workspace, then publish the version
version = create_version(creds, "123456", "987654", workspace_id, name="v2", notes="Cleanup")
version_id = version["containerVersion"]["containerVersionId"]
publish_version(creds, "123456", "987654", version_id)

# Or do both in one call (raises RuntimeError and skips publishing on a compiler error)
publish_workspace(creds, "123456", "987654", workspace_id, name="v3", notes="Release")
```

> ⚠️ Deletion and publishing change live container state. Review before running.

---

### 4. BigQuery Integration

Run custom SQL queries or extract full tables directly into Pandas DataFrames.

```python
from digital_analytics_toolkit import bq_functions

service_account_file = "path/to/service_account.json"
project_id = "my-gcp-project"

# List Datasets
datasets = bq_functions.list_bq_datasets(credentials=None, gcp_project_id=project_id)

# Execute SQL query to DataFrame
query = """
    SELECT event_name, COUNT(1) AS event_count
    FROM `my-gcp-project.analytics_123456789.events_*`
    WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', CURRENT_DATE())
    GROUP BY 1
"""
df = bq_functions.get_ga4_data_from_bq(
    project_id=project_id,
    query=query,
    service_account_file=service_account_file
)
```

---

## 🛠 Project Structure

```
digital-analytics-toolkit/
├── pyproject.toml
├── README.md
└── digital_analytics_toolkit/
    ├── __init__.py               # Package entrypoint & exported symbols
    ├── free_form_report_GA4.py   # GA4 Free-form reporting & dimension filter generation
    ├── funnel_report_GA4.py      # GA4 Funnel report engine
    ├── ga4_admin_functions.py    # GA4 Admin API helpers (Accounts, Properties, Key Events, BQ Links, Retention, Signals, Streams, Custom Dimensions, Audiences, MP Secrets)
    ├── ga4_audience.py           # GA4 Audience creation & condition parser
    ├── gtm_functions.py          # Google Tag Manager (GTM) helpers (inspect, delete, version, publish)
    ├── bq_functions.py           # BigQuery query execution & dataset tools
    └── utils.py                  # Utility functions & metadata extractors
```

---

## 💬 Support & Inquiries

- For questions, bug reports, or feature requests, contact: **[hacker.knight177@gmail.com](mailto:hacker.knight177@gmail.com)** or **[kris.dsouza64@gmail.com](mailto:kris.dsouza64@gmail.com)**

---

## 📄 License

Digital Analytics Toolkit is proprietary software.

It is free to install and use for personal, educational, research,
and commercial purposes.

Modification, redistribution, sublicensing, resale, and creation of
derivative works are not permitted without explicit written
permission from the copyright holders.

See the [LICENSE](LICENSE) file for the complete terms.
