memEx/lib/memex/accounts/invite.ex

64 lines
1.9 KiB
Elixir
Raw Permalink Normal View History

2023-02-04 17:22:06 -05:00
defmodule Memex.Accounts.Invite do
2022-02-25 21:52:17 -05:00
@moduledoc """
An invite, created by an admin to allow someone to join their instance. An
invite can be enabled or disabled, and can have an optional number of uses if
`:uses_left` is defined.
"""
use Ecto.Schema
import Ecto.Changeset
2023-02-04 17:22:06 -05:00
alias Ecto.{Association, Changeset, UUID}
alias Memex.Accounts.User
2022-02-25 21:52:17 -05:00
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "invites" do
field :name, :string
field :token, :string
field :uses_left, :integer, default: nil
field :disabled_at, :naive_datetime
2023-02-04 17:22:06 -05:00
belongs_to :created_by, User
has_many :users, User
2022-02-25 21:52:17 -05:00
timestamps()
end
2023-02-04 17:22:06 -05:00
@type t :: %__MODULE__{
2022-02-25 21:52:17 -05:00
id: id(),
name: String.t(),
2023-02-04 17:22:06 -05:00
token: token(),
2022-02-25 21:52:17 -05:00
uses_left: integer() | nil,
disabled_at: NaiveDateTime.t(),
2023-02-04 17:22:06 -05:00
created_by: User.t() | nil | Association.NotLoaded.t(),
created_by_id: User.id() | nil,
users: [User.t()] | Association.NotLoaded.t(),
2022-02-25 21:52:17 -05:00
inserted_at: NaiveDateTime.t(),
updated_at: NaiveDateTime.t()
}
2023-02-04 17:22:06 -05:00
@type new_invite :: %__MODULE__{}
2022-02-25 21:52:17 -05:00
@type id :: UUID.t()
2023-02-04 17:22:06 -05:00
@type changeset :: Changeset.t(t() | new_invite())
@type token :: String.t()
2022-02-25 21:52:17 -05:00
@doc false
2023-02-04 17:22:06 -05:00
@spec create_changeset(User.t(), token(), attrs :: map()) :: changeset()
def create_changeset(%User{id: user_id}, token, attrs) do
%__MODULE__{}
|> change(token: token, created_by_id: user_id)
|> cast(attrs, [:name, :uses_left, :disabled_at])
|> validate_required([:name, :token, :created_by_id])
2022-02-25 21:52:17 -05:00
|> validate_number(:uses_left, greater_than_or_equal_to: 0)
end
@doc false
2023-02-04 17:22:06 -05:00
@spec update_changeset(t() | new_invite(), attrs :: map()) :: changeset()
2022-02-25 21:52:17 -05:00
def update_changeset(invite, attrs) do
invite
|> cast(attrs, [:name, :uses_left, :disabled_at])
2023-02-04 17:22:06 -05:00
|> validate_required([:name])
2022-02-25 21:52:17 -05:00
|> validate_number(:uses_left, greater_than_or_equal_to: 0)
end
end