@@ -10,10 +10,13 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
10
10
alias GroupherServer . { Accounts , CMS , Repo , Statistics }
11
11
12
12
alias Accounts.User
13
- alias CMS.Community
13
+ alias CMS . { Community , Delegate }
14
14
alias Statistics . { CommunityContribute , UserContribute }
15
15
16
+ alias Delegate.CommunityCURD
17
+
16
18
alias Helper . { Cache , Later , ORM , QueryBuilder }
19
+ alias Ecto.Multi
17
20
18
21
@ community_contribute_days get_config ( :general , :community_contribute_days )
19
22
@ user_contribute_months get_config ( :general , :user_contribute_months )
@@ -39,13 +42,23 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
39
42
def make_contribute ( % Community { id: id } ) do
40
43
today = Timex . today ( ) |> Date . to_iso8601 ( )
41
44
42
- case ORM . find_by ( CommunityContribute , community_id: id , date: today ) do
43
- { :ok , contribute } ->
44
- update_contribute_record ( contribute )
45
+ Multi . new ( )
46
+ |> Multi . run ( :make_contribute , fn _ , _ ->
47
+ case ORM . find_by ( CommunityContribute , % { community_id: id , date: today } ) do
48
+ { :ok , contribute } -> update_contribute_record ( contribute )
49
+ { :error , _ } -> insert_contribute_record ( % Community { id: id } )
50
+ end
51
+ end )
52
+ |> Multi . run ( :update_community_field , fn _ , _ ->
53
+ contributes_digest =
54
+ % Community { id: id }
55
+ |> do_get_contributes ( )
56
+ |> to_counts_digest ( days: @ community_contribute_days )
45
57
46
- { :error , _ } ->
47
- insert_contribute_record ( % Community { id: id } )
48
- end
58
+ CommunityCURD . update_community ( id , % { contributes_digest: contributes_digest } )
59
+ end )
60
+ |> Repo . transaction ( )
61
+ |> result ( )
49
62
end
50
63
51
64
@ doc """
@@ -161,15 +174,13 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
161
174
return_count = abs ( count ) + 1
162
175
enmpty_tuple = return_count |> repeat ( 0 ) |> List . to_tuple ( )
163
176
164
- results =
165
- Enum . reduce ( record , enmpty_tuple , fn record , acc ->
166
- diff = Timex . diff ( Timex . to_date ( record . date ) , today , :days )
167
- index = diff + abs ( count )
177
+ Enum . reduce ( record , enmpty_tuple , fn record , acc ->
178
+ diff = Timex . diff ( Timex . to_date ( record . date ) , today , :days )
179
+ index = diff + abs ( count )
168
180
169
- put_elem ( acc , index , record . count )
170
- end )
171
-
172
- results |> Tuple . to_list ( )
181
+ put_elem ( acc , index , record . count )
182
+ end )
183
+ |> Tuple . to_list ( )
173
184
end
174
185
end
175
186
@@ -194,4 +205,7 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
194
205
195
206
put_in ( contribute . count , result )
196
207
end
208
+
209
+ defp result ( { :ok , % { make_contribute: result } } ) , do: { :ok , result }
210
+ defp result ( { :error , _ , result , _steps } ) , do: { :error , result }
197
211
end