| 1 |
|
defmodule DaProductApp.Accounts do |
| 2 |
|
@moduledoc """ |
| 3 |
|
Accounts context: users, organizations, roles. |
| 4 |
|
""" |
| 5 |
|
|
| 6 |
|
import Ecto.Query, warn: false |
| 7 |
|
alias DaProductApp.Repo |
| 8 |
|
alias DaProductApp.Accounts.{User, Organization, Role} |
| 9 |
|
|
| 10 |
|
# Organizations |
| 11 |
|
def list_organizations do |
| 12 |
:-( |
Repo.all(Organization) |
| 13 |
|
end |
| 14 |
|
|
| 15 |
:-( |
def get_organization!(id), do: Repo.get!(Organization, id) |
| 16 |
|
|
| 17 |
:-( |
def create_organization(attrs \\ %{}) do |
| 18 |
|
%Organization{} |
| 19 |
|
|> Organization.changeset(attrs) |
| 20 |
:-( |
|> Repo.insert() |
| 21 |
|
end |
| 22 |
|
|
| 23 |
|
def update_organization(%Organization{} = organization, attrs) do |
| 24 |
|
organization |
| 25 |
|
|> Organization.changeset(attrs) |
| 26 |
:-( |
|> Repo.update() |
| 27 |
|
end |
| 28 |
|
|
| 29 |
:-( |
def delete_organization(%Organization{} = organization), do: Repo.delete(organization) |
| 30 |
|
|
| 31 |
:-( |
def change_organization(%Organization{} = organization, attrs \\ %{}) do |
| 32 |
:-( |
Organization.changeset(organization, attrs) |
| 33 |
|
end |
| 34 |
|
|
| 35 |
|
# Roles |
| 36 |
|
def list_roles do |
| 37 |
:-( |
Repo.all(Role) |
| 38 |
|
end |
| 39 |
|
|
| 40 |
:-( |
def get_role!(id), do: Repo.get!(Role, id) |
| 41 |
|
|
| 42 |
:-( |
def create_role(attrs \\ %{}) do |
| 43 |
|
%Role{} |
| 44 |
|
|> Role.changeset(attrs) |
| 45 |
:-( |
|> Repo.insert() |
| 46 |
|
end |
| 47 |
|
|
| 48 |
|
# Users |
| 49 |
|
def list_users do |
| 50 |
:-( |
Repo.all(User) |> Repo.preload([:organization, :role]) |
| 51 |
|
end |
| 52 |
|
|
| 53 |
:-( |
def get_user!(id), do: Repo.get!(User, id) |> Repo.preload([:organization, :role]) |
| 54 |
|
|
| 55 |
|
def get_user_by_email(email) when is_binary(email) do |
| 56 |
:-( |
Repo.get_by(User, email: email) |> Repo.preload([:organization, :role]) |
| 57 |
|
end |
| 58 |
|
|
| 59 |
:-( |
def create_user(attrs \\ %{}) do |
| 60 |
|
%User{} |
| 61 |
|
|> User.changeset(attrs) |
| 62 |
:-( |
|> Repo.insert() |
| 63 |
|
end |
| 64 |
|
|
| 65 |
|
def update_user(%User{} = user, attrs) do |
| 66 |
|
user |
| 67 |
|
|> User.changeset(attrs) |
| 68 |
:-( |
|> Repo.update() |
| 69 |
|
end |
| 70 |
|
|
| 71 |
:-( |
def delete_user(%User{} = user), do: Repo.delete(user) |
| 72 |
|
|
| 73 |
:-( |
def change_user(%User{} = user, attrs \\ %{}) do |
| 74 |
:-( |
User.changeset(user, attrs) |
| 75 |
|
end |
| 76 |
|
|
| 77 |
|
def assign_role(%User{} = user, %Role{} = role) do |
| 78 |
:-( |
update_user(user, %{role_id: role.id}) |
| 79 |
|
end |
| 80 |
|
end |