defp to_live_select_option(%{label: label, value: value}) do
%{label: label, value: value}
end
end
lib/moldb/compounds/compound.ex
defmodule Moldb.Compounds.Compound do
@moduledoc """
Module for handling compounds in Moldb.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, UUIDv7, autogenerate: true}
schema "compounds" do
field :iupac_name, :string
field :molecular_formula, :string
field :molecular_weight, :decimal
field :canonical_smiles, :string
field :inchi, :string
field :inchi_key, :string
defmodule Moldb.Compounds.Substance do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, UUIDv7, autogenerate: true}
schema "substances" do
field :substance_name, :string
field :physical_state, :string
field :salt_form, :string
field :stereochemistry, :string
@doc false
def changeset(substance, attrs) do
substance
|> cast(attrs, [:substance_name, :physical_state, :salt_form, :stereochemistry, :compound_id])
|> validate_required([:substance_name, :compound_id])
|> foreign_key_constraint(:compound_id)
end
end
lib/moldb/compounds.ex
defmodule Moldb.Compounds do
@moduledoc """
The Compounds context handles all interactions with compounds and substances in the database.
"""
import Ecto.Query, warn: false
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
Compound Functions
@doc """
Returns the list of compounds.
"""
def list_compounds, do: Repo.all(Compound)
@doc """
Gets a single compound.
Raises Ecto.NoResultsError if the Compound does not exist.
"""
def get_compound!(id), do: Repo.get!(Compound, id)
defmodule Moldb.Compounds.CompoundProperty do
@moduledoc """
Defines the CompoundProperty schema and changeset functions.
"""
use Ecto.Schema
import Ecto.Changeset
schema "compound_properties" do
field :property_name, :string
field :property_value, :decimal
field :property_unit, :string
field :property_category, :string
defmodule Moldb.Compounds.CompoundSynonym do
@moduledoc """
Defines the CompoundSynonym schema and changeset functions.
"""
use Ecto.Schema
import Ecto.Changeset
"""
def get_user_by_email_and_password(email, password)
when is_binary(email) and is_binary(password) do
user = Repo.get_by(User, email: email)
if User.valid_password?(user, password), do: user
end
@doc """
Gets a single user.
Raises Ecto.NoResultsError if the User does not exist.
"""
def apply_user_email(user, password, attrs) do
user
|> User.email_changeset(attrs)
|> User.validate_current_password(password)
|> Ecto.Changeset.apply_action(:update)
end
@doc """
Updates the user email using the given token.
If the token matches, the user email is updated and the token is deleted.
The confirmed_at date is also updated to the current time.
"""
def update_user_email(user, token) do
context = "change:#{user.email}"
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
:ok
else
_ -> :error
end
end
defp user_email_multi(user, email, context) do
changeset =
user
|> User.email_changeset(%{email: email})
|> User.confirm_changeset()
"""
def update_user_password(user, password, attrs) do
changeset =
user
|> User.password_changeset(attrs)
|> User.validate_current_password(password)
Ecto.Multi.new()
|> Ecto.Multi.update(:user, changeset)
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
Session
@doc """
Generates a session token.
"""
def generate_user_session_token(user) do
{token, user_token} = UserToken.build_session_token(user)
Repo.insert!(user_token)
token
end
@doc """
Gets the user with the given signed token.
"""
def get_user_by_session_token(token) do
{:ok, query} = UserToken.verify_session_token_query(token)
Repo.one(query)
end
@doc """
Deletes the signed token with the given context.
"""
def delete_user_session_token(token) do
Repo.delete_all(UserToken.by_token_and_context_query(token, "session"))
:ok
end
Confirmation
@doc ~S"""
Delivers the confirmation email instructions to the given user.
"""
def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
when is_function(confirmation_url_fun, 1) do
if user.confirmed_at do
{:error, :already_confirmed}
else
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
Repo.insert!(user_token)
UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
end
end
@doc """
Confirms a user by the given token.
If the token matches, the user account is marked as confirmed
and the token is deleted.
"""
def confirm_user(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
%User{} = user <- Repo.one(query),
{:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
{:ok, user}
else
_ -> :error
end
end
defp confirm_user_multi(user) do
Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.confirm_changeset(user))
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, ["confirm"]))
end
Reset password
@doc ~S"""
Delivers the reset password email to the given user.
"""
def get_user_by_reset_password_token(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
%User{} = user <- Repo.one(query) do
user
else
_ -> nil
end
end
@doc """
Resets the user password.
Examples
iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
{:ok, %User{}}
iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
{:error, %Ecto.Changeset{}}
"""
def reset_user_password(user, attrs) do
Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.password_changeset(user, attrs))
|> Ecto.Multi.delete_all(:tokens, UserToken.by_user_and_contexts_query(user, :all))
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
end
Review this code from phoenix framework web application. Ensure that state and events are valid, properly implemented and not redundant. Propose improvements, refactors.
After reviewing your code, I can see that you're implementing a LiveView for searching compounds and substances using a live_select component. There are some areas where the state and event handling can be simplified to make the code more efficient and easier to maintain. Below are the proposed improvements and refactors:
Use options_from in LiveSelect Component
Instead of manually handling the live_select_change event to fetch and assign options, you can utilize the options_from attribute provided by the live_select component. This attribute allows the component to call a function to fetch options dynamically as the user types, eliminating the need for the live_select_change event handler.
With options_from handling the options fetching, you can remove the handle_event("live_select_change", ...) and the options assign from the socket as they are no longer needed.
# lib/moldb_web/live/home_live.ex
defmodule MoldbWeb.HomeLive do
use MoldbWeb, :live_view
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, form: to_form(%{"compound" => ""}))}
end
# Remove the handle_event for "live_select_change" as it's no longer needed
@impl true
def handle_event("change", %{"compound" => compound}, socket) do
{:noreply, assign(socket, form: to_form(%{"compound" => compound}))}
end
# The "blur" and "clear" events can be handled internally by the live_select component or removed if unnecessary
end
Simplify Event Handling and State Management
Since the live_select component updates the form's compound field automatically, the handle_event("change", ...) might be redundant. You can remove it unless you have additional logic that needs to be executed when the form changes.
If Additional Logic is Not Required
defmodule MoldbWeb.HomeLive do
use MoldbWeb, :live_view
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, form: to_form(%{"compound" => ""}))}
end
# Remove the "change" event handler if it's not performing any essential tasks
end
Remove Unnecessary Assigns and Handlers
By utilizing options_from, you no longer need to keep track of the options in your socket assigns. This reduces the amount of state your LiveView needs to manage.
Remove Options from Assigns
Remove options from the mount/3 function.
Eliminate any references to options in your module.
Improve the Search Function
In your Moldb.Search module, you can optimize the search query by combining the compound and substance searches more efficiently. Also, ensure that you handle cases where the search query might be nil or empty.
Updated Search Module
defmodule Moldb.Search do
@moduledoc """
The Search context.
"""
import Ecto.Query
alias Moldb.Repo
alias Moldb.Compounds.{Compound, Substance}
@search_limit 10
@spec search_options(String.t()) :: [map()]
def search_options("" <> query) do
query
|> String.trim()
|> search_query()
|> Repo.all()
|> Enum.map(&to_live_select_option/1)
|> Enum.sort_by(& &1.label)
end
defp search_query(query) do
from(item in union_all_queries(query),
limit: @search_limit,
select: %{label: item.label, value: item.value}
)
end
defp union_all_queries(query) do
compound_query = from(c in Compound,
where: ilike(c.iupac_name, ^"%#{query}%"),
select: %{label: c.iupac_name, value: c.id}
)
substance_query = from(s in Substance,
where: ilike(s.substance_name, ^"%#{query}%"),
select: %{label: s.substance_name, value: s.id}
)
union_all(compound_query, ^substance_query)
end
defp to_live_select_option(%{label: label, value: value}) do
%{label: label, value: value}
end
end
Handle IDs Properly in Options
Ensure that you're using the IDs (c.id and s.id) as values in the options so that you can uniquely identify the selected compound or substance.
Remove Unused Context Functions
In your Moldb.Compounds context, consider removing any functions that are not being used. This will simplify the context and make it easier to maintain.
Summary of Improvements
Utilize options_from in the live_select component to fetch options dynamically, eliminating the need for manual event handling and state management of options.
Simplify the HomeLive module by removing unnecessary event handlers and assigns.
Optimize the search queries and ensure that IDs are used appropriately in options.
Clean up the context modules by removing unused functions.
By making these changes, you'll have a cleaner and more maintainable codebase with less redundancy and better utilization of the Phoenix framework features.