Skip to content

Commit

Permalink
Merge branch 'master' into phoenix_1.7
Browse files Browse the repository at this point in the history
  • Loading branch information
thbar authored Jan 9, 2024
2 parents cc4d9d3 + dbc0022 commit 3d1bbed
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
23 changes: 17 additions & 6 deletions apps/transport/lib/jobs/update_contacts_job.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,23 @@ defmodule Transport.Jobs.UpdateContactsJob do
DB.Contact.base_query()
|> where([contact: c], c.datagouv_user_id in ^ids)
|> DB.Repo.all()
|> Enum.each(fn %DB.Contact{datagouv_user_id: datagouv_user_id} = contact ->
{:ok, %{"organizations" => organizations}} = Datagouvfr.Client.User.get(datagouv_user_id)
|> Enum.each(&update_contact/1)
end

defp update_contact(%DB.Contact{datagouv_user_id: datagouv_user_id} = contact) do
# https://doc.data.gouv.fr/api/reference/#/users/get_user
# 404 status code: User not found
# 410 status code: User is not active or has been deleted
case Datagouvfr.Client.User.get(datagouv_user_id) do
{:ok, %{"organizations" => organizations}} ->
contact
|> DB.Contact.changeset(%{organizations: organizations})
|> DB.Repo.update!()

contact
|> DB.Contact.changeset(%{organizations: organizations})
|> DB.Repo.update!()
end)
{:error, reason} when reason in [:not_found, :gone] ->
contact
|> DB.Contact.changeset(%{organizations: [], datagouv_user_id: nil})
|> DB.Repo.update!()
end
end
end
22 changes: 22 additions & 0 deletions apps/transport/test/transport/jobs/update_contacts_job_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,26 @@ defmodule Transport.Test.Transport.Jobs.UpdateContactsJobTest do
assert [%DB.Organization{name: ^org_name, id: ^org_id}] = contact.organizations
assert %DB.Contact{organization: ^org_name} = contact
end

test "removes datagouv_user_id and organizations when API responds with 404 or 410" do
Enum.each([404, 410], fn status_code ->
contact =
insert_contact(%{
datagouv_user_id: user_id = Ecto.UUID.generate(),
organizations: [:organization |> build() |> Map.from_struct()]
})

url = "https://demo.data.gouv.fr/api/1/users/#{user_id}/"

Transport.HTTPoison.Mock
|> expect(:request, fn :get, ^url, "", [], [follow_redirect: true] ->
{:ok, %HTTPoison.Response{status_code: status_code, body: ""}}
end)

assert :ok == perform_job(UpdateContactsJob, %{contact_ids: [user_id]})

assert %DB.Contact{datagouv_user_id: nil, organizations: []} =
contact |> DB.Repo.reload!() |> DB.Repo.preload([:organizations])
end)
end
end

0 comments on commit 3d1bbed

Please sign in to comment.