file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
lib/example/accounts/user.ex | Elixir | defmodule Example.Accounts.User do
use Ash.Resource,
data_layer: AshPostgres.DataLayer,
extensions: [AshAuthentication]
attributes do
uuid_primary_key :id
attribute :email, :ci_string, allow_nil?: false
attribute :hashed_password, :string, allow_nil?: false, sensitive?: true
end
authentication do
api Example.Accounts
strategies do
password :password do
identity_field(:email)
end
end
tokens do
enabled?(true)
token_resource(Example.Accounts.Token)
signing_secret(Application.get_env(:example, ExampleWeb.Endpoint)[:secret_key_base])
end
end
postgres do
table "users"
repo Example.Repo
end
identities do
identity :unique_email, [:email]
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example/application.ex | Elixir | defmodule Example.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
# Start the Telemetry supervisor
ExampleWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: Example.PubSub},
# Start Finch
{Finch, name: Example.Finch},
# Start the Endpoint (http/https)
ExampleWeb.Endpoint,
# Start a worker by calling: Example.Worker.start_link(arg)
# {Example.Worker, arg}
Example.Repo,
{AshAuthentication.Supervisor, otp_app: :example}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Example.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
@impl true
def config_change(changed, _new, removed) do
ExampleWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example/mailer.ex | Elixir | defmodule Example.Mailer do
use Swoosh.Mailer, otp_app: :example
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example/repo.ex | Elixir | defmodule Example.Repo do
use AshPostgres.Repo, otp_app: :example
def installed_extensions do
["uuid-ossp", "citext"]
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web.ex | Elixir | defmodule ExampleWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, components, channels, and so on.
This can be used in your application as:
use ExampleWeb, :controller
use ExampleWeb, :html
The definitions below will be executed for every controller,
component, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define additional modules and import
those modules here.
"""
def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
def router do
quote do
use Phoenix.Router, helpers: true
# Import common connection and controller functions to use in pipelines
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end
def channel do
quote do
use Phoenix.Channel
end
end
def controller do
quote do
use Phoenix.Controller,
formats: [:html, :json],
layouts: [html: ExampleWeb.Layouts]
import Plug.Conn
import ExampleWeb.Gettext
unquote(verified_routes())
end
end
def live_view do
quote do
use Phoenix.LiveView,
layout: {ExampleWeb.Layouts, :app}
unquote(html_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(html_helpers())
end
end
def html do
quote do
use Phoenix.Component
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_csrf_token: 0, view_module: 1, view_template: 1]
# Include general helpers for rendering HTML
unquote(html_helpers())
end
end
defp html_helpers do
quote do
# HTML escaping functionality
import Phoenix.HTML
# Core UI components and translation
import ExampleWeb.CoreComponents
import ExampleWeb.Gettext
# Shortcut for generating JS commands
alias Phoenix.LiveView.JS
# Routes generation with the ~p sigil
unquote(verified_routes())
end
end
def verified_routes do
quote do
use Phoenix.VerifiedRoutes,
endpoint: ExampleWeb.Endpoint,
router: ExampleWeb.Router,
statics: ExampleWeb.static_paths()
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/components/core_components.ex | Elixir | defmodule ExampleWeb.CoreComponents do
@moduledoc """
Provides core UI components.
The components in this module use Tailwind CSS, a utility-first CSS framework.
See the [Tailwind CSS documentation](https://tailwindcss.com) to learn how to
customize the generated components in this module.
Icons are provided by [heroicons](https://heroicons.com), using the
[heroicons_elixir](https://github.com/mveytsman/heroicons_elixir) project.
"""
use Phoenix.Component
alias Phoenix.LiveView.JS
import ExampleWeb.Gettext
@doc """
Renders a modal.
## Examples
<.modal id="confirm-modal">
Are you sure?
<:confirm>OK</:confirm>
<:cancel>Cancel</:cancel>
</.modal>
JS commands may be passed to the `:on_cancel` and `on_confirm` attributes
for the caller to react to each button press, for example:
<.modal id="confirm" on_confirm={JS.push("delete")} on_cancel={JS.navigate(~p"/posts")}>
Are you sure you?
<:confirm>OK</:confirm>
<:cancel>Cancel</:cancel>
</.modal>
"""
attr :id, :string, required: true
attr :show, :boolean, default: false
attr :on_cancel, JS, default: %JS{}
attr :on_confirm, JS, default: %JS{}
slot :inner_block, required: true
slot :title
slot :subtitle
slot :confirm
slot :cancel
def modal(assigns) do
~H"""
<div
id={@id}
phx-mounted={@show && show_modal(@id)}
phx-remove={hide_modal(@id)}
class="relative z-50 hidden"
>
<div id={"#{@id}-bg"} class="fixed inset-0 bg-zinc-50/90 transition-opacity" aria-hidden="true" />
<div
class="fixed inset-0 overflow-y-auto"
aria-labelledby={"#{@id}-title"}
aria-describedby={"#{@id}-description"}
role="dialog"
aria-modal="true"
tabindex="0"
>
<div class="flex min-h-full items-center justify-center">
<div class="w-full max-w-3xl p-4 sm:p-6 lg:py-8">
<.focus_wrap
id={"#{@id}-container"}
phx-mounted={@show && show_modal(@id)}
phx-window-keydown={hide_modal(@on_cancel, @id)}
phx-key="escape"
phx-click-away={hide_modal(@on_cancel, @id)}
class="hidden relative rounded-2xl bg-white p-14 shadow-lg shadow-zinc-700/10 ring-1 ring-zinc-700/10 transition"
>
<div class="absolute top-6 right-5">
<button
phx-click={hide_modal(@on_cancel, @id)}
type="button"
class="-m-3 flex-none p-3 opacity-20 hover:opacity-40"
aria-label={gettext("close")}
>
<Heroicons.x_mark solid class="h-5 w-5 stroke-current" />
</button>
</div>
<div id={"#{@id}-content"}>
<header :if={@title != []}>
<h1 id={"#{@id}-title"} class="text-lg font-semibold leading-8 text-zinc-800">
<%= render_slot(@title) %>
</h1>
<p
:if={@subtitle != []}
id={"#{@id}-description"}
class="mt-2 text-sm leading-6 text-zinc-600"
>
<%= render_slot(@subtitle) %>
</p>
</header>
<%= render_slot(@inner_block) %>
<div :if={@confirm != [] or @cancel != []} class="ml-6 mb-4 flex items-center gap-5">
<.button
:for={confirm <- @confirm}
id={"#{@id}-confirm"}
phx-click={@on_confirm}
phx-disable-with
class="py-2 px-3"
>
<%= render_slot(confirm) %>
</.button>
<.link
:for={cancel <- @cancel}
phx-click={hide_modal(@on_cancel, @id)}
class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
>
<%= render_slot(cancel) %>
</.link>
</div>
</div>
</.focus_wrap>
</div>
</div>
</div>
</div>
"""
end
@doc """
Renders flash notices.
## Examples
<.flash kind={:info} flash={@flash} />
<.flash kind={:info} phx-mounted={show("#flash")}>Welcome Back!</.flash>
"""
attr :id, :string, default: "flash", doc: "the optional id of flash container"
attr :flash, :map, default: %{}, doc: "the map of flash messages to display"
attr :title, :string, default: nil
attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup"
attr :autoshow, :boolean, default: true, doc: "whether to auto show the flash on mount"
attr :close, :boolean, default: true, doc: "whether the flash can be closed"
attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container"
slot :inner_block, doc: "the optional inner block that renders the flash message"
def flash(assigns) do
~H"""
<div
:if={msg = render_slot(@inner_block) || Phoenix.Flash.get(@flash, @kind)}
id={@id}
phx-mounted={@autoshow && show("##{@id}")}
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
role="alert"
class={[
"fixed hidden top-2 right-2 w-80 sm:w-96 z-50 rounded-lg p-3 shadow-md shadow-zinc-900/5 ring-1",
@kind == :info && "bg-emerald-50 text-emerald-800 ring-emerald-500 fill-cyan-900",
@kind == :error && "bg-rose-50 p-3 text-rose-900 shadow-md ring-rose-500 fill-rose-900"
]}
{@rest}
>
<p :if={@title} class="flex items-center gap-1.5 text-[0.8125rem] font-semibold leading-6">
<Heroicons.information_circle :if={@kind == :info} mini class="h-4 w-4" />
<Heroicons.exclamation_circle :if={@kind == :error} mini class="h-4 w-4" />
<%= @title %>
</p>
<p class="mt-2 text-[0.8125rem] leading-5"><%= msg %></p>
<button
:if={@close}
type="button"
class="group absolute top-2 right-1 p-2"
aria-label={gettext("close")}
>
<Heroicons.x_mark solid class="h-5 w-5 stroke-current opacity-40 group-hover:opacity-70" />
</button>
</div>
"""
end
@doc """
Renders a simple form.
## Examples
<.simple_form :let={f} for={:user} phx-change="validate" phx-submit="save">
<.input field={{f, :email}} label="Email"/>
<.input field={{f, :username}} label="Username" />
<:actions>
<.button>Save</.button>
</:actions>
</.simple_form>
"""
attr :for, :any, default: nil, doc: "the datastructure for the form"
attr :as, :any, default: nil, doc: "the server side parameter to collect all input under"
attr :rest, :global,
include: ~w(autocomplete name rel action enctype method novalidate target),
doc: "the arbitrary HTML attributes to apply to the form tag"
slot :inner_block, required: true
slot :actions, doc: "the slot for form actions, such as a submit button"
def simple_form(assigns) do
~H"""
<.form :let={f} for={@for} as={@as} {@rest}>
<div class="space-y-8 bg-white mt-10">
<%= render_slot(@inner_block, f) %>
<div :for={action <- @actions} class="mt-2 flex items-center justify-between gap-6">
<%= render_slot(action, f) %>
</div>
</div>
</.form>
"""
end
@doc """
Renders a button.
## Examples
<.button>Send!</.button>
<.button phx-click="go" class="ml-2">Send!</.button>
"""
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def button(assigns) do
~H"""
<button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-700 py-2 px-3",
"text-sm font-semibold leading-6 text-white active:text-white/80",
@class
]}
{@rest}
>
<%= render_slot(@inner_block) %>
</button>
"""
end
@doc """
Renders an input with label and error messages.
A `%Phoenix.HTML.Form{}` and field name may be passed to the input
to build input names and error messages, or all the attributes and
errors may be passed explicitly.
## Examples
<.input field={{f, :email}} type="email" />
<.input name="my-input" errors={["oh no!"]} />
"""
attr :id, :any
attr :name, :any
attr :label, :string, default: nil
attr :type, :string,
default: "text",
values: ~w(checkbox color date datetime-local email file hidden month number password
range radio search select tel text textarea time url week)
attr :value, :any
attr :field, :any, doc: "a %Phoenix.HTML.Form{}/field name tuple, for example: {f, :email}"
attr :errors, :list
attr :checked, :boolean, doc: "the checked flag for checkbox inputs"
attr :prompt, :string, default: nil, doc: "the prompt for select inputs"
attr :options, :list, doc: "the options to pass to Phoenix.HTML.Form.options_for_select/2"
attr :multiple, :boolean, default: false, doc: "the multiple flag for select inputs"
attr :rest, :global, include: ~w(autocomplete cols disabled form max maxlength min minlength
pattern placeholder readonly required rows size step)
slot :inner_block
def input(%{field: {f, field}} = assigns) do
assigns
|> assign(field: nil)
|> assign_new(:name, fn ->
name = Phoenix.HTML.Form.input_name(f, field)
if assigns.multiple, do: name <> "[]", else: name
end)
|> assign_new(:id, fn -> Phoenix.HTML.Form.input_id(f, field) end)
|> assign_new(:value, fn -> Phoenix.HTML.Form.input_value(f, field) end)
|> assign_new(:errors, fn -> translate_errors(f.errors || [], field) end)
|> input()
end
def input(%{type: "checkbox"} = assigns) do
assigns = assign_new(assigns, :checked, fn -> input_equals?(assigns.value, "true") end)
~H"""
<label phx-feedback-for={@name} class="flex items-center gap-4 text-sm leading-6 text-zinc-600">
<input type="hidden" name={@name} value="false" />
<input
type="checkbox"
id={@id || @name}
name={@name}
value="true"
checked={@checked}
class="rounded border-zinc-300 text-zinc-900 focus:ring-zinc-900"
{@rest}
/>
<%= @label %>
</label>
"""
end
def input(%{type: "select"} = assigns) do
~H"""
<div phx-feedback-for={@name}>
<.label for={@id}><%= @label %></.label>
<select
id={@id}
name={@name}
class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-zinc-500 focus:border-zinc-500 sm:text-sm"
multiple={@multiple}
{@rest}
>
<option :if={@prompt} value=""><%= @prompt %></option>
<%= Phoenix.HTML.Form.options_for_select(@options, @value) %>
</select>
<.error :for={msg <- @errors}><%= msg %></.error>
</div>
"""
end
def input(%{type: "textarea"} = assigns) do
~H"""
<div phx-feedback-for={@name}>
<.label for={@id}><%= @label %></.label>
<textarea
id={@id || @name}
name={@name}
class={[
input_border(@errors),
"mt-2 block min-h-[6rem] w-full rounded-lg border-zinc-300 py-[7px] px-[11px]",
"text-zinc-900 focus:border-zinc-400 focus:outline-none focus:ring-4 focus:ring-zinc-800/5 sm:text-sm sm:leading-6",
"phx-no-feedback:border-zinc-300 phx-no-feedback:focus:border-zinc-400 phx-no-feedback:focus:ring-zinc-800/5"
]}
{@rest}
>
<%= @value %></textarea>
<.error :for={msg <- @errors}><%= msg %></.error>
</div>
"""
end
def input(assigns) do
~H"""
<div phx-feedback-for={@name}>
<.label for={@id}><%= @label %></.label>
<input
type={@type}
name={@name}
id={@id || @name}
value={@value}
class={[
input_border(@errors),
"mt-2 block w-full rounded-lg border-zinc-300 py-[7px] px-[11px]",
"text-zinc-900 focus:outline-none focus:ring-4 sm:text-sm sm:leading-6",
"phx-no-feedback:border-zinc-300 phx-no-feedback:focus:border-zinc-400 phx-no-feedback:focus:ring-zinc-800/5"
]}
{@rest}
/>
<.error :for={msg <- @errors}><%= msg %></.error>
</div>
"""
end
defp input_border([] = _errors),
do: "border-zinc-300 focus:border-zinc-400 focus:ring-zinc-800/5"
defp input_border([_ | _] = _errors),
do: "border-rose-400 focus:border-rose-400 focus:ring-rose-400/10"
@doc """
Renders a label.
"""
attr :for, :string, default: nil
slot :inner_block, required: true
def label(assigns) do
~H"""
<label for={@for} class="block text-sm font-semibold leading-6 text-zinc-800">
<%= render_slot(@inner_block) %>
</label>
"""
end
@doc """
Generates a generic error message.
"""
slot :inner_block, required: true
def error(assigns) do
~H"""
<p class="phx-no-feedback:hidden mt-3 flex gap-3 text-sm leading-6 text-rose-600">
<Heroicons.exclamation_circle mini class="mt-0.5 h-5 w-5 flex-none fill-rose-500" />
<%= render_slot(@inner_block) %>
</p>
"""
end
@doc """
Renders a header with title.
"""
attr :class, :string, default: nil
slot :inner_block, required: true
slot :subtitle
slot :actions
def header(assigns) do
~H"""
<header class={[@actions != [] && "flex items-center justify-between gap-6", @class]}>
<div>
<h1 class="text-lg font-semibold leading-8 text-zinc-800">
<%= render_slot(@inner_block) %>
</h1>
<p :if={@subtitle != []} class="mt-2 text-sm leading-6 text-zinc-600">
<%= render_slot(@subtitle) %>
</p>
</div>
<div class="flex-none"><%= render_slot(@actions) %></div>
</header>
"""
end
@doc ~S"""
Renders a table with generic styling.
## Examples
<.table id="users" rows={@users}>
<:col :let={user} label="id"><%= user.id %></:col>
<:col :let={user} label="username"><%= user.username %></:col>
</.table>
"""
attr :id, :string, required: true
attr :row_click, :any, default: nil
attr :rows, :list, required: true
slot :col, required: true do
attr :label, :string
end
slot :action, doc: "the slot for showing user actions in the last table column"
def table(assigns) do
~H"""
<div id={@id} class="overflow-y-auto px-4 sm:overflow-visible sm:px-0">
<table class="mt-11 w-[40rem] sm:w-full">
<thead class="text-left text-[0.8125rem] leading-6 text-zinc-500">
<tr>
<th :for={col <- @col} class="p-0 pb-4 pr-6 font-normal"><%= col[:label] %></th>
<th class="relative p-0 pb-4"><span class="sr-only"><%= gettext("Actions") %></span></th>
</tr>
</thead>
<tbody class="relative divide-y divide-zinc-100 border-t border-zinc-200 text-sm leading-6 text-zinc-700">
<tr
:for={row <- @rows}
id={"#{@id}-#{Phoenix.Param.to_param(row)}"}
class="relative group hover:bg-zinc-50"
>
<td
:for={{col, i} <- Enum.with_index(@col)}
phx-click={@row_click && @row_click.(row)}
class={["p-0", @row_click && "hover:cursor-pointer"]}
>
<div :if={i == 0}>
<span class="absolute h-full w-4 top-0 -left-4 group-hover:bg-zinc-50 sm:rounded-l-xl" />
<span class="absolute h-full w-4 top-0 -right-4 group-hover:bg-zinc-50 sm:rounded-r-xl" />
</div>
<div class="block py-4 pr-6">
<span class={["relative", i == 0 && "font-semibold text-zinc-900"]}>
<%= render_slot(col, row) %>
</span>
</div>
</td>
<td :if={@action != []} class="p-0 w-14">
<div class="relative whitespace-nowrap py-4 text-right text-sm font-medium">
<span
:for={action <- @action}
class="relative ml-4 font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
>
<%= render_slot(action, row) %>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
"""
end
@doc """
Renders a data list.
## Examples
<.list>
<:item title="Title"><%= @post.title %></:item>
<:item title="Views"><%= @post.views %></:item>
</.list>
"""
slot :item, required: true do
attr :title, :string, required: true
end
def list(assigns) do
~H"""
<div class="mt-14">
<dl class="-my-4 divide-y divide-zinc-100">
<div :for={item <- @item} class="flex gap-4 py-4 sm:gap-8">
<dt class="w-1/4 flex-none text-[0.8125rem] leading-6 text-zinc-500"><%= item.title %></dt>
<dd class="text-sm leading-6 text-zinc-700"><%= render_slot(item) %></dd>
</div>
</dl>
</div>
"""
end
@doc """
Renders a back navigation link.
## Examples
<.back navigate={~p"/posts"}>Back to posts</.back>
"""
attr :navigate, :any, required: true
slot :inner_block, required: true
def back(assigns) do
~H"""
<div class="mt-16">
<.link
navigate={@navigate}
class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
>
<Heroicons.arrow_left solid class="w-3 h-3 stroke-current inline" />
<%= render_slot(@inner_block) %>
</.link>
</div>
"""
end
## JS Commands
def show(js \\ %JS{}, selector) do
JS.show(js,
to: selector,
transition:
{"transition-all transform ease-out duration-300",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",
"opacity-100 translate-y-0 sm:scale-100"}
)
end
def hide(js \\ %JS{}, selector) do
JS.hide(js,
to: selector,
time: 200,
transition:
{"transition-all transform ease-in duration-200",
"opacity-100 translate-y-0 sm:scale-100",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"}
)
end
def show_modal(js \\ %JS{}, id) when is_binary(id) do
js
|> JS.show(to: "##{id}")
|> JS.show(
to: "##{id}-bg",
transition: {"transition-all transform ease-out duration-300", "opacity-0", "opacity-100"}
)
|> show("##{id}-container")
|> JS.add_class("overflow-hidden", to: "body")
|> JS.focus_first(to: "##{id}-content")
end
def hide_modal(js \\ %JS{}, id) do
js
|> JS.hide(
to: "##{id}-bg",
transition: {"transition-all transform ease-in duration-200", "opacity-100", "opacity-0"}
)
|> hide("##{id}-container")
|> JS.hide(to: "##{id}", transition: {"block", "block", "hidden"})
|> JS.remove_class("overflow-hidden", to: "body")
|> JS.pop_focus()
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(ExampleWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(ExampleWeb.Gettext, "errors", msg, opts)
end
end
@doc """
Translates the errors for a field from a keyword list of errors.
"""
def translate_errors(errors, field) when is_list(errors) do
for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts})
end
defp input_equals?(val1, val2) do
Phoenix.HTML.html_escape(val1) == Phoenix.HTML.html_escape(val2)
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/components/layouts.ex | Elixir | defmodule ExampleWeb.Layouts do
use ExampleWeb, :html
embed_templates "layouts/*"
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/auth_controller.ex | Elixir | defmodule ExampleWeb.AuthController do
use ExampleWeb, :controller
use AshAuthentication.Phoenix.Controller
def success(conn, _activity, user, _token) do
return_to = get_session(conn, :return_to) || ~p"/"
conn
|> delete_session(:return_to)
|> store_in_session(user)
|> assign(:current_user, user)
|> redirect(to: return_to)
end
def failure(conn, _activity, _reason) do
conn
|> put_status(401)
|> render("failure.html")
end
def sign_out(conn, _params) do
return_to = get_session(conn, :return_to) || ~p"/"
conn
|> clear_session()
|> redirect(to: return_to)
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/auth_html.ex | Elixir | defmodule ExampleWeb.AuthHTML do
use ExampleWeb, :html
embed_templates "auth_html/*"
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/error_html.ex | Elixir | defmodule ExampleWeb.ErrorHTML do
use ExampleWeb, :html
# If you want to customize your error pages,
# uncomment the embed_templates/1 call below
# and add pages to the error directory:
#
# * lib/example_web/controllers/error_html/404.html.heex
# * lib/example_web/controllers/error_html/500.html.heex
#
# embed_templates "error_html/*"
# The default is to render a plain text page based on
# the template name. For example, "404.html" becomes
# "Not Found".
def render(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/error_json.ex | Elixir | defmodule ExampleWeb.ErrorJSON do
# If you want to customize a particular status code,
# you may add your own clauses, such as:
#
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def render(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/page_controller.ex | Elixir | defmodule ExampleWeb.PageController do
use ExampleWeb, :controller
def home(conn, _params) do
# The home page is often custom made,
# so skip the default app layout.
render(conn, :home, layout: false)
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/controllers/page_html.ex | Elixir | defmodule ExampleWeb.PageHTML do
use ExampleWeb, :html
embed_templates "page_html/*"
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/endpoint.ex | Elixir | defmodule ExampleWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :example
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_example_key",
signing_salt: "kKmWnpsT",
same_site: "Lax"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :example,
gzip: false,
only: ExampleWeb.static_paths()
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug ExampleWeb.Router
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/gettext.ex | Elixir | defmodule ExampleWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ExampleWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :example
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/router.ex | Elixir | defmodule ExampleWeb.Router do
use ExampleWeb, :router
use AshAuthentication.Phoenix.Router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {ExampleWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :load_from_session
end
pipeline :api do
plug :accepts, ["json"]
plug :load_from_bearer
end
scope "/", ExampleWeb do
pipe_through :browser
sign_in_route()
sign_out_route AuthController
auth_routes_for Example.Accounts.User, to: AuthController
get "/", PageController, :home
end
# Other scopes may use custom stacks.
# scope "/api", ExampleWeb do
# pipe_through :api
# end
# Enable LiveDashboard and Swoosh mailbox preview in development
if Application.compile_env(:example, :dev_routes) do
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
import Phoenix.LiveDashboard.Router
scope "/dev" do
pipe_through :browser
live_dashboard "/dashboard", metrics: ExampleWeb.Telemetry
forward "/mailbox", Plug.Swoosh.MailboxPreview
end
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/example_web/telemetry.ex | Elixir | defmodule ExampleWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
@impl true
def init(_arg) do
children = [
# Telemetry poller will execute the given period measurements
# every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics
{:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
# Add reporters as children of your supervision tree.
# {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
]
Supervisor.init(children, strategy: :one_for_one)
end
def metrics do
[
# Phoenix Metrics
summary("phoenix.endpoint.start.system_time",
unit: {:native, :millisecond}
),
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.start.system_time",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.exception.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.socket_connected.duration",
unit: {:native, :millisecond}
),
summary("phoenix.channel_join.duration",
unit: {:native, :millisecond}
),
summary("phoenix.channel_handled_in.duration",
tags: [:event],
unit: {:native, :millisecond}
),
# VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}),
summary("vm.total_run_queue_lengths.total"),
summary("vm.total_run_queue_lengths.cpu"),
summary("vm.total_run_queue_lengths.io")
]
end
defp periodic_measurements do
[
# A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above.
# {ExampleWeb, :count_users, []}
]
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
mix.exs | Elixir | defmodule Example.MixProject do
use Mix.Project
def project do
[
app: :example,
version: "0.1.0",
elixir: "~> 1.14",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Example.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.7.0-rc.2", override: true},
{:phoenix_html, "~> 3.0"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:phoenix_live_view, "~> 0.18.3"},
{:heroicons, "~> 0.5"},
{:floki, ">= 0.30.0", only: :test},
{:phoenix_live_dashboard, "~> 0.7.2"},
{:esbuild, "~> 0.5", runtime: Mix.env() == :dev},
{:tailwind, "~> 0.1.8", runtime: Mix.env() == :dev},
{:swoosh, "~> 1.3"},
{:finch, "~> 0.13"},
{:telemetry_metrics, "~> 0.6"},
{:telemetry_poller, "~> 1.0"},
{:gettext, "~> 0.20"},
{:jason, "~> 1.2"},
{:plug_cowboy, "~> 2.5"},
{:ash, "~> 2.5.11"},
{:ash_authentication, "~> 3.7.3"},
{:ash_authentication_phoenix, "~> 1.4.6"},
{:ash_postgres, "~> 1.3.2"},
{:elixir_sense, github: "elixir-lsp/elixir_sense", only: [:dev, :test]}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "assets.setup"],
"assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"],
"assets.deploy": ["tailwind default --minify", "esbuild default --minify", "phx.digest"]
]
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20230130074333_install_2_extensions.exs | Elixir | defmodule Example.Repo.Migrations.Install2Extensions do
@moduledoc """
Installs any extensions that are mentioned in the repo's `installed_extensions/0` callback
This file was autogenerated with `mix ash_postgres.generate_migrations`
"""
use Ecto.Migration
def up do
execute("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"")
execute("CREATE EXTENSION IF NOT EXISTS \"citext\"")
end
def down do
# Uncomment this if you actually want to uninstall the extensions
# when this migration is rolled back:
# execute("DROP EXTENSION IF EXISTS \"uuid-ossp\"")
# execute("DROP EXTENSION IF EXISTS \"citext\"")
end
end | wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20230130074335_add_user_and_token.exs | Elixir | defmodule Example.Repo.Migrations.AddUserAndToken do
@moduledoc """
Updates resources based on their most recent snapshots.
This file was autogenerated with `mix ash_postgres.generate_migrations`
"""
use Ecto.Migration
def up do
create table(:users, primary_key: false) do
add :id, :uuid, null: false, default: fragment("uuid_generate_v4()"), primary_key: true
add :email, :citext, null: false
add :hashed_password, :text, null: false
end
create unique_index(:users, [:email], name: "users_unique_email_index")
create table(:tokens, primary_key: false) do
add :updated_at, :utc_datetime_usec, null: false, default: fragment("now()")
add :created_at, :utc_datetime_usec, null: false, default: fragment("now()")
add :extra_data, :map
add :purpose, :text, null: false
add :expires_at, :utc_datetime, null: false
add :subject, :text, null: false
add :jti, :text, null: false, primary_key: true
end
end
def down do
drop table(:tokens)
drop_if_exists unique_index(:users, [:email], name: "users_unique_email_index")
drop table(:users)
end
end | wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/example_web/controllers/error_html_test.exs | Elixir | defmodule ExampleWeb.ErrorHTMLTest do
use ExampleWeb.ConnCase, async: true
# Bring render_to_string/4 for testing custom views
import Phoenix.Template
test "renders 404.html" do
assert render_to_string(ExampleWeb.ErrorHTML, "404", "html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(ExampleWeb.ErrorHTML, "500", "html", []) == "Internal Server Error"
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/example_web/controllers/error_json_test.exs | Elixir | defmodule ExampleWeb.ErrorJSONTest do
use ExampleWeb.ConnCase, async: true
test "renders 404" do
assert ExampleWeb.ErrorJSON.render("404.json", %{}) == %{errors: %{detail: "Not Found"}}
end
test "renders 500" do
assert ExampleWeb.ErrorJSON.render("500.json", %{}) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/example_web/controllers/page_controller_test.exs | Elixir | defmodule ExampleWeb.PageControllerTest do
use ExampleWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, ~p"/")
assert html_response(conn, 200) =~ "Peace of mind from prototype to production"
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/support/conn_case.ex | Elixir | defmodule ExampleWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use ExampleWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# The default endpoint for testing
@endpoint ExampleWeb.Endpoint
use ExampleWeb, :verified_routes
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import ExampleWeb.ConnCase
end
end
setup _tags do
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/test_helper.exs | Elixir | ExUnit.start()
| wintermeyer/ash-authentication-phoenix-example | 0 | This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
.formatter.exs | Elixir | # Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
| wintermeyer/cologne_phonetic | 0 | Cologne phonetics encoder for Elixir | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/cologne_phonetic.ex | Elixir | defmodule ColognePhonetic do
@moduledoc """
Documentation for `ColognePhonetic`.
"""
@doc """
Encode string to cologne phonetics.
## Examples
iex> ColognePhonetic.encode("Elixir")
"05487"
"""
def encode(sentence) do
sentence
|> String.downcase()
|> String.split(" ")
|> Enum.map(&encode_word/1)
|> Enum.join(" ")
end
defp encode_word(word) do
word
|> String.graphemes()
|> Enum.with_index()
|> Enum.map(fn {char, index} -> phonetic_code(char, word, index) end)
|> Enum.dedup()
|> Enum.join()
|> replace_not_leading_zeros()
end
defp phonetic_code(char, word, index) do
prev = get_char_at(word, index - 1)
next = get_char_at(word, index + 1)
is_initial = index == 0
case {char, prev, next, is_initial} do
{"a", _, _, _} -> "0"
{"e", _, _, _} -> "0"
{"i", _, _, _} -> "0"
{"j", _, _, _} -> "0"
{"o", _, _, _} -> "0"
{"u", _, _, _} -> "0"
{"y", _, _, _} -> "0"
{"ä", _, _, _} -> "0"
{"ö", _, _, _} -> "0"
{"ü", _, _, _} -> "0"
{"h", _, _, _} -> ""
{"b", _, _, _} -> "1"
{"p", _, _, _} when prev not in ["s", "z"] -> "1"
{"d", _, _, _} when next not in ["c", "s", "z"] -> "2"
{"t", _, _, _} when next not in ["c", "s", "z"] -> "2"
{"f", _, _, _} -> "3"
{"v", _, _, _} -> "3"
{"w", _, _, _} -> "3"
{"p", _, _, _} when prev in ["s", "z"] -> "3"
{"g", _, _, _} -> "4"
{"k", _, _, _} -> "4"
{"q", _, _, _} -> "4"
{"c", _, _, true} when next in ["a", "h", "k", "l", "o", "q", "r", "u", "x"] -> "4"
{"c", _, _, _} when prev in ["s", "z"] -> "8"
{"c", _, _, _} when prev in ["c", "k", "q", "x"] -> "8"
{"c", _, _, _} when next in ["a", "h", "k", "o", "q", "u", "x"] -> "4"
{"x", _, _, _} when prev not in ["c", "k", "q"] -> "48"
{"x", _, _, _} when prev in ["c", "k", "q"] -> "8"
{"l", _, _, _} -> "5"
{"m", _, _, _} -> "6"
{"n", _, _, _} -> "6"
{"r", _, _, _} -> "7"
{"s", _, _, _} -> "8"
{"z", _, _, _} -> "8"
{"ß", _, _, _} -> "8"
_ -> ""
end
end
defp get_char_at(word, index) do
if index >= 0 and index < String.length(word) do
String.at(word, index)
else
nil
end
end
defp replace_not_leading_zeros(string) do
Regex.replace(~r/(?<=\d)0/, string, "")
end
end
| wintermeyer/cologne_phonetic | 0 | Cologne phonetics encoder for Elixir | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
mix.exs | Elixir | defmodule ColognePhonetic.MixProject do
use Mix.Project
def project do
[
app: :cologne_phonetic,
version: "0.1.0",
elixir: "~> 1.14",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
| wintermeyer/cologne_phonetic | 0 | Cologne phonetics encoder for Elixir | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/cologne_phonetic_test.exs | Elixir | defmodule ColognePhoneticTest do
use ExUnit.Case
doctest ColognePhonetic
describe "encode/1" do
test "encodes words correctly" do
assert ColognePhonetic.encode("Wikipedia") == "3412"
assert ColognePhonetic.encode("Müller-Lüdenscheidt") == "65752682"
assert ColognePhonetic.encode("Erika Mustermann") == "074 682766"
assert ColognePhonetic.encode("Heinz Classen") == "068 4586"
assert ColognePhonetic.encode("HeinzClassen") == "068586"
assert ColognePhonetic.encode("Maier") == "67"
assert ColognePhonetic.encode("Meier") == "67"
assert ColognePhonetic.encode("Mayer") == "67"
assert ColognePhonetic.encode("Mayr") == "67"
assert ColognePhonetic.encode("Elixir") == "05487"
end
test "handles empty string" do
assert ColognePhonetic.encode("") == ""
end
test "handles non-alphabetic characters" do
assert ColognePhonetic.encode("Elixir!123") == "05487"
end
test "handles uppercase characters" do
assert ColognePhonetic.encode("ELIXIR") == "05487"
end
end
end
| wintermeyer/cologne_phonetic | 0 | Cologne phonetics encoder for Elixir | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/test_helper.exs | Elixir | ExUnit.start()
| wintermeyer/cologne_phonetic | 0 | Cologne phonetics encoder for Elixir | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
.formatter.exs | Elixir | [
import_deps: [:ecto, :ecto_sql, :phoenix],
subdirectories: ["priv/*/migrations"],
plugins: [Phoenix.LiveView.HTMLFormatter],
inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
]
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
assets/css/app.css | CSS | /* See the Tailwind configuration guide for advanced usage
https://tailwindcss.com/docs/configuration */
@import "tailwindcss" source(none);
@source "../css";
@source "../js";
@source "../../lib/koblenzomat_web";
/* A Tailwind plugin that makes "hero-#{ICON}" classes available.
The heroicons installation itself is managed by your mix.exs */
@plugin "../vendor/heroicons";
/* daisyUI Tailwind Plugin. You can update this file by fetching the latest version with:
curl -sLO https://github.com/saadeghi/daisyui/releases/latest/download/daisyui.js
Make sure to look at the daisyUI changelog: https://daisyui.com/docs/changelog/ */
@plugin "../vendor/daisyui" {
themes: false;
}
/* daisyUI theme plugin. You can update this file by fetching the latest version with:
curl -sLO https://github.com/saadeghi/daisyui/releases/latest/download/daisyui-theme.js
We ship with two themes, a light one inspired on Phoenix colors and a dark one inspired
on Elixir colors. Build your own at: https://daisyui.com/theme-generator/ */
@plugin "../vendor/daisyui-theme" {
name: "dark";
default: false;
prefersdark: true;
color-scheme: "dark";
--color-base-100: oklch(30.33% 0.016 252.42);
--color-base-200: oklch(25.26% 0.014 253.1);
--color-base-300: oklch(20.15% 0.012 254.09);
--color-base-content: oklch(97.807% 0.029 256.847);
--color-primary: oklch(58% 0.233 277.117);
--color-primary-content: oklch(96% 0.018 272.314);
--color-secondary: oklch(58% 0.233 277.117);
--color-secondary-content: oklch(96% 0.018 272.314);
--color-accent: oklch(60% 0.25 292.717);
--color-accent-content: oklch(96% 0.016 293.756);
--color-neutral: oklch(37% 0.044 257.287);
--color-neutral-content: oklch(98% 0.003 247.858);
--color-info: oklch(58% 0.158 241.966);
--color-info-content: oklch(97% 0.013 236.62);
--color-success: oklch(60% 0.118 184.704);
--color-success-content: oklch(98% 0.014 180.72);
--color-warning: oklch(66% 0.179 58.318);
--color-warning-content: oklch(98% 0.022 95.277);
--color-error: oklch(58% 0.253 17.585);
--color-error-content: oklch(96% 0.015 12.422);
--radius-selector: 0.25rem;
--radius-field: 0.25rem;
--radius-box: 0.5rem;
--size-selector: 0.21875rem;
--size-field: 0.21875rem;
--border: 1.5px;
--depth: 1;
--noise: 0;
}
@plugin "../vendor/daisyui-theme" {
name: "light";
default: true;
prefersdark: false;
color-scheme: "light";
--color-base-100: oklch(98% 0 0);
--color-base-200: oklch(96% 0.001 286.375);
--color-base-300: oklch(92% 0.004 286.32);
--color-base-content: oklch(21% 0.006 285.885);
--color-primary: oklch(70% 0.213 47.604);
--color-primary-content: oklch(98% 0.016 73.684);
--color-secondary: oklch(55% 0.027 264.364);
--color-secondary-content: oklch(98% 0.002 247.839);
--color-accent: oklch(0% 0 0);
--color-accent-content: oklch(100% 0 0);
--color-neutral: oklch(44% 0.017 285.786);
--color-neutral-content: oklch(98% 0 0);
--color-info: oklch(62% 0.214 259.815);
--color-info-content: oklch(97% 0.014 254.604);
--color-success: oklch(70% 0.14 182.503);
--color-success-content: oklch(98% 0.014 180.72);
--color-warning: oklch(66% 0.179 58.318);
--color-warning-content: oklch(98% 0.022 95.277);
--color-error: oklch(65% 0.241 354.308);
--color-error-content: oklch(97% 0.014 343.198);
--radius-selector: 0.25rem;
--radius-field: 0.25rem;
--radius-box: 0.5rem;
--size-selector: 0.21875rem;
--size-field: 0.21875rem;
--border: 1.5px;
--depth: 1;
--noise: 0;
}
/* Add variants based on LiveView classes */
@custom-variant phx-click-loading ([".phx-click-loading&", ".phx-click-loading &"]);
@custom-variant phx-submit-loading ([".phx-submit-loading&", ".phx-submit-loading &"]);
@custom-variant phx-change-loading ([".phx-change-loading&", ".phx-change-loading &"]);
/* Make LiveView wrapper divs transparent for layout */
[data-phx-root-id] { display: contents }
/* This file is for your main application CSS */
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
assets/js/app.js | JavaScript | // If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
// import "./user_socket.js"
// You can include dependencies in two ways.
//
// The simplest option is to put them in assets/vendor and
// import them using relative paths:
//
// import "../vendor/some-package.js"
//
// Alternatively, you can `npm install some-package --prefix assets` and import
// them using a path starting with the package name:
//
// import "some-package"
//
// If you have dependencies that try to import CSS, esbuild will generate a separate `app.css` file.
// To load it, simply add a second `<link>` to your `root.html.heex` file.
// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
const liveSocket = new LiveSocket("/live", Socket, {
longPollFallbackMs: 2500,
params: {_csrf_token: csrfToken}
})
// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", _info => topbar.show(300))
window.addEventListener("phx:page-loading-stop", _info => topbar.hide())
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket
// The lines below enable quality of life phoenix_live_reload
// development features:
//
// 1. stream server logs to the browser console
// 2. click on elements to jump to their definitions in your code editor
//
if (process.env.NODE_ENV === "development") {
window.addEventListener("phx:live_reload:attached", ({detail: reloader}) => {
// Enable server log streaming to client.
// Disable with reloader.disableServerLogs()
reloader.enableServerLogs()
// Open configured PLUG_EDITOR at file:line of the clicked element's HEEx component
//
// * click with "c" key pressed to open at caller location
// * click with "d" key pressed to open at function component definition location
let keyDown
window.addEventListener("keydown", e => keyDown = e.key)
window.addEventListener("keyup", e => keyDown = null)
window.addEventListener("click", e => {
if(keyDown === "c"){
e.preventDefault()
e.stopImmediatePropagation()
reloader.openEditorAtCaller(e.target)
} else if(keyDown === "d"){
e.preventDefault()
e.stopImmediatePropagation()
reloader.openEditorAtDef(e.target)
}
}, true)
window.liveReloader = reloader
})
}
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
config/config.exs | Elixir | # This file is responsible for configuring your application
# and its dependencies with the aid of the Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
import Config
config :koblenzomat,
ecto_repos: [Koblenzomat.Repo],
generators: [timestamp_type: :utc_datetime]
# Configures the endpoint
config :koblenzomat, KoblenzomatWeb.Endpoint,
url: [host: "localhost"],
adapter: Bandit.PhoenixAdapter,
render_errors: [
formats: [html: KoblenzomatWeb.ErrorHTML, json: KoblenzomatWeb.ErrorJSON],
layout: false
],
pubsub_server: Koblenzomat.PubSub,
live_view: [signing_salt: "qpna/j9T"]
# Configures the mailer
#
# By default it uses the "Local" adapter which stores the emails
# locally. You can see the emails in your browser, at "/dev/mailbox".
#
# For production it's recommended to configure a different adapter
# at the `config/runtime.exs`.
config :koblenzomat, Koblenzomat.Mailer, adapter: Swoosh.Adapters.Local
# Configure esbuild (the version is required)
config :esbuild,
version: "0.17.11",
koblenzomat: [
args:
~w(js/app.js --bundle --target=es2022 --outdir=../priv/static/assets/js --external:/fonts/* --external:/images/*),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
# Configure tailwind (the version is required)
config :tailwind,
version: "4.0.9",
koblenzomat: [
args: ~w(
--input=assets/css/app.css
--output=priv/static/assets/css/app.css
),
cd: Path.expand("..", __DIR__)
]
# Configures Elixir's Logger
config :logger, :default_formatter,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{config_env()}.exs"
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
config/dev.exs | Elixir | import Config
# Configure your database
config :koblenzomat, Koblenzomat.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "koblenzomat_dev",
stacktrace: true,
show_sensitive_data_on_connection_error: true,
pool_size: 10
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we can use it
# to bundle .js and .css sources.
config :koblenzomat, KoblenzomatWeb.Endpoint,
# Binding to loopback ipv4 address prevents access from other machines.
# Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
http: [ip: {127, 0, 0, 1}, port: 4000],
check_origin: false,
code_reloader: true,
debug_errors: true,
secret_key_base: "nHRyPMYU2kO6mgh9RsxNRsza39++WnY2UQ510Au13TsFXh4/3prgP5T9yzsQl/wb",
watchers: [
esbuild: {Esbuild, :install_and_run, [:koblenzomat, ~w(--sourcemap=inline --watch)]},
tailwind: {Tailwind, :install_and_run, [:koblenzomat, ~w(--watch)]}
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :koblenzomat, KoblenzomatWeb.Endpoint,
live_reload: [
web_console_logger: true,
patterns: [
~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/koblenzomat_web/(controllers|live|components)/.*(ex|heex)$"
]
]
# Enable dev routes for dashboard and mailbox
config :koblenzomat, dev_routes: true
# Do not include metadata nor timestamps in development logs
config :logger, :default_formatter, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
config :phoenix_live_view,
# Include HEEx debug annotations as HTML comments in rendered markup.
# Changing this configuration will require mix clean and a full recompile.
debug_heex_annotations: true,
# Enable helpful, but potentially expensive runtime checks
enable_expensive_runtime_checks: true
# Disable swoosh api client as it is only required for production adapters.
config :swoosh, :api_client, false
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
config/prod.exs | Elixir | import Config
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix assets.deploy` task,
# which you should run after static files are built and
# before starting your production server.
config :koblenzomat, KoblenzomatWeb.Endpoint,
cache_static_manifest: "priv/static/cache_manifest.json"
# Configures Swoosh API Client
config :swoosh, api_client: Swoosh.ApiClient.Req
# Disable Swoosh Local Memory Storage
config :swoosh, local: false
# Do not print debug messages in production
config :logger, level: :info
# Runtime production configuration, including reading
# of environment variables, is done on config/runtime.exs.
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
config/runtime.exs | Elixir | import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
# ## Using releases
#
# If you use `mix release`, you need to explicitly enable the server
# by passing the PHX_SERVER=true when you start it:
#
# PHX_SERVER=true bin/koblenzomat start
#
# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
# script that automatically sets the env var above.
if System.get_env("PHX_SERVER") do
config :koblenzomat, KoblenzomatWeb.Endpoint, server: true
end
if config_env() == :prod do
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: []
config :koblenzomat, Koblenzomat.Repo,
# ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
# For machines with several cores, consider starting multiple pools of `pool_size`
# pool_count: 4,
socket_options: maybe_ipv6
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
host = System.get_env("PHX_HOST") || "example.com"
port = String.to_integer(System.get_env("PORT") || "4000")
config :koblenzomat, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")
config :koblenzomat, KoblenzomatWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://hexdocs.pm/bandit/Bandit.html#t:options/0
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0},
port: port
],
secret_key_base: secret_key_base
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to your endpoint configuration:
#
# config :koblenzomat, KoblenzomatWeb.Endpoint,
# https: [
# ...,
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your config/prod.exs,
# ensuring no data is ever sent via http, always redirecting to https:
#
# config :koblenzomat, KoblenzomatWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Configuring the mailer
#
# In production you need to configure the mailer to use a different adapter.
# Also, you may need to configure the Swoosh API client of your choice if you
# are not using SMTP. Here is an example of the configuration:
#
# config :koblenzomat, Koblenzomat.Mailer,
# adapter: Swoosh.Adapters.Mailgun,
# api_key: System.get_env("MAILGUN_API_KEY"),
# domain: System.get_env("MAILGUN_DOMAIN")
#
# For this example you need include a HTTP client required by Swoosh API client.
# Swoosh supports Hackney, Req and Finch out of the box:
#
# config :swoosh, :api_client, Swoosh.ApiClient.Hackney
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
config/test.exs | Elixir | import Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :koblenzomat, Koblenzomat.Repo,
username: "postgres",
password: "postgres",
hostname: "localhost",
database: "koblenzomat_test#{System.get_env("MIX_TEST_PARTITION")}",
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: System.schedulers_online() * 2
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :koblenzomat, KoblenzomatWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "TX2ZmFNDwsSNZgIGNT3pmCt1WY2Zi4p5A0sLqoEf/Mf2E8I8dTb0V7vz/JElsRWL",
server: false
# In test we don't send emails
config :koblenzomat, Koblenzomat.Mailer, adapter: Swoosh.Adapters.Test
# Disable swoosh api client as it is only required for production adapters
config :swoosh, :api_client, false
# Print only warnings and errors during test
config :logger, level: :warning
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime
# Enable helpful, but potentially expensive runtime checks
config :phoenix_live_view,
enable_expensive_runtime_checks: true
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat.ex | Elixir | defmodule Koblenzomat do
@moduledoc """
Koblenzomat keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/application.ex | Elixir | defmodule Koblenzomat.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
KoblenzomatWeb.Telemetry,
Koblenzomat.Repo,
{DNSCluster, query: Application.get_env(:koblenzomat, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: Koblenzomat.PubSub},
# Start a worker by calling: Koblenzomat.Worker.start_link(arg)
# {Koblenzomat.Worker, arg},
# Start to serve requests, typically the last entry
KoblenzomatWeb.Endpoint
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Koblenzomat.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
@impl true
def config_change(changed, _new, removed) do
KoblenzomatWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/election.ex | Elixir | defmodule Koblenzomat.Election do
@moduledoc """
The Election schema represents a single election event in the system.
Each election can have many associated theses (questions/statements) that users interact with.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "elections" do
field :name, :string
has_many :theses, Koblenzomat.Thesis
timestamps(type: :utc_datetime)
end
@doc """
Returns a changeset for creating or updating an election.
## Parameters
- election: the %Election{} struct
- attrs: a map of attributes to update
## Returns
- %Ecto.Changeset{}
"""
def changeset(election, attrs) do
election
|> cast(attrs, [:name])
|> validate_required([:name])
|> unique_constraint(:name)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/hashtag.ex | Elixir | defmodule Koblenzomat.Hashtag do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "hashtags" do
field :name, :string
timestamps(type: :utc_datetime)
end
@doc false
def changeset(hashtag, attrs) do
hashtag
|> cast(attrs, [:name])
|> validate_required([:name])
|> unique_constraint(:name)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/hashtags_to_theses.ex | Elixir | defmodule Koblenzomat.HashtagsToTheses do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "hashtags_to_theses" do
field :thesis_id, :binary_id
field :hashtag_id, :binary_id
timestamps(type: :utc_datetime)
end
@doc false
def changeset(hashtags_to_theses, attrs) do
hashtags_to_theses
|> cast(attrs, [])
|> validate_required([])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/mailer.ex | Elixir | defmodule Koblenzomat.Mailer do
use Swoosh.Mailer, otp_app: :koblenzomat
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/repo.ex | Elixir | defmodule Koblenzomat.Repo do
use Ecto.Repo,
otp_app: :koblenzomat,
adapter: Ecto.Adapters.Postgres
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/thesis.ex | Elixir | defmodule Koblenzomat.Thesis do
@moduledoc """
The Thesis schema represents a single statement or question within an election.
Each thesis belongs to an election and can be associated with multiple hashtags for categorization.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "theses" do
field :name, :string
field :position, :integer
belongs_to :election, Koblenzomat.Election, type: :binary_id
many_to_many :hashtags, Koblenzomat.Hashtag, join_through: "hashtags_to_theses"
timestamps(type: :utc_datetime)
end
@doc """
Returns a changeset for creating or updating a thesis.
## Parameters
- thesis: the %Thesis{} struct
- attrs: a map of attributes to update (must include :name, :position, :election_id)
## Returns
- %Ecto.Changeset{}
"""
def changeset(thesis, attrs) do
thesis
|> cast(attrs, [:name, :position, :election_id])
|> validate_required([:name, :position, :election_id])
|> unique_constraint(:name)
|> unique_constraint(:position, name: :theses_election_id_position_index)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat/voting.ex | Elixir | defmodule Koblenzomat.Voting do
@moduledoc """
The Voting context is responsible for all business logic related to elections, theses (questions/statements), hashtags, and their associations.
This context provides functions to create theses (with automatic position handling) and to list elections with their associated theses and hashtags. It acts as the main entry point for election-related operations in the application.
"""
alias Koblenzomat.{Repo, Thesis, Election}
import Ecto.Query
@doc """
Creates a thesis for a given election. If no position is provided, it will automatically assign the next available position within the election.
## Parameters
- attrs: a map with thesis attributes, including :name, :election_id, and optionally :position
## Returns
- {:ok, %Thesis{}} on success
- {:error, %Ecto.Changeset{}} on failure
"""
def create_thesis(attrs) do
position =
case Map.get(attrs, :position) do
nil ->
_election_id = Map.fetch!(attrs, :election_id)
max =
Repo.one(
from(t in Thesis,
where: t.election_id == ^attrs[:election_id],
select: max(t.position)
)
) || 0
max + 1
pos ->
pos
end
attrs = Map.put(attrs, :position, position)
%Thesis{}
|> Thesis.changeset(attrs)
|> Repo.insert()
end
@doc """
Returns a list of all elections, each preloaded with their associated theses and hashtags.
## Returns
- A list of %Election{} structs, each with a :theses field containing associated theses (and their hashtags)
"""
def list_elections_with_theses do
Repo.all(from e in Election, order_by: e.id, preload: [theses: [:hashtags]])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web.ex | Elixir | defmodule KoblenzomatWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, components, channels, and so on.
This can be used in your application as:
use KoblenzomatWeb, :controller
use KoblenzomatWeb, :html
The definitions below will be executed for every controller,
component, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define additional modules and import
those modules here.
"""
def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
def router do
quote do
use Phoenix.Router, helpers: false
# Import common connection and controller functions to use in pipelines
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end
def channel do
quote do
use Phoenix.Channel
end
end
def controller do
quote do
use Phoenix.Controller, formats: [:html, :json]
use Gettext, backend: KoblenzomatWeb.Gettext
import Plug.Conn
unquote(verified_routes())
end
end
def live_view do
quote do
use Phoenix.LiveView
unquote(html_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(html_helpers())
end
end
def html do
quote do
use Phoenix.Component
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_csrf_token: 0, view_module: 1, view_template: 1]
# Include general helpers for rendering HTML
unquote(html_helpers())
end
end
defp html_helpers do
quote do
# Translation
use Gettext, backend: KoblenzomatWeb.Gettext
# HTML escaping functionality
import Phoenix.HTML
# Core UI components
import KoblenzomatWeb.CoreComponents
# Common modules used in templates
alias Phoenix.LiveView.JS
alias KoblenzomatWeb.Layouts
# Routes generation with the ~p sigil
unquote(verified_routes())
end
end
def verified_routes do
quote do
use Phoenix.VerifiedRoutes,
endpoint: KoblenzomatWeb.Endpoint,
router: KoblenzomatWeb.Router,
statics: KoblenzomatWeb.static_paths()
end
end
@doc """
When used, dispatch to the appropriate controller/live_view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/components/core_components.ex | Elixir | defmodule KoblenzomatWeb.CoreComponents do
@moduledoc """
Provides core UI components.
At first glance, this module may seem daunting, but its goal is to provide
core building blocks for your application, such as tables, forms, and
inputs. The components consist mostly of markup and are well-documented
with doc strings and declarative assigns. You may customize and style
them in any way you want, based on your application growth and needs.
The foundation for styling is Tailwind CSS, a utility-first CSS framework,
augmented with daisyUI, a Tailwind CSS plugin that provides UI components
and themes. Here are useful references:
* [daisyUI](https://daisyui.com/docs/intro/) - a good place to get
started and see the available components.
* [Tailwind CSS](https://tailwindcss.com) - the foundational framework
we build on. You will use it for layout, sizing, flexbox, grid, and
spacing.
* [Heroicons](https://heroicons.com) - see `icon/1` for usage.
* [Phoenix.Component](https://hexdocs.pm/phoenix_live_view/Phoenix.Component.html) -
the component system used by Phoenix. Some components, such as `<.link>`
and `<.form>`, are defined there.
"""
use Phoenix.Component
use Gettext, backend: KoblenzomatWeb.Gettext
alias Phoenix.LiveView.JS
@doc """
Renders flash notices.
## Examples
<.flash kind={:info} flash={@flash} />
<.flash kind={:info} phx-mounted={show("#flash")}>Welcome Back!</.flash>
"""
attr :id, :string, doc: "the optional id of flash container"
attr :flash, :map, default: %{}, doc: "the map of flash messages to display"
attr :title, :string, default: nil
attr :kind, :atom, values: [:info, :error], doc: "used for styling and flash lookup"
attr :rest, :global, doc: "the arbitrary HTML attributes to add to the flash container"
slot :inner_block, doc: "the optional inner block that renders the flash message"
def flash(assigns) do
assigns = assign_new(assigns, :id, fn -> "flash-#{assigns.kind}" end)
~H"""
<div
:if={msg = render_slot(@inner_block) || Phoenix.Flash.get(@flash, @kind)}
id={@id}
phx-click={JS.push("lv:clear-flash", value: %{key: @kind}) |> hide("##{@id}")}
role="alert"
class="toast toast-top toast-end z-50"
{@rest}
>
<div class={[
"alert w-80 sm:w-96 max-w-80 sm:max-w-96 text-wrap",
@kind == :info && "alert-info",
@kind == :error && "alert-error"
]}>
<.icon :if={@kind == :info} name="hero-information-circle-mini" class="size-5 shrink-0" />
<.icon :if={@kind == :error} name="hero-exclamation-circle-mini" class="size-5 shrink-0" />
<div>
<p :if={@title} class="font-semibold">{@title}</p>
<p>{msg}</p>
</div>
<div class="flex-1" />
<button type="button" class="group self-start cursor-pointer" aria-label={gettext("close")}>
<.icon name="hero-x-mark-solid" class="size-5 opacity-40 group-hover:opacity-70" />
</button>
</div>
</div>
"""
end
@doc """
Renders a button with navigation support.
## Examples
<.button>Send!</.button>
<.button phx-click="go" variant="primary">Send!</.button>
<.button navigate={~p"/"}>Home</.button>
"""
attr :rest, :global, include: ~w(href navigate patch)
attr :variant, :string, values: ~w(primary)
slot :inner_block, required: true
def button(%{rest: rest} = assigns) do
variants = %{"primary" => "btn-primary", nil => "btn-primary btn-soft"}
assigns = assign(assigns, :class, Map.fetch!(variants, assigns[:variant]))
if rest[:href] || rest[:navigate] || rest[:patch] do
~H"""
<.link class={["btn", @class]} {@rest}>
{render_slot(@inner_block)}
</.link>
"""
else
~H"""
<button class={["btn", @class]} {@rest}>
{render_slot(@inner_block)}
</button>
"""
end
end
@doc """
Renders an input with label and error messages.
A `Phoenix.HTML.FormField` may be passed as argument,
which is used to retrieve the input name, id, and values.
Otherwise all attributes may be passed explicitly.
## Types
This function accepts all HTML input types, considering that:
* You may also set `type="select"` to render a `<select>` tag
* `type="checkbox"` is used exclusively to render boolean values
* For live file uploads, see `Phoenix.Component.live_file_input/1`
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
for more information. Unsupported types, such as hidden and radio,
are best written directly in your templates.
## Examples
<.input field={@form[:email]} type="email" />
<.input name="my-input" errors={["oh no!"]} />
"""
attr :id, :any, default: nil
attr :name, :any
attr :label, :string, default: nil
attr :value, :any
attr :type, :string,
default: "text",
values: ~w(checkbox color date datetime-local email file month number password
range search select tel text textarea time url week)
attr :field, Phoenix.HTML.FormField,
doc: "a form field struct retrieved from the form, for example: @form[:email]"
attr :errors, :list, default: []
attr :checked, :boolean, doc: "the checked flag for checkbox inputs"
attr :prompt, :string, default: nil, doc: "the prompt for select inputs"
attr :options, :list, doc: "the options to pass to Phoenix.HTML.Form.options_for_select/2"
attr :multiple, :boolean, default: false, doc: "the multiple flag for select inputs"
attr :rest, :global,
include: ~w(accept autocomplete capture cols disabled form list max maxlength min minlength
multiple pattern placeholder readonly required rows size step)
def input(%{field: %Phoenix.HTML.FormField{} = field} = assigns) do
errors = if Phoenix.Component.used_input?(field), do: field.errors, else: []
assigns
|> assign(field: nil, id: assigns.id || field.id)
|> assign(:errors, Enum.map(errors, &translate_error(&1)))
|> assign_new(:name, fn -> if assigns.multiple, do: field.name <> "[]", else: field.name end)
|> assign_new(:value, fn -> field.value end)
|> input()
end
def input(%{type: "checkbox"} = assigns) do
assigns =
assign_new(assigns, :checked, fn ->
Phoenix.HTML.Form.normalize_value("checkbox", assigns[:value])
end)
~H"""
<fieldset class="fieldset mb-2">
<label>
<input type="hidden" name={@name} value="false" disabled={@rest[:disabled]} />
<span class="fieldset-label">
<input
type="checkbox"
id={@id}
name={@name}
value="true"
checked={@checked}
class="checkbox checkbox-sm"
{@rest}
/>{@label}
</span>
</label>
<.error :for={msg <- @errors}>{msg}</.error>
</fieldset>
"""
end
def input(%{type: "select"} = assigns) do
~H"""
<fieldset class="fieldset mb-2">
<label>
<span :if={@label} class="fieldset-label mb-1">{@label}</span>
<select
id={@id}
name={@name}
class={["w-full select", @errors != [] && "select-error"]}
multiple={@multiple}
{@rest}
>
<option :if={@prompt} value="">{@prompt}</option>
{Phoenix.HTML.Form.options_for_select(@options, @value)}
</select>
</label>
<.error :for={msg <- @errors}>{msg}</.error>
</fieldset>
"""
end
def input(%{type: "textarea"} = assigns) do
~H"""
<fieldset class="fieldset mb-2">
<label>
<span :if={@label} class="fieldset-label mb-1">{@label}</span>
<textarea
id={@id}
name={@name}
class={["w-full textarea", @errors != [] && "textarea-error"]}
{@rest}
>{Phoenix.HTML.Form.normalize_value("textarea", @value)}</textarea>
</label>
<.error :for={msg <- @errors}>{msg}</.error>
</fieldset>
"""
end
# All other inputs text, datetime-local, url, password, etc. are handled here...
def input(assigns) do
~H"""
<fieldset class="fieldset mb-2">
<label>
<span :if={@label} class="fieldset-label mb-1">{@label}</span>
<input
type={@type}
name={@name}
id={@id}
value={Phoenix.HTML.Form.normalize_value(@type, @value)}
class={["w-full input", @errors != [] && "input-error"]}
{@rest}
/>
</label>
<.error :for={msg <- @errors}>{msg}</.error>
</fieldset>
"""
end
# Helper used by inputs to generate form errors
defp error(assigns) do
~H"""
<p class="mt-1.5 flex gap-2 items-center text-sm text-error">
<.icon name="hero-exclamation-circle-mini" class="size-5" />
{render_slot(@inner_block)}
</p>
"""
end
@doc """
Renders a header with title.
"""
attr :class, :string, default: nil
slot :inner_block, required: true
slot :subtitle
slot :actions
def header(assigns) do
~H"""
<header class={[@actions != [] && "flex items-center justify-between gap-6", "pb-4", @class]}>
<div>
<h1 class="text-lg font-semibold leading-8">
{render_slot(@inner_block)}
</h1>
<p :if={@subtitle != []} class="text-sm text-base-content/70">
{render_slot(@subtitle)}
</p>
</div>
<div class="flex-none">{render_slot(@actions)}</div>
</header>
"""
end
@doc ~S"""
Renders a table with generic styling.
## Examples
<.table id="users" rows={@users}>
<:col :let={user} label="id">{user.id}</:col>
<:col :let={user} label="username">{user.username}</:col>
</.table>
"""
attr :id, :string, required: true
attr :rows, :list, required: true
attr :row_id, :any, default: nil, doc: "the function for generating the row id"
attr :row_click, :any, default: nil, doc: "the function for handling phx-click on each row"
attr :row_item, :any,
default: &Function.identity/1,
doc: "the function for mapping each row before calling the :col and :action slots"
slot :col, required: true do
attr :label, :string
end
slot :action, doc: "the slot for showing user actions in the last table column"
def table(assigns) do
assigns =
with %{rows: %Phoenix.LiveView.LiveStream{}} <- assigns do
assign(assigns, row_id: assigns.row_id || fn {id, _item} -> id end)
end
~H"""
<table class="table table-zebra">
<thead>
<tr>
<th :for={col <- @col}>{col[:label]}</th>
<th :if={@action != []}>
<span class="sr-only">{gettext("Actions")}</span>
</th>
</tr>
</thead>
<tbody id={@id} phx-update={is_struct(@rows, Phoenix.LiveView.LiveStream) && "stream"}>
<tr :for={row <- @rows} id={@row_id && @row_id.(row)}>
<td
:for={col <- @col}
phx-click={@row_click && @row_click.(row)}
class={@row_click && "hover:cursor-pointer"}
>
{render_slot(col, @row_item.(row))}
</td>
<td :if={@action != []} class="w-0 font-semibold">
<div class="flex gap-4">
<%= for action <- @action do %>
{render_slot(action, @row_item.(row))}
<% end %>
</div>
</td>
</tr>
</tbody>
</table>
"""
end
@doc """
Renders a data list.
## Examples
<.list>
<:item title="Title">{@post.title}</:item>
<:item title="Views">{@post.views}</:item>
</.list>
"""
slot :item, required: true do
attr :title, :string, required: true
end
def list(assigns) do
~H"""
<ul class="list">
<li :for={item <- @item} class="list-row">
<div>
<div class="font-bold">{item.title}</div>
<div>{render_slot(item)}</div>
</div>
</li>
</ul>
"""
end
@doc """
Renders a [Heroicon](https://heroicons.com).
Heroicons come in three styles – outline, solid, and mini.
By default, the outline style is used, but solid and mini may
be applied by using the `-solid` and `-mini` suffix.
You can customize the size and colors of the icons by setting
width, height, and background color classes.
Icons are extracted from the `deps/heroicons` directory and bundled within
your compiled app.css by the plugin in `assets/vendor/heroicons.js`.
## Examples
<.icon name="hero-x-mark-solid" />
<.icon name="hero-arrow-path" class="ml-1 size-3 motion-safe:animate-spin" />
"""
attr :name, :string, required: true
attr :class, :string, default: "size-4"
def icon(%{name: "hero-" <> _} = assigns) do
~H"""
<span class={[@name, @class]} />
"""
end
## JS Commands
def show(js \\ %JS{}, selector) do
JS.show(js,
to: selector,
time: 300,
transition:
{"transition-all ease-out duration-300",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",
"opacity-100 translate-y-0 sm:scale-100"}
)
end
def hide(js \\ %JS{}, selector) do
JS.hide(js,
to: selector,
time: 200,
transition:
{"transition-all ease-in duration-200", "opacity-100 translate-y-0 sm:scale-100",
"opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"}
)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# However the error messages in our forms and APIs are generated
# dynamically, so we need to translate them by calling Gettext
# with our gettext backend as first argument. Translations are
# available in the errors.po file (as we use the "errors" domain).
if count = opts[:count] do
Gettext.dngettext(KoblenzomatWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(KoblenzomatWeb.Gettext, "errors", msg, opts)
end
end
@doc """
Translates the errors for a field from a keyword list of errors.
"""
def translate_errors(errors, field) when is_list(errors) do
for {^field, {msg, opts}} <- errors, do: translate_error({msg, opts})
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/components/layouts.ex | Elixir | defmodule KoblenzomatWeb.Layouts do
@moduledoc """
This module holds different layouts used by your application.
See the `layouts` directory for all templates available.
The "root" layout is a skeleton rendered as part of the
application router. The "app" layout is rendered as component
in regular views and live views.
"""
use KoblenzomatWeb, :html
embed_templates "layouts/*"
def app(assigns) do
~H"""
<header class="navbar px-4 sm:px-6 lg:px-8">
<div class="flex-1">
<a href="/" class="flex-1 flex items-center gap-2">
<img src={~p"/images/logo.svg"} width="36" />
<span class="text-sm font-semibold">v{Application.spec(:phoenix, :vsn)}</span>
</a>
</div>
<div class="flex-none">
<ul class="flex flex-column px-1 space-x-4 items-center">
<li>
<a href="https://phoenixframework.org/" class="btn btn-ghost">Website</a>
</li>
<li>
<a href="https://github.com/phoenixframework/phoenix" class="btn btn-ghost">GitHub</a>
</li>
<li>
<.theme_toggle />
</li>
<li>
<a href="https://hexdocs.pm/phoenix/overview.html" class="btn btn-primary">
Get Started <span aria-hidden="true">→</span>
</a>
</li>
</ul>
</div>
</header>
<main class="px-4 py-20 sm:px-6 lg:px-8">
<div class="mx-auto max-w-2xl space-y-4">
{render_slot(@inner_block)}
</div>
</main>
<.flash_group flash={@flash} />
"""
end
@doc """
Shows the flash group with standard titles and content.
## Examples
<.flash_group flash={@flash} />
"""
attr :flash, :map, required: true, doc: "the map of flash messages"
attr :id, :string, default: "flash-group", doc: "the optional id of flash container"
def flash_group(assigns) do
~H"""
<div id={@id} aria-live="polite">
<.flash kind={:info} flash={@flash} />
<.flash kind={:error} flash={@flash} />
<.flash
id="client-error"
kind={:error}
title={gettext("We can't find the internet")}
phx-disconnected={show(".phx-client-error #client-error") |> JS.remove_attribute("hidden")}
phx-connected={hide("#client-error") |> JS.set_attribute({"hidden", ""})}
hidden
>
{gettext("Attempting to reconnect")}
<.icon name="hero-arrow-path" class="ml-1 h-3 w-3 motion-safe:animate-spin" />
</.flash>
<.flash
id="server-error"
kind={:error}
title={gettext("Something went wrong!")}
phx-disconnected={show(".phx-client-error #client-error") |> JS.remove_attribute("hidden")}
phx-connected={hide("#client-error") |> JS.set_attribute({"hidden", ""})}
hidden
>
{gettext("Hang in there while we get back on track")}
<.icon name="hero-arrow-path" class="ml-1 h-3 w-3 motion-safe:animate-spin" />
</.flash>
</div>
"""
end
@doc """
Provides dark vs light theme toggle based on themes defined in app.css.
See <head> in root.html.heex which applies the theme before page load.
"""
def theme_toggle(assigns) do
~H"""
<div class="card relative flex flex-row items-center border-2 border-base-300 bg-base-300 rounded-full">
<div class="absolute w-[33%] h-full rounded-full border-1 border-base-200 bg-base-100 brightness-200 left-0 [[data-theme=light]_&]:left-[33%] [[data-theme=dark]_&]:left-[66%] transition-[left]" />
<button phx-click={JS.dispatch("phx:set-theme", detail: %{theme: "system"})} class="flex p-2">
<.icon name="hero-computer-desktop-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
<button phx-click={JS.dispatch("phx:set-theme", detail: %{theme: "light"})} class="flex p-2">
<.icon name="hero-sun-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
<button phx-click={JS.dispatch("phx:set-theme", detail: %{theme: "dark"})} class="flex p-2">
<.icon name="hero-moon-micro" class="size-4 opacity-75 hover:opacity-100" />
</button>
</div>
"""
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/controllers/error_html.ex | Elixir | defmodule KoblenzomatWeb.ErrorHTML do
@moduledoc """
This module is invoked by your endpoint in case of errors on HTML requests.
See config/config.exs.
"""
use KoblenzomatWeb, :html
# If you want to customize your error pages,
# uncomment the embed_templates/1 call below
# and add pages to the error directory:
#
# * lib/koblenzomat_web/controllers/error_html/404.html.heex
# * lib/koblenzomat_web/controllers/error_html/500.html.heex
#
# embed_templates "error_html/*"
# The default is to render a plain text page based on
# the template name. For example, "404.html" becomes
# "Not Found".
def render(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/controllers/error_json.ex | Elixir | defmodule KoblenzomatWeb.ErrorJSON do
@moduledoc """
This module is invoked by your endpoint in case of errors on JSON requests.
See config/config.exs.
"""
# If you want to customize a particular status code,
# you may add your own clauses, such as:
#
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def render(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/controllers/page_controller.ex | Elixir | defmodule KoblenzomatWeb.PageController do
use KoblenzomatWeb, :controller
def home(conn, _params) do
# The home page is often custom made,
# so skip the default app layout.
render(conn, :home, layout: false)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/controllers/page_html.ex | Elixir | defmodule KoblenzomatWeb.PageHTML do
@moduledoc """
This module contains pages rendered by PageController.
See the `page_html` directory for all templates available.
"""
use KoblenzomatWeb, :html
embed_templates "page_html/*"
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/endpoint.ex | Elixir | defmodule KoblenzomatWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :koblenzomat
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_koblenzomat_key",
signing_salt: "xYj+Zf+/",
same_site: "Lax"
]
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [session: @session_options]],
longpoll: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# When code reloading is disabled (e.g., in production),
# the `gzip` option is enabled to serve compressed
# static files generated by running `phx.digest`.
plug Plug.Static,
at: "/",
from: :koblenzomat,
gzip: not code_reloading?,
only: KoblenzomatWeb.static_paths()
if Code.ensure_loaded?(Tidewave) do
plug Tidewave
end
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :koblenzomat
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug KoblenzomatWeb.Router
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/gettext.ex | Elixir | defmodule KoblenzomatWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext), your module compiles translations
that you can use in your application. To use this Gettext backend module,
call `use Gettext` and pass it as an option:
use Gettext, backend: KoblenzomatWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext.Backend, otp_app: :koblenzomat
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/live/home_live.ex | Elixir | defmodule KoblenzomatWeb.HomeLive do
use KoblenzomatWeb, :live_view
alias Koblenzomat.Voting
@impl true
def mount(_params, _session, socket) do
theses = load_and_shuffle_theses()
socket = assign(socket, theses: theses, current: 0)
{:ok, socket}
end
@impl true
def handle_event("next", _params, socket) do
next = socket.assigns.current + 1
{:noreply, assign(socket, current: next)}
end
@impl true
def handle_event("choose", _params, socket) do
next = socket.assigns.current + 1
{:noreply, assign(socket, current: next)}
end
defp load_and_shuffle_theses do
# Get the first election and its theses, shuffle them
case Voting.list_elections_with_theses() do
[%{theses: theses} | _] -> Enum.shuffle(theses)
_ -> []
end
end
@impl true
def render(assigns) do
~H"""
<main
class="min-h-screen flex flex-col items-center justify-center relative overflow-hidden"
aria-label="Koblenz-O-Mat"
>
<div
class="absolute inset-0 z-[-10] bg-cover bg-center"
style="background-image: url('/images/koblenz-bg.png');"
aria-hidden="true"
>
</div>
<div
class="absolute inset-0 z-0 pointer-events-none"
style="backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);"
>
</div>
<div class="absolute inset-0 bg-black/30 z-10" aria-hidden="true"></div>
<header class="w-full max-w-4xl mx-auto text-center pt-8 md:pt-16 pb-8 z-10 relative">
<h1 class="text-5xl md:text-7xl font-bold tracking-tight text-white drop-shadow-lg">
Koblenz-O-Mat
</h1>
<h2 class="text-2xl md:text-3xl font-semibold mt-2 text-white/80 drop-shadow">
{gettext("Oberbürgermeisterwahl Koblenz 2025")}
</h2>
</header>
<section
class="bg-white/90 rounded-xl shadow-xl px-4 sm:px-8 py-10 max-w-sm sm:max-w-md md:max-w-2xl w-full mx-2 sm:mx-auto flex flex-col items-center relative z-10"
aria-labelledby="frage-titel"
>
<div
class="absolute -top-8 left-1/2 -translate-x-1/2 w-0 h-0 border-l-8 border-r-8 border-b-[32px] border-l-transparent border-r-transparent border-b-white/90"
aria-hidden="true"
>
</div>
<div class="w-full text-left mb-4">
<span id="frage-titel" class="font-semibold text-base text-slate-800">
{@current + 1}/{length(@theses)} {gettext("These")}
</span>
</div>
<div class="w-full text-left mb-8">
<span class="block text-2xl md:text-3xl font-medium text-slate-900 leading-snug">
{(Enum.at(@theses, @current) && Enum.at(@theses, @current).name) ||
gettext("No more theses.")}
</span>
<div class="mt-2 flex flex-wrap gap-2">
<%= for hashtag <- (Enum.at(@theses, @current) && Enum.at(@theses, @current).hashtags) || [] do %>
<span class="inline-block bg-cyan-100 text-cyan-800 rounded px-2 py-1 text-xs font-semibold">
#{hashtag.name}
</span>
<% end %>
</div>
</div>
<div
class="flex flex-col sm:flex-row gap-4 w-full justify-center mb-4"
role="group"
aria-labelledby="frage-titel"
>
<button
phx-click="choose"
phx-value-choice="disagree"
class="flex-1 bg-cyan-400 hover:bg-cyan-500 text-slate-900 font-semibold py-3 rounded-lg transition focus:outline focus:outline-2 focus:outline-cyan-700"
aria-label="Stimme nicht zu"
>
{gettext("stimme nicht zu")} 👎
</button>
<button
phx-click="choose"
phx-value-choice="neutral"
class="flex-1 bg-sky-200 hover:bg-sky-300 text-slate-900 font-semibold py-3 rounded-lg transition focus:outline focus:outline-2 focus:outline-cyan-700"
aria-label="Neutral"
>
{gettext("neutral")}
</button>
<button
phx-click="choose"
phx-value-choice="agree"
class="flex-1 bg-cyan-400 hover:bg-cyan-500 text-slate-900 font-semibold py-3 rounded-lg transition focus:outline focus:outline-2 focus:outline-cyan-700"
aria-label="Stimme zu"
>
👍 {gettext("stimme zu")}
</button>
</div>
</section>
<nav
aria-label="Frage-Fortschritt"
class="absolute bottom-10 left-1/2 -translate-x-1/2 flex gap-2 z-10"
>
<ol class="flex gap-2" role="list" aria-label="Frage-Fortschritt">
<%= for i <- 0..(length(@theses)-1) do %>
<li class={"w-3 h-3 rounded-full inline-block " <> if i == @current, do: "bg-white", else: "bg-white/30"}>
<span class="sr-only">{gettext("Frage")} {i + 1}</span>
</li>
<% end %>
</ol>
</nav>
<div class="absolute bottom-2 left-1/2 -translate-x-1/2 w-full max-w-2xl px-4 text-center z-10 pointer-events-none">
<span class="text-xs text-white/70 select-none" style="font-size: 0.7rem;">
{gettext(
"Alle Antworten werden anonymisiert gespeichert und können von jedem in einer Gesamtstatistik eingesehen werden."
)}
</span>
</div>
</main>
"""
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/router.ex | Elixir | defmodule KoblenzomatWeb.Router do
use KoblenzomatWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {KoblenzomatWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", KoblenzomatWeb do
pipe_through :browser
live "/", HomeLive, :index
# get "/", PageController, :home # moved to test only
end
# Other scopes may use custom stacks.
# scope "/api", KoblenzomatWeb do
# pipe_through :api
# end
# Enable LiveDashboard and Swoosh mailbox preview in development
if Application.compile_env(:koblenzomat, :dev_routes) do
# If you want to use the LiveDashboard in production, you should put
# it behind authentication and allow only admins to access it.
# If your application does not have an admins-only section yet,
# you can use Plug.BasicAuth to set up some basic authentication
# as long as you are also using SSL (which you should anyway).
import Phoenix.LiveDashboard.Router
scope "/dev" do
pipe_through :browser
live_dashboard "/dashboard", metrics: KoblenzomatWeb.Telemetry
forward "/mailbox", Plug.Swoosh.MailboxPreview
end
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/koblenzomat_web/telemetry.ex | Elixir | defmodule KoblenzomatWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
@impl true
def init(_arg) do
children = [
# Telemetry poller will execute the given period measurements
# every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics
{:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
# Add reporters as children of your supervision tree.
# {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
]
Supervisor.init(children, strategy: :one_for_one)
end
def metrics do
[
# Phoenix Metrics
summary("phoenix.endpoint.start.system_time",
unit: {:native, :millisecond}
),
summary("phoenix.endpoint.stop.duration",
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.start.system_time",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.exception.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.router_dispatch.stop.duration",
tags: [:route],
unit: {:native, :millisecond}
),
summary("phoenix.socket_connected.duration",
unit: {:native, :millisecond}
),
sum("phoenix.socket_drain.count"),
summary("phoenix.channel_joined.duration",
unit: {:native, :millisecond}
),
summary("phoenix.channel_handled_in.duration",
tags: [:event],
unit: {:native, :millisecond}
),
# Database Metrics
summary("koblenzomat.repo.query.total_time",
unit: {:native, :millisecond},
description: "The sum of the other measurements"
),
summary("koblenzomat.repo.query.decode_time",
unit: {:native, :millisecond},
description: "The time spent decoding the data received from the database"
),
summary("koblenzomat.repo.query.query_time",
unit: {:native, :millisecond},
description: "The time spent executing the query"
),
summary("koblenzomat.repo.query.queue_time",
unit: {:native, :millisecond},
description: "The time spent waiting for a database connection"
),
summary("koblenzomat.repo.query.idle_time",
unit: {:native, :millisecond},
description:
"The time the connection spent waiting before being checked out for the query"
),
# VM Metrics
summary("vm.memory.total", unit: {:byte, :kilobyte}),
summary("vm.total_run_queue_lengths.total"),
summary("vm.total_run_queue_lengths.cpu"),
summary("vm.total_run_queue_lengths.io")
]
end
defp periodic_measurements do
[
# A module, function and arguments to be invoked periodically.
# This function must call :telemetry.execute/3 and a metric must be added above.
# {KoblenzomatWeb, :count_users, []}
]
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
mix.exs | Elixir | defmodule Koblenzomat.MixProject do
use Mix.Project
def project do
[
app: :koblenzomat,
version: "0.1.0",
elixir: "~> 1.15",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
consolidate_protocols: Mix.env() != :dev,
aliases: aliases(),
deps: deps(),
listeners: [Phoenix.CodeReloader]
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Koblenzomat.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:tidewave, "~> 0.1", only: [:dev]},
{:igniter, "~> 0.5", only: [:dev, :test]},
{:phoenix, "~> 1.8.0-rc.0", override: true},
{:phoenix_ecto, "~> 4.5"},
{:ecto_sql, "~> 3.10"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 4.1"},
{:phoenix_live_reload, "~> 1.2", only: :dev},
{:phoenix_live_view, "~> 1.0"},
{:floki, ">= 0.30.0", only: :test},
{:phoenix_live_dashboard, "~> 0.8.3"},
{:esbuild, "~> 0.9", runtime: Mix.env() == :dev},
{:tailwind, "~> 0.3", runtime: Mix.env() == :dev},
{:heroicons,
github: "tailwindlabs/heroicons",
tag: "v2.1.1",
sparse: "optimized",
app: false,
compile: false,
depth: 1},
{:swoosh, "~> 1.16"},
{:req, "~> 0.5"},
{:telemetry_metrics, "~> 1.0"},
{:telemetry_poller, "~> 1.0"},
{:gettext, "~> 0.26"},
{:jason, "~> 1.2"},
{:dns_cluster, "~> 0.1.1"},
{:bandit, "~> 1.5"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to install project dependencies and perform other setup tasks, run:
#
# $ mix setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "ecto.setup", "assets.setup", "assets.build"],
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"],
"assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"],
"assets.build": ["tailwind koblenzomat", "esbuild koblenzomat"],
"assets.deploy": [
"tailwind koblenzomat --minify",
"esbuild koblenzomat --minify",
"phx.digest"
]
]
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/.formatter.exs | Elixir | [
import_deps: [:ecto_sql],
inputs: ["*.exs"]
]
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20250610132244_create_elections.exs | Elixir | defmodule Koblenzomat.Repo.Migrations.CreateElections do
use Ecto.Migration
def change do
create table(:elections, primary_key: false) do
add :id, :binary_id, primary_key: true
add :name, :string
timestamps(type: :utc_datetime)
end
create unique_index(:elections, [:name])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20250610132248_create_theses.exs | Elixir | defmodule Koblenzomat.Repo.Migrations.CreateTheses do
use Ecto.Migration
def change do
create table(:theses, primary_key: false) do
add :id, :binary_id, primary_key: true
add :name, :string
add :position, :integer, null: false
add :election_id,
references(:elections, type: :binary_id, on_delete: :delete_all),
null: false
timestamps(type: :utc_datetime)
end
create unique_index(:theses, [:name])
create index(:theses, [:election_id])
create unique_index(:theses, [:election_id, :position],
name: :theses_election_id_position_index
)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20250610132251_create_hashtags.exs | Elixir | defmodule Koblenzomat.Repo.Migrations.CreateHashtags do
use Ecto.Migration
def change do
create table(:hashtags, primary_key: false) do
add :id, :binary_id, primary_key: true
add :name, :string
timestamps(type: :utc_datetime)
end
create unique_index(:hashtags, [:name])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/migrations/20250610132253_create_hashtags_to_theses.exs | Elixir | defmodule Koblenzomat.Repo.Migrations.CreateHashtagsToTheses do
use Ecto.Migration
def change do
create table(:hashtags_to_theses, primary_key: false) do
add :id, :binary_id, primary_key: true
add :thesis_id, references(:theses, on_delete: :nothing, type: :binary_id)
add :hashtag_id, references(:hashtags, on_delete: :nothing, type: :binary_id)
timestamps(type: :utc_datetime)
end
create index(:hashtags_to_theses, [:thesis_id])
create index(:hashtags_to_theses, [:hashtag_id])
create unique_index(:hashtags_to_theses, [:thesis_id, :hashtag_id])
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/repo/seeds.exs | Elixir | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Koblenzomat.Repo.insert!(%Koblenzomat.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
alias Koblenzomat.{Repo, Hashtag, HashtagsToTheses}
seed_data = [
{"Koblenz soll neue Baugebiete ausweisen, auch wenn dafür Freiflächen genutzt werden müssen.",
["Stadtentwicklung", "Wohnen"]},
{"Die Innenstadt soll stärker verdichtet bebaut werden, statt neue Siedlungsflächen am Stadtrand zu schaffen.",
["Stadtentwicklung", "Wohnen"]},
{"Die Seilbahn über den Rhein soll über 2026 hinaus dauerhaft erhalten bleiben.",
["Tourismus", "Verkehr"]},
{"Koblenz soll die BUGA 2029 aktiv als Motor für Stadtentwicklungsprojekte nutzen.",
["Stadtentwicklung", "Kultur", "Tourismus"]},
{"Mehr ausgewiesene Fahrradstraßen und Radwege auch auf Kosten von Parkplätzen.",
["Mobilität", "Radverkehr"]},
{"Flächendeckend Tempo 30 als Regelgeschwindigkeit (Ausnahmen für Hauptachsen).",
["Mobilität", "Verkehr", "Sicherheit"]},
{"Höhere Parkgebühren in der Innenstadt, um Autoverkehr zu reduzieren.",
["Mobilität", "Auto", "Finanzen"]},
{"Die Fußgängerzone in der Innenstadt soll erweitert werden.",
["Mobilität", "Stadtentwicklung"]},
{"Der ÖPNV soll langfristig ticketfrei werden.", ["ÖPNV", "Mobilität", "Finanzen"]},
{"Die Stadt soll die Einführung eines Stadtbahn-/Straßenbahnsystems prüfen.",
["ÖPNV", "Infrastruktur"]},
{"Mehr öffentliche E-Ladesäulen im gesamten Stadtgebiet.",
["Energie", "Mobilität", "Klimaschutz"]},
{"Die Stadt soll zusätzliche Sozialwohnungen bauen bzw. bauen lassen.", ["Wohnen", "Soziales"]},
{"Bei Neubauprojekten soll ein fester Anteil bezahlbarer Wohnraum gesichert werden.",
["Wohnen", "Soziales"]},
{"Die Umwandlung von Wohnungen in Ferienwohnungen soll strenger geregelt werden.",
["Wohnen", "Stadtentwicklung", "Tourismus"]},
{"Kommunale Baugrundstücke bevorzugt an gemeinnützige oder genossenschaftliche Projekte vergeben.",
["Wohnen", "Soziales"]},
{"Gegen dauerhaften Leerstand von Wohnungen soll konsequent vorgegangen werden.",
["Wohnen", "Stadtentwicklung"]},
{"Neubau und Sanierung von Schulen und Sporthallen erhalten höchste Priorität.",
["Bildung", "Infrastruktur"]},
{"Alle Koblenzer Schulen sollen vollständig digital ausgestattet sein.",
["Bildung", "Digitalisierung"]},
{"Das Netz ganztägiger Schulangebote soll ausgeweitet werden.", ["Bildung", "Soziales"]},
{"Wohnortnahe Kita-Plätze sollen deutlich ausgebaut werden.", ["Kita", "Familie", "Soziales"]},
{"Die Stadtverwaltung soll bis 2030 sämtliche Bürgerdienste digital anbieten.",
["Digitalisierung", "Verwaltung"]},
{"Kostenloses öffentliches WLAN auf zentralen Plätzen einrichten.",
["Digitalisierung", "Infrastruktur"]},
{"Smart-City-Technologien wie intelligente Ampeln flächendeckend einführen.",
["Digitalisierung", "Infrastruktur", "Mobilität"]},
{"Eine städtische Bürger-App für Meldungen und Informationen einführen.",
["Digitalisierung", "Bürgerbeteiligung"]},
{"Erneuerbare Energien auf städtischen Flächen deutlich ausbauen.", ["Energie", "Klimaschutz"]},
{"Für alle Neubauten soll eine Solardachpflicht gelten.", ["Energie", "Klimaschutz"]},
{"Koblenz soll den Klimanotstand ausrufen und Klimaschutz priorisieren.",
["Klimaschutz", "Umwelt"]},
{"Einführung einer Umweltzone, die hochemittierende Fahrzeuge ausschließt.",
["Umwelt", "Mobilität"]},
{"Städtische Veranstaltungen sollen weitgehend auf Einwegplastik verzichten.",
["Umwelt", "Kultur"]},
{"Fluss- und Bachufer im Stadtgebiet sollen renaturiert werden.", ["Umwelt", "Klimaanpassung"]},
{"Die Gewerbesteuer soll gesenkt werden, um Unternehmen anzuziehen.",
["Wirtschaft", "Finanzen"]},
{"Stadtmarketing und Tourismusförderung sollen ausgebaut werden.", ["Wirtschaft", "Tourismus"]},
{"Verkaufsoffene Sonntage sollen ermöglicht werden.", ["Wirtschaft", "Einzelhandel"]},
{"Videoüberwachung an öffentlichen Plätzen soll ausgeweitet werden.",
["Sicherheit", "Überwachung"]},
{"Nächtliche Alkoholverbote auf ausgewählten Plätzen einführen.", ["Sicherheit", "Soziales"]},
{"Präventionsprogramme gegen Gewalt und Drogen für Jugendliche ausbauen.",
["Soziales", "Jugend", "Sicherheit"]},
{"Mehr kostenlose Beratungs- und Hilfsangebote für obdachlose Menschen.",
["Soziales", "Wohnen"]},
{"Zusätzliche Jugendzentren und Freizeiteinrichtungen schaffen.", ["Soziales", "Jugend"]},
{"Integration Zugewanderter durch städtische Programme stärker fördern.",
["Integration", "Soziales"]},
{"Ein Sozialticket für den ÖPNV einführen.", ["ÖPNV", "Soziales", "Mobilität"]},
{"Kulturelle Einrichtungen sollen höhere städtische Zuschüsse erhalten.",
["Kultur", "Finanzen"]},
{"Verwaltungsprozesse sollen vereinfacht und Genehmigungen beschleunigt werden.",
["Verwaltung", "Digitalisierung"]},
{"Einführung eines Bürgerhaushalts mit Entscheidungsrecht der Bevölkerung.",
["Bürgerbeteiligung", "Finanzen"]},
{"Arbeitsbedingungen und Bezahlung im Rathaus verbessern, um Fachkräfte zu gewinnen.",
["Verwaltung", "Personal"]},
{"Die Stadt soll keine neuen Schulden aufnehmen und einen ausgeglichenen Haushalt anstreben.",
["Finanzen", "Haushalt"]},
{"Notwendige Investitionen sollen notfalls auch kreditfinanziert umgesetzt werden.",
["Finanzen", "Infrastruktur"]},
{"Die Grundsteuer soll gesenkt werden.", ["Finanzen", "Wohnen"]},
{"Kultur- und Sportförderung soll auch in Haushaltskrisen nicht gekürzt werden.",
["Kultur", "Sport", "Finanzen"]},
{"Bundeswehrstandorte in Koblenz sollen aktiv unterstützt und ausgebaut werden.",
["Bundeswehr", "Wirtschaft", "Sicherheit"]},
{"Bürgerentscheide zu großen Projekten sollen ermöglicht werden, wenn ein Quorum erreicht wird.",
["DirekteDemokratie", "Bürgerbeteiligung"]}
]
# Insert hashtags
hashtags =
seed_data
|> Enum.flat_map(fn {_, tags} -> tags end)
|> Enum.uniq()
|> Enum.map(fn tag ->
Repo.insert!(%Hashtag{name: tag}, on_conflict: :nothing, conflict_target: :name)
Repo.get_by!(Hashtag, name: tag)
end)
hashtag_map = Map.new(hashtags, &{&1.name, &1.id})
# Create an election for all theses
election = Repo.insert!(%Koblenzomat.Election{name: "Seed Election"})
# Insert theses and associations
for {thesis_text, tags} <- seed_data do
{:ok, thesis} =
Koblenzomat.Voting.create_thesis(%{
name: thesis_text,
election_id: election.id
})
for tag <- tags do
Repo.insert!(%HashtagsToTheses{thesis_id: thesis.id, hashtag_id: hashtag_map[tag]})
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/koblenzomat_web/controllers/error_html_test.exs | Elixir | defmodule KoblenzomatWeb.ErrorHTMLTest do
use KoblenzomatWeb.ConnCase, async: true
# Bring render_to_string/4 for testing custom views
import Phoenix.Template, only: [render_to_string: 4]
test "renders 404.html" do
assert render_to_string(KoblenzomatWeb.ErrorHTML, "404", "html", []) == "Not Found"
end
test "renders 500.html" do
assert render_to_string(KoblenzomatWeb.ErrorHTML, "500", "html", []) ==
"Internal Server Error"
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/koblenzomat_web/controllers/error_json_test.exs | Elixir | defmodule KoblenzomatWeb.ErrorJSONTest do
use KoblenzomatWeb.ConnCase, async: true
test "renders 404" do
assert KoblenzomatWeb.ErrorJSON.render("404.json", %{}) == %{errors: %{detail: "Not Found"}}
end
test "renders 500" do
assert KoblenzomatWeb.ErrorJSON.render("500.json", %{}) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/koblenzomat_web/controllers/page_controller_test.exs | Elixir | defmodule KoblenzomatWeb.PageControllerTest do
use KoblenzomatWeb.ConnCase
test "GET /", %{conn: conn} do
conn = get(conn, ~p"/")
assert html_response(conn, 200) =~ "Koblenz-O-Mat"
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/koblenzomat_web/live/home_live_test.exs | Elixir | defmodule KoblenzomatWeb.HomeLiveTest do
use KoblenzomatWeb.ConnCase, async: true
import Phoenix.LiveViewTest
test "renders and shuffles through theses", %{conn: conn} do
{:ok, view, _html} = live(conn, "/")
assert has_element?(view, "main[aria-label=\"Koblenz-O-Mat\"]")
assert has_element?(view, "button", "stimme zu")
assert has_element?(view, "button", "neutral")
assert has_element?(view, "button", "stimme nicht zu")
end
test "clicking a choice advances to the next thesis", %{conn: conn} do
{:ok, view, _html} = live(conn, "/")
# Get the current thesis text
current_thesis = render(view)
# Click 'stimme zu'
assert view |> element("button[phx-value-choice=agree]") |> render_click()
next_thesis = render(view)
assert current_thesis != next_thesis
# Click 'neutral'
assert view |> element("button[phx-value-choice=neutral]") |> render_click()
next_thesis2 = render(view)
assert next_thesis != next_thesis2
# Click 'stimme nicht zu'
assert view |> element("button[phx-value-choice=disagree]") |> render_click()
next_thesis3 = render(view)
assert next_thesis2 != next_thesis3
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/seeds_test.exs | Elixir | defmodule Koblenzomat.SeedsTest do
use Koblenzomat.DataCase, async: true
alias Koblenzomat.{Repo, Thesis, Hashtag, HashtagsToTheses}
@seed_data [
{"Koblenz soll neue Baugebiete ausweisen, auch wenn dafür Freiflächen genutzt werden müssen.",
["Stadtentwicklung", "Wohnen"]},
{"Die Innenstadt soll stärker verdichtet bebaut werden, statt neue Siedlungsflächen am Stadtrand zu schaffen.",
["Stadtentwicklung", "Wohnen"]},
{"Die Seilbahn über den Rhein soll über 2026 hinaus dauerhaft erhalten bleiben.",
["Tourismus", "Verkehr"]},
{"Koblenz soll die BUGA 2029 aktiv als Motor für Stadtentwicklungsprojekte nutzen.",
["Stadtentwicklung", "Kultur", "Tourismus"]},
{"Mehr ausgewiesene Fahrradstraßen und Radwege auch auf Kosten von Parkplätzen.",
["Mobilität", "Radverkehr"]},
{"Flächendeckend Tempo 30 als Regelgeschwindigkeit (Ausnahmen für Hauptachsen).",
["Mobilität", "Verkehr", "Sicherheit"]},
{"Höhere Parkgebühren in der Innenstadt, um Autoverkehr zu reduzieren.",
["Mobilität", "Auto", "Finanzen"]},
{"Die Fußgängerzone in der Innenstadt soll erweitert werden.",
["Mobilität", "Stadtentwicklung"]},
{"Der ÖPNV soll langfristig ticketfrei werden.", ["ÖPNV", "Mobilität", "Finanzen"]},
{"Die Stadt soll die Einführung eines Stadtbahn-/Straßenbahnsystems prüfen.",
["ÖPNV", "Infrastruktur"]},
{"Mehr öffentliche E-Ladesäulen im gesamten Stadtgebiet.",
["Energie", "Mobilität", "Klimaschutz"]},
{"Die Stadt soll zusätzliche Sozialwohnungen bauen bzw. bauen lassen.",
["Wohnen", "Soziales"]},
{"Bei Neubauprojekten soll ein fester Anteil bezahlbarer Wohnraum gesichert werden.",
["Wohnen", "Soziales"]},
{"Die Umwandlung von Wohnungen in Ferienwohnungen soll strenger geregelt werden.",
["Wohnen", "Stadtentwicklung", "Tourismus"]},
{"Kommunale Baugrundstücke bevorzugt an gemeinnützige oder genossenschaftliche Projekte vergeben.",
["Wohnen", "Soziales"]},
{"Gegen dauerhaften Leerstand von Wohnungen soll konsequent vorgegangen werden.",
["Wohnen", "Stadtentwicklung"]},
{"Neubau und Sanierung von Schulen und Sporthallen erhalten höchste Priorität.",
["Bildung", "Infrastruktur"]},
{"Alle Koblenzer Schulen sollen vollständig digital ausgestattet sein.",
["Bildung", "Digitalisierung"]},
{"Das Netz ganztägiger Schulangebote soll ausgeweitet werden.", ["Bildung", "Soziales"]},
{"Wohnortnahe Kita-Plätze sollen deutlich ausgebaut werden.",
["Kita", "Familie", "Soziales"]},
{"Die Stadtverwaltung soll bis 2030 sämtliche Bürgerdienste digital anbieten.",
["Digitalisierung", "Verwaltung"]},
{"Kostenloses öffentliches WLAN auf zentralen Plätzen einrichten.",
["Digitalisierung", "Infrastruktur"]},
{"Smart-City-Technologien wie intelligente Ampeln flächendeckend einführen.",
["Digitalisierung", "Infrastruktur", "Mobilität"]},
{"Eine städtische Bürger-App für Meldungen und Informationen einführen.",
["Digitalisierung", "Bürgerbeteiligung"]},
{"Erneuerbare Energien auf städtischen Flächen deutlich ausbauen.",
["Energie", "Klimaschutz"]},
{"Für alle Neubauten soll eine Solardachpflicht gelten.", ["Energie", "Klimaschutz"]},
{"Koblenz soll den Klimanotstand ausrufen und Klimaschutz priorisieren.",
["Klimaschutz", "Umwelt"]},
{"Einführung einer Umweltzone, die hochemittierende Fahrzeuge ausschließt.",
["Umwelt", "Mobilität"]},
{"Städtische Veranstaltungen sollen weitgehend auf Einwegplastik verzichten.",
["Umwelt", "Kultur"]},
{"Fluss- und Bachufer im Stadtgebiet sollen renaturiert werden.",
["Umwelt", "Klimaanpassung"]},
{"Die Gewerbesteuer soll gesenkt werden, um Unternehmen anzuziehen.",
["Wirtschaft", "Finanzen"]},
{"Stadtmarketing und Tourismusförderung sollen ausgebaut werden.",
["Wirtschaft", "Tourismus"]},
{"Verkaufsoffene Sonntage sollen ermöglicht werden.", ["Wirtschaft", "Einzelhandel"]},
{"Videoüberwachung an öffentlichen Plätzen soll ausgeweitet werden.",
["Sicherheit", "Überwachung"]},
{"Nächtliche Alkoholverbote auf ausgewählten Plätzen einführen.", ["Sicherheit", "Soziales"]},
{"Präventionsprogramme gegen Gewalt und Drogen für Jugendliche ausbauen.",
["Soziales", "Jugend", "Sicherheit"]},
{"Mehr kostenlose Beratungs- und Hilfsangebote für obdachlose Menschen.",
["Soziales", "Wohnen"]},
{"Zusätzliche Jugendzentren und Freizeiteinrichtungen schaffen.", ["Soziales", "Jugend"]},
{"Integration Zugewanderter durch städtische Programme stärker fördern.",
["Integration", "Soziales"]},
{"Ein Sozialticket für den ÖPNV einführen.", ["ÖPNV", "Soziales", "Mobilität"]},
{"Kulturelle Einrichtungen sollen höhere städtische Zuschüsse erhalten.",
["Kultur", "Finanzen"]},
{"Verwaltungsprozesse sollen vereinfacht und Genehmigungen beschleunigt werden.",
["Verwaltung", "Digitalisierung"]},
{"Einführung eines Bürgerhaushalts mit Entscheidungsrecht der Bevölkerung.",
["Bürgerbeteiligung", "Finanzen"]},
{"Arbeitsbedingungen und Bezahlung im Rathaus verbessern, um Fachkräfte zu gewinnen.",
["Verwaltung", "Personal"]},
{"Die Stadt soll keine neuen Schulden aufnehmen und einen ausgeglichenen Haushalt anstreben.",
["Finanzen", "Haushalt"]},
{"Notwendige Investitionen sollen notfalls auch kreditfinanziert umgesetzt werden.",
["Finanzen", "Infrastruktur"]},
{"Die Grundsteuer soll gesenkt werden.", ["Finanzen", "Wohnen"]},
{"Kultur- und Sportförderung soll auch in Haushaltskrisen nicht gekürzt werden.",
["Kultur", "Sport", "Finanzen"]},
{"Bundeswehrstandorte in Koblenz sollen aktiv unterstützt und ausgebaut werden.",
["Bundeswehr", "Wirtschaft", "Sicherheit"]},
{"Bürgerentscheide zu großen Projekten sollen ermöglicht werden, wenn ein Quorum erreicht wird.",
["DirekteDemokratie", "Bürgerbeteiligung"]}
]
test "seeds can be inserted and associated" do
election = Repo.insert!(%Koblenzomat.Election{name: "Seed Q"})
# Insert hashtags
hashtags =
@seed_data
|> Enum.flat_map(fn {_, tags} -> tags end)
|> Enum.uniq()
|> Enum.map(fn tag ->
Repo.insert!(
%Hashtag{name: tag},
on_conflict: :nothing,
conflict_target: :name
)
Repo.get_by!(Hashtag, name: tag)
end)
hashtag_map = Map.new(hashtags, &{&1.name, &1.id})
# Insert theses and associations
Enum.with_index(@seed_data, 1)
|> Enum.each(fn {{thesis_text, tags}, pos} ->
Repo.insert!(
%Thesis{name: thesis_text, position: pos, election_id: election.id},
on_conflict: :nothing,
conflict_target: [:name]
)
thesis = Repo.get_by!(Thesis, name: thesis_text)
for tag <- tags do
Repo.insert!(
%HashtagsToTheses{thesis_id: thesis.id, hashtag_id: hashtag_map[tag]},
on_conflict: :nothing,
conflict_target: [:thesis_id, :hashtag_id]
)
end
end)
assert Repo.aggregate(Thesis, :count, :id) == length(@seed_data)
assert Repo.aggregate(Hashtag, :count, :id) ==
@seed_data |> Enum.flat_map(fn {_, tags} -> tags end) |> Enum.uniq() |> length()
assert Repo.aggregate(HashtagsToTheses, :count, :id) ==
Enum.reduce(@seed_data, 0, fn {_, tags}, acc -> acc + length(tags) end)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/support/conn_case.ex | Elixir | defmodule KoblenzomatWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use KoblenzomatWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# The default endpoint for testing
@endpoint KoblenzomatWeb.Endpoint
use KoblenzomatWeb, :verified_routes
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import KoblenzomatWeb.ConnCase
end
end
setup tags do
Koblenzomat.DataCase.setup_sandbox(tags)
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/support/data_case.ex | Elixir | defmodule Koblenzomat.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use Koblenzomat.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Koblenzomat.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Koblenzomat.DataCase
end
end
setup tags do
Koblenzomat.DataCase.setup_sandbox(tags)
:ok
end
@doc """
Sets up the sandbox based on the test tags.
"""
def setup_sandbox(tags) do
pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Koblenzomat.Repo, shared: not tags[:async])
on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, changeset} = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/test_helper.exs | Elixir | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Koblenzomat.Repo, :manual)
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/voting_test.exs | Elixir | defmodule Koblenzomat.VotingTest do
@moduledoc """
Tests for the Voting context, covering election, thesis, hashtag, and their associations.
These tests ensure that the core business logic for creating and validating elections and theses works as expected, including position uniqueness and auto-increment behavior.
"""
use Koblenzomat.DataCase
alias Koblenzomat.{Election, Thesis, Hashtag, HashtagsToTheses}
describe "election schema" do
test "valid changeset" do
changeset = Election.changeset(%Election{}, %{name: "Q1"})
assert changeset.valid?
end
end
describe "thesis schema" do
test "valid changeset" do
election = %Koblenzomat.Election{id: Ecto.UUID.generate(), name: "Q1"}
changeset =
Thesis.changeset(%Thesis{}, %{name: "T1", position: 1, election_id: election.id})
assert changeset.valid?
end
end
describe "hashtag schema" do
test "valid changeset" do
changeset = Hashtag.changeset(%Hashtag{}, %{name: "H1"})
assert changeset.valid?
end
end
describe "hashtags_to_theses schema" do
test "valid changeset" do
changeset = HashtagsToTheses.changeset(%HashtagsToTheses{}, %{name: "HT1"})
assert changeset.valid?
end
end
describe "thesis position uniqueness and requirements" do
setup do
election = Koblenzomat.Repo.insert!(%Koblenzomat.Election{name: "Q1"})
%{election: election}
end
test "position is required", %{election: election} do
changeset = Thesis.changeset(%Thesis{}, %{name: "T1", election_id: election.id})
refute changeset.valid?
assert {:position, {"can't be blank", [validation: :required]}} in changeset.errors
end
test "position is unique within election", %{election: election} do
attrs = %{name: "T1", position: 1, election_id: election.id}
changeset1 = Thesis.changeset(%Thesis{}, attrs)
{:ok, _} = Koblenzomat.Repo.insert(changeset1)
changeset2 =
Thesis.changeset(%Thesis{}, %{name: "T2", position: 1, election_id: election.id})
{:error, changeset2} = Koblenzomat.Repo.insert(changeset2)
assert {:position,
{"has already been taken",
[constraint: :unique, constraint_name: "theses_election_id_position_index"]}} in changeset2.errors
end
end
describe "thesis auto-increment position" do
test "auto-increments position within election" do
election = Koblenzomat.Repo.insert!(%Koblenzomat.Election{name: "QAuto"})
attrs = %{name: "T1", election_id: election.id}
{:ok, thesis1} = Koblenzomat.Voting.create_thesis(attrs)
{:ok, thesis2} =
Koblenzomat.Voting.create_thesis(%{
name: "T2",
election_id: election.id
})
assert thesis1.position == 1
assert thesis2.position == 2
end
end
end
| wintermeyer/koblenzomat | 0 | Wahlentscheidungshilfe für die OB Wahl in Koblenz | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
.formatter.exs | Elixir | # Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/mix/tasks/phx_gen_tailwind.ex | Elixir | defmodule Mix.Tasks.Phx.Gen.Tailwind do
@shortdoc "Generates controller, views, and context for an HTML resource with Tailwind CSS"
@moduledoc """
Generates controller, views, and context for an HTML resource with
Tailwind CSS.
mix phx.gen.tailwind Accounts User users name:string age:integer
The first argument is the context module followed by the schema module
and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for
the given resource. A context often holds many related resources.
Therefore, if the context already exists, it will be augmented with
functions for the given resource.
> Note: A resource may also be split
> over distinct contexts (such as `Accounts.User` and `Payments.User`).
The schema is responsible for mapping the database fields into an
Elixir struct. It is followed by an optional list of attributes,
with their respective names and types. See `mix tailwind.gen.schema`
for more information on attributes.
Overall, this generator will add the following files to `lib/`:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with an `users` table
* a view in `lib/app_web/views/user_view.ex`
* a controller in `lib/app_web/controllers/user_controller.ex`
* default CRUD templates in `lib/app_web/templates/user`
## The context app
A migration file for the repository and test files for the context and
controller features will also be generated.
The location of the web files (controllers, views, templates, etc) in an
umbrella application will vary based on the `:context_app` config located
in your applications `:generators` configuration. When set, the Phoenix
generators will generate web files directly in your lib and test folders
since the application is assumed to be isolated to web specific functionality.
If `:context_app` is not set, the generators will place web related lib
and test files in a `web/` directory since the application is assumed
to be handling both web and domain specific functionality.
Example configuration:
config :my_app_web, :generators, context_app: :my_app
Alternatively, the `--context-app` option may be supplied to the generator:
mix phx.gen.tailwind Sales User users --context-app warehouse
## Web namespace
By default, the controller and view will be namespaced by the schema name.
You can customize the web module namespace by passing the `--web` flag with a
module name, for example:
mix phx.gen.tailwind Sales User users --web Sales
Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and
`lib/app_web/views/sales/user_view.ex`.
## Customising the context, schema, tables and migrations
In some cases, you may wish to bootstrap HTML templates, controllers,
and controller tests, but leave internal implementation of the context
or schema to yourself. You can use the `--no-context` and `--no-schema`
flags for file generation control.
You can also change the table name or configure the migrations to
use binary ids for primary keys, see `mix tailwind.gen.schema` for more
information.
"""
use Mix.Task
alias Mix.Phoenix.{Context, Schema}
alias Mix.Tasks.Phx.Gen
@doc false
def run(args) do
if Mix.Project.umbrella?() do
Mix.raise "mix phx.gen.tailwind must be invoked from within your *_web application root directory"
end
{context, schema} = Gen.Context.build(args)
Gen.Context.prompt_for_code_injection(context)
binding = [context: context, schema: schema, inputs: inputs(schema)]
paths = [:phx_tailwind_generators, :phoenix]
prompt_for_conflicts(context)
context
|> copy_new_files(paths, binding)
|> inject_error_helper(paths, binding)
|> print_shell_instructions()
end
defp prompt_for_conflicts(context) do
context
|> files_to_be_generated()
|> Kernel.++(context_files(context))
|> Mix.Phoenix.prompt_for_conflicts()
end
defp context_files(%Context{generate?: true} = context) do
Gen.Context.files_to_be_generated(context)
end
defp context_files(%Context{generate?: false}) do
[]
end
@doc false
def files_to_be_generated(%Context{schema: schema, context_app: context_app}) do
web_prefix = Mix.Phoenix.web_path(context_app)
test_prefix = Mix.Phoenix.web_test_path(context_app)
web_path = to_string(schema.web_path)
[
{:eex, "controller.ex", Path.join([web_prefix, "controllers", web_path, "#{schema.singular}_controller.ex"])},
{:eex, "edit.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "edit.html.eex"])},
{:eex, "form.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "form.html.eex"])},
{:eex, "index.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "index.html.eex"])},
{:eex, "new.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "new.html.eex"])},
{:eex, "show.html.eex", Path.join([web_prefix, "templates", web_path, schema.singular, "show.html.eex"])},
{:eex, "view.ex", Path.join([web_prefix, "views", web_path, "#{schema.singular}_view.ex"])},
{:eex, "controller_test.exs", Path.join([test_prefix, "controllers", web_path, "#{schema.singular}_controller_test.exs"])},
]
end
@doc false
def copy_new_files(%Context{} = context, paths, binding) do
files = files_to_be_generated(context)
Mix.Phoenix.copy_from(paths, "priv/templates/phx.gen.tailwind", binding, files)
if context.generate?, do: Gen.Context.copy_new_files(context, paths, binding)
context
end
@doc false
def print_shell_instructions(%Context{schema: schema, context_app: ctx_app} = context) do
if schema.web_namespace do
Mix.shell().info """
Add the resource to your #{schema.web_namespace} :browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
scope "/#{schema.web_path}", #{inspect Module.concat(context.web_module, schema.web_namespace)}, as: :#{schema.web_path} do
pipe_through :browser
...
resources "/#{schema.plural}", #{inspect schema.alias}Controller
end
"""
else
Mix.shell().info """
Add the resource to your browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
resources "/#{schema.plural}", #{inspect schema.alias}Controller
"""
end
if context.generate?, do: Gen.Context.print_shell_instructions(context)
end
@doc false
def inputs(%Schema{} = schema) do
Enum.map(schema.attrs, fn
{_, {:references, _}} ->
{nil, nil, nil}
{key, :integer} ->
{label(key), ~s(<%= number_input f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :float} ->
{label(key), ~s(<%= number_input f, #{inspect(key)}, step: "any", class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :decimal} ->
{label(key), ~s(<%= number_input f, #{inspect(key)}, step: "any", class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :boolean} ->
{label(key), ~s(<%= checkbox f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :text} ->
{label(key), ~s(<%= textarea f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :date} ->
{label(key), ~s(<%= date_select f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :time} ->
{label(key), ~s(<%= time_select f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :utc_datetime} ->
{label(key), ~s(<%= datetime_select f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, :naive_datetime} ->
{label(key), ~s(<%= datetime_select f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, {:array, :integer}} ->
{label(key), ~s(<%= multiple_select f, #{inspect(key)}, ["1": 1, "2": 2], class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
{key, {:array, _}} ->
{label(key), ~s(<%= multiple_select f, #{inspect(key)}, ["Option 1": "option1", "Option 2": "option2"] %>), error(key)}
{key, _} ->
{label(key), ~s(<%= text_input f, #{inspect(key)}, class: "max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md" %>), error(key)}
end)
end
defp label(key) do
~s(<%= label f, #{inspect(key)}, class: "block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2" %>)
end
defp error(field) do
~s(<%= tailwind_error_tag f, #{inspect(field)} %>)
end
defp inject_error_helper(%Context{context_app: ctx_app} = context, _paths, _binding) do
web_prefix = Mix.Phoenix.web_path(ctx_app)
file_path = Path.join(web_prefix, "views/error_helpers.ex")
"""
def tailwind_error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:p, translate_error(error),
class: "mt-2 text-sm text-red-500",
phx_feedback_for: input_name(form, field)
)
end)
end
"""
|> inject_before_final_end(file_path)
context
end
defp inject_before_final_end(content_to_inject, file_path) do
with {:ok, file} <- read_file(file_path),
{:ok, new_file} <- PhxTailwindGenerators.inject_before_final_end(file, content_to_inject) do
print_injecting(file_path)
File.write!(file_path, new_file)
else
:already_injected ->
:ok
{:error, {:file_read_error, _}} ->
:ok
# print_injecting(file_path)
#
# print_unable_to_read_file_error(
# file_path,
# """
# Please add the following to the end of your equivalent
# #{Path.relative_to_cwd(file_path)} module:
# #{indent_spaces(content_to_inject, 2)}
# """
# )
end
end
defp read_file(file_path) do
case File.read(file_path) do
{:ok, file} -> {:ok, file}
{:error, reason} -> {:error, {:file_read_error, reason}}
end
end
defp print_injecting(file_path, suffix \\ []) do
Mix.shell().info([:green, "* injecting ", :reset, Path.relative_to_cwd(file_path), suffix])
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
lib/phx_tailwind_generators.ex | Elixir | defmodule PhxTailwindGenerators do
@moduledoc """
Documentation for `PhxTailwindGenerators`.
"""
@doc """
Injects snippet before the final end in a file
"""
@spec inject_before_final_end(String.t(), String.t()) :: {:ok, String.t()} | :already_injected
def inject_before_final_end(code, code_to_inject) when is_binary(code) and is_binary(code_to_inject) do
if String.contains?(code, code_to_inject) do
:already_injected
else
new_code =
code
|> String.trim_trailing()
|> String.trim_trailing("end")
|> Kernel.<>(code_to_inject)
|> Kernel.<>("end\n")
{:ok, new_code}
end
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
mix.exs | Elixir | defmodule PhxTailwindGenerators.MixProject do
use Mix.Project
def project do
[
app: :phx_tailwind_generators,
version: "0.1.7",
elixir: "~> 1.11",
start_permanent: Mix.env() == :prod,
deps: deps(),
description: "Generators to create templates with Tailwind CSS.",
name: "PhxTailwindGenerators",
package: %{
maintainers: ["Stefan Wintermeyer"],
licenses: ["MIT"],
links: %{
github: "https://github.com/wintermeyer/phx_tailwind_generators"
}
},
source_url: "https://github.com/wintermeyer/phx_tailwind_generators",
homepage_url: "https://github.com/wintermeyer/phx_tailwind_generators"
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:phoenix, ">= 1.5.7"},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false}
]
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/templates/phx.gen.tailwind/controller.ex | Elixir | defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>Controller do
use <%= inspect context.web_module %>, :controller
alias <%= inspect context.module %>
alias <%= inspect schema.module %>
def index(conn, _params) do
<%= schema.plural %> = <%= inspect context.alias %>.list_<%= schema.plural %>()
render(conn, "index.html", <%= schema.plural %>: <%= schema.plural %>)
end
def new(conn, _params) do
changeset = <%= inspect context.alias %>.change_<%= schema.singular %>(%<%= inspect schema.alias %>{})
render(conn, "new.html", changeset: changeset)
end
def create(conn, %{<%= inspect schema.singular %> => <%= schema.singular %>_params}) do
case <%= inspect context.alias %>.create_<%= schema.singular %>(<%= schema.singular %>_params) do
{:ok, <%= schema.singular %>} ->
conn
|> put_flash(:info, "<%= schema.human_singular %> created successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
render(conn, "show.html", <%= schema.singular %>: <%= schema.singular %>)
end
def edit(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
changeset = <%= inspect context.alias %>.change_<%= schema.singular %>(<%= schema.singular %>)
render(conn, "edit.html", <%= schema.singular %>: <%= schema.singular %>, changeset: changeset)
end
def update(conn, %{"id" => id, <%= inspect schema.singular %> => <%= schema.singular %>_params}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
case <%= inspect context.alias %>.update_<%= schema.singular %>(<%= schema.singular %>, <%= schema.singular %>_params) do
{:ok, <%= schema.singular %>} ->
conn
|> put_flash(:info, "<%= schema.human_singular %> updated successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "edit.html", <%= schema.singular %>: <%= schema.singular %>, changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
{:ok, _<%= schema.singular %>} = <%= inspect context.alias %>.delete_<%= schema.singular %>(<%= schema.singular %>)
conn
|> put_flash(:info, "<%= schema.human_singular %> deleted successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :index))
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/templates/phx.gen.tailwind/controller_test.exs | Elixir | defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>ControllerTest do
use <%= inspect context.web_module %>.ConnCase
alias <%= inspect context.module %>
@create_attrs <%= inspect schema.params.create %>
@update_attrs <%= inspect schema.params.update %>
@invalid_attrs <%= inspect for {key, _} <- schema.params.create, into: %{}, do: {key, nil} %>
def fixture(:<%= schema.singular %>) do
{:ok, <%= schema.singular %>} = <%= inspect context.alias %>.create_<%= schema.singular %>(@create_attrs)
<%= schema.singular %>
end
describe "index" do
test "lists all <%= schema.plural %>", %{conn: conn} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :index))
assert html_response(conn, 200) =~ "Listing <%= schema.human_plural %>"
end
end
describe "new <%= schema.singular %>" do
test "renders form", %{conn: conn} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :new))
assert html_response(conn, 200) =~ "New <%= schema.human_singular %>"
end
end
describe "create <%= schema.singular %>" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post(conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @create_attrs)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, id)
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, id))
assert html_response(conn, 200) =~ "Show <%= schema.human_singular %>"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @invalid_attrs)
assert html_response(conn, 200) =~ "New <%= schema.human_singular %>"
end
end
describe "edit <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "renders form for editing chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :edit, <%= schema.singular %>))
assert html_response(conn, 200) =~ "Edit <%= schema.human_singular %>"
end
end
describe "update <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "redirects when data is valid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = put(conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @update_attrs)
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>)
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))<%= if schema.string_attr do %>
assert html_response(conn, 200) =~ <%= inspect Mix.Phoenix.Schema.default_param(schema, :update) %><% else %>
assert html_response(conn, 200)<% end %>
end
test "renders errors when data is invalid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = put(conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @invalid_attrs)
assert html_response(conn, 200) =~ "Edit <%= schema.human_singular %>"
end
end
describe "delete <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "deletes chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = delete(conn, Routes.<%= schema.route_helper %>_path(conn, :delete, <%= schema.singular %>))
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :index)
assert_error_sent 404, fn ->
get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
end
end
end
defp create_<%= schema.singular %>(_) do
<%= schema.singular %> = fixture(:<%= schema.singular %>)
%{<%= schema.singular %>: <%= schema.singular %>}
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
priv/templates/phx.gen.tailwind/view.ex | Elixir | defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>View do
use <%= inspect context.web_module %>, :view
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/phx_tailwind_generators_test.exs | Elixir | defmodule PhxTailwindGeneratorsTest do
use ExUnit.Case
doctest PhxTailwindGenerators
test "greets the world" do
assert PhxTailwindGenerators.hello() == :world
end
end
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
test/test_helper.exs | Elixir | ExUnit.start()
| wintermeyer/phx_tailwind_generators | 110 | Scaffold Generator which uses TailwindCSS. | Elixir | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
entrypoint.sh | Shell | #!/bin/sh -l
set -e
file_name=$1
tag_version=$2
echo "\nInput file name: $file_name : $tag_version"
echo "Git Head Ref: ${GITHUB_HEAD_REF}"
echo "Git Base Ref: ${GITHUB_BASE_REF}"
echo "Git Event Name: ${GITHUB_EVENT_NAME}"
echo "\nStarting Git Operations"
git config --global user.email "Bump-N-Tag@github-action.com"
git config --global user.name "Bump-N-Tag App"
github_ref=""
if test "${GITHUB_EVENT_NAME}" = "push"
then
github_ref=${GITHUB_REF}
else
github_ref=${GITHUB_HEAD_REF}
git checkout $github_ref
fi
echo "Git Checkout"
perl -i -pe 's/version: \"\d+\.\d+\.\K(\d+)/ $1+1 /e' mix.exs
git add -A
git commit -m "Incremented minor version" -m "[skip ci]"
git show-ref
echo "Git Push"
git push --follow-tags "https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" HEAD:$github_ref
echo "\nEnd of Action\n\n"
exit 0 | wintermeyer/version-bump | 0 | GitHub Action which bumps the version number. | Shell | wintermeyer | Stefan Wintermeyer | Wintermeyer Consulting |
build.gradle.kts | Kotlin | plugins {
kotlin("jvm") version "2.2.21"
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.wire:wire-apps-jvm-sdk:0.0.19")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
// Ktor (REQUIRED once you add HTTP features)
implementation("io.ktor:ktor-client-core:2.3.12")
implementation("io.ktor:ktor-client-cio:2.3.12")
implementation("org.slf4j:slf4j-simple:2.0.13")
}
application {
mainClass.set("MainKt")
}
kotlin {
jvmToolchain(17)
}
| wireapp/Appy | 0 | Appy is a tiny smart assistant for Wire! Mention @Appy to get jokes, weather updates, calculations, timers, echoes, . A playful demo bot built using the Wire Apps SDK | Kotlin | wireapp | Wire Swiss GmbH | |
settings.gradle.kts | Kotlin | plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "Appy" | wireapp/Appy | 0 | Appy is a tiny smart assistant for Wire! Mention @Appy to get jokes, weather updates, calculations, timers, echoes, . A playful demo bot built using the Wire Apps SDK | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/Main.kt | Kotlin | import com.wire.sdk.WireAppSdk
import com.wire.sdk.WireEventsHandlerSuspending
import com.wire.sdk.model.*
import kotlinx.coroutines.*
import java.io.File
import java.net.URL
import java.time.LocalDate
import java.time.format.TextStyle
import java.util.*
import kotlin.math.round
import kotlin.math.roundToInt
import com.wire.sdk.model.AssetResource
import com.wire.sdk.model.asset.AssetRetention
/* ============================================================
* MAIN
* ============================================================ */
fun main() {
val sdk = WireAppSdk(
applicationId = UUID.randomUUID(),
apiToken = "REPLACE_WITH_REAL_TOKEN",
apiHost = "https://staging-nginz-https.zinfra.io",
cryptographyStorageKey = "12345678901234567890123456789012".toByteArray(),
wireEventsHandler = AppyHandler()
)
sdk.startListening()
}
/* ============================================================
* HANDLER
* ============================================================ */
class AppyHandler : WireEventsHandlerSuspending() {
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
override suspend fun onTextMessageReceived(msg: WireMessage.Text) {
val parsed = CommandParser.parse(msg.text) ?: return
when (parsed.name) {
"help" ->
reply(msg, Help.render())
"timer" ->
runCatching {
startTimer(parsed.requireArg(), msg)
}.onFailure {
reply(msg, it.userMessage())
}
"echo" ->
reply(msg, "🦜 ${parsed.requireArg()}")
"calc" ->
reply(msg, Calculator.evaluate(parsed.requireArg()))
"joke" ->
reply(msg, Joke.random())
"weather" ->
fetchWeather(parsed.requireArg(), msg)
else ->
reply(msg, "🤔 Unknown command. Try `@Appy help`")
}
}
/* ============================================================
* TIMER — COUNT UP, EDIT EVERY SECOND, FINAL GIF
* ============================================================ */
private fun startTimer(input: String, original: WireMessage.Text) {
val seconds =
Regex("""(\d+)\s*s""", RegexOption.IGNORE_CASE)
.find(input)?.groupValues?.get(1)?.toInt()
?: throw UserError("Usage: `@Appy timer 20s`")
val total = seconds.coerceIn(1, 60)
scope.launch {
// Initial message (1s)
val initial = WireMessage.Text.create(
conversationId = original.conversationId,
text = renderBar(total, 1)
)
var messageId = manager.sendMessageSuspending(initial)
// Edit every second
for (current in 2..total) {
delay(1_000)
val edited = WireMessage.TextEdited.create(
replacingMessageId = messageId,
conversationId = original.conversationId,
text = renderBar(total, current)
)
messageId = manager.sendMessageSuspending(edited)
}
// 🔔 Final ping
manager.sendMessage(
WireMessage.Ping.create(conversationId = original.conversationId)
)
// 🎬 Send GIF
sendGif(original.conversationId)
}
}
/* ============================================================
* TIMER BAR RENDERING
* ============================================================ */
private fun renderBar(total: Int, current: Int): String {
val blocks = 10
val filled = (current.toFloat() / total * blocks).roundToInt()
val block = if (current == total) "🔴" else "🟦"
val bar = block.repeat(filled) + "⬜".repeat(blocks - filled)
return "⏱️ $bar ${current}s"
}
/* ============================================================
* GIF ASSET SENDER
* ============================================================ */
private suspend fun sendGif(conversationId: com.wire.sdk.model.QualifiedId) {
try {
val gifFile = File("/Users/vinayaksankarj/Appy/assets/that's all folks GIF by Space Jam.gif")
if (!gifFile.exists()) {
println("❌ GIF file not found: ${gifFile.absolutePath}")
return
}
val bytes = gifFile.readBytes()
manager.sendAssetSuspending(
conversationId = conversationId,
asset = AssetResource(bytes),
name = "thats_all_folks.gif",
mimeType = "image/gif",
retention = AssetRetention.ETERNAL
)
println("✅ GIF sent successfully")
} catch (e: Throwable) {
println("❌ Failed to send GIF: ${e.message}")
e.printStackTrace()
}
}
/* ============================================================
* WEATHER (10-DAY)
* ============================================================ */
private fun fetchWeather(city: String, original: WireMessage.Text) {
reply(original, "🌤️ Fetching weather…")
scope.launch {
try {
val geo = URL(
"https://geocoding-api.open-meteo.com/v1/search?name=$city&count=1"
).readText()
val lat = Regex("\"latitude\":([0-9.\\-]+)").find(geo)!!.groupValues[1]
val lon = Regex("\"longitude\":([0-9.\\-]+)").find(geo)!!.groupValues[1]
val forecast = URL(
"https://api.open-meteo.com/v1/forecast" +
"?latitude=$lat&longitude=$lon" +
"&daily=temperature_2m_max,temperature_2m_min" +
"&forecast_days=10&timezone=auto"
).readText()
val dates =
Regex("\"time\":\\[(.*?)\\]")
.find(forecast)!!.groupValues[1]
.split(",").map { it.replace("\"", "") }
val max =
Regex("\"temperature_2m_max\":\\[(.*?)\\]")
.find(forecast)!!.groupValues[1].split(",")
val min =
Regex("\"temperature_2m_min\":\\[(.*?)\\]")
.find(forecast)!!.groupValues[1].split(",")
val lines = dates.take(10).indices.map {
val d = LocalDate.parse(dates[it])
val day = d.dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.ENGLISH)
"• $day: ${min[it]}°C / ${max[it]}°C"
}
manager.sendMessage(
WireMessage.Text.create(
conversationId = original.conversationId,
text = buildString {
appendLine("🌤️ Weather in ${city.replaceFirstChar { it.uppercase() }}")
lines.forEach { appendLine(it) }
appendLine("\n_Source: Open-Meteo_")
}
)
)
} catch (_: Throwable) {
reply(original, "❌ Could not fetch weather for `$city`")
}
}
}
/* ============================================================
* HELPERS
* ============================================================ */
private fun reply(original: WireMessage.Text, text: String) {
manager.sendMessage(
WireMessage.Text.createReply(
conversationId = original.conversationId,
text = text,
originalMessage = original,
mentions = original.mentions
)
)
}
}
/* ============================================================
* COMMAND PARSING
* ============================================================ */
data class Command(val name: String, val args: String?)
object CommandParser {
fun parse(text: String): Command? {
if (!text.startsWith("@")) return null
val parts = text.split("\\s+".toRegex(), limit = 3)
if (parts.size < 2) return Command("help", null)
return Command(parts[1].lowercase(), parts.getOrNull(2))
}
}
fun Command.requireArg(): String =
args ?: throw UserError("Missing argument. Try `@Appy help`")
/* ============================================================
* HELP
* ============================================================ */
object Help {
fun render() = """
🎩 **Appy Commands**
⏱️ timer <seconds>
🦜 echo <text>
🧮 calc <expression>
😂 joke
🌤️ weather <city>
Examples:
• @Appy timer 20s
• @Appy calc (2+3)*4
• @Appy weather berlin
""".trimIndent()
}
/* ============================================================
* UTILITIES
* ============================================================ */
class UserError(message: String) : RuntimeException(message)
fun Throwable.userMessage() =
if (this is UserError) "⚠️ ${message}" else "❌ Something went wrong."
object Joke {
fun random() =
"😂 Why do Java developers wear glasses? Because they can’t C#."
}
/* ============================================================
* CALCULATOR
* ============================================================ */
object Calculator {
fun evaluate(expr: String): String =
try {
val result = ExpressionEvaluator.evaluate(expr)
"🧮 Result: ${round(result * 100) / 100}"
} catch (_: Throwable) {
"⚠️ Invalid expression"
}
}
object ExpressionEvaluator {
fun evaluate(expr: String): Double {
val clean = expr.replace("×", "*").replace("÷", "/")
val tokens =
Regex("""\d+(\.\d+)?|[+\-*/()]""")
.findAll(clean).map { it.value }.toList()
val output = mutableListOf<String>()
val ops = ArrayDeque<String>()
fun prec(op: String) = if (op == "+" || op == "-") 1 else 2
for (t in tokens) {
when {
t.toDoubleOrNull() != null -> output += t
t == "(" -> ops += t
t == ")" -> {
while (ops.last() != "(") output += ops.removeLast()
ops.removeLast()
}
else -> {
while (ops.isNotEmpty() && prec(ops.last()) >= prec(t))
output += ops.removeLast()
ops += t
}
}
}
while (ops.isNotEmpty()) output += ops.removeLast()
val stack = ArrayDeque<Double>()
for (t in output) {
t.toDoubleOrNull()?.let { stack += it } ?: run {
val b = stack.removeLast()
val a = stack.removeLast()
stack += when (t) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> 0.0
}
}
}
return stack.single()
}
}
| wireapp/Appy | 0 | Appy is a tiny smart assistant for Wire! Mention @Appy to get jokes, weather updates, calculations, timers, echoes, . A playful demo bot built using the Wire Apps SDK | Kotlin | wireapp | Wire Swiss GmbH | |
build.gradle.kts | Kotlin | plugins {
kotlin("jvm") version "2.3.0"
id("io.gitlab.arturbosch.detekt") version "1.23.8"
id("org.jlleitschuh.gradle.ktlint") version "14.0.1"
}
group = "com.wire.apps.jira"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
detekt {
toolVersion = "1.23.7"
config.setFrom(file("$rootDir/config/detekt/detekt.yml"))
baseline = file("$rootDir/config/detekt/baseline.xml")
parallel = true
buildUponDefaultConfig = true
source.setFrom("src/main/kotlin")
}
dependencies {
implementation("io.javalin:javalin:6.7.0")
implementation("org.slf4j:slf4j-simple:2.0.17")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.21.0")
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.0")
implementation("io.insert-koin:koin-core:4.1.1")
implementation("com.wire:wire-apps-jvm-sdk:0.0.18")
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(21)
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
settings.gradle.kts | Kotlin | plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
}
rootProject.name = "jira-app"
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/Main.kt | Kotlin | package com.wire.apps.jira
import com.wire.apps.jira.api.registerRoutes
import com.wire.apps.jira.infra.config.AppConfig
private const val APP_PORT = 8888
fun main() {
AppConfig
.setup()
.apply { registerRoutes() }
.start(APP_PORT)
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/api/CommandHandler.kt | Kotlin | package com.wire.apps.jira.api
import com.wire.apps.jira.core.GetJiraIssue
import com.wire.apps.jira.core.SendHelp
import com.wire.apps.jira.core.exceptions.InvalidCommandException
import org.slf4j.LoggerFactory
/**
* Handler for processing commands in the API layer.
* This follows proper layering by acting as an adapter between
* the external world and use cases.
*/
class CommandHandler(
private val getJiraIssue: GetJiraIssue,
private val sendHelp: SendHelp,
) {
private val logger = LoggerFactory.getLogger(CommandHandler::class.java)
/**
* Processes a command from a conversation.
* @param conversationId The conversation identifier
* @param command The raw command string
*/
fun handleCommand(
conversationId: String,
command: String,
) {
logger.info("Handling command: $command for conversation: $conversationId")
try {
when {
command.isBlank() -> {
throw InvalidCommandException("Command cannot be blank")
}
command.startsWith("/jira help") -> {
handleHelpCommand(conversationId)
}
command.startsWith("/jira ") -> {
handleJiraIssueCommand(conversationId, command)
}
else -> {
throw InvalidCommandException(command)
}
}
} catch (e: Exception) {
logger.error("Error handling command: $command", e)
// Don't throw - this is an event handler, throwing would crash the app
// In a real implementation, you might want to send an error message back
}
}
private fun handleHelpCommand(conversationId: String) {
logger.info("Help command requested for conversation: $conversationId")
sendHelp(conversationId)
}
private fun handleJiraIssueCommand(
conversationId: String,
command: String,
) {
val issueKey = command.removePrefix("/jira ").trim()
if (!issueKey.matches(Regex("[A-Z]+-\\d+"))) {
throw InvalidCommandException("Invalid Jira issue key format: $issueKey")
}
logger.info("Fetching Jira issue: $issueKey")
getJiraIssue(conversationId to issueKey)
}
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/api/CommandMapper.kt | Kotlin | package com.wire.apps.jira.api
import com.wire.sdk.model.QualifiedId
import org.koin.core.component.KoinComponent
import org.slf4j.LoggerFactory
/**
* Maps Wire SDK commands to the CommandHandler.
* This acts as an adapter between Wire SDK types and domain types.
*/
object CommandMapper : KoinComponent {
private val logger = LoggerFactory.getLogger(CommandMapper::class.java)
private val commandHandler: com.wire.apps.jira.api.CommandHandler by lazy { getKoin().get() }
fun mapCommands(
conversationId: QualifiedId,
rawCommand: String,
) {
logger.debug("Mapping command from Wire SDK: $rawCommand")
// Convert Wire SDK QualifiedId to String representation for domain layer
val conversationIdString = "${conversationId.id}@${conversationId.domain}"
commandHandler.handleCommand(conversationIdString, rawCommand)
}
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/api/HealthController.kt | Kotlin | package com.wire.apps.jira.api
import io.javalin.http.Context
class HealthController {
fun get(context: Context) {
context.json(mapOf("status" to "UP"))
}
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/api/Routes.kt | Kotlin | package com.wire.apps.jira.api
import io.javalin.Javalin
import org.koin.java.KoinJavaComponent.inject
fun Javalin.registerRoutes() {
get("/") { context -> context.redirect("/health") }
val healthController: HealthController by inject(HealthController::class.java)
get("/health", healthController::get)
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/core/GetJiraIssue.kt | Kotlin | package com.wire.apps.jira.core
import com.wire.apps.jira.core.model.JiraIssue
import org.slf4j.LoggerFactory
/**
* Use case for retrieving a Jira issue and sending it to a conversation.
* This use case is now independent of infrastructure details.
*/
class GetJiraIssue(
private val jiraRepository: JiraRepository,
private val messagingGateway: MessagingGateway,
) : UseCase<Pair<String, String>, Unit> {
private val logger = LoggerFactory.getLogger(GetJiraIssue::class.java)
override fun invoke(input: Pair<String, String>) {
val (conversationId, issueKey) = input
logger.info("Fetching Jira issue: $issueKey for conversation: $conversationId")
// Fetch issue from repository (domain layer)
val jiraIssue = jiraRepository.getIssue(issueKey)
val message = formatJiraIssueMessage(jiraIssue)
// Send message via gateway
messagingGateway.sendMessage(conversationId, message)
logger.info("Successfully sent Jira issue: $issueKey to conversation: $conversationId")
}
private fun formatJiraIssueMessage(issue: JiraIssue): String =
buildString {
appendLine("### 📋 ${issue.key}: ${issue.summary}")
appendLine("- ⚙️ **Status**: ${issue.status}")
appendLine("- 👤 **Assignee**: ${issue.assignee}")
issue.sprintName?.let {
appendLine("- 🏃 **Sprint**: $it")
}
issue.epicLink?.let {
appendLine("- 🗂 **Epic**: [$it](https://wearezeta.atlassian.net/browse/$it)")
}
appendLine("- 🌐 **Ticket**: [${issue.key}](https://wearezeta.atlassian.net/browse/${issue.key})")
}
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/core/JiraRepository.kt | Kotlin | package com.wire.apps.jira.core
import com.wire.apps.jira.core.model.JiraIssue
/**
* Repository interface for accessing Jira issue data.
* This abstraction keeps the core layer independent of infrastructure details.
*/
interface JiraRepository {
/**
* Retrieves a Jira issue by its key.
* @param key The Jira issue key (e.g., "WPB-123")
* @return The Jira issue domain model
* @throws com.wire.apps.jira.core.exceptions.JiraIssueNotFoundException if the issue doesn't exist
* @throws com.wire.apps.jira.core.exceptions.JiraConnectionException if there's a connection error
*/
fun getIssue(key: String): JiraIssue
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/core/MessagingGateway.kt | Kotlin | package com.wire.apps.jira.core
/**
* Gateway interface for sending messages to conversations.
* This abstraction keeps the core layer independent of messaging infrastructure.
*/
interface MessagingGateway {
/**
* Sends a text message to a conversation.
* @param conversationId The unique identifier for the conversation
* @param message The text message to send
*/
fun sendMessage(
conversationId: String,
message: String,
)
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/core/SendHelp.kt | Kotlin | package com.wire.apps.jira.core
import org.slf4j.LoggerFactory
class SendHelp(
private val messagingGateway: MessagingGateway,
) : UseCase<String, Unit> {
private val logger = LoggerFactory.getLogger(SendHelp::class.java)
override fun invoke(input: String) {
val message = formatMessage()
messagingGateway.sendMessage(conversationId = input, message = message)
logger.info("Help message sent to conversation: $input")
}
private fun formatMessage(): String =
buildString {
appendLine("### 🆘 Jira App quick guide")
appendLine()
appendLine("To use this app, you can send the following commands:")
appendLine("- `/jira ISSUE-KEY`: Retrieves details for the specified Jira issue.")
appendLine("- `/jira help`: Displays this help message.")
appendLine()
}
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH | |
src/main/kotlin/com/wire/apps/jira/core/UseCase.kt | Kotlin | package com.wire.apps.jira.core
/**
* Use cases contract.
*/
interface UseCase<in Input, out Output> {
operator fun invoke(input: Input): Output
}
| wireapp/jira-app | 0 | Jira app demo for wire integration using the jvm sdk. | Kotlin | wireapp | Wire Swiss GmbH |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.