@@ -5,6 +5,8 @@ defmodule Algora.Accounts do
55
66 alias Algora.Accounts.Identity
77 alias Algora.Accounts.User
8+ alias Algora.Bounties.Bounty
9+ alias Algora.Organizations
810 alias Algora.Payments.Transaction
911 alias Algora.Repo
1012
@@ -367,6 +369,43 @@ defmodule Algora.Accounts do
367369 { :ok , Repo . preload ( user , :identities , force: true ) }
368370 end
369371
372+ def last_context ( % { last_context: nil } = user ) do
373+ orgs = Organizations . get_user_orgs ( user )
374+
375+ last_debit_query =
376+ from ( t in Transaction ,
377+ join: u in assoc ( t , :user ) ,
378+ where: t . type == :debit ,
379+ where: u . id in ^ Enum . map ( orgs , & & 1 . id ) ,
380+ order_by: [ desc: t . succeeded_at ] ,
381+ limit: 1
382+ )
383+
384+ last_bounty_query =
385+ from ( b in Bounty ,
386+ join: c in assoc ( b , :creator ) ,
387+ where: c . id in ^ Enum . map ( orgs , & & 1 . id ) ,
388+ order_by: [ desc: b . created_at ] ,
389+ limit: 1
390+ )
391+
392+ last_sponsored_on_behalf_of =
393+ cond do
394+ last_debit = Repo . one ( last_debit_query ) -> last_debit . user
395+ last_bounty = Repo . one ( last_bounty_query ) -> last_bounty . owner
396+ true -> nil
397+ end
398+
399+ case last_sponsored_on_behalf_of do
400+ % { type: :organization } -> last_sponsored_on_behalf_of . handle
401+ _ -> default_context ( )
402+ end
403+ end
404+
405+ def last_context ( % { last_context: last_context } ) , do: last_context
406+
407+ def default_context , do: "personal"
408+
370409 defp get_flag ( user ) , do: Algora.Misc.CountryEmojis . get ( user . country , "🌎" )
371410
372411 # TODO: implement this
0 commit comments