diff --git a/apps/hellgate/src/hellgate.erl b/apps/hellgate/src/hellgate.erl index 275e5ba8..751f180b 100644 --- a/apps/hellgate/src/hellgate.erl +++ b/apps/hellgate/src/hellgate.erl @@ -90,7 +90,7 @@ construct_health_routes(readiness, Check) -> enable_health_logging(Check) -> EvHandler = {erl_health_event_handler, []}, - maps:map(fun(_, V = {_, _, _}) -> #{runner => V, event_handler => EvHandler} end, Check). + maps:map(fun(_, {_, _, _} = V) -> #{runner => V, event_handler => EvHandler} end, Check). construct_service_handler(Name, Module, Opts) -> FullOpts = maps:merge(#{handler => Module}, Opts), diff --git a/apps/hellgate/src/hg_allocation.erl b/apps/hellgate/src/hg_allocation.erl index d505c144..8713cac1 100644 --- a/apps/hellgate/src/hg_allocation.erl +++ b/apps/hellgate/src/hg_allocation.erl @@ -54,18 +54,21 @@ -spec calculate(allocation_prototype(), party(), shop(), cash(), allocation_terms()) -> {error, calculate_errors()}. calculate(AllocationPrototype, Party, Shop, Cost, PaymentAllocationServiceTerms) -> - case assert_allocatable(AllocationPrototype, PaymentAllocationServiceTerms, Party, Shop, Cost) of - % ok -> - % try calculate(AllocationPrototype, Party#domain_PartyConfig.id, Shop#domain_ShopConfig.id, Cost) of - % Result -> - % {ok, Result} - % catch - % throw:Error -> - % {error, Error} - % end; - {error, Error} -> - {error, Error} - end. + %% NOTE Allocation is temporarily disabled. + %% case assert_allocatable(AllocationPrototype, PaymentAllocationServiceTerms, Party, Shop, Cost) of + %% ok -> + %% try calculate(AllocationPrototype, Party#domain_PartyConfig.id, Shop#domain_ShopConfig.id, Cost) of + %% Result -> + %% {ok, Result} + %% catch + %% throw:Error -> + %% {error, Error} + %% end; + %% {error, Error} -> + %% {error, Error} + %% end. + {error, Error} = assert_allocatable(AllocationPrototype, PaymentAllocationServiceTerms, Party, Shop, Cost), + {error, Error}. -spec sub(allocation(), allocation()) -> {ok, allocation()} | {error, sub_errors()}. sub(Allocation, SubAllocation) -> diff --git a/apps/hellgate/src/hg_cashflow.erl b/apps/hellgate/src/hg_cashflow.erl index 986e6dce..d5f8631b 100644 --- a/apps/hellgate/src/hg_cashflow.erl +++ b/apps/hellgate/src/hg_cashflow.erl @@ -164,7 +164,7 @@ compute_volume(?product(Fun, CVs) = CV0, Context) -> error({misconfiguration, {'Cash volume product over empty set', CV0}}) end. -compute_parts_of(P, Q, Cash = #domain_Cash{amount = Amount}, RoundingMethod) -> +compute_parts_of(P, Q, #domain_Cash{amount = Amount} = Cash, RoundingMethod) -> Cash#domain_Cash{ amount = genlib_rational:round( genlib_rational:mul( @@ -182,7 +182,7 @@ compute_product(Fun, [CV | CVRest], CV0, Context) -> CVRest ). -compute_product(Fun, CV, CVMin = #domain_Cash{amount = AmountMin, currency = Currency}, CV0, Context) -> +compute_product(Fun, CV, #domain_Cash{amount = AmountMin, currency = Currency} = CVMin, CV0, Context) -> case compute_volume(CV, Context) of #domain_Cash{amount = Amount, currency = Currency} -> CVMin#domain_Cash{amount = compute_product_fun(Fun, AmountMin, Amount)}; diff --git a/apps/hellgate/src/hg_cashflow_utils.erl b/apps/hellgate/src/hg_cashflow_utils.erl index fad186d8..387f25e4 100644 --- a/apps/hellgate/src/hg_cashflow_utils.erl +++ b/apps/hellgate/src/hg_cashflow_utils.erl @@ -94,12 +94,12 @@ collect_allocation_cash_flow( construct_transaction_cashflow( Amount, PaymentInstitution, - Context = #{ + #{ revision := Revision, operation := OpType, shop := {_, Shop}, varset := VS - } + } = Context ) -> MerchantPaymentsTerms1 = case maps:get(merchant_terms, Context, undefined) of @@ -114,7 +114,7 @@ construct_transaction_cashflow( AccountMap = hg_accounting:collect_account_map(make_collect_account_context(PaymentInstitution, Context)), construct_final_cashflow(MerchantCashflow, #{operation_amount => Amount}, AccountMap). -construct_provider_cashflow(PaymentInstitution, Context = #{provision_terms := ProvisionTerms}) -> +construct_provider_cashflow(PaymentInstitution, #{provision_terms := ProvisionTerms} = Context) -> ProviderCashflowSelector = get_provider_cashflow_selector(ProvisionTerms), ProviderCashflow = get_selector_value(provider_payment_cash_flow, ProviderCashflowSelector), AccountMap = hg_accounting:collect_account_map(make_collect_account_context(PaymentInstitution, Context)), diff --git a/apps/hellgate/src/hg_datetime.erl b/apps/hellgate/src/hg_datetime.erl index 4f9b0efc..51c9c651 100644 --- a/apps/hellgate/src/hg_datetime.erl +++ b/apps/hellgate/src/hg_datetime.erl @@ -34,7 +34,7 @@ %% -spec format_dt(datetime()) -> timestamp(). -format_dt(Dt = {_, _}) -> +format_dt({_, _} = Dt) -> Ts = genlib_time:daytime_to_unixtime(Dt), format_ts(Ts). diff --git a/apps/hellgate/src/hg_fault_detector_client.erl b/apps/hellgate/src/hg_fault_detector_client.erl index be309d2a..3899fdbf 100644 --- a/apps/hellgate/src/hg_fault_detector_client.erl +++ b/apps/hellgate/src/hg_fault_detector_client.erl @@ -89,24 +89,24 @@ build_operation_id(ServiceType, IDs) -> hg_utils:construct_complex_id(lists:flatten([<<"hellgate_operation">>, genlib:to_binary(ServiceType), MappedIDs])). -spec init_service(service_id(), service_config()) -> {ok, initialised} | {error, any()} | disabled. -init_service(ServiceId, ServiceConfig) -> - call('InitService', {ServiceId, ServiceConfig}). +init_service(ServiceID, ServiceConfig) -> + call('InitService', {ServiceID, ServiceConfig}). -spec get_statistics([service_id()]) -> [service_stats()]. -get_statistics(ServiceIds) when is_list(ServiceIds) -> - call('GetStatistics', {ServiceIds}). +get_statistics(ServiceIDs) when is_list(ServiceIDs) -> + call('GetStatistics', {ServiceIDs}). -spec register_operation(operation_status(), service_id(), operation_id(), service_config()) -> {ok, registered} | {error, not_found} | {error, any()} | disabled. -register_operation(Status, ServiceId, OperationId, ServiceConfig) -> +register_operation(Status, ServiceID, OperationID, ServiceConfig) -> OperationState = case Status of start -> {Status, ?state_start(hg_datetime:format_now())}; error -> {Status, ?state_error(hg_datetime:format_now())}; finish -> {Status, ?state_finish(hg_datetime:format_now())} end, - Operation = ?operation(OperationId, OperationState), - call('RegisterOperation', {ServiceId, Operation, ServiceConfig}). + Operation = ?operation(OperationID, OperationState), + call('RegisterOperation', {ServiceID, Operation, ServiceConfig}). %% PRIVATE @@ -125,7 +125,7 @@ maybe_call(false = _FDEnabled, 'GetStatistics', _Args, _Opts, _Deadline) -> maybe_call(false = _FDEnabled, _Service, _Args, _Opts, _Deadline) -> disabled. -do_call('InitService', {ServiceId, _ServiceConfig} = Args, Opts, Deadline) -> +do_call('InitService', {ServiceID, _ServiceConfig} = Args, Opts, Deadline) -> try hg_woody_wrapper:call(fault_detector, 'InitService', Args, Opts, Deadline) of {ok, _Result} -> {ok, initialised} catch @@ -134,14 +134,14 @@ do_call('InitService', {ServiceId, _ServiceConfig} = Args, Opts, Deadline) -> Class =:= result_unknown -> ErrorText = "Unable to init service ~p in fault detector, ~p:~p", - _ = logger:warning(ErrorText, [ServiceId, error, Reason]), + _ = logger:warning(ErrorText, [ServiceID, error, Reason]), {error, Reason}; error:{woody_error, {_Source, result_unexpected, _Details}} = Reason -> ErrorText = "Unable to init service ~p in fault detector, ~p:~p", - _ = logger:error(ErrorText, [ServiceId, error, Reason]), + _ = logger:error(ErrorText, [ServiceID, error, Reason]), {error, Reason} end; -do_call('GetStatistics', {ServiceIds} = Args, Opts, Deadline) -> +do_call('GetStatistics', {ServiceIDs} = Args, Opts, Deadline) -> try hg_woody_wrapper:call(fault_detector, 'GetStatistics', Args, Opts, Deadline) of {ok, Stats} -> Stats catch @@ -150,14 +150,14 @@ do_call('GetStatistics', {ServiceIds} = Args, Opts, Deadline) -> Class =:= result_unknown -> String = "Unable to get statistics for services ~p from fault detector, ~p:~p", - _ = logger:warning(String, [ServiceIds, error, Reason]), + _ = logger:warning(String, [ServiceIDs, error, Reason]), []; error:{woody_error, {_Source, result_unexpected, _Details}} = Reason -> String = "Unable to get statistics for services ~p from fault detector, ~p:~p", - _ = logger:error(String, [ServiceIds, error, Reason]), + _ = logger:error(String, [ServiceIDs, error, Reason]), [] end; -do_call('RegisterOperation', {ServiceId, OperationId, _ServiceConfig} = Args, Opts, Deadline) -> +do_call('RegisterOperation', {ServiceID, OperationID, _ServiceConfig} = Args, Opts, Deadline) -> try hg_woody_wrapper:call(fault_detector, 'RegisterOperation', Args, Opts, Deadline) of {ok, _Result} -> {ok, registered}; @@ -169,10 +169,10 @@ do_call('RegisterOperation', {ServiceId, OperationId, _ServiceConfig} = Args, Op Class =:= result_unknown -> ErrorText = "Unable to register operation ~p for service ~p in fault detector, ~p:~p", - _ = logger:warning(ErrorText, [OperationId, ServiceId, error, Reason]), + _ = logger:warning(ErrorText, [OperationID, ServiceID, error, Reason]), {error, Reason}; error:{woody_error, {_Source, result_unexpected, _Details}} = Reason -> ErrorText = "Unable to register operation ~p for service ~p in fault detector, ~p:~p", - _ = logger:error(ErrorText, [OperationId, ServiceId, error, Reason]), + _ = logger:error(ErrorText, [OperationID, ServiceID, error, Reason]), {error, Reason} end. diff --git a/apps/hellgate/src/hg_inspector.erl b/apps/hellgate/src/hg_inspector.erl index 4efd5d5d..25edf860 100644 --- a/apps/hellgate/src/hg_inspector.erl +++ b/apps/hellgate/src/hg_inspector.erl @@ -100,10 +100,10 @@ inspect( RiskScore. get_payment_info( - Shop = #domain_ShopConfig{ + #domain_ShopConfig{ category = CategoryRef, location = Location - }, + } = Shop, #domain_Invoice{ party_ref = PartyConfigRef, shop_ref = ShopConfigRef, diff --git a/apps/hellgate/src/hg_invoice.erl b/apps/hellgate/src/hg_invoice.erl index ad4822d0..d20a5460 100644 --- a/apps/hellgate/src/hg_invoice.erl +++ b/apps/hellgate/src/hg_invoice.erl @@ -90,8 +90,8 @@ %% API -spec get(hg_machine:id()) -> {ok, st()} | {error, notfound}. -get(Id) -> - case hg_machine:get_history(?NS, Id) of +get(ID) -> + case hg_machine:get_history(?NS, ID) of {ok, History} -> {ok, collapse_history(unmarshal_history(History))}; Error -> @@ -108,7 +108,7 @@ get_payment(PaymentID, St) -> end. -spec get_payment_opts(st()) -> hg_invoice_payment:opts(). -get_payment_opts(St = #st{invoice = Invoice, party = undefined}) -> +get_payment_opts(#st{invoice = Invoice, party = undefined} = St) -> {PartyConfigRef, Party} = hg_party:get_party(get_party_config_ref(St)), #{ party => Party, @@ -126,7 +126,7 @@ get_payment_opts(#st{invoice = Invoice, party = Party, party_config_ref = PartyC -spec get_payment_opts(hg_domain:revision(), st()) -> hg_invoice_payment:opts(). -get_payment_opts(Revision, St = #st{invoice = Invoice}) -> +get_payment_opts(Revision, #st{invoice = Invoice} = St) -> {PartyConfigRef, Party} = hg_party:checkout(get_party_config_ref(St), Revision), #{ party => Party, @@ -144,7 +144,7 @@ get_payment_opts(Revision, St = #st{invoice = Invoice}) -> revision() ) -> invoice(). -create(ID, InvoiceTplID, V = #payproc_InvoiceParams{}, _Allocation, Mutations, DomainRevision) -> +create(ID, InvoiceTplID, #payproc_InvoiceParams{} = V, _Allocation, Mutations, DomainRevision) -> PartyConfigRef = V#payproc_InvoiceParams.party_id, ShopConfigRef = V#payproc_InvoiceParams.shop_id, Cost = V#payproc_InvoiceParams.cost, @@ -262,8 +262,8 @@ process_with_tag(Tag, F) -> %% -spec fail(hg_machine:id()) -> ok. -fail(Id) -> - try hg_machine:call(?NS, Id, fail) of +fail(ID) -> + try hg_machine:call(?NS, ID, fail) of {error, failed} -> ok; {error, Error} -> @@ -315,7 +315,7 @@ handle_repair({changes, Changes, RepairAction, Params}, St) -> }; handle_repair({scenario, _}, #st{activity = Activity}) when Activity =:= invoice orelse Activity =:= undefined -> throw({exception, invoice_has_no_active_payment}); -handle_repair({scenario, Scenario}, St = #st{activity = {payment, PaymentID}}) -> +handle_repair({scenario, Scenario}, #st{activity = {payment, PaymentID}} = St) -> PaymentSession = get_payment_session(PaymentID, St), Activity = hg_invoice_payment:get_activity(PaymentSession), case {Scenario, Activity} of @@ -329,11 +329,11 @@ handle_repair({scenario, Scenario}, St = #st{activity = {payment, PaymentID}}) - process_signal(Signal, #{history := History}) -> handle_result(handle_signal(Signal, collapse_history(unmarshal_history(History)))). -handle_signal(timeout, St = #st{activity = {payment, PaymentID}}) -> +handle_signal(timeout, #st{activity = {payment, PaymentID}} = St) -> % there's a payment pending PaymentSession = get_payment_session(PaymentID, St), process_payment_signal(timeout, PaymentID, PaymentSession, St); -handle_signal(timeout, St = #st{activity = invoice}) -> +handle_signal(timeout, #st{activity = invoice} = St) -> % invoice is expired handle_expiration(St). @@ -493,10 +493,10 @@ handle_call({session_change, _Tag, _SessionChange} = Call, St) -> -spec dispatch_to_session({callback, tag(), callback()} | {session_change, tag(), session_change()}, st()) -> call_result(). -dispatch_to_session({callback, Tag, {provider, Payload}}, St = #st{activity = {payment, PaymentID}}) -> +dispatch_to_session({callback, Tag, {provider, Payload}}, #st{activity = {payment, PaymentID}} = St) -> PaymentSession = get_payment_session(PaymentID, St), process_payment_call({callback, Tag, Payload}, PaymentID, PaymentSession, St); -dispatch_to_session({session_change, _Tag, _SessionChange} = Call, St = #st{activity = {payment, PaymentID}}) -> +dispatch_to_session({session_change, _Tag, _SessionChange} = Call, #st{activity = {payment, PaymentID}} = St) -> PaymentSession = get_payment_session(PaymentID, St), process_payment_call(Call, PaymentID, PaymentSession, St); dispatch_to_session(_Call, _St) -> @@ -733,7 +733,7 @@ define_refund_id(#payproc_InvoicePaymentRefundParams{id = ID}, _PaymentSession) -define(MANUAL_REFUND_ID_PREFIX, "m"). %% If something breaks - this is why -force_refund_id_format(manual_refund, Correct = <>) -> +force_refund_id_format(manual_refund, <> = Correct) -> Correct; force_refund_id_format(manual_refund, Incorrect) -> <>; @@ -816,7 +816,7 @@ try_to_get_repair_state({complex, #payproc_InvoiceRepairComplex{scenarios = Scen try_to_get_repair_state(Scenario, St) -> repair_scenario(Scenario, St). -repair_complex([], St = #st{activity = {payment, PaymentID}}) -> +repair_complex([], #st{activity = {payment, PaymentID}} = St) -> PaymentSession = get_payment_session(PaymentID, St), Activity = hg_invoice_payment:get_activity(PaymentSession), throw({exception, {activity_not_compatible_with_complex_scenario, Activity}}); @@ -828,7 +828,7 @@ repair_complex([Scenario | Rest], St) -> repair_complex(Rest, St) end. -repair_scenario(Scenario, St = #st{activity = {payment, PaymentID}}) -> +repair_scenario(Scenario, #st{activity = {payment, PaymentID}} = St) -> PaymentSession = get_payment_session(PaymentID, St), Activity = hg_invoice_payment:get_activity(PaymentSession), NewActivity = @@ -923,7 +923,7 @@ try_get_payment_session(PaymentID, #st{payments = Payments}) -> undefined end. -set_payment_session(PaymentID, PaymentSession, St = #st{payments = Payments}) -> +set_payment_session(PaymentID, PaymentSession, #st{payments = Payments} = St) -> St#st{payments = lists:keystore(PaymentID, 1, Payments, {PaymentID, PaymentSession})}. %% diff --git a/apps/hellgate/src/hg_invoice_mutation.erl b/apps/hellgate/src/hg_invoice_mutation.erl index b06caa43..c3b45ea2 100644 --- a/apps/hellgate/src/hg_invoice_mutation.erl +++ b/apps/hellgate/src/hg_invoice_mutation.erl @@ -67,7 +67,7 @@ cart_is_not_valid_for_mutation(Lines) -> apply_mutations(Mutations, Invoice) -> lists:foldl(fun apply_mutation/2, Invoice, genlib:define(Mutations, [])). -apply_mutation(Mutation = {amount, #domain_InvoiceAmountMutation{mutated = NewAmount}}, Invoice) -> +apply_mutation({amount, #domain_InvoiceAmountMutation{mutated = NewAmount}} = Mutation, Invoice) -> #domain_Invoice{cost = Cost, mutations = Mutations} = Invoice, update_invoice_details_price(NewAmount, Invoice#domain_Invoice{ cost = Cost#domain_Cash{amount = NewAmount}, @@ -76,7 +76,7 @@ apply_mutation(Mutation = {amount, #domain_InvoiceAmountMutation{mutated = NewAm apply_mutation(_, Invoice) -> Invoice. -update_invoice_details_price(NewAmount, Invoice = #domain_Invoice{details = Details}) -> +update_invoice_details_price(NewAmount, #domain_Invoice{details = Details} = Invoice) -> case Details#domain_InvoiceDetails.cart of Cart = #domain_InvoiceCart{lines = [Line]} -> NewCart = Cart#domain_InvoiceCart{ @@ -89,7 +89,7 @@ update_invoice_details_price(NewAmount, Invoice = #domain_Invoice{details = Deta Invoice end. -update_invoice_line_price(NewAmount, Line = #domain_InvoiceLine{price = Price}) -> +update_invoice_line_price(NewAmount, #domain_InvoiceLine{price = Price} = Line) -> Line#domain_InvoiceLine{price = Price#domain_Cash{amount = NewAmount}}. -spec make_mutations([mutation_params()], mutation_context()) -> [mutation()]. diff --git a/apps/hellgate/src/hg_invoice_payment.erl b/apps/hellgate/src/hg_invoice_payment.erl index 4fff41d1..2b37a63b 100644 --- a/apps/hellgate/src/hg_invoice_payment.erl +++ b/apps/hellgate/src/hg_invoice_payment.erl @@ -405,7 +405,7 @@ init(PaymentID, PaymentParams, Opts) -> ). -spec init_(payment_id(), _, opts()) -> {st(), result()}. -init_(PaymentID, Params, Opts = #{timestamp := CreatedAt}) -> +init_(PaymentID, Params, #{timestamp := CreatedAt} = Opts) -> #payproc_InvoicePaymentParams{ payer = PayerParams, flow = FlowParams, @@ -839,12 +839,12 @@ collect_validation_varset_(PartyConfigRef, {#domain_ShopConfigRef{id = ShopConfi %% -spec construct_payment_plan_id(st()) -> payment_plan_id(). -construct_payment_plan_id(St = #st{opts = Opts, payment = Payment}) -> +construct_payment_plan_id(#st{opts = Opts, payment = Payment} = St) -> Iter = get_iter(St), construct_payment_plan_id(get_invoice(Opts), Payment, Iter, normal). -spec construct_payment_plan_id(st(), legacy | normal) -> payment_plan_id(). -construct_payment_plan_id(St = #st{opts = Opts, payment = Payment}, Mode) -> +construct_payment_plan_id(#st{opts = Opts, payment = Payment} = St, Mode) -> Iter = get_iter(St), construct_payment_plan_id(get_invoice(Opts), Payment, Iter, Mode). @@ -911,18 +911,11 @@ maybe_allocation(AllocationPrototype, Cost, MerchantTerms, Revision, Opts) -> } = MerchantTerms, Party = get_party(Opts), Shop = get_shop(Opts, Revision), - case - hg_allocation:calculate( - AllocationPrototype, - Party, - Shop, - Cost, - AllocationSelector - ) - of - {error, allocation_not_allowed} -> - throw(#payproc_AllocationNotAllowed{}) - end. + + %% NOTE Allocation is currently not allowed. + {error, allocation_not_allowed} = + hg_allocation:calculate(AllocationPrototype, Party, Shop, Cost, AllocationSelector), + throw(#payproc_AllocationNotAllowed{}). total_capture(St, Reason, Cart, Allocation) -> Payment = get_payment(St), @@ -972,7 +965,7 @@ assert_capture_cost_currency(?cash(_, PassedSymCode), #domain_InvoicePayment{cos passed_currency = PassedSymCode }). -validate_processing_deadline(#domain_InvoicePayment{processing_deadline = Deadline}, _TargetType = processed) -> +validate_processing_deadline(#domain_InvoicePayment{processing_deadline = Deadline}, processed = _TargetType) -> case hg_invoice_utils:check_deadline(Deadline) of ok -> ok; @@ -1079,7 +1072,7 @@ validate_payment_status(_, #domain_InvoicePayment{status = Status}) -> throw(#payproc_InvalidPaymentStatus{status = Status}). -spec refund(refund_params(), st(), opts()) -> {domain_refund(), result()}. -refund(Params, St0, Opts = #{timestamp := CreatedAt}) -> +refund(Params, St0, #{timestamp := CreatedAt} = Opts) -> St = St0#st{opts = Opts}, Revision = hg_domain:head(), Payment = get_payment(St), @@ -1094,7 +1087,7 @@ refund(Params, St0, Opts = #{timestamp := CreatedAt}) -> {Refund, {Changes, hg_machine_action:instant()}}. -spec manual_refund(refund_params(), st(), opts()) -> {domain_refund(), result()}. -manual_refund(Params, St0, Opts = #{timestamp := CreatedAt}) -> +manual_refund(Params, St0, #{timestamp := CreatedAt} = Opts) -> St = St0#st{opts = Opts}, Revision = hg_domain:head(), Payment = get_payment(St), @@ -1222,7 +1215,7 @@ get_remaining_payment_balance(St) -> _ -> Acc end; - (CB = #domain_InvoicePaymentChargeback{}, Acc) -> + (#domain_InvoicePaymentChargeback{} = CB, Acc) -> case hg_invoice_payment_chargeback:get_status(CB) of ?chargeback_status_accepted() -> hg_cash:sub(Acc, hg_invoice_payment_chargeback:get_body(CB)); @@ -1517,7 +1510,7 @@ get_cash_flow_for_target_status({failed, _}, _St, _Opts) -> []. -spec calculate_cashflow(cashflow_context(), opts()) -> final_cash_flow(). -calculate_cashflow(Context = #{route := Route, revision := Revision}, Opts) -> +calculate_cashflow(#{route := Route, revision := Revision} = Context, Opts) -> CollectCashflowContext = genlib_map:compact(Context#{ operation => payment, party => get_party_obj(Opts), @@ -1527,7 +1520,7 @@ calculate_cashflow(Context = #{route := Route, revision := Revision}, Opts) -> hg_cashflow_utils:collect_cashflow(CollectCashflowContext). -spec calculate_cashflow(hg_payment_institution:t(), cashflow_context(), opts()) -> final_cash_flow(). -calculate_cashflow(PaymentInstitution, Context = #{route := Route, revision := Revision}, Opts) -> +calculate_cashflow(PaymentInstitution, #{route := Route, revision := Revision} = Context, Opts) -> CollectCashflowContext = genlib_map:compact(Context#{ operation => payment, party => get_party_obj(Opts), @@ -1739,7 +1732,7 @@ process_timeout({adjustment_pending, ID}, Action, St) -> process_timeout({payment, flow_waiting}, Action, St) -> finalize_payment(Action, St). -process_refund(ID, St = #st{opts = Options0, payment = Payment, repair_scenario = Scenario}) -> +process_refund(ID, #st{opts = Options0, payment = Payment, repair_scenario = Scenario} = St) -> RepairScenario = case hg_invoice_repair:check_for_action(repair_session, Scenario) of call -> undefined; @@ -1781,7 +1774,7 @@ process_refund_result(Changes, Refund0, St) -> end, Changes ++ PaymentEvents. -repair_process_timeout(Activity, Action, St = #st{repair_scenario = Scenario}) -> +repair_process_timeout(Activity, Action, #st{repair_scenario = Scenario} = St) -> case hg_invoice_repair:check_for_action(fail_pre_processing, Scenario) of {result, Result} when Activity =:= {payment, routing} orelse @@ -1867,7 +1860,7 @@ construct_shop_limit_failure(limit_overflow, IDs) -> Reason = genlib:format("Limits with following IDs overflowed: ~p", [IDs]), {failure, payproc_errors:construct('PaymentFailure', Error, Reason)}. -process_shop_limit_failure(Action, St = #st{failure = Failure}) -> +process_shop_limit_failure(Action, #st{failure = Failure} = St) -> Opts = get_opts(St), _ = rollback_shop_limits(Opts, St, [ignore_business_error, ignore_not_found]), {done, {[?payment_status_changed(?failed(Failure))], hg_machine_action:set_timeout(0, Action)}}. @@ -1933,7 +1926,7 @@ run_routing_decision_pipeline(Ctx0, VS, St) -> ] ). -produce_routing_events(Ctx = #{error := Error}, _Revision, St) when Error =/= undefined -> +produce_routing_events(#{error := Error} = Ctx, _Revision, St) when Error =/= undefined -> %% TODO Pass failure subcode from error. Say, if last candidates were %% rejected because of provider gone critical, then use subcode to highlight %% the offender. Like 'provider_dead' or 'conversion_lacking'. @@ -2033,7 +2026,7 @@ construct_routing_failure({rejected_routes, {_SubCode, RejectedRoutes}}) -> construct_routing_failure([forbidden], genlib:format(RejectedRoutes)); construct_routing_failure({misconfiguration = Code, Details}) -> construct_routing_failure([unknown, {unknown_error, atom_to_binary(Code)}], genlib:format(Details)); -construct_routing_failure(Code = risk_score_is_too_high) -> +construct_routing_failure(risk_score_is_too_high = Code) -> construct_routing_failure([Code], undefined); construct_routing_failure(Error) when is_atom(Error) -> construct_routing_failure([{unknown_error, Error}], undefined). @@ -2077,7 +2070,7 @@ process_cash_flow_building(Action, St) -> %% -spec process_chargeback(chargeback_activity_type(), chargeback_id(), action(), st()) -> machine_result(). -process_chargeback(Type = finalising_accounter, ID, Action0, St) -> +process_chargeback(finalising_accounter = Type, ID, Action0, St) -> ChargebackState = get_chargeback_state(ID, St), ChargebackOpts = get_chargeback_opts(St), ChargebackBody = hg_invoice_payment_chargeback:get_body(ChargebackState), @@ -2131,7 +2124,7 @@ process_adjustment_cashflow(ID, _Action, St) -> Events = [?adjustment_ev(ID, ?adjustment_status_changed(?adjustment_processed()))], {next, {Events, hg_machine_action:instant()}}. -process_accounter_update(Action, St = #st{partial_cash_flow = FinalCashflow, capture_data = CaptureData}) -> +process_accounter_update(Action, #st{partial_cash_flow = FinalCashflow, capture_data = CaptureData} = St) -> #payproc_InvoicePaymentCaptureData{ reason = Reason, cash = Cost, @@ -2180,7 +2173,7 @@ process_session(undefined, St0) -> Failure -> process_failure(get_activity(St0), [], Action, Failure, St0) end; -process_session(Session0, St = #st{repair_scenario = Scenario}) -> +process_session(Session0, #st{repair_scenario = Scenario} = St) -> Session1 = case hg_invoice_repair:check_for_action(repair_session, Scenario) of RepairScenario = {result, _} -> @@ -2253,7 +2246,7 @@ finalize_payment(Action, St) -> process_result(Action, St) -> process_result(get_activity(St), Action, St). -process_result({payment, processing_accounter}, Action, St0 = #st{new_cash = Cost}) when +process_result({payment, processing_accounter}, Action, #st{new_cash = Cost} = St0) when Cost =/= undefined -> %% Rebuild cashflow for new cost @@ -2292,12 +2285,12 @@ process_result({payment, processing_accounter}, Action, St) -> Target = get_target(St), NewAction = get_action(Target, Action, St), {done, {[?payment_status_changed(Target)], NewAction}}; -process_result({payment, routing_failure}, Action, St = #st{failure = Failure}) -> +process_result({payment, routing_failure}, Action, #st{failure = Failure} = St) -> NewAction = hg_machine_action:set_timeout(0, Action), Routes = get_candidate_routes(St), _ = rollback_payment_limits(Routes, get_iter(St), St, [ignore_business_error, ignore_not_found]), {done, {[?payment_status_changed(?failed(Failure))], NewAction}}; -process_result({payment, processing_failure}, Action, St = #st{failure = Failure}) -> +process_result({payment, processing_failure}, Action, #st{failure = Failure} = St) -> NewAction = hg_machine_action:set_timeout(0, Action), %% We need to rollback only current route. %% Previously used routes are supposed to have their limits already rolled back. @@ -2711,11 +2704,11 @@ do_try_with_ids([ID | OtherIDs], Func) when is_function(Func, 1) -> end. get_cashflow_plan( - St = #st{ + #st{ partial_cash_flow = PartialCashFlow, new_cash_provided = true, new_cash_flow = NewCashFlow - } + } = St ) when PartialCashFlow =/= undefined -> [ {1, get_cashflow(St)}, @@ -2724,13 +2717,13 @@ get_cashflow_plan( {4, hg_cashflow:revert(PartialCashFlow)}, {5, NewCashFlow} ]; -get_cashflow_plan(St = #st{new_cash_provided = true, new_cash_flow = NewCashFlow}) -> +get_cashflow_plan(#st{new_cash_provided = true, new_cash_flow = NewCashFlow} = St) -> [ {1, get_cashflow(St)}, {2, hg_cashflow:revert(get_cashflow(St))}, {3, NewCashFlow} ]; -get_cashflow_plan(St = #st{partial_cash_flow = PartialCashFlow}) when PartialCashFlow =/= undefined -> +get_cashflow_plan(#st{partial_cash_flow = PartialCashFlow} = St) when PartialCashFlow =/= undefined -> [ {1, get_cashflow(St)}, {2, hg_cashflow:revert(get_cashflow(St))}, @@ -3353,13 +3346,13 @@ latest_adjustment_id(#st{adjustments = Adjustments}) -> Adjustment#domain_InvoicePaymentAdjustment.id. get_routing_attempt_limit( - St = #st{ + #st{ payment = #domain_InvoicePayment{ party_ref = PartyConfigRef, shop_ref = ShopConfigRef, domain_revision = Revision } - } + } = St ) -> {PartyConfigRef, _Party} = hg_party:checkout(PartyConfigRef, Revision), ShopObj = {_, Shop} = hg_party:get_shop(ShopConfigRef, PartyConfigRef, Revision), @@ -3489,7 +3482,7 @@ try_accrue_waiting_timing(Opts, #st{payment = Payment, timings = Timings}) -> get_cashflow(#st{cash_flow = FinalCashflow}) -> FinalCashflow. -set_cashflow(Cashflow, St = #st{}) -> +set_cashflow(Cashflow, #st{} = St) -> St#st{ cash_flow = Cashflow, final_cash_flow = Cashflow @@ -3503,9 +3496,9 @@ get_final_cashflow(#st{final_cash_flow = Cashflow}) -> get_trx(#st{trx = Trx}) -> Trx. -set_trx(undefined, St = #st{}) -> +set_trx(undefined, #st{} = St) -> St; -set_trx(Trx, St = #st{}) -> +set_trx(Trx, #st{} = St) -> St#st{trx = Trx}. try_get_refund_state(ID, #st{refunds = Rs}) -> @@ -3516,7 +3509,7 @@ try_get_refund_state(ID, #st{refunds = Rs}) -> undefined end. -set_chargeback_state(ID, ChargebackSt, St = #st{chargebacks = CBs}) -> +set_chargeback_state(ID, ChargebackSt, #st{chargebacks = CBs} = St) -> St#st{chargebacks = CBs#{ID => ChargebackSt}}. try_get_chargeback_state(ID, #st{chargebacks = CBs}) -> @@ -3527,7 +3520,7 @@ try_get_chargeback_state(ID, #st{chargebacks = CBs}) -> undefined end. -set_refund_state(ID, RefundSt, St = #st{refunds = Rs}) -> +set_refund_state(ID, RefundSt, #st{refunds = Rs} = St) -> St#st{refunds = Rs#{ID => RefundSt}}. -spec get_origin(st() | undefined) -> dmsl_domain_thrift:'InvoicePaymentRegistrationOrigin'() | undefined. @@ -3543,7 +3536,7 @@ get_captured_allocation(#domain_InvoicePaymentCaptured{allocation = Allocation}) Allocation. -spec create_session_event_context(target(), st(), change_opts()) -> hg_session:event_context(). -create_session_event_context(Target, St, Opts = #{invoice_id := InvoiceID}) -> +create_session_event_context(Target, St, #{invoice_id := InvoiceID} = Opts) -> #{ timestamp => define_event_timestamp(Opts), target => Target, @@ -3584,7 +3577,7 @@ try_get_adjustment(ID, #st{adjustments = As}) -> undefined end. -set_adjustment(ID, Adjustment, St = #st{adjustments = As}) -> +set_adjustment(ID, Adjustment, #st{adjustments = As} = St) -> St#st{adjustments = lists:keystore(ID, #domain_InvoicePaymentAdjustment.id, As, Adjustment)}. get_invoice_state(InvoiceID) -> @@ -3615,12 +3608,12 @@ get_session(Target, #st{sessions = Sessions, routes = [Route | _PreviousRoutes]} end. -spec add_session(target(), session(), st()) -> st(). -add_session(Target, Session, St = #st{sessions = Sessions}) -> +add_session(Target, Session, #st{sessions = Sessions} = St) -> TargetType = get_target_type(Target), TargetTypeSessions = maps:get(TargetType, Sessions, []), St#st{sessions = Sessions#{TargetType => [Session | TargetTypeSessions]}}. -update_session(Target, Session, St = #st{sessions = Sessions}) -> +update_session(Target, Session, #st{sessions = Sessions} = St) -> TargetType = get_target_type(Target), [_ | Rest] = maps:get(TargetType, Sessions, []), St#st{sessions = Sessions#{TargetType => [Session | Rest]}}. @@ -3670,7 +3663,7 @@ get_route_provider(#domain_PaymentRoute{provider = ProviderRef}) -> get_route_provider(Route, Revision) -> hg_domain:get(Revision, {provider, get_route_provider_ref(Route)}). -inspect(Payment = #domain_InvoicePayment{domain_revision = Revision}, PaymentInstitution, Opts) -> +inspect(#domain_InvoicePayment{domain_revision = Revision} = Payment, PaymentInstitution, Opts) -> InspectorRef = get_selector_value(inspector, PaymentInstitution#domain_PaymentInstitution.inspector), Inspector = hg_domain:get(Revision, {inspector, InspectorRef}), hg_inspector:inspect(get_shop(Opts, Revision), get_invoice(Opts), Payment, Inspector). diff --git a/apps/hellgate/src/hg_invoice_payment_chargeback.erl b/apps/hellgate/src/hg_invoice_payment_chargeback.erl index e89887e9..90967845 100644 --- a/apps/hellgate/src/hg_invoice_payment_chargeback.erl +++ b/apps/hellgate/src/hg_invoice_payment_chargeback.erl @@ -353,7 +353,7 @@ update_cash_flow(State, Action, Opts) -> -spec finalise(state(), action(), opts()) -> result() | no_return(). finalise(#chargeback_st{target_status = Status = ?chargeback_status_pending()}, Action, _Opts) -> {[?chargeback_status_changed(Status)], Action}; -finalise(State = #chargeback_st{target_status = Status}, Action, Opts) when +finalise(#chargeback_st{target_status = Status} = State, Action, Opts) when Status =:= ?chargeback_status_rejected(); Status =:= ?chargeback_status_accepted(); Status =:= ?chargeback_status_cancelled() diff --git a/apps/hellgate/src/hg_invoice_payment_refund.erl b/apps/hellgate/src/hg_invoice_payment_refund.erl index 0d594ec7..e0463015 100644 --- a/apps/hellgate/src/hg_invoice_payment_refund.erl +++ b/apps/hellgate/src/hg_invoice_payment_refund.erl @@ -204,7 +204,7 @@ route(#{route := V}) -> %% API -spec create(params()) -> events(). -create(Params = #{refund := Refund, cash_flow := Cashflow}) -> +create(#{refund := Refund, cash_flow := Cashflow} = Params) -> TransactionInfo = maps:get(transaction_info, Params, undefined), ID = Refund#domain_InvoicePaymentRefund.id, [?refund_ev(ID, ?refund_created(Refund, Cashflow, TransactionInfo))]. diff --git a/apps/hellgate/src/hg_invoice_registered_payment.erl b/apps/hellgate/src/hg_invoice_registered_payment.erl index aa936779..ec68df5d 100644 --- a/apps/hellgate/src/hg_invoice_registered_payment.erl +++ b/apps/hellgate/src/hg_invoice_registered_payment.erl @@ -31,7 +31,7 @@ init(PaymentID, Params, Opts) -> -spec init_(hg_invoice_payment:payment_id(), _, hg_invoice_payment:opts()) -> {hg_invoice_payment:st(), hg_invoice_payment:result()}. -init_(PaymentID, Params, Opts = #{timestamp := CreatedAt0}) -> +init_(PaymentID, Params, #{timestamp := CreatedAt0} = Opts) -> #payproc_RegisterInvoicePaymentParams{ payer_params = PayerParams, route = Route, diff --git a/apps/hellgate/src/hg_invoice_template.erl b/apps/hellgate/src/hg_invoice_template.erl index df6f1c69..7c178e0b 100644 --- a/apps/hellgate/src/hg_invoice_template.erl +++ b/apps/hellgate/src/hg_invoice_template.erl @@ -37,8 +37,8 @@ %% API -spec get(tpl_id()) -> tpl(). -get(TplId) -> - get_invoice_template(TplId). +get(TplID) -> + get_invoice_template(TplID). get_invoice_template(ID) -> History = get_history(ID), diff --git a/apps/hellgate/src/hg_invoice_utils.erl b/apps/hellgate/src/hg_invoice_utils.erl index 50d584d2..815ed574 100644 --- a/apps/hellgate/src/hg_invoice_utils.erl +++ b/apps/hellgate/src/hg_invoice_utils.erl @@ -49,7 +49,7 @@ validate_amount(_) -> throw(#base_InvalidRequest{errors = [<<"Invalid amount">>]}). -spec validate_currency(currency(), shop()) -> ok. -validate_currency(Currency, Shop = #domain_ShopConfig{}) -> +validate_currency(Currency, #domain_ShopConfig{} = Shop) -> validate_currency_(Currency, get_shop_currency(Shop)). -spec validate_cash_range(cash_range()) -> ok. diff --git a/apps/hellgate/src/hg_limiter.erl b/apps/hellgate/src/hg_limiter.erl index 8eeb24f6..e448861f 100644 --- a/apps/hellgate/src/hg_limiter.erl +++ b/apps/hellgate/src/hg_limiter.erl @@ -99,8 +99,8 @@ get_batch_limit_values(_Context, [], _OperationIdSegments) -> get_batch_limit_values(Context, TurnoverLimits, OperationIdSegments) -> {LimitRequest, TurnoverLimitsMap} = prepare_limit_request(TurnoverLimits, OperationIdSegments), lists:map( - fun(#limiter_Limit{id = Id, amount = Amount}) -> - #payproc_TurnoverLimitValue{limit = maps:get(Id, TurnoverLimitsMap), value = Amount} + fun(#limiter_Limit{id = ID, amount = Amount}) -> + #payproc_TurnoverLimitValue{limit = maps:get(ID, TurnoverLimitsMap), value = Amount} end, hg_limiter_client:get_batch(LimitRequest, Context) ). @@ -395,14 +395,14 @@ maybe_route_context(#base_Route{provider = Provider, terminal = Terminal}) -> prepare_limit_request(TurnoverLimits, IdSegments) -> {TurnoverLimitsIdList, LimitChanges} = lists:unzip( lists:map( - fun(TurnoverLimit = #domain_TurnoverLimit{ref = ?ref(LimitID), domain_revision = DomainRevision}) -> + fun(#domain_TurnoverLimit{ref = ?ref(LimitID), domain_revision = DomainRevision} = TurnoverLimit) -> {{LimitID, TurnoverLimit}, #limiter_LimitChange{id = LimitID, version = DomainRevision}} end, TurnoverLimits ) ), - OperationId = make_operation_id(IdSegments), - LimitRequest = #limiter_LimitRequest{operation_id = OperationId, limit_changes = LimitChanges}, + OperationID = make_operation_id(IdSegments), + LimitRequest = #limiter_LimitRequest{operation_id = OperationID, limit_changes = LimitChanges}, TurnoverLimitsMap = maps:from_list(TurnoverLimitsIdList), {LimitRequest, TurnoverLimitsMap}. diff --git a/apps/hellgate/src/hg_machine.erl b/apps/hellgate/src/hg_machine.erl index 5fdc4c1f..91a98829 100644 --- a/apps/hellgate/src/hg_machine.erl +++ b/apps/hellgate/src/hg_machine.erl @@ -117,16 +117,16 @@ %% -spec start(ns(), id(), term()) -> {ok, term()} | {error, exists | term()} | no_return(). -start(Ns, ID, Args) -> - call_automaton('Start', {Ns, ID, wrap_args(Args)}). +start(NS, ID, Args) -> + call_automaton('Start', {NS, ID, wrap_args(Args)}). -spec thrift_call(ns(), id(), service_name(), function_ref(), args()) -> response() | {error, notfound | failed}. -thrift_call(Ns, Id, Service, FunRef, Args) -> - thrift_call(Ns, Id, Service, FunRef, Args, undefined, undefined, forward). +thrift_call(NS, ID, Service, FunRef, Args) -> + thrift_call(NS, ID, Service, FunRef, Args, undefined, undefined, forward). --spec thrift_call(Ns, Id, Service, FunRef, Args, After, Limit, Direction) -> Result when - Ns :: ns(), - Id :: id(), +-spec thrift_call(NS, ID, Service, FunRef, Args, After, Limit, Direction) -> Result when + NS :: ns(), + ID :: id(), Service :: service_name(), FunRef :: function_ref(), Args :: args(), @@ -134,10 +134,10 @@ thrift_call(Ns, Id, Service, FunRef, Args) -> Limit :: integer() | undefined, Direction :: forward | backward, Result :: response() | {error, notfound | failed}. -thrift_call(Ns, Id, Service, FunRef, Args, After, Limit, Direction) -> +thrift_call(NS, ID, Service, FunRef, Args, After, Limit, Direction) -> EncodedArgs = marshal_thrift_args(Service, FunRef, Args), Call = {thrift_call, Service, FunRef, EncodedArgs}, - case do_call(Ns, Id, Call, After, Limit, Direction) of + case do_call(NS, ID, Call, After, Limit, Direction) of {ok, Response} -> % should be specific to a processing interface already unmarshal_thrift_response(Service, FunRef, Response); @@ -146,19 +146,19 @@ thrift_call(Ns, Id, Service, FunRef, Args, After, Limit, Direction) -> end. -spec call(ns(), id(), Args :: term()) -> response() | {error, notfound | failed}. -call(Ns, Id, Args) -> - call(Ns, Id, Args, undefined, undefined, forward). +call(NS, ID, Args) -> + call(NS, ID, Args, undefined, undefined, forward). --spec call(Ns, Id, Args, After, Limit, Direction) -> Result when - Ns :: ns(), - Id :: id(), +-spec call(NS, ID, Args, After, Limit, Direction) -> Result when + NS :: ns(), + ID :: id(), Args :: args(), After :: event_id() | undefined, Limit :: integer() | undefined, Direction :: forward | backward, Result :: response() | {error, notfound | failed}. -call(Ns, Id, Args, After, Limit, Direction) -> - case do_call(Ns, Id, {schemaless_call, Args}, After, Limit, Direction) of +call(NS, ID, Args, After, Limit, Direction) -> + case do_call(NS, ID, {schemaless_call, Args}, After, Limit, Direction) of {ok, Response} -> unmarshal_schemaless_response(Response); {error, _} = Error -> @@ -167,23 +167,23 @@ call(Ns, Id, Args, After, Limit, Direction) -> -spec repair(ns(), id(), term()) -> {ok, term()} | {error, notfound | failed | working | {repair, {failed, binary()}}} | no_return(). -repair(Ns, Id, Args) -> - Descriptor = prepare_descriptor(Ns, Id, #mg_stateproc_HistoryRange{}), +repair(NS, ID, Args) -> + Descriptor = prepare_descriptor(NS, ID, #mg_stateproc_HistoryRange{}), call_automaton('Repair', {Descriptor, wrap_args(Args)}). -spec get_history(ns(), id()) -> {ok, history()} | {error, notfound} | no_return(). -get_history(Ns, Id) -> - get_history(Ns, Id, undefined, undefined, forward). +get_history(NS, ID) -> + get_history(NS, ID, undefined, undefined, forward). -spec get_history(ns(), id(), undefined | event_id(), undefined | non_neg_integer()) -> {ok, history()} | {error, notfound} | no_return(). -get_history(Ns, Id, AfterID, Limit) -> - get_history(Ns, Id, AfterID, Limit, forward). +get_history(NS, ID, AfterID, Limit) -> + get_history(NS, ID, AfterID, Limit, forward). -spec get_history(ns(), id(), undefined | event_id(), undefined | non_neg_integer(), direction()) -> {ok, history()} | {error, notfound} | no_return(). -get_history(Ns, Id, AfterID, Limit, Direction) -> - case get_machine(Ns, Id, AfterID, Limit, Direction) of +get_history(NS, ID, AfterID, Limit, Direction) -> + case get_machine(NS, ID, AfterID, Limit, Direction) of {ok, #{history := History}} -> {ok, History}; Error -> @@ -192,9 +192,9 @@ get_history(Ns, Id, AfterID, Limit, Direction) -> -spec get_machine(ns(), id(), undefined | event_id(), undefined | non_neg_integer(), direction()) -> {ok, machine()} | {error, notfound} | no_return(). -get_machine(Ns, Id, AfterID, Limit, Direction) -> +get_machine(NS, ID, AfterID, Limit, Direction) -> Range = #mg_stateproc_HistoryRange{'after' = AfterID, limit = Limit, direction = Direction}, - Descriptor = prepare_descriptor(Ns, Id, Range), + Descriptor = prepare_descriptor(NS, ID, Range), case call_automaton('GetMachine', {Descriptor}) of {ok, #mg_stateproc_Machine{} = Machine} -> {ok, unmarshal_machine(Machine)}; @@ -204,21 +204,21 @@ get_machine(Ns, Id, AfterID, Limit, Direction) -> %% --spec do_call(Ns, Id, Args, After, Limit, Direction) -> Result when - Ns :: ns(), - Id :: id(), +-spec do_call(NS, ID, Args, After, Limit, Direction) -> Result when + NS :: ns(), + ID :: id(), Args :: args(), After :: event_id() | undefined, Limit :: integer() | undefined, Direction :: forward | backward, Result :: {ok, response()} | {error, notfound | failed}. -do_call(Ns, Id, Args, After, Limit, Direction) -> +do_call(NS, ID, Args, After, Limit, Direction) -> HistoryRange = #mg_stateproc_HistoryRange{ 'after' = After, 'limit' = Limit, 'direction' = Direction }, - Descriptor = prepare_descriptor(Ns, Id, HistoryRange), + Descriptor = prepare_descriptor(NS, ID, HistoryRange), case call_automaton('Call', {Descriptor, wrap_args(Args)}) of {ok, Response} -> {ok, unmarshal_response(Response)}; @@ -262,31 +262,31 @@ handle_function(Func, Args, Opts) -> ). -spec handle_function_(func(), woody:args(), #{ns := ns()}) -> term() | no_return(). -handle_function_('ProcessSignal', {Args}, #{ns := Ns} = _Opts) -> +handle_function_('ProcessSignal', {Args}, #{ns := NS} = _Opts) -> #mg_stateproc_SignalArgs{signal = {Type, Signal}, machine = #mg_stateproc_Machine{id = ID} = Machine} = Args, scoper:add_meta(#{ - namespace => Ns, + namespace => NS, id => ID, activity => signal, signal => Type }), - dispatch_signal(Ns, Signal, unmarshal_machine(Machine)); -handle_function_('ProcessCall', {Args}, #{ns := Ns} = _Opts) -> + dispatch_signal(NS, Signal, unmarshal_machine(Machine)); +handle_function_('ProcessCall', {Args}, #{ns := NS} = _Opts) -> #mg_stateproc_CallArgs{arg = Payload, machine = #mg_stateproc_Machine{id = ID} = Machine} = Args, scoper:add_meta(#{ - namespace => Ns, + namespace => NS, id => ID, activity => call }), - dispatch_call(Ns, Payload, unmarshal_machine(Machine)); -handle_function_('ProcessRepair', {Args}, #{ns := Ns} = _Opts) -> + dispatch_call(NS, Payload, unmarshal_machine(Machine)); +handle_function_('ProcessRepair', {Args}, #{ns := NS} = _Opts) -> #mg_stateproc_RepairArgs{arg = Payload, machine = #mg_stateproc_Machine{id = ID} = Machine} = Args, scoper:add_meta(#{ - namespace => Ns, + namespace => NS, id => ID, activity => repair }), - dispatch_repair(Ns, Payload, unmarshal_machine(Machine)). + dispatch_repair(NS, Payload, unmarshal_machine(Machine)). %% @@ -296,19 +296,19 @@ handle_function_('ProcessRepair', {Args}, #{ns := Ns} = _Opts) -> | mg_proto_state_processing_thrift:'TimeoutSignal'(), Result :: mg_proto_state_processing_thrift:'SignalResult'(). -dispatch_signal(Ns, #mg_stateproc_InitSignal{arg = Payload}, Machine) -> +dispatch_signal(NS, #mg_stateproc_InitSignal{arg = Payload}, Machine) -> Args = unwrap_args(Payload), _ = log_dispatch(init, Args, Machine), - Module = get_handler_module(Ns), + Module = get_handler_module(NS), Result = Module:init(Args, Machine), marshal_signal_result(Result, Machine); -dispatch_signal(Ns, #mg_stateproc_TimeoutSignal{}, Machine) -> +dispatch_signal(NS, #mg_stateproc_TimeoutSignal{}, Machine) -> _ = log_dispatch(timeout, Machine), - Module = get_handler_module(Ns), + Module = get_handler_module(NS), Result = Module:process_signal(timeout, Machine), marshal_signal_result(Result, Machine). -marshal_signal_result(Result = #{}, #{aux_state := AuxStWas}) -> +marshal_signal_result(#{} = Result, #{aux_state := AuxStWas}) -> _ = logger:debug("signal result = ~p", [Result]), Change = #mg_stateproc_MachineStateChange{ events = marshal_events(maps:get(events, Result, [])), @@ -322,10 +322,10 @@ marshal_signal_result(Result = #{}, #{aux_state := AuxStWas}) -> -spec dispatch_call(ns(), Call, machine()) -> Result when Call :: mg_proto_state_processing_thrift:'Args'(), Result :: mg_proto_state_processing_thrift:'CallResult'(). -dispatch_call(Ns, Payload, Machine) -> +dispatch_call(NS, Payload, Machine) -> Args = unwrap_args(Payload), _ = log_dispatch(call, Args, Machine), - Module = get_handler_module(Ns), + Module = get_handler_module(NS), do_dispatch_call(Module, Args, Machine). do_dispatch_call(Module, {schemaless_call, Args}, Machine) -> @@ -352,10 +352,10 @@ marshal_call_result(Response, Result, #{aux_state := AuxStWas}) -> -spec dispatch_repair(ns(), Args, machine()) -> Result when Args :: mg_proto_state_processing_thrift:'Args'(), Result :: mg_proto_state_processing_thrift:'RepairResult'(). -dispatch_repair(Ns, Payload, Machine) -> +dispatch_repair(NS, Payload, Machine) -> Args = unwrap_args(Payload), _ = log_dispatch(repair, Args, Machine), - Module = get_handler_module(Ns), + Module = get_handler_module(NS), try Result = Module:process_repair(Args, Machine), marshal_repair_result(ok, Result, Machine) @@ -365,7 +365,7 @@ dispatch_repair(Ns, Payload, Machine) -> woody_error:raise(business, marshal_repair_failed(Error)) end. -marshal_repair_result(Response, RepairResult = #{}, #{aux_state := AuxStWas}) -> +marshal_repair_result(Response, #{} = RepairResult, #{aux_state := AuxStWas}) -> _ = logger:debug("repair response = ~p with result = ~p", [Response, RepairResult]), Change = #mg_stateproc_MachineStateChange{ events = marshal_events(maps:get(events, RepairResult, [])), @@ -400,9 +400,9 @@ get_service_handlers(MachineHandlers, Opts) -> [get_service_handler(H, Opts) || H <- MachineHandlers]. get_service_handler(MachineHandler, Opts) -> - Ns = MachineHandler:namespace(), - FullOpts = maps:merge(#{ns => Ns, handler => ?MODULE}, Opts), - {Path, Service} = hg_proto:get_service_spec(processor, #{namespace => Ns}), + NS = MachineHandler:namespace(), + FullOpts = maps:merge(#{ns => NS, handler => ?MODULE}, Opts), + {Path, Service} = hg_proto:get_service_spec(processor, #{namespace => NS}), {Path, {Service, {hg_woody_service_wrapper, FullOpts}}}. %% @@ -422,8 +422,8 @@ init(MachineHandlers) -> %% -spec get_handler_module(ns()) -> module(). -get_handler_module(Ns) -> - ets:lookup_element(?TABLE, Ns, 2). +get_handler_module(NS) -> + ets:lookup_element(?TABLE, NS, 2). log_dispatch(Operation, #{id := ID, history := History, aux_state := AuxSt}) -> logger:debug( @@ -561,9 +561,9 @@ unmarshal_term({bin, B}) -> binary_to_term(B). -spec prepare_descriptor(ns(), id(), history_range()) -> descriptor(). -prepare_descriptor(NS, Id, Range) -> +prepare_descriptor(NS, ID, Range) -> #mg_stateproc_MachineDescriptor{ ns = NS, - ref = {id, Id}, + ref = {id, ID}, range = Range }. diff --git a/apps/hellgate/src/hg_machine_action.erl b/apps/hellgate/src/hg_machine_action.erl index 3ea0d501..29984a43 100644 --- a/apps/hellgate/src/hg_machine_action.erl +++ b/apps/hellgate/src/hg_machine_action.erl @@ -56,7 +56,7 @@ set_timer(Timer) -> set_timer(Timer, new()). -spec set_timer(timer(), t()) -> t(). -set_timer(Timer, Action = #mg_stateproc_ComplexAction{}) -> +set_timer(Timer, #mg_stateproc_ComplexAction{} = Action) -> % TODO pass range and processing timeout explicitly too Action#mg_stateproc_ComplexAction{timer = {set_timer, #mg_stateproc_SetTimerAction{timer = Timer}}}. @@ -65,16 +65,16 @@ unset_timer() -> unset_timer(new()). -spec unset_timer(t()) -> t(). -unset_timer(Action = #mg_stateproc_ComplexAction{}) -> +unset_timer(#mg_stateproc_ComplexAction{} = Action) -> Action#mg_stateproc_ComplexAction{timer = {unset_timer, #mg_stateproc_UnsetTimerAction{}}}. -spec mark_removal(t()) -> t(). -mark_removal(Action = #mg_stateproc_ComplexAction{}) -> +mark_removal(#mg_stateproc_ComplexAction{} = Action) -> Action#mg_stateproc_ComplexAction{remove = #mg_stateproc_RemoveAction{}}. %% -try_format_dt(Datetime = {_, _}) -> +try_format_dt({_, _} = Datetime) -> Seconds = genlib_time:daytime_to_unixtime(Datetime), genlib_rfc3339:format(Seconds, second); try_format_dt(Datetime) when is_binary(Datetime) -> diff --git a/apps/hellgate/src/hg_session.erl b/apps/hellgate/src/hg_session.erl index 40352d2f..a84ee8e4 100644 --- a/apps/hellgate/src/hg_session.erl +++ b/apps/hellgate/src/hg_session.erl @@ -235,7 +235,7 @@ do_process(suspended, Session) -> do_process(finished, Session) -> {{[], hg_machine_action:new()}, Session}. -repair(Session = #{repair_scenario := {result, ProxyResult}}) -> +repair(#{repair_scenario := {result, ProxyResult}} = Session) -> Result = handle_proxy_result(ProxyResult, Session), apply_result(Result, Session). @@ -342,7 +342,7 @@ handle_proxy_callback_result( Events2 = hg_proxy_provider:update_proxy_state(ProxyState, Session), {Events1 ++ Events2, hg_machine_action:new()}. -apply_result(Result = {Events, _Action}, T) -> +apply_result({Events, _Action} = Result, T) -> {Result, update_state_with(Events, T)}. handle_proxy_intent(#proxy_provider_FinishIntent{status = {success, Success}}, Action, Session) -> diff --git a/apps/hellgate/test/hg_dummy_provider.erl b/apps/hellgate/test/hg_dummy_provider.erl index bac03cb7..25aa3b3e 100644 --- a/apps/hellgate/test/hg_dummy_provider.erl +++ b/apps/hellgate/test/hg_dummy_provider.erl @@ -370,7 +370,7 @@ mk_trx_extra(#proxy_provider_InvoicePayment{ prefix_extra(<<"payer_session_info">>, mk_trx_extra(PayerSessionInfo)), prefix_extra(<<"payment_service">>, mk_trx_extra(PaymentService)) ]); -mk_trx_extra(R = #domain_PayerSessionInfo{}) -> +mk_trx_extra(#domain_PayerSessionInfo{} = R) -> record_to_map(R, record_info(fields, domain_PayerSessionInfo)); mk_trx_extra(#domain_PaymentService{name = Name, brand_name = BrandName}) -> #{<<"name">> => Name, <<"brand_name">> => BrandName}; @@ -678,16 +678,16 @@ make_payment_tool({Code, Timeout}, PSys) when Code =:= preauth_3ds orelse Code = make_payment_tool({scenario, Scenario}, PSys) -> BinScenario = encode_failure_scenario(Scenario), ?SESSION42(make_bank_card_payment_tool(<<"scenario_", BinScenario/binary>>, PSys)); -make_payment_tool(terminal, PSrv = #domain_PaymentServiceRef{}) -> +make_payment_tool(terminal, #domain_PaymentServiceRef{} = PSrv) -> ?DEFAULT_SESSION({payment_terminal, #domain_PaymentTerminal{payment_service = PSrv}}); -make_payment_tool(digital_wallet, PSrv = #domain_PaymentServiceRef{}) -> +make_payment_tool(digital_wallet, #domain_PaymentServiceRef{} = PSrv) -> ?DEFAULT_SESSION(make_digital_wallet_payment_tool(PSrv)); make_payment_tool(tokenized_bank_card, {PSys, Provider, Method}) -> {_, BCard} = make_bank_card_payment_tool(<<"no_preauth">>, PSys), ?SESSION42({bank_card, BCard#domain_BankCard{payment_token = Provider, tokenization_method = Method}}); -make_payment_tool(crypto_currency, Type = #domain_CryptoCurrencyRef{}) -> +make_payment_tool(crypto_currency, #domain_CryptoCurrencyRef{} = Type) -> ?DEFAULT_SESSION({crypto_currency, Type}); -make_payment_tool({mobile_commerce, Exp}, Operator = #domain_MobileOperatorRef{}) -> +make_payment_tool({mobile_commerce, Exp}, #domain_MobileOperatorRef{} = Operator) -> ?DEFAULT_SESSION(make_mobile_commerce_payment_tool(Operator, phone(Exp))). make_digital_wallet_payment_tool(PSrv) -> diff --git a/apps/hellgate/test/hg_invoice_tests_SUITE.erl b/apps/hellgate/test/hg_invoice_tests_SUITE.erl index 63f9866c..9e226dfc 100644 --- a/apps/hellgate/test/hg_invoice_tests_SUITE.erl +++ b/apps/hellgate/test/hg_invoice_tests_SUITE.erl @@ -692,38 +692,38 @@ init_per_testcase(Name, C) when Fixture = get_payment_adjustment_fixture(Revision), _ = hg_domain:upsert(Fixture), [{original_domain_revision, Revision} | init_per_testcase_(Name, C)]; -init_per_testcase(Name = rounding_cashflow_volume, C) -> +init_per_testcase(rounding_cashflow_volume = Name, C) -> override_domain_fixture(fun get_cashflow_rounding_fixture/2, Name, C); -init_per_testcase(Name = payments_w_bank_card_issuer_conditions, C) -> +init_per_testcase(payments_w_bank_card_issuer_conditions = Name, C) -> override_domain_fixture(fun payments_w_bank_card_issuer_conditions_fixture/2, Name, C); -init_per_testcase(Name = payments_w_bank_conditions, C) -> +init_per_testcase(payments_w_bank_conditions = Name, C) -> override_domain_fixture(fun payments_w_bank_conditions_fixture/2, Name, C); -init_per_testcase(Name = payment_w_misconfigured_routing_failed, C) -> +init_per_testcase(payment_w_misconfigured_routing_failed = Name, C) -> override_domain_fixture(fun payment_w_misconfigured_routing_failed_fixture/2, Name, C); -init_per_testcase(Name = ineligible_payment_partial_refund, C) -> +init_per_testcase(ineligible_payment_partial_refund = Name, C) -> override_domain_fixture(fun(_, _) -> construct_term_set_for_refund_eligibility_time(1) end, Name, C); -init_per_testcase(Name = invalid_permit_partial_capture_in_service, C) -> +init_per_testcase(invalid_permit_partial_capture_in_service = Name, C) -> override_domain_fixture(fun construct_term_set_for_partial_capture_service_permit/2, Name, C); -init_per_testcase(Name = invalid_permit_partial_capture_in_provider, C) -> +init_per_testcase(invalid_permit_partial_capture_in_provider = Name, C) -> override_domain_fixture(fun construct_term_set_for_partial_capture_provider_permit/2, Name, C); -init_per_testcase(Name = limit_hold_currency_error, C) -> +init_per_testcase(limit_hold_currency_error = Name, C) -> override_domain_fixture(fun patch_limit_config_w_invalid_currency/2, Name, C); -init_per_testcase(Name = limit_hold_operation_not_supported, C) -> +init_per_testcase(limit_hold_operation_not_supported = Name, C) -> override_domain_fixture(fun patch_limit_config_for_withdrawal/2, Name, C); -init_per_testcase(Name = limit_hold_payment_tool_not_supported, C) -> +init_per_testcase(limit_hold_payment_tool_not_supported = Name, C) -> override_domain_fixture(fun patch_with_unsupported_payment_tool/2, Name, C); -init_per_testcase(Name = limit_hold_two_routes_failure, C) -> +init_per_testcase(limit_hold_two_routes_failure = Name, C) -> override_domain_fixture(fun patch_providers_limits_to_fail_and_overflow/2, Name, C); -init_per_testcase(Name = create_chargeback_provision_terms_not_allowed, C) -> +init_per_testcase(create_chargeback_provision_terms_not_allowed = Name, C) -> override_domain_fixture(fun unset_providers_chargebacks_terms/2, Name, C); -init_per_testcase(Name = repair_fail_routing_succeeded, C) -> +init_per_testcase(repair_fail_routing_succeeded = Name, C) -> meck:expect( hg_limiter, check_limits, fun override_check_limits/5 ), init_per_testcase_(Name, C); -init_per_testcase(Name = repair_fail_cash_flow_building_succeeded, C) -> +init_per_testcase(repair_fail_cash_flow_building_succeeded = Name, C) -> meck:expect( hg_cashflow_utils, collect_cashflow, @@ -1283,9 +1283,9 @@ payment_routes_limit_values(C) -> Client = hg_client_invoicing:start_link(hg_ct_helper:create_client(RootUrl)), #payproc_Invoice{ - invoice = #domain_Invoice{id = InvoiceId}, + invoice = #domain_Invoice{id = InvoiceID}, payments = [ - #payproc_InvoicePayment{payment = #domain_InvoicePayment{id = PaymentId}} + #payproc_InvoicePayment{payment = #domain_InvoicePayment{id = PaymentID}} ] } = create_payment(PartyConfigRef, ShopConfigRef, 10000, Client, ?pmt_sys(<<"visa-ref">>)), Route = ?route(?prv(5), ?trm(12)), @@ -1296,7 +1296,7 @@ payment_routes_limit_values(C) -> value = 10000 } ] - } = hg_client_invoicing:get_limit_values(InvoiceId, PaymentId, Client). + } = hg_client_invoicing:get_limit_values(InvoiceID, PaymentID, Client). -spec register_payment_limit_success(config()) -> test_return(). register_payment_limit_success(C0) -> diff --git a/apps/hellgate/test/hg_limiter_helper.erl b/apps/hellgate/test/hg_limiter_helper.erl index 01041fba..ae80109a 100644 --- a/apps/hellgate/test/hg_limiter_helper.erl +++ b/apps/hellgate/test/hg_limiter_helper.erl @@ -65,7 +65,7 @@ maybe_uninitialized_limit({exception, _}) -> }. -spec get_payment_limit_amount(_, _, _, _) -> _. -get_payment_limit_amount(LimitId, Version, Payment, Invoice) -> +get_payment_limit_amount(LimitID, Version, Payment, Invoice) -> Context = #limiter_LimitContext{ payment_processing = #context_payproc_Context{ op = {invoice_payment, #context_payproc_OperationInvoicePayment{}}, @@ -79,7 +79,7 @@ get_payment_limit_amount(LimitId, Version, Payment, Invoice) -> }, LimitRequest = #limiter_LimitRequest{ operation_id = ?PLACEHOLDER_OPERATION_GET_LIMIT_VALUES, - limit_changes = [#limiter_LimitChange{id = LimitId, version = Version}] + limit_changes = [#limiter_LimitChange{id = LimitID, version = Version}] }, try hg_limiter_client:get_values(LimitRequest, Context) of [L] -> diff --git a/apps/hg_client/src/hg_client_event_poller.erl b/apps/hg_client/src/hg_client_event_poller.erl index 3df8fa79..21aa313f 100644 --- a/apps/hg_client/src/hg_client_event_poller.erl +++ b/apps/hg_client/src/hg_client_event_poller.erl @@ -62,7 +62,7 @@ wait_timeout(StartTs, TimeoutWas) -> update_last_event_id([], St) -> St; -update_last_event_id(Events, St = #{get_event_id := GetEventID}) -> +update_last_event_id(Events, #{get_event_id := GetEventID} = St) -> St#{last_event_id => GetEventID(lists:last(Events))}. call(Range, Client, #{rpc := {Name, Function, Args}}) -> diff --git a/apps/hg_client/src/hg_client_invoice_templating.erl b/apps/hg_client/src/hg_client_invoice_templating.erl index 59804e14..0f0a4071 100644 --- a/apps/hg_client/src/hg_client_invoice_templating.erl +++ b/apps/hg_client/src/hg_client_invoice_templating.erl @@ -95,10 +95,10 @@ init(ApiClient) -> {ok, #state{pollers = #{}, client = ApiClient}}. -spec handle_call(term(), callref(), state()) -> {reply, term(), state()} | {noreply, state()}. -handle_call({call, Function, Args}, _From, St = #state{client = Client}) -> +handle_call({call, Function, Args}, _From, #state{client = Client} = St) -> {Result, ClientNext} = hg_client_api:call(invoice_templating, Function, Args, Client), {reply, Result, St#state{client = ClientNext}}; -handle_call({pull_event, InvoiceID, Timeout}, _From, St = #state{client = Client}) -> +handle_call({pull_event, InvoiceID, Timeout}, _From, #state{client = Client} = St) -> Poller = get_poller(InvoiceID, St), {Result, ClientNext, PollerNext} = hg_client_event_poller:poll(1, Timeout, Client, Poller), StNext = set_poller(InvoiceID, PollerNext, St#state{client = ClientNext}), @@ -137,7 +137,7 @@ code_change(_OldVsn, _State, _Extra) -> get_poller(ID, #state{pollers = Pollers}) -> maps:get(ID, Pollers, construct_poller(ID)). -set_poller(ID, Poller, St = #state{pollers = Pollers}) -> +set_poller(ID, Poller, #state{pollers = Pollers} = St) -> St#state{pollers = maps:put(ID, Poller, Pollers)}. construct_poller(ID) -> diff --git a/apps/hg_client/src/hg_client_invoicing.erl b/apps/hg_client/src/hg_client_invoicing.erl index 06fbdedd..58ce97a3 100644 --- a/apps/hg_client/src/hg_client_invoicing.erl +++ b/apps/hg_client/src/hg_client_invoicing.erl @@ -364,7 +364,7 @@ init(ApiClient) -> {ok, #state{pollers = #{}, client = ApiClient}}. -spec handle_call(term(), callref(), state()) -> {reply, term(), state()} | {noreply, state()}. -handle_call({call, Function, Args, OtelCtx}, _From, St = #state{client = Client}) -> +handle_call({call, Function, Args, OtelCtx}, _From, #state{client = Client} = St) -> _ = otel_ctx:attach(OtelCtx), {Result, ClientNext} = hg_client_api:call(invoicing, Function, Args, Client), {reply, Result, St#state{client = ClientNext}}; @@ -400,7 +400,7 @@ code_change(_OldVsn, _State, _Extra) -> %% -handle_pull_event(InvoiceID, Timeout, St = #state{client = Client}) -> +handle_pull_event(InvoiceID, Timeout, #state{client = Client} = St) -> Poller = get_poller(InvoiceID, St), {Result, ClientNext, PollerNext} = hg_client_event_poller:poll(1, Timeout, Client, Poller), StNext = set_poller(InvoiceID, PollerNext, St#state{client = ClientNext}), @@ -413,7 +413,7 @@ handle_pull_event(InvoiceID, Timeout, St = #state{client = Client}) -> {Error, StNext} end. -handle_pull_change(InvoiceID, Timeout, St = #state{changes = ChangesMap}) -> +handle_pull_change(InvoiceID, Timeout, #state{changes = ChangesMap} = St) -> case ChangesMap of #{InvoiceID := [ResultChange | RemainingChanges]} -> ChangesMapNext = ChangesMap#{InvoiceID => RemainingChanges}, @@ -432,7 +432,7 @@ handle_pull_change(InvoiceID, Timeout, St = #state{changes = ChangesMap}) -> get_poller(InvoiceID, #state{pollers = Pollers}) -> maps:get(InvoiceID, Pollers, construct_poller(InvoiceID)). -set_poller(InvoiceID, Poller, St = #state{pollers = Pollers}) -> +set_poller(InvoiceID, Poller, #state{pollers = Pollers} = St) -> St#state{pollers = maps:put(InvoiceID, Poller, Pollers)}. construct_poller(InvoiceID) -> diff --git a/apps/hg_progressor/src/hg_progressor.erl b/apps/hg_progressor/src/hg_progressor.erl index 77315e1c..406d6bce 100644 --- a/apps/hg_progressor/src/hg_progressor.erl +++ b/apps/hg_progressor/src/hg_progressor.erl @@ -111,7 +111,7 @@ cleanup() -> customer, recurrent_paytools ], - lists:foreach(fun(NsId) -> progressor:cleanup(#{ns => NsId}) end, Namespaces). + lists:foreach(fun(NsID) -> progressor:cleanup(#{ns => NsID}) end, Namespaces). %-endif. @@ -120,11 +120,11 @@ cleanup() -> -spec process({task_t(), encoded_args(), process()}, map(), encoded_ctx()) -> process_result(). process({CallType, BinArgs, Process}, #{ns := NS} = Options, Ctx) -> _ = set_context(Ctx), - #{last_event_id := LastEventId} = Process, + #{last_event_id := LastEventID} = Process, Machine = marshal(process, Process#{ns => NS}), Func = marshal(function, CallType), Args = marshal(args, {CallType, BinArgs, Machine}), - handle_result(hg_machine:handle_function(Func, {Args}, Options), LastEventId). + handle_result(hg_machine:handle_function(Func, {Args}, Options), LastEventID). %% Internal functions @@ -136,11 +136,11 @@ handle_result( }, action = Action }, - LastEventId + LastEventID ) -> {ok, genlib_map:compact(#{ - events => unmarshal(events, {Events, LastEventId}), + events => unmarshal(events, {Events, LastEventID}), aux_state => maybe_unmarshal(term, AuxState), action => maybe_unmarshal(action, Action) })}; @@ -153,12 +153,12 @@ handle_result( }, action = Action }, - LastEventId + LastEventID ) -> {ok, genlib_map:compact(#{ response => Response, - events => unmarshal(events, {Events, LastEventId}), + events => unmarshal(events, {Events, LastEventID}), aux_state => maybe_unmarshal(term, AuxState), action => maybe_unmarshal(action, Action) })}; @@ -171,16 +171,16 @@ handle_result( }, action = Action }, - LastEventId + LastEventID ) -> {ok, genlib_map:compact(#{ response => Response, - events => unmarshal(events, {Events, LastEventId}), + events => unmarshal(events, {Events, LastEventID}), aux_state => maybe_unmarshal(term, AuxState), action => maybe_unmarshal(action, Action) })}; -handle_result(_Unexpected, _LastEventId) -> +handle_result(_Unexpected, _LastEventID) -> {error, <<"unexpected result">>}. -spec handle_exception(_) -> no_return(). @@ -232,14 +232,14 @@ marshal( marshal( event, #{ - event_id := EventId, + event_id := EventID, timestamp := Timestamp, payload := Payload } = Event ) -> Meta = maps:get(metadata, Event, #{}), #mg_stateproc_Event{ - id = EventId, + id = EventID, created_at = marshal(timestamp, Timestamp), format_version = format_version(Meta), data = marshal(term, Payload) @@ -292,22 +292,22 @@ maybe_unmarshal(_, undefined) -> maybe_unmarshal(Type, Value) -> unmarshal(Type, Value). -unmarshal(events, {undefined, _Id}) -> +unmarshal(events, {undefined, _ID}) -> []; unmarshal(events, {[], _}) -> []; -unmarshal(events, {Events, LastEventId}) -> +unmarshal(events, {Events, LastEventID}) -> Ts = erlang:system_time(second), lists:foldl( fun(#mg_stateproc_Content{format_version = Ver, data = Payload}, Acc) -> - PrevId = + PrevID = case Acc of - [] -> LastEventId; - [#{event_id := Id} | _] -> Id + [] -> LastEventID; + [#{event_id := ID} | _] -> ID end, [ genlib_map:compact(#{ - event_id => PrevId + 1, + event_id => PrevID + 1, timestamp => Ts, metadata => #{<<"format_version">> => Ver}, payload => unmarshal(term, Payload) diff --git a/apps/hg_proto/src/hg_proto.erl b/apps/hg_proto/src/hg_proto.erl index 358a5ec1..29114695 100644 --- a/apps/hg_proto/src/hg_proto.erl +++ b/apps/hg_proto/src/hg_proto.erl @@ -48,11 +48,11 @@ get_service_spec(Name) -> get_service_spec(Name, #{}). -spec get_service_spec(Name :: atom(), Opts :: #{namespace => binary()}) -> service_spec(). -get_service_spec(Name = invoicing, #{}) -> +get_service_spec(invoicing = Name, #{}) -> {?VERSION_PREFIX ++ "/processing/invoicing", get_service(Name)}; -get_service_spec(Name = invoice_templating, #{}) -> +get_service_spec(invoice_templating = Name, #{}) -> {?VERSION_PREFIX ++ "/processing/invoice_templating", get_service(Name)}; -get_service_spec(Name = processor, #{namespace := Ns}) when is_binary(Ns) -> +get_service_spec(processor = Name, #{namespace := Ns}) when is_binary(Ns) -> {?VERSION_PREFIX ++ "/stateproc/" ++ binary_to_list(Ns), get_service(Name)}; -get_service_spec(Name = proxy_host_provider, #{}) -> +get_service_spec(proxy_host_provider = Name, #{}) -> {?VERSION_PREFIX ++ "/proxyhost/provider", get_service(Name)}. diff --git a/apps/hg_proto/src/hg_woody_wrapper.erl b/apps/hg_proto/src/hg_woody_wrapper.erl index 82069165..c0b865ed 100644 --- a/apps/hg_proto/src/hg_woody_wrapper.erl +++ b/apps/hg_proto/src/hg_woody_wrapper.erl @@ -59,7 +59,7 @@ raise(Exception) -> %% Internal functions -construct_opts(Opts = #{url := Url}) -> +construct_opts(#{url := Url} = Opts) -> Opts#{url := genlib:to_binary(Url)}; construct_opts(Url) -> #{url => genlib:to_binary(Url)}. diff --git a/apps/routing/src/hg_routing.erl b/apps/routing/src/hg_routing.erl index 84c62e67..45eea342 100644 --- a/apps/routing/src/hg_routing.erl +++ b/apps/routing/src/hg_routing.erl @@ -479,7 +479,7 @@ balance_routes(FailRatedRoutes) -> balance_route_groups(FilteredRouteGroups). -spec group_routes_by_priority(fail_rated_route(), Acc :: route_groups_by_priority()) -> route_groups_by_priority(). -group_routes_by_priority(FailRatedRoute = {Route, {ProviderCondition, _}}, SortedRoutes) -> +group_routes_by_priority({Route, {ProviderCondition, _}} = FailRatedRoute, SortedRoutes) -> TerminalPriority = hg_route:priority(Route), Key = {ProviderCondition, TerminalPriority}, Routes = maps:get(Key, SortedRoutes, []), diff --git a/apps/routing/src/hg_routing_ctx.erl b/apps/routing/src/hg_routing_ctx.erl index 820dfe8c..ee483360 100644 --- a/apps/routing/src/hg_routing_ctx.erl +++ b/apps/routing/src/hg_routing_ctx.erl @@ -81,7 +81,7 @@ error(#{error := Error}) -> Error. -spec reject(atom(), hg_route:rejected_route(), t()) -> t(). -reject(GroupReason, RejectedRoute, Ctx = #{rejections := Rejections, candidates := Candidates}) -> +reject(GroupReason, RejectedRoute, #{rejections := Rejections, candidates := Candidates} = Ctx) -> RejectedList = maps:get(GroupReason, Rejections, []) ++ [RejectedRoute], Ctx#{ rejections := Rejections#{GroupReason => RejectedList}, @@ -147,7 +147,7 @@ accounted_candidates(Ctx) -> maps:get(stashed_candidates, Ctx, initial_candidates(Ctx)). -spec stash_current_candidates(t()) -> t(). -stash_current_candidates(Ctx = #{candidates := []}) -> +stash_current_candidates(#{candidates := []} = Ctx) -> Ctx; stash_current_candidates(Ctx) -> Ctx#{stashed_candidates => candidates(Ctx)}. @@ -175,7 +175,7 @@ route_scores(Ctx) -> maps:get(route_scores, Ctx, undefined). -spec stash_route_scores(route_scores(), t()) -> t(). -stash_route_scores(RouteScoresNew, Ctx = #{route_scores := RouteScores}) -> +stash_route_scores(RouteScoresNew, #{route_scores := RouteScores} = Ctx) -> Ctx#{route_scores => maps:merge(RouteScores, RouteScoresNew)}; stash_route_scores(RouteScores, Ctx) -> Ctx#{route_scores => RouteScores}. diff --git a/apps/routing/src/hg_routing_explanation.erl b/apps/routing/src/hg_routing_explanation.erl index 9aea6e16..f1d0af7f 100644 --- a/apps/routing/src/hg_routing_explanation.erl +++ b/apps/routing/src/hg_routing_explanation.erl @@ -140,7 +140,7 @@ candidate_rejection_explanation( " was reached, if you see this message contact developer.">>, check_route_limits(RouteLimits, IfEmpty); candidate_rejection_explanation( - R = #{scores := #domain_PaymentRouteScores{blacklist_condition = 1}}, + #{scores := #domain_PaymentRouteScores{blacklist_condition = 1}} = R, _ ) -> check_route_blacklisted(R); @@ -157,7 +157,7 @@ candidate_rejection_explanation( IfEmpty = <<"No explanation for rejection can be found. Check in with developer.">>, check_route_limits(RouteLimits, IfEmpty); candidate_rejection_explanation( - R = #{scores := RouteScores, limits := RouteLimits}, + #{scores := RouteScores, limits := RouteLimits} = R, #{scores := ChosenScores} ) when RouteScores < ChosenScores -> Explanation0 = check_route_blacklisted(R), diff --git a/elvis.config b/elvis.config index a8bb940e..49988ab4 100644 --- a/elvis.config +++ b/elvis.config @@ -5,6 +5,7 @@ #{ dirs => ["apps/*/**"], filter => "*.erl", + ruleset => erl_files, rules => [ {elvis_text_style, line_length, #{limit => 120, skip_comments => false}}, {elvis_text_style, no_tabs}, @@ -28,8 +29,10 @@ {elvis_style, invalid_dynamic_call, #{ignore => [hg_proto_utils]}}, {elvis_style, used_ignored_variable}, {elvis_style, no_behavior_info}, + {elvis_style, macro_names, #{regex => "^([a-zA-Z][a-zA-Z_0-9]+)$"}}, {elvis_style, module_naming_convention, #{regex => "^[a-z]([a-z0-9]*_?)*(_SUITE)?$"}}, {elvis_style, function_naming_convention, #{regex => "^[a-z]([a-z0-9]*_?)*$"}}, + {elvis_style, atom_naming_convention, #{regex => "^[a-z]([a-zA-Z0-9]*_?)*$"}}, {elvis_style, state_record_and_type, #{ignore => [hg_profiler]}}, {elvis_style, no_spec_with_records}, {elvis_style, dont_repeat_yourself, #{ @@ -42,7 +45,18 @@ hg_invoice_helper ] }}, - {elvis_style, no_debug_call, #{}} + {elvis_style, no_block_expressions, #{ + ignore => [ + hg_invoice_template_tests_SUITE, + hg_invoice_tests_SUITE + ] + }}, + {elvis_style, max_function_arity, #{max_arity => 10}}, + {elvis_style, no_debug_call, #{}}, + {elvis_style, no_throw, disable}, + {elvis_style, no_import, disable}, + {elvis_style, private_data_types, disable}, + {elvis_style, export_used_types, disable} ] }, #{