### Start Example Server Source: https://hexdocs.pm/phoenix_analytics/readme.html Navigate to an example project directory, get dependencies, and start the Phoenix server. ```bash cd examples/sqlite/ mix deps.get mix phx.server ``` -------------------------------- ### Run example application Source: https://hexdocs.pm/phoenix_analytics/index.html Start the example server to view the dashboard. ```bash cd examples/sqlite/ mix deps.get mix phx.server ``` -------------------------------- ### Install Dependencies and Compile Assets Source: https://hexdocs.pm/phoenix_analytics/readme.html Run the mix setup command to install dependencies, assets, and compile CSS/JS for development. ```bash mix setup ``` -------------------------------- ### PhoenixAnalytics.Services.Batcher - child_spec/1 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Batcher.html Returns a specification to start the Batcher module under a supervisor. ```APIDOC ## Supervisor Integration ### Description Provides a supervisor child specification for starting the `PhoenixAnalytics.Services.Batcher` GenServer. ### Method N/A (Function for Supervisor configuration) ### Endpoint N/A ### Parameters #### Function Parameters - **init_arg** (any) - Optional - Initialization argument for the GenServer. ### Response #### Success Response (N/A) - **child_spec** (map) - A map representing the supervisor child specification. ### Example Usage (in Supervisor) ```elixir children = [ {PhoenixAnalytics.Services.Batcher, init_arg} ] Supervisor.start_link(children, strategy: :one_for_one) ``` ``` -------------------------------- ### Get Configuration Value Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Retrieves a configuration value using a key, with an optional default. Useful for accessing settings. ```elixir iex> PhoenixAnalytics.Services.Utility.get_config(:pool_size, 10) 10 ``` -------------------------------- ### Get PubSub server name Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Retrieves the atom identifier for the PubSub server. ```elixir @spec name() :: atom() ``` ```elixir iex> PhoenixAnalytics.Services.PubSub.name() :pa_pubsub ``` -------------------------------- ### Get Database Type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Determines the current database type based on configuration. Returns :postgres, :sqlite, or :mysql. ```elixir iex> PhoenixAnalytics.Services.Utility.database_type() :postgres ``` -------------------------------- ### GET /api/analytics/devices/usage Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Device.html Retrieves device usage statistics for a given date range. This endpoint is part of the PhoenixAnalytics module for analyzing device patterns. ```APIDOC ## GET /api/analytics/devices/usage ### Description Gets device usage statistics for a given date range. ### Method GET ### Endpoint /api/analytics/devices/usage ### Parameters #### Query Parameters - **from_date** (date) - Required - The start date for the statistics. - **to_date** (date) - Required - The end date for the statistics. ### Response #### Success Response (200) - **data** (object) - Contains device usage statistics. - **device_type** (string) - The type of device. - **count** (integer) - The number of usage instances for the device type. #### Response Example ```json { "data": [ { "device_type": "mobile", "count": 1500 }, { "device_type": "desktop", "count": 800 } ] } ``` ``` -------------------------------- ### PhoenixAnalytics.Services.PubSub - Get PubSub Server Name Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Returns the name of the PubSub server. This function provides the atom used to identify the PubSub server. ```APIDOC ## GET /pubsub/name ### Description Returns the name of the PubSub server. ### Method GET ### Endpoint /pubsub/name ### Response #### Success Response (200) - **server_name** (atom) - The atom identifying the PubSub server, e.g., `:pa_pubsub`. #### Response Example ```json { "server_name": ":pa_pubsub" } ``` ``` -------------------------------- ### Configure Phoenix Analytics Source: https://hexdocs.pm/phoenix_analytics/index.html Set up the repository and environment variables in your configuration file. ```elixir # config/dev.exs config :phoenix_analytics, repo: MyApp.Repo, app_domain: System.get_env("PHX_HOST") || "example.com", cache_ttl: System.get_env("CACHE_TTL") || 60 ``` -------------------------------- ### Run Ecto Migrations Source: https://hexdocs.pm/phoenix_analytics/readme.html Execute the pending Ecto migrations to apply changes to your database. ```bash mix ecto.migrate ``` -------------------------------- ### Seed Database with Data Source: https://hexdocs.pm/phoenix_analytics/readme.html Use mix run to seed your database with data. Specify the database type (sqlite, postgres, mysql) and optionally the number of records. ```bash # For SQLite3 mix run priv/repo/seeds.exs sqlite 10000 # For PostgreSQL mix run priv/repo/seeds.exs postgres # For MySQL mix run priv/repo/seeds.exs mysql 10000 ``` -------------------------------- ### Get Current UTC Timestamp Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Returns the current UTC timestamp formatted for database compatibility. Includes millisecond precision. ```elixir iex> PhoenixAnalytics.Services.Utility.inserted_at() "2023-05-15 14:30:45.123" ``` -------------------------------- ### Define migration modules Source: https://hexdocs.pm/phoenix_analytics/index.html Implement the migration logic for the analytics table and indexes. ```elixir defmodule MyApp.Repo.Migrations.AddPhoenixAnalytics do use Ecto.Migration def up, do: PhoenixAnalytics.Migration.up() def down, do: PhoenixAnalytics.Migration.down() end # indexes, no sqlite support defmodule MyApp.Repo.Migrations.AddPhoenixAnalyticsIndexes do def change do PhoenixAnalytics.Migration.add_indexes() end end ``` -------------------------------- ### Define path type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the request path as a string. ```elixir @type path() :: String.t() ``` -------------------------------- ### Send a batch of RequestLogs Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Batcher.html Manually triggers the insertion of a provided list of RequestLog structs into the database. ```elixir iex> PhoenixAnalytics.Services.Batcher.send_batch([%PhoenixAnalytics.Entities.RequestLog{}, %PhoenixAnalytics.Entities.RequestLog{}]) ``` -------------------------------- ### create_requests() Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Table.html Creates the requests table using Ecto schema. Intended for development and testing environments. ```APIDOC ## create_requests() ### Description Creates the requests table using Ecto schema. This function is primarily for development/testing. For production, use proper Ecto migrations. ``` -------------------------------- ### PhoenixAnalytics.Services.Utility Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html A helper module containing static utility functions for Phoenix Analytics. ```APIDOC ## PhoenixAnalytics.Services.Utility ### Description A helper module containing static utility functions for Phoenix Analytics. This module provides various utility functions that are used across the Phoenix Analytics application. It includes functions for timestamp generation and device type detection based on user agent strings. ### Functions - `database_type()`: Determines the current database type based on configuration. - `get_config(key, default \\ nil)`: Gets a configuration value with an optional default. - `get_device_type(agent_string)`: Determines the device type based on the user agent string. - `has_config?(key)`: Checks if a specific configuration key exists and has a value. - `inserted_at()`: Returns the current UTC timestamp in database-compatible format. - `mode()`: Placeholder for mode function. - `uuid()`: Generates a new UUID (Universally Unique Identifier). ## database_type() ### Description Determines the current database type based on configuration. This function checks the application environment for database configurations to determine the current database type being used. ### Returns An atom indicating the database type: * `:postgres` if PostgreSQL is configured * `:sqlite` if SQLite is configured * `:mysql` if MySQL is configured * `:postgres` as a fallback if no valid configuration is found ### Examples ```iex PhoenixAnalytics.Services.Utility.database_type() #=> :postgres ``` ## get_config(key, default \\ nil) ### Description Gets a configuration value with an optional default. ### Parameters - **key** (any) - The configuration key to retrieve - **default** (any) - The default value if the key is not found ### Returns The configuration value or the default value. ### Examples ```iex PhoenixAnalytics.Services.Utility.get_config(:pool_size, 10) #=> 10 ``` ## get_device_type(agent_string) ### Description Determines the device type based on the user agent string. This function provides a simple and fast way to categorize devices as mobile, tablet, or desktop based on the user agent string. It was implemented as a lightweight alternative to ua_parser and ua_inspector, which were found to be excessively slow for this use case. While this method is not as comprehensive as full-fledged user agent parsing libraries, it offers a quick classification that is sufficient for many analytics purposes. ### Parameters - **agent_string** (string) - The user agent string to analyze ### Returns A string indicating the device type: * "mobile" for mobile devices * "tablet" for tablet devices * "desktop" for desktop devices or any unrecognized device type ### Examples ```iex PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1") #=> "mobile" PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (iPad; CPU OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1") #=> "tablet" PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") #=> "desktop" ``` ## has_config?(key) ### Description Checks if a specific configuration key exists and has a value. ### Parameters - **key** (any) - The configuration key to check ### Returns A boolean indicating whether the configuration exists and has a value. ### Examples ```iex PhoenixAnalytics.Services.Utility.has_config?(:postgres_conn) #=> true ``` ## inserted_at() ### Description Returns the current UTC timestamp in database-compatible format. This function generates a timestamp string that is compatible with standard database TIMESTAMP data types. The timestamp is in UTC and includes millisecond precision. ### Returns A string in the format "YYYY-MM-DD HH:MM:SS.mmm". ### Examples ```iex PhoenixAnalytics.Services.Utility.inserted_at() #=> "2023-05-15 14:30:45.123" ``` ## mode() ### Description Placeholder for mode function. ## uuid() ### Description Generates a new UUID (Universally Unique Identifier). This function creates a version 4 UUID, which is randomly generated. ### Returns A string representation of the UUID. ### Examples ```iex PhoenixAnalytics.Services.Utility.uuid() #=> "550e8400-e29b-41d4-a716-446655440000" ``` ``` -------------------------------- ### Define user_agent type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the client user agent string or nil. ```elixir @type user_agent() :: String.t() | nil ``` -------------------------------- ### Check Configuration Key Existence Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Verifies if a specific configuration key exists and has an assigned value. Returns a boolean. ```elixir iex> PhoenixAnalytics.Services.Utility.has_config?(:postgres_conn) true ``` -------------------------------- ### name() Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Table.html Retrieves the configured table name for requests. ```APIDOC ## name() ### Description Gets the table name for requests. ``` -------------------------------- ### Define referer type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the referer URL as a string or nil. ```elixir @type referer() :: String.t() | nil ``` -------------------------------- ### Add RequestTracker Plug to Endpoint Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Plugs.RequestTracker.html Add this plug to your endpoint directly after static plugs or the router to begin tracking requests. ```elixir plug PhoenixAnalytics.Plugs.RequestTracker ``` -------------------------------- ### PhoenixAnalytics.Config Functions Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Config.html Functions for retrieving configuration values for the PhoenixAnalytics library. ```APIDOC ## Configuration Functions ### get_app_domain() - **Description**: Gets the application domain for filtering external referrers. ### get_cache_ttl() - **Description**: Gets the cache TTL in seconds. ### get_otp_app() - **Description**: Gets the OTP app name (if needed for specific configurations). ### get_repo() - **Description**: Gets the user's configured Ecto repository. ``` -------------------------------- ### Define method type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the HTTP method as a string. ```elixir @type method() :: String.t() ``` -------------------------------- ### PhoenixAnalytics.Queries.Helpers Functions Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Helpers.html A collection of helper functions to refine Ecto queries for analytics data. ```APIDOC ## PhoenixAnalytics.Queries.Helpers Functions ### Description Helper functions to build Ecto queries for analytics data. ### Functions - **exclude_dev(query)**: Excludes development-only paths from a query. - **exclude_non_page(query)**: Excludes non-page requests (static files, assets, etc.) from a query. - **filter_by_date(query, from_date, to_date)**: Applies date range filtering to a query. - **filter_external_referrers(query, app_domain)**: Filters query to exclude internal referrers. - **filter_get_requests(query)**: Filters query to only include GET requests. - **filter_not_found(query)**: Filters query to only include 404 requests. - **filter_successful(query)**: Filters query to only include successful requests (status 200). ``` -------------------------------- ### Define dashboard routes with phoenix_analytics_dashboard Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Web.Router.html Use this macro within your router to mount the Phoenix Analytics dashboard at a specific path. ```elixir phoenix_analytics_dashboard "/analytics" ``` -------------------------------- ### Add RequestTracker Plug to Router Pipeline Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Plugs.RequestTracker.html Using the plug within a router pipeline is possible, but it means static files won't be tracked. Ensure it's placed appropriately within your pipeline. ```elixir pipeline :browser do ... plug PhoenixAnalytics.Plugs.RequestTracker end ``` -------------------------------- ### Detect Device Type from User Agent Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Classifies a device as 'mobile', 'tablet', or 'desktop' based on its user agent string. This is a lightweight alternative to full parsing libraries. ```elixir iex> PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1") "mobile" ``` ```elixir iex> PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (iPad; CPU OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1") "tablet" ``` ```elixir iex> PhoenixAnalytics.Services.Utility.get_device_type("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") "desktop" ``` -------------------------------- ### Define device_type type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the device type as a string or nil. ```elixir @type device_type() :: String.t() | nil ``` -------------------------------- ### Run Phoenix Analytics Migration Directly Source: https://hexdocs.pm/phoenix_analytics/readme.html Alternatively, run the Phoenix Analytics migration directly in an IEx session if not using Ecto migrations. ```elixir iex -S mix PhoenixAnalytics.Migration.up() ``` -------------------------------- ### Generate Phoenix Analytics Migration Source: https://hexdocs.pm/phoenix_analytics/readme.html Generate a migration file to add the analytics table to your database. ```bash mix ecto.gen.migration add_phoenix_analytics ``` -------------------------------- ### Subscribe to request topic Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Subscribes the current process to receive messages from the request topic. ```elixir @spec subscribe() :: :ok | {:error, term()} ``` ```elixir iex> PhoenixAnalytics.Services.PubSub.subscribe() :ok ``` -------------------------------- ### Fetch or compute a value from the cache Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Fetches a value by key. If the value is not present, it computes and caches it using the provided callback function. This is useful for data that is expensive to compute. ```iex iex> PhoenixAnalytics.Services.Cache.fetch("some_key", fn -> "computed_value" end) {:commit, "computed_value"} iex> PhoenixAnalytics.Services.Cache.fetch("existing_key", fn -> "new_value" end) {:ok, "cached_value"} ``` -------------------------------- ### Configure Phoenix Analytics Repository Source: https://hexdocs.pm/phoenix_analytics/readme.html Configure Phoenix Analytics to use your existing Ecto repository and set cache TTL in config/dev.exs. ```elixir config :phoenix_analytics, repo: MyApp.Repo, app_domain: System.get_env("PHX_HOST") || "example.com", cache_ttl: System.get_env("CACHE_TTL") || 60 ``` -------------------------------- ### Popular Device Types Query Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Popular.html Retrieves a list of popular device types within a specified date range. ```APIDOC ## GET /analytics/popular/device_types ### Description Gets popular device types for a given date range. ### Method GET ### Endpoint /analytics/popular/device_types ### Query Parameters - **from_date** (date) - Required - The start date for the query. - **to_date** (date) - Required - The end date for the query. ### Response #### Success Response (200) - **device_type** (string) - The type of device. - **count** (integer) - The number of occurrences. #### Response Example ```json { "data": [ { "device_type": "desktop", "count": 1500 }, { "device_type": "mobile", "count": 1200 } ] } ``` ``` -------------------------------- ### Broadcast an event Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Broadcasts a RequestLog struct to all subscribers of the request topic. ```elixir @spec broadcast(PhoenixAnalytics.Entities.RequestLog.t()) :: :ok | {:error, term()} ``` ```elixir iex> request_log = %PhoenixAnalytics.Entities.RequestLog{request_id: "123", path: "/api/users"} iex> PhoenixAnalytics.Services.PubSub.broadcast(request_log) :ok ``` -------------------------------- ### Add Phoenix Analytics Dependency Source: https://hexdocs.pm/phoenix_analytics/readme.html Add the phoenix_analytics package to your project's dependencies in mix.exs. ```elixir def deps do [ {:phoenix_analytics, "~> 0.4"} ] end ``` -------------------------------- ### PhoenixAnalytics.Plugs.RequestTracker Plug Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Plugs.RequestTracker.html This plug tracks and logs HTTP requests, measures duration, collects data, and handles session tracking. It prepares and validates request data before broadcasting it asynchronously. ```APIDOC ## POST / ### Description This plug tracks and logs HTTP requests, measures duration, collects data, and handles session tracking. It prepares and validates request data before broadcasting it asynchronously. ### Method PLUG ### Endpoint N/A (This is a Plug, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```elixir plug PhoenixAnalytics.Plugs.RequestTracker ``` ### Response #### Success Response (200) Returns the `Plug.Conn` struct, potentially modified by subsequent plugs or handlers. #### Response Example ```elixir %Plug.Conn{} ``` ``` -------------------------------- ### PhoenixAnalytics.Services.PubSub - Subscribe to Topic Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Subscribes the current process to the request topic. After subscribing, the process will receive messages broadcasted to the request topic. ```APIDOC ## POST /pubsub/subscribe ### Description Subscribes the current process to the request topic. ### Method POST ### Endpoint /pubsub/subscribe ### Response #### Success Response (200) - **status** (atom) - Indicates success, typically `:ok`. #### Response Example ```json { "status": ":ok" } ``` #### Error Handling - May raise an error if the PubSub server is not available or if there's an issue with the subscription. ``` -------------------------------- ### Insert a RequestLog Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Batcher.html Adds a RequestLog struct to the batch queue for processing. ```elixir PhoenixAnalytics.Services.Batcher.insert(%PhoenixAnalytics.Entities.RequestLog{}) ``` ```elixir iex> PhoenixAnalytics.Services.Batcher.insert(%PhoenixAnalytics.Entities.RequestLog{}) ``` -------------------------------- ### Retrieve a value from the cache Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Retrieves a value directly from the cache using its key. Returns `{:ok, nil}` if the key is not found. ```iex iex> PhoenixAnalytics.Services.Cache.get("some_key") {:ok, nil} iex> PhoenixAnalytics.Services.Cache.get("existing_key") {:ok, "cached_value"} ``` -------------------------------- ### changeset/2 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Function to create a changeset for the RequestLog schema. ```APIDOC ## changeset(request_log, attrs) ### Description Creates a changeset for RequestLog to validate and cast attributes. ### Parameters - **request_log** (RequestLog) - The struct to apply changes to - **attrs** (Map) - The attributes to apply ``` -------------------------------- ### Broadcast a RequestLog via PubSub Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Batcher.html Sends a request log event to PubSub, suitable for distributed application scenarios. ```elixir PhoenixAnalytics.Services.PubSub.broadcast(:request_sent, %PhoenixAnalytics.Entities.RequestLog{}) ``` ```elixir iex> PhoenixAnalytics.Services.PubSub.broadcast(:request_sent, %PhoenixAnalytics.Entities.RequestLog{}) ``` -------------------------------- ### PhoenixAnalytics.Services.Batcher - insert/1 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Batcher.html Inserts a RequestLog into the batch queue. The batch is processed and inserted into the database either when it reaches 1_000 logs or after 1 second, whichever comes first. ```APIDOC ## POST /request_logs/batch ### Description Inserts a RequestLog into the batch queue for efficient database insertion. ### Method POST ### Endpoint /request_logs/batch ### Parameters #### Request Body - **request_log** (PhoenixAnalytics.Entities.RequestLog) - Required - A struct representing the request log to be inserted. ### Request Example ```json { "request_log": { "field1": "value1", "field2": "value2" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation, e.g., "accepted". #### Response Example ```json { "status": "accepted" } ``` ### Usage Notes Alternatively, you can use PubSub for distributed applications: ```elixir PhoenixAnalytics.Services.PubSub.broadcast(:request_sent, %PhoenixAnalytics.Entities.RequestLog{}) ``` ``` -------------------------------- ### Popular User Agents Query Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Popular.html Retrieves a list of popular user agents within a specified date range. ```APIDOC ## GET /analytics/popular/user_agents ### Description Gets popular user agents for a given date range. ### Method GET ### Endpoint /analytics/popular/user_agents ### Query Parameters - **from_date** (date) - Required - The start date for the query. - **to_date** (date) - Required - The end date for the query. ### Response #### Success Response (200) - **user_agent** (string) - The user agent string. - **count** (integer) - The number of occurrences. #### Response Example ```json { "data": [ { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "count": 8000 }, { "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/604.1", "count": 6000 } ] } ``` ``` -------------------------------- ### Option Parsing Function Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Web.Router.html The `parse_options` function processes the options passed to the `phoenix_analytics_dashboard` macro, setting up default configurations and allowing for custom hooks. ```APIDOC ## FUNCTION parse_options/2 ### Description Processes the options passed to the `phoenix_analytics_dashboard` macro. ### Parameters - **opts** (keyword list) - Required - The options keyword list. - **path** (string) - Required - The base path for the dashboard. ### Returns - **tuple** - A tuple containing the session name and session options. ### Details This function sets up the default on_mount hooks, including a custom hook to set the dashboard path, and allows for additional custom hooks to be added. It also configures the root layout for the dashboard. ``` -------------------------------- ### PhoenixAnalytics.Services.Cache.fetch/2 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Fetches a value from the cache for the given key. If the key is not found, it computes the value using the provided callback function and caches it. ```APIDOC ## POST /cache/fetch ### Description Fetches a value from the cache for the given key, or computes and caches it if not present. ### Method POST ### Endpoint /cache/fetch ### Parameters #### Request Body - **key** (string) - Required - The key to fetch from the cache. - **callback** (function) - Required - A function that computes the value if it's not in the cache. ### Request Example ```json { "key": "some_key", "callback": "fn -> \"computed_value\" end" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the result of the operation. Possible values include `{:ok, value}`, `{:commit, value}`, or `{:error, reason}`. #### Response Example ```json { "status": "{:commit, \"computed_value\"}" } ``` ``` -------------------------------- ### PhoenixAnalytics.Queries.Insert API Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Functions for inserting and upserting RequestLog entries. ```APIDOC ## PhoenixAnalytics.Queries.Insert ### Description Ecto-based insert operations for PhoenixAnalytics. This module provides functions for inserting RequestLog entries using Ecto's insert and insert_all functions. ### Functions #### insert_many(request_data_list) ##### Description Inserts multiple RequestLog entries using Ecto's insert_all. ##### Specification ```elixir @spec insert_many([PhoenixAnalytics.Entities.RequestLog.t()]) :: {:ok, integer()} | {:error, term()} ``` #### insert_many_with_changesets(changesets) ##### Description Inserts multiple RequestLog entries with custom changesets. ##### Specification ```elixir @spec insert_many_with_changesets([Ecto.Changeset.t()]) :: {:ok, integer()} | {:error, term()} ``` #### insert_one(request_data) ##### Description Inserts a single RequestLog entry using Ecto. ##### Specification ```elixir @spec insert_one(PhoenixAnalytics.Entities.RequestLog.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, Ecto.Changeset.t()} ``` #### insert_one_with_changeset(changeset) ##### Description Inserts a single RequestLog entry with a custom changeset. ##### Specification ```elixir @spec insert_one_with_changeset(Ecto.Changeset.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, Ecto.Changeset.t()} ``` #### upsert_many(request_data_list) ##### Description Bulk upserts multiple RequestLog entries. ##### Specification ```elixir @spec upsert_many([PhoenixAnalytics.Entities.RequestLog.t()]) :: {:ok, integer()} | {:error, term()} ``` #### upsert_one(request_data) ##### Description Upserts a RequestLog entry (insert if not exists, update if exists). ##### Specification ```elixir @spec upsert_one(PhoenixAnalytics.Entities.RequestLog.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, term()} ``` ``` -------------------------------- ### Popular Pages Query Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Popular.html Retrieves a list of popular pages within a specified date range. ```APIDOC ## GET /analytics/popular/pages ### Description Gets popular pages for a given date range. ### Method GET ### Endpoint /analytics/popular/pages ### Query Parameters - **from_date** (date) - Required - The start date for the query. - **to_date** (date) - Required - The end date for the query. ### Response #### Success Response (200) - **page_path** (string) - The path of the page. - **count** (integer) - The number of views. #### Response Example ```json { "data": [ { "page_path": "/", "count": 5000 }, { "page_path": "/about", "count": 2500 } ] } ``` ``` -------------------------------- ### Define remote_ip type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the client IP address as a string or nil. ```elixir @type remote_ip() :: String.t() | nil ``` -------------------------------- ### Popular Referrer Query Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Popular.html Retrieves a list of popular external referrers within a specified date range. ```APIDOC ## GET /analytics/popular/referrers ### Description Gets popular external referrers for a given date range. ### Method GET ### Endpoint /analytics/popular/referrers ### Query Parameters - **from_date** (date) - Required - The start date for the query. - **to_date** (date) - Required - The end date for the query. ### Response #### Success Response (200) - **referrer_url** (string) - The URL of the referrer. - **count** (integer) - The number of referrals. #### Response Example ```json { "data": [ { "referrer_url": "https://www.google.com", "count": 10000 }, { "referrer_url": "https://www.bing.com", "count": 5000 } ] } ``` ``` -------------------------------- ### Insert many RequestLog entries Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Inserts multiple RequestLog entries using Ecto's insert_all. ```elixir @spec insert_many([PhoenixAnalytics.Entities.RequestLog.t()]) :: {:ok, integer()} | {:error, term()} ``` -------------------------------- ### Insert a single entry with a custom changeset Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Inserts a single RequestLog entry using a custom Ecto changeset. ```elixir @spec insert_one_with_changeset(Ecto.Changeset.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, Ecto.Changeset.t()} ``` -------------------------------- ### Telemetry Logging Functions Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Telemetry.html Functions for logging errors and successes. ```APIDOC ## PhoenixAnalytics.Services.Telemetry ### Description Provides functions to log errors and successes for telemetry purposes. ### Functions #### log_error(error, reason) ##### Description Logs an error with a specific reason. ##### Parameters - **error** (any) - Required - The error to log. - **reason** (any) - Required - The reason for the error. #### log_success(event) ##### Description Logs a successful event. ##### Parameters - **event** (any) - Required - The event to log. ``` -------------------------------- ### Define inserted_at type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the insertion timestamp as a NaiveDateTime or nil. ```elixir @type inserted_at() :: NaiveDateTime.t() | nil ``` -------------------------------- ### Add a value to the cache Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Use this function to store a value in the cache under a specified key. Ensure the key and value are appropriate for caching. ```iex iex> PhoenixAnalytics.Services.Cache.add("new_key", "new_value") {:ok, true} iex> PhoenixAnalytics.Services.Cache.add("existing_key", "updated_value") {:ok, true} ``` -------------------------------- ### Insert many with custom changesets Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Inserts multiple RequestLog entries using custom Ecto changesets. ```elixir @spec insert_many_with_changesets([Ecto.Changeset.t()]) :: {:ok, integer()} | {:error, term()} ``` -------------------------------- ### PhoenixAnalytics Dashboard Routing Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Web.Router.html The `phoenix_analytics_dashboard` macro sets up the necessary routes for the Phoenix Analytics dashboard. It accepts a base path and optional configuration options. ```APIDOC ## MACRO phoenix_analytics_dashboard/2 ### Description Creates routes for the Phoenix Analytics dashboard. ### Parameters - **path** (string) - Required - The base path for the dashboard routes. - **opts** (keyword list) - Optional - Keyword list of configuration options. ### Options - **:as** (atom) - Optional - The name for the live session (default: :phoenix_analytics_dashboard) - **:on_mount** (list) - Optional - Additional mount hooks to be executed (default: []) ### Usage ```elixir phoenix_analytics_dashboard "/analytics" phoenix_analytics_dashboard "/my-analytics", as: :my_dashboard ``` ``` -------------------------------- ### Generate UUID Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Utility.html Creates a new version 4 UUID (Universally Unique Identifier). Returns a string representation. ```elixir iex> PhoenixAnalytics.Services.Utility.uuid() "550e8400-e29b-41d4-a716-446655440000" ``` -------------------------------- ### Bulk upsert RequestLog entries Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Performs a bulk upsert operation for multiple RequestLog entries. ```elixir @spec upsert_many([PhoenixAnalytics.Entities.RequestLog.t()]) :: {:ok, integer()} | {:error, term()} ``` -------------------------------- ### Add Dashboard Route Source: https://hexdocs.pm/phoenix_analytics/readme.html Include the phoenix_analytics_dashboard route in your router.ex to access the analytics dashboard. ```elixir use PhoenixAnalytics.Web, :router phoenix_analytics_dashboard "/analytics" ``` -------------------------------- ### Popular Not Found Pages Query Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Popular.html Retrieves a list of popular 404 pages within a specified date range. ```APIDOC ## GET /analytics/popular/not_found ### Description Gets popular 404 pages for a given date range. ### Method GET ### Endpoint /analytics/popular/not_found ### Query Parameters - **from_date** (date) - Required - The start date for the query. - **to_date** (date) - Required - The end date for the query. ### Response #### Success Response (200) - **page_path** (string) - The path of the 404 page. - **count** (integer) - The number of occurrences. #### Response Example ```json { "data": [ { "page_path": "/old/page", "count": 50 }, { "page_path": "/nonexistent/resource", "count": 30 } ] } ``` ``` -------------------------------- ### Insert a single RequestLog entry Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Inserts a single RequestLog entry using Ecto. ```elixir @spec insert_one(PhoenixAnalytics.Entities.RequestLog.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, Ecto.Changeset.t()} ``` -------------------------------- ### slowest_resources(from_date, to_date) Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Charts.Slowest.html Retrieves a list of the slowest non-page resources based on response time within the specified date range. ```APIDOC ## slowest_resources(from_date, to_date) ### Description Gets slowest resources (non-page requests) for a given date range. ### Parameters - **from_date** (DateTime) - Required - The start of the date range. - **to_date** (DateTime) - Required - The end of the date range. ``` -------------------------------- ### PhoenixAnalytics.Entities.RequestLog Schema Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Defines the structure and data types for HTTP request logs. ```APIDOC ## RequestLog Schema ### Description Represents a log entry for an HTTP request, containing metadata such as method, path, status code, and duration. ### Fields - **request_id** (String) - Unique identifier for the request - **method** (String) - HTTP method of the request - **path** (String) - Path of the request - **status_code** (Integer) - HTTP status code of the response - **duration_ms** (Integer) - Duration of the request in milliseconds - **device_type** (String) - Type of device used - **remote_ip** (String) - IP address of the client - **user_agent** (String) - User agent string - **referer** (String) - Referer URL - **session_id** (String) - Unique identifier for the session - **session_page_views** (Integer) - Number of page views in the session - **inserted_at** (NaiveDateTime) - Timestamp of insertion ``` -------------------------------- ### Define RequestLog struct type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html The primary struct type for the RequestLog entity. ```elixir @type t() :: %PhoenixAnalytics.Entities.RequestLog{ __meta__: term(), device_type: device_type(), duration_ms: duration_ms(), inserted_at: inserted_at(), method: method(), path: path(), referer: referer(), remote_ip: remote_ip(), request_id: request_id(), session_id: session_id(), session_page_views: session_page_views(), status_code: status_code(), user_agent: user_agent() } ``` -------------------------------- ### PhoenixAnalytics.Services.Cache.add/2 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Adds a value to the cache with the given key. This function is useful for pre-populating the cache or storing frequently accessed data. ```APIDOC ## POST /cache/add ### Description Adds a value to the cache with the given key. ### Method POST ### Endpoint /cache/add ### Parameters #### Request Body - **key** (string) - Required - The key under which to store the value in the cache. - **value** (any) - Required - The value to be stored in the cache. ### Request Example ```json { "key": "new_key", "value": "new_value" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the result of the operation. Expected values are `{:ok, true}` or `{:ok, :error}`. #### Response Example ```json { "status": "{:ok, true}" } ``` ``` -------------------------------- ### Define duration_ms type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the request duration in milliseconds as an integer. ```elixir @type duration_ms() :: integer() ``` -------------------------------- ### Define Phoenix Analytics Migration Source: https://hexdocs.pm/phoenix_analytics/readme.html Define the up and down functions for the Phoenix Analytics migration using Ecto.Migration. ```elixir defmodule MyApp.Repo.Migrations.AddPhoenixAnalytics do use Ecto.Migration def up, do: PhoenixAnalytics.Migration.up() def down, do: PhoenixAnalytics.Migration.down() end ``` -------------------------------- ### Define request_id type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the unique request identifier as a string. ```elixir @type request_id() :: String.t() ``` -------------------------------- ### PhoenixAnalytics.Services.Cache.get/1 Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.Cache.html Retrieves a value from the cache for the given key without attempting to compute it if it's missing. ```APIDOC ## GET /cache/get ### Description Retrieves a value from the cache for the given key. ### Method GET ### Endpoint /cache/get ### Parameters #### Query Parameters - **key** (string) - Required - The key to retrieve from the cache. ### Request Example ``` GET /cache/get?key=some_key ``` ### Response #### Success Response (200) - **value** (any) - The cached data if the key is found, or `nil` if the key is not found. #### Response Example ```json { "value": null } ``` ``` -------------------------------- ### Analytics Queries API Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.html This section outlines the available functions for querying analytics data, categorized by their purpose (e.g., stats, charts). Each function typically requires a date range. ```APIDOC ## Analytics Queries ### Description Provides access to various analytics query functions organized by category. ### Functions - **average_response_time(from_date, to_date)**: Calculates the average response time within a given date range. - **average_views_per_visit(from_date, to_date)**: Calculates the average number of views per visit. - **average_visit_duration(from_date, to_date, interval \"day")**: Calculates the average visit duration, with an optional interval. - **bounce_rate(from_date, to_date)**: Calculates the bounce rate. - **bounce_rate_per_period_limited(from_date, to_date)**: Calculates the bounce rate per period, limited. - **device_type_distribution(from_date, to_date)**: Shows the distribution of device types. - **devices_usage(from_date, to_date)**: Provides data on devices usage. - **popular_device_types(from_date, to_date)**: Lists the most popular device types. - **popular_not_found(from_date, to_date)**: Lists popular "not found" pages. - **popular_pages(from_date, to_date)**: Lists the most popular pages. - **popular_referer(from_date, to_date)**: Lists the most popular referrers. - **popular_user_agents(from_date, to_date)**: Lists the most popular user agents. - **slowest_pages(from_date, to_date)**: Lists the slowest pages. - **slowest_resources(from_date, to_date)**: Lists the slowest resources. - **status_code_distribution(from_date, to_date)**: Shows the distribution of status codes. - **statuses_per_period(from_date, to_date, interval)**: Provides status code data per period. - **total_pageviews(from_date, to_date)**: Calculates the total number of page views. - **total_pageviews_per_period_limited(from_date, to_date)**: Calculates total page views per period, limited. - **total_requests(from_date, to_date)**: Calculates the total number of requests. - **total_requests_per_period(from_date, to_date, interval)**: Calculates total requests per period. - **total_requests_per_period_limited(from_date, to_date)**: Calculates total requests per period, limited. - **unique_visitors(from_date, to_date)**: Calculates the number of unique visitors. - **unique_visitors_per_period_limited(from_date, to_date)**: Calculates unique visitors per period, limited. - **views_per_visit_per_period_limited(from_date, to_date)**: Calculates views per visit per period, limited. - **visit_duration_per_period_limited(from_date, to_date)**: Calculates visit duration per period, limited. - **visits_per_period(from_date, to_date, interval)**: Provides visit data per period. ### Parameters - **from_date** (date): The start date for the query. - **to_date** (date): The end date for the query. - **interval** (string, optional): The interval for period-based queries (e.g., \"day\"). ### Notes Detailed implementation and specific return types can be found by following the \"See ...\" links provided for each function. ``` -------------------------------- ### Upsert a single RequestLog entry Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Insert.html Upserts a single RequestLog entry, inserting if it does not exist or updating if it does. ```elixir @spec upsert_one(PhoenixAnalytics.Entities.RequestLog.t()) :: {:ok, PhoenixAnalytics.Entities.RequestLog.t()} | {:error, term()} ``` -------------------------------- ### Define session_id type Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Entities.RequestLog.html Represents the unique session identifier as a string or nil. ```elixir @type session_id() :: String.t() | nil ``` -------------------------------- ### drop_requests() Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Table.html Drops the requests table from the database. ```APIDOC ## drop_requests() ### Description Drops the requests table. ``` -------------------------------- ### Add Phoenix Analytics Indexes Migration Source: https://hexdocs.pm/phoenix_analytics/readme.html Define a migration to add indexes for Phoenix Analytics. Note: This does not support SQLite. ```elixir defmodule MyApp.Repo.Migrations.AddPhoenixAnalyticsIndexes do def change do PhoenixAnalytics.Migration.add_indexes() end end ``` -------------------------------- ### Analytics Statistics Query Functions Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Queries.Analytics.Stats.Stat.html A collection of functions to retrieve various analytics metrics based on date ranges. ```APIDOC ## Analytics Statistics Functions ### Description Functions to generate Ecto queries for calculating analytics statistics. ### Parameters #### Query Parameters - **from_date** (date) - Required - Start date for the statistics range. - **to_date** (date) - Required - End date for the statistics range. - **interval** (string) - Optional - Time interval for duration calculations (default: "day"). ### Functions - **average_response_time(from_date, to_date)**: Gets average response time. - **average_views_per_visit(from_date, to_date)**: Gets average views per visit. - **average_visit_duration(from_date, to_date, interval)**: Gets average visit duration. - **bounce_rate(from_date, to_date)**: Gets bounce rate. - **device_type_distribution(from_date, to_date)**: Gets device type distribution. - **status_code_distribution(from_date, to_date)**: Gets status code distribution. - **total_pageviews(from_date, to_date)**: Gets total pageviews count. - **total_requests(from_date, to_date)**: Gets total requests count. - **unique_visitors(from_date, to_date)**: Gets unique visitors count. ``` -------------------------------- ### PhoenixAnalytics.Services.PubSub - Broadcast Event Source: https://hexdocs.pm/phoenix_analytics/PhoenixAnalytics.Services.PubSub.html Broadcasts an event to all subscribers of the request topic. This function sends the provided event to all processes that have subscribed to the request topic. It's typically used to distribute information about new requests. ```APIDOC ## POST /pubsub/broadcast ### Description Broadcasts an event to all subscribers of the request topic. ### Method POST ### Endpoint /pubsub/broadcast ### Parameters #### Request Body - **event** (PhoenixAnalytics.Entities.RequestLog.t()) - Required - A struct representing the event to be broadcasted. ### Request Example ```json { "event": { "request_id": "123", "path": "/api/users" } } ``` ### Response #### Success Response (200) - **status** (atom) - Indicates success, typically `:ok`. #### Response Example ```json { "status": ":ok" } ``` #### Error Handling - May return `{:error, term()}` if there's an issue with broadcasting the message. ```