@@ -66,14 +66,31 @@ defmodule Algora.Bounties do
66
66
end
67
67
end
68
68
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
+
69
81
@ spec create_bounty (
70
82
% {
71
83
creator: User . t ( ) ,
72
84
owner: User . t ( ) ,
73
85
amount: Money . t ( ) ,
74
86
ticket_ref: % { owner: String . t ( ) , repo: String . t ( ) , number: integer ( ) }
75
87
} ,
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
+ ]
77
94
) ::
78
95
{ :ok , Bounty . t ( ) } | { :error , atom ( ) }
79
96
def create_bounty (
@@ -96,7 +113,14 @@ defmodule Algora.Bounties do
96
113
Repo . transact ( fn ->
97
114
with { :ok , token } <- token_res ,
98
115
{ :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 ) ,
100
124
{ :ok , _job } <-
101
125
notify_bounty ( % { owner: owner , bounty: bounty , ticket_ref: ticket_ref } ,
102
126
installation_id: installation_id ,
0 commit comments