Fix cycle end calculation for misaligned cycle_start dates
Make cycle generation idempotent by skipping existing cycles
This commit is contained in:
parent
e3d615acb8
commit
3241dd7d96
2 changed files with 43 additions and 9 deletions
|
|
@ -386,18 +386,44 @@ defmodule Mv.MembershipFees.CycleGenerator do
|
|||
{:ok, cycle} ->
|
||||
{:ok, cycle, []}
|
||||
|
||||
{:error, %Ash.Error.Invalid{errors: [%Ash.Error.Changes.InvalidAttribute{private_vars: %{constraint: constraint, constraint_type: :unique}}]}} = error ->
|
||||
# Cycle already exists (unique constraint violation) - skip it silently
|
||||
# This makes the function idempotent and prevents errors on server restart
|
||||
if constraint == "membership_fee_cycles_unique_cycle_per_member_index" do
|
||||
{:skip, cycle_start}
|
||||
else
|
||||
{:error, {cycle_start, error}}
|
||||
end
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, {cycle_start, reason}}
|
||||
end
|
||||
end)
|
||||
|
||||
{successes, errors} = Enum.split_with(results, &match?({:ok, _, _}, &1))
|
||||
{successes, skips, errors} =
|
||||
Enum.reduce(results, {[], [], []}, fn
|
||||
{:ok, cycle, notifications}, {successes, skips, errors} ->
|
||||
{[{:ok, cycle, notifications} | successes], skips, errors}
|
||||
|
||||
{:skip, cycle_start}, {successes, skips, errors} ->
|
||||
{successes, [cycle_start | skips], errors}
|
||||
|
||||
{:error, error}, {successes, skips, errors} ->
|
||||
{successes, skips, [error | errors]}
|
||||
end)
|
||||
|
||||
all_notifications =
|
||||
Enum.flat_map(successes, fn {:ok, _cycle, notifications} -> notifications end)
|
||||
|
||||
if Enum.empty?(errors) do
|
||||
successful_cycles = Enum.map(successes, fn {:ok, cycle, _notifications} -> cycle end)
|
||||
|
||||
if Enum.any?(skips) do
|
||||
Logger.debug(
|
||||
"Skipped #{length(skips)} cycles that already exist for member #{member_id}"
|
||||
)
|
||||
end
|
||||
|
||||
{:ok, successful_cycles, all_notifications}
|
||||
else
|
||||
Logger.warning("Some cycles failed to create: #{inspect(errors)}")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue