Skip to content

Commit 7bb2157

Browse files
committed
add strategy param
1 parent e0fff5c commit 7bb2157

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

lib/algora/bounties/bounties.ex

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,31 @@ defmodule Algora.Bounties do
6666
end
6767
end
6868

69+
@type strategy :: :create | :set | :increase
70+
71+
@spec strategy_to_action(Bounty.t() | nil, strategy() | nil) :: {:ok, strategy()} | {:error, atom()}
72+
defp strategy_to_action(bounty, strategy) do
73+
case {bounty, strategy} do
74+
{_, nil} -> strategy_to_action(bounty, :increase)
75+
{nil, _} -> {:ok, :create}
76+
{_existing, :create} -> {:error, :already_exists}
77+
{_existing, strategy} -> {:ok, strategy}
78+
end
79+
end
80+
6981
@spec create_bounty(
7082
%{
7183
creator: User.t(),
7284
owner: User.t(),
7385
amount: Money.t(),
7486
ticket_ref: %{owner: String.t(), repo: String.t(), number: integer()}
7587
},
76-
opts :: [installation_id: integer(), command_id: integer(), command_source: :ticket | :comment]
88+
opts :: [
89+
strategy: strategy(),
90+
installation_id: integer(),
91+
command_id: integer(),
92+
command_source: :ticket | :comment
93+
]
7794
) ::
7895
{:ok, Bounty.t()} | {:error, atom()}
7996
def create_bounty(
@@ -96,7 +113,14 @@ defmodule Algora.Bounties do
96113
Repo.transact(fn ->
97114
with {:ok, token} <- token_res,
98115
{:ok, ticket} <- Workspace.ensure_ticket(token, repo_owner, repo_name, number),
99-
{:ok, bounty} <- do_create_bounty(%{creator: creator, owner: owner, amount: amount, ticket: ticket}),
116+
existing = Repo.get_by(Bounty, ticket_id: ticket.id),
117+
{:ok, strategy} <- strategy_to_action(existing, opts[:strategy]),
118+
{:ok, bounty} <-
119+
(case strategy do
120+
:create -> do_create_bounty(%{creator: creator, owner: owner, amount: amount, ticket: ticket})
121+
:set -> existing |> Bounty.changeset(%{amount: amount}) |> Repo.update()
122+
:increase -> existing |> Bounty.changeset(%{amount: Money.add!(existing.amount, amount)}) |> Repo.update()
123+
end),
100124
{:ok, _job} <-
101125
notify_bounty(%{owner: owner, bounty: bounty, ticket_ref: ticket_ref},
102126
installation_id: installation_id,

0 commit comments

Comments
 (0)