@@ -10,10 +10,13 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
1010 alias GroupherServer . { Accounts , CMS , Repo , Statistics }
1111
1212 alias Accounts.User
13- alias CMS.Community
13+ alias CMS . { Community , Delegate }
1414 alias Statistics . { CommunityContribute , UserContribute }
1515
16+ alias Delegate.CommunityCURD
17+
1618 alias Helper . { Cache , Later , ORM , QueryBuilder }
19+ alias Ecto.Multi
1720
1821 @ community_contribute_days get_config ( :general , :community_contribute_days )
1922 @ user_contribute_months get_config ( :general , :user_contribute_months )
@@ -39,13 +42,23 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
3942 def make_contribute ( % Community { id: id } ) do
4043 today = Timex . today ( ) |> Date . to_iso8601 ( )
4144
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 )
4557
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 ( )
4962 end
5063
5164 @ doc """
@@ -161,15 +174,13 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
161174 return_count = abs ( count ) + 1
162175 enmpty_tuple = return_count |> repeat ( 0 ) |> List . to_tuple ( )
163176
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 )
168180
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 ( )
173184 end
174185 end
175186
@@ -194,4 +205,7 @@ defmodule GroupherServer.Statistics.Delegate.Contribute do
194205
195206 put_in ( contribute . count , result )
196207 end
208+
209+ defp result ( { :ok , % { make_contribute: result } } ) , do: { :ok , result }
210+ defp result ( { :error , _ , result , _steps } ) , do: { :error , result }
197211end
0 commit comments