Skip to content

Commit

Permalink
feat(Services.Service): evaluate if a service runs on a date
Browse files Browse the repository at this point in the history
semi-adapted from the V3 API's approach
  • Loading branch information
thecristen committed Oct 3, 2023
1 parent e4e99e9 commit 9ac9ef1
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions apps/services/lib/service.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule Services.Service do
@moduledoc "Processes Services, including dates and notes"
alias JsonApi.Item
use Timex

defstruct added_dates: [],
added_dates_notes: [],
Expand Down Expand Up @@ -153,4 +154,49 @@ defmodule Services.Service do
defp typicality(5), do: :unplanned_disruption
defp typicality(6), do: :canonical
defp typicality(_), do: :unknown

@spec serves_date?(t(), Date.t()) :: boolean
def serves_date?(service, date) do
date in dates_for_service(service)
end

@spec dates_for_service(t()) :: [Date.t()]
defp dates_for_service(%__MODULE__{
start_date: from,
end_date: until,
added_dates: added_dates,
removed_dates: removed_dates,
valid_days: valid_days
}) do
dates =
if from == until do
[from]
else
[
from: from,
until: until,
right_open: false
]
|> Interval.new()
|> Enum.map(& &1)
end

removed_dates = parse_listed_dates(removed_dates)

(dates ++ parse_listed_dates(added_dates))
|> Enum.reject(&Enum.member?(removed_dates, &1))
|> Enum.reject(fn date ->
Timex.weekday(date) not in valid_days
end)
|> Enum.map(&Timex.to_date/1)
|> Enum.uniq()
end

@spec parse_listed_dates([String.t()]) :: [NaiveDateTime.t()]
defp parse_listed_dates(date_strings) do
date_strings
|> Enum.map(&Timex.parse(&1, "{YYYY}-{0M}-{D}"))
|> Enum.filter(&(elem(&1, 0) == :ok))
|> Enum.map(&elem(&1, 1))
end
end

0 comments on commit 9ac9ef1

Please sign in to comment.