Search documentation of phoenix_kit

# PhoenixKit.ReferralCodeUsage (phoenix_kit v1.6.19)

View Source

ReferralCodeUsage schema for tracking referral code usage in PhoenixKit.

This schema records when and by whom referral codes are used. It provides an audit trail for code usage and helps with analytics.

## Fields

- `code_id`: Foreign key to the referral code that was used
- `used_by`: User ID of the user who used the code
- `date_used`: Timestamp when the code was used

## Associations

- `referral_code`: Belongs to the referral code that was used
- `user`: Belongs to the User who used the code (via used_by field)

## Usage Examples

    # Record a code usage
    %ReferralCodeUsage{}
    |> ReferralCodeUsage.changeset(%{
      code_id: referral_code.id,
      used_by: user.id
    })
    |> Repo.insert()

    # Get all usage records for a code
    from(usage in ReferralCodeUsage, where: usage.code_id == ^code_id)
    |> Repo.all()

# Summary

## Functions

changeset(usage_record, attrs)

Creates a changeset for referral code usage records.

for_code(code_id)

Gets all usage records for a specific referral code.

for_user(user_id)

Gets all usage records for a specific user.

get_usage_stats(code_id)

Gets usage statistics for a referral code.

user_used_code?(user_id, code_id)

Checks if a user has already used a specific referral code.

# Functions

# changeset(usage_record, attrs)

Creates a changeset for referral code usage records.

Validates that all required fields are present and automatically sets date_used on new records.

# for_code(code_id)

Gets all usage records for a specific referral code.

Returns a query that can be executed to get usage records ordered by date_used (most recent first).

## Examples

    iex> ReferralCodeUsage.for_code(code_id) |> Repo.all()
    [%ReferralCodeUsage{}, ...]

# for_user(user_id)

Gets all usage records for a specific user.

Returns a query that can be executed to get usage records ordered by date_used (most recent first).

## Examples

    iex> ReferralCodeUsage.for_user(user_id) |> Repo.all()
    [%ReferralCodeUsage{}, ...]

# get_usage_stats(code_id)

Gets usage statistics for a referral code.

Returns a map with usage counts and recent activity information.

## Examples

    iex> ReferralCodeUsage.get_usage_stats(code_id)
    %{
      total_uses: 5,
      unique_users: 3,
      last_used: ~U[2024-01-15 10:30:00.000000Z],
      recent_users: [user_id1, user_id2]
    }

# user_used_code?(user_id, code_id)

Checks if a user has already used a specific referral code.

Returns true if the user has used the code before, false otherwise.

## Examples

    iex> ReferralCodeUsage.user_used_code?(user_id, code_id)
    false