defmodule TradeMachine.GMGradeV2.Pillars.CapFlexibility.TransactionFlexibility do @moduledoc """ Scores AVC's four supporting Transaction Flexibility calculations. Signing mechanisms, capability flags, usable trade exceptions, roster space, and waivability are consumed from `CapState`; no CBA rule is re-derived here. The one time-based calculation discounts a TPE's recorded remaining amount against the snapshot's frozen `as_of_date`. `CapState.signing_mechanisms.best` is deliberately authoritative even where `05-D58-APRON-MLE` records that the engine overstates apron-team MLE access. Narrowing it here would violate D-55 by restating the engine's CBA rule. ## What is behind each sub-score (`inputs.detail`) Beside the totals, the result records what three of the sub-scores were worked out from, so the Grading Studio can show it without working it out again. Nothing reads it back to compute a score. * `trade_tools`: the five trade tools in one fixed order (the order of their costs, largest first), each with whether it is open and what it costs when it is not. 100 less the costs of the closed ones, never below 0, is `supporting.trade_tools`. * `trade_exceptions`: every exception the team holds, the ones that count for most first (ties keep the cap state's order): `label` (the player it came from, `nil` when the row names none), what is left, the expiry date and the days left to it, whether it passed each of the two tests (usable; at least 5% of the mid-level left), the expiry multiplier applied, and what it `counted` for. One that failed a test has `multiplier: nil` and `counted: 0.0`. The largest `counted` plus a quarter of the second, over `inputs.non_taxpayer_mle`, capped at 1, times 100, is `supporting.trade_exception_capacity`. Recording reads no more of an exception than scoring does. Scoring never reads the amount or the date of an exception that is not usable, nor the date of one that is too small, so a cap state may leave those out and still be scored. The record then says `nil` for what it was not given: `remaining_amount` and `large_enough` (not usable, no amount), `expiration_date` and `days_left` (does not count, no date). `CapState.build/2` always gives all of them. * `roster`: open standard spots and their score, the easily waivable players (id and name) and the score for their count. `open_spot_score x 0.70 + waivable_score x 0.30` is `supporting.roster_maneuverability`. Each test and amount is the same private function the sub-score uses, so the record cannot disagree with the score. """ alias TradeMachine.GMGradeV2.ModelVersion alias TradeMachine.GMGradeV2.Result.MetricResult @component_weights %{ signing_tools: 0.30, trade_tools: 0.40, trade_exception_capacity: 0.20, roster_maneuverability: 0.10 } @trade_penalties %{ can_aggregate: 25.0, can_take_back_more: 20.0, can_receive_sign_and_trade: 15.0, can_use_existing_tpe: 15.0, can_send_cash: 5.0 } # The order `inputs.detail.trade_tools` lists the five tools in. A map's own # order depends on when its keys were first used in the running system, so # it is not a fixed order. @trade_tool_order [ :can_aggregate, :can_take_back_more, :can_receive_sign_and_trade, :can_use_existing_tpe, :can_send_cash ] if Enum.sort(@trade_tool_order) != Enum.sort(Map.keys(@trade_penalties)) do raise "the trade tool order must name each penalised trade tool once" end @doc "Returns the full-precision Transaction Flexibility metric result." @spec score(map()) :: MetricResult.t() def score(%{ season: season, as_of_date: %Date{} = as_of_date, thresholds: thresholds, signing_mechanisms: signing_mechanisms, capabilities: capabilities, trade_exceptions: trade_exceptions, roster: roster }) do ntmle = thresholds |> Map.fetch!(season) |> Map.fetch!(:non_taxpayer_mle) components = %{ signing_tools: signing_tools(signing_mechanisms, ntmle), trade_tools: trade_tools(capabilities), trade_exception_capacity: trade_exception_capacity(trade_exceptions, ntmle, as_of_date), roster_maneuverability: roster_maneuverability(roster) } detail = %{ trade_tools: trade_tool_detail(capabilities), trade_exceptions: trade_exception_detail(trade_exceptions, ntmle, as_of_date), roster: roster_room_detail(roster) } %MetricResult{ key: :transaction_flexibility, version: ModelVersion.model_version(), score: combine_components(components), inputs: %{ as_of_date: as_of_date, non_taxpayer_mle: ntmle, largest_usable_signing_mechanism: signing_mechanisms.best, detail: detail }, supporting: components, weights: @component_weights, explanation: "Transaction Flexibility combines the cap state's usable signing, trade, " <> "trade-exception, and roster pathways at AVC's 30/40/20/10 weights." } end @doc "Scores the largest usable CapState signing mechanism against the NTMLE." @spec signing_tools(map(), pos_integer()) :: float() def signing_tools(%{best: nil}, _ntmle), do: 0.0 def signing_tools(%{best: %{type: :minimum}}, _ntmle), do: 20.0 def signing_tools(%{best: %{remaining: remaining}}, ntmle) when is_number(remaining) and remaining > 0 and is_number(ntmle) and ntmle > 0 do min(100.0, 20.0 + 80.0 * remaining / ntmle) end @doc "Scores the five Capabilities flags using AVC's fixed penalties." @spec trade_tools(map()) :: float() def trade_tools(capabilities) when is_map(capabilities) do penalty = Enum.reduce(@trade_penalties, 0.0, fn {capability, points}, total -> if tool_open?(capabilities, capability), do: total, else: total + points end) max(0.0, 100.0 - penalty) end @doc """ Scores the largest and second-largest practical TPEs after expiration discounts. A TPE must be marked usable by CapState and carry at least 5% of the NTMLE in remaining nominal value before its expiration multiplier is applied. """ @spec trade_exception_capacity([map()], pos_integer(), Date.t()) :: float() def trade_exception_capacity(trade_exceptions, ntmle, %Date{} = as_of_date) when is_list(trade_exceptions) and is_number(ntmle) and ntmle > 0 do # Deliberate overlap with Trade Tools: CapState's `:usable` already folds in # `can_use_existing_tpe`, so a barred team loses both the general trade # capability and the practical capacity of TPEs it cannot consume. These # are separate AVC supporting calculations, not duplicate arithmetic. [largest, second | _rest] = trade_exceptions |> Enum.filter(&tpe_counts?(&1, ntmle)) |> Enum.map(&tpe_counted_amount(&1, as_of_date)) |> Enum.sort(:desc) |> Kernel.++([0.0, 0.0]) 100.0 * min(1.0, (largest + 0.25 * second) / ntmle) end @doc "Returns AVC's expiration multiplier for a TPE's remaining whole days." @spec expiration_multiplier(integer()) :: float() def expiration_multiplier(days) when days < 30, do: 0.40 def expiration_multiplier(days) when days <= 90, do: 0.65 def expiration_multiplier(days) when days <= 180, do: 0.85 def expiration_multiplier(_days), do: 1.00 @doc "Combines open standard spots and easily-waivable contracts at 70/30." @spec roster_maneuverability(map()) :: float() def roster_maneuverability(%{ open_standard_spots: open_spots, easily_waivable: easily_waivable }) do open_spot_score(open_spots) * 0.70 + waivable_score(length(easily_waivable)) * 0.30 end @doc "Combines the four supporting calculations at AVC's 30/40/20/10 weights." @spec combine_components(map()) :: float() def combine_components(components) when is_map(components) do Enum.reduce(@component_weights, 0.0, fn {component, weight}, total -> total + Map.fetch!(components, component) * weight end) end defp open_spot_score(open_spots) when open_spots in 1..2, do: 100.0 defp open_spot_score(3), do: 90.0 defp open_spot_score(0), do: 75.0 defp open_spot_score(4), do: 75.0 defp open_spot_score(open_spots) when open_spots >= 5, do: 50.0 defp waivable_score(0), do: 50.0 defp waivable_score(1), do: 75.0 defp waivable_score(2), do: 90.0 defp waivable_score(count) when count >= 3, do: 100.0 # Whether a trade tool is open: the test `trade_tools/1` charges a closed # tool's cost by, and the one the detail records. defp tool_open?(capabilities, tool), do: Map.fetch!(capabilities, tool) not in [false, nil] # The two tests a trade exception must pass to count toward capacity, and # what one that passes counts for. `trade_exception_capacity/3` and the # detail both use these, so the record cannot disagree with the score. defp tpe_counts?(tpe, ntmle), do: tpe_usable?(tpe) and tpe_large_enough?(tpe, ntmle) defp tpe_usable?(tpe), do: Map.fetch!(tpe, :usable) defp tpe_large_enough?(tpe, ntmle), do: Map.fetch!(tpe, :remaining_amount) >= ntmle * 0.05 defp tpe_counted_amount(tpe, as_of_date) do Map.fetch!(tpe, :remaining_amount) * expiration_multiplier(tpe_days_left(tpe, as_of_date)) end defp tpe_days_left(tpe, as_of_date), do: Date.diff(Map.fetch!(tpe, :expiration_date), as_of_date) # ── What is behind each sub-score (`inputs.detail`) ───────────────── # # Their names sort after `score/1` and `roster_maneuverability/1`, and the # compiler lays functions out in name order. That keeps the four sub-score # names first used, and so created, in the order they were before: since # OTP 26 a small map with atom keys is walked in the order its atoms were # created, and that is the order `combine_components/1` adds the weighted # sub-scores in. A different order can move the score in its last bit. defp trade_tool_detail(capabilities) do Enum.map(@trade_tool_order, fn tool -> %{ tool: tool, open: tool_open?(capabilities, tool), cost: Map.fetch!(@trade_penalties, tool) } end) end # Reads exactly what `trade_exception_capacity/3` reads of each exception, # and requires no more (Astra's review of SBD-01). That function tests # `usable` first and stops there for one that is not, and reads the date # only of one that passed both tests. So `Map.fetch!` is used here only # where it is used there, and anything else is read with `Map.get/2` and # recorded as `nil` when the cap state did not give it: a cap state that # scored before this record existed still scores. defp trade_exception_detail(trade_exceptions, ntmle, as_of_date) do trade_exceptions |> Enum.map(fn tpe -> usable? = tpe_usable?(tpe) counts? = tpe_counts?(tpe, ntmle) %{ label: Map.get(tpe, :source_player_name), remaining_amount: tpe_recorded_amount(tpe, usable?), expiration_date: tpe_recorded_date(tpe, counts?), days_left: tpe_recorded_days_left(tpe, counts?, as_of_date), usable: usable?, large_enough: tpe_recorded_large_enough(tpe, usable?, ntmle), multiplier: if(counts?, do: expiration_multiplier(tpe_days_left(tpe, as_of_date))), counted: if(counts?, do: tpe_counted_amount(tpe, as_of_date), else: 0.0) } end) |> Enum.sort_by(& &1.counted, :desc) end # A usable exception's amount is read by the scorer, so it is required. One # that is not usable is recorded with whatever amount it was given. defp tpe_recorded_amount(tpe, true), do: Map.fetch!(tpe, :remaining_amount) defp tpe_recorded_amount(tpe, false), do: Map.get(tpe, :remaining_amount) defp tpe_recorded_large_enough(tpe, true, ntmle), do: tpe_large_enough?(tpe, ntmle) defp tpe_recorded_large_enough(tpe, false, ntmle) do case Map.get(tpe, :remaining_amount) do amount when is_number(amount) -> amount >= ntmle * 0.05 _not_given -> nil end end # Only an exception that counts has its date read by the scorer. defp tpe_recorded_date(tpe, true), do: Map.fetch!(tpe, :expiration_date) defp tpe_recorded_date(tpe, false), do: Map.get(tpe, :expiration_date) defp tpe_recorded_days_left(tpe, true, as_of_date), do: tpe_days_left(tpe, as_of_date) defp tpe_recorded_days_left(tpe, false, as_of_date) do case Map.get(tpe, :expiration_date) do %Date{} = date -> Date.diff(date, as_of_date) _not_given -> nil end end defp waivable_detail(entry), do: %{player_id: Map.get(entry, :player_id), name: Map.get(entry, :name)} defp roster_room_detail(%{open_standard_spots: open_spots, easily_waivable: easily_waivable}) do %{ open_standard_spots: open_spots, open_spot_score: open_spot_score(open_spots), easily_waivable: Enum.map(easily_waivable, &waivable_detail/1), waivable_score: waivable_score(length(easily_waivable)) } end end