Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
# You SHOULD specify point releases here so that build time and run time Erlang/OTPs
# are the same. See: https://github.com/erlware/relx/pull/902
SERVICE_NAME=hellgate
OTP_VERSION=27.1.2
OTP_VERSION=27.3.4
REBAR_VERSION=3.24
THRIFT_VERSION=0.14.2.3
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ tags
/.image.*
Makefile.env
*.iml
CLAUDE.md
.claude/
2 changes: 2 additions & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
rebar 3.24.0
erlang 27.3.4
1 change: 1 addition & 0 deletions apps/hellgate/include/hg_invoice_payment.hrl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
chargebacks = #{} :: #{hg_invoice_payment_chargeback:id() => hg_invoice_payment_chargeback:state()},
adjustments = [] :: [hg_invoice_payment:adjustment()],
recurrent_token :: undefined | dmsl_domain_thrift:'Token'(),
cascade_recurrent_tokens :: undefined | hg_customer_client:cascade_tokens(),
opts :: undefined | hg_invoice_payment:opts(),
repair_scenario :: undefined | hg_invoice_repair:scenario(),
capture_data :: undefined | hg_invoice_payment:capture_data(),
Expand Down
4 changes: 4 additions & 0 deletions apps/hellgate/include/payment_events.hrl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@
{invoice_payment_rec_token_acquired, #payproc_InvoicePaymentRecTokenAcquired{token = Token}}
).

-define(cascade_tokens_loaded(Tokens),
{invoice_payment_cascade_tokens_loaded, #payproc_InvoicePaymentCascadeTokensLoaded{tokens = Tokens}}
).

-define(cash_changed(OldCash, NewCash),
{invoice_payment_cash_changed, #payproc_InvoicePaymentCashChanged{old_cash = OldCash, new_cash = NewCash}}
).
Expand Down
166 changes: 166 additions & 0 deletions apps/hellgate/src/hg_customer_client.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
-module(hg_customer_client).

-include_lib("damsel/include/dmsl_customer_thrift.hrl").
-include_lib("damsel/include/dmsl_domain_thrift.hrl").

%% BankCard operations
-export([find_or_create_bank_card/2]).
-export([get_recurrent_tokens_by_card/2]).
-export([save_recurrent_token_by_card/3]).
-export([tokens_to_map/1]).

%% Customer operations
-export([create_customer/1]).
-export([get_by_parent_payment/2]).
-export([get_recurrent_tokens/2]).
-export([add_payment/3]).
-export([link_bank_card/2]).

-export_type([cascade_tokens/0]).

-type invoice_id() :: dmsl_domain_thrift:'InvoiceID'().
-type payment_id() :: dmsl_domain_thrift:'InvoicePaymentID'().
-type provider_terminal_key() :: dmsl_customer_thrift:'ProviderTerminalKey'().
-type token() :: dmsl_domain_thrift:'Token'().
-type recurrent_token() :: dmsl_customer_thrift:'RecurrentToken'().
-type cascade_tokens() :: #{provider_terminal_key() => token()}.

%% BankCard operations

-spec find_or_create_bank_card(dmsl_domain_thrift:'PartyConfigRef'(), token()) ->
dmsl_customer_thrift:'BankCard'().
find_or_create_bank_card(PartyConfigRef, BankCardToken) ->
case find_bank_card(PartyConfigRef, BankCardToken) of
{ok, BankCard} ->
BankCard;
{exception, #customer_BankCardNotFound{}} ->
{ok, BankCard} = call(
bank_card_storage,
'Create',
{PartyConfigRef, #customer_BankCardParams{bank_card_token = BankCardToken}}
),
BankCard
end.

-spec get_recurrent_tokens_by_card(dmsl_domain_thrift:'PartyConfigRef'(), token()) ->
[recurrent_token()].
get_recurrent_tokens_by_card(PartyConfigRef, BankCardToken) ->
case find_bank_card(PartyConfigRef, BankCardToken) of
{ok, #customer_BankCard{id = BankCardID}} ->
{ok, Tokens} = call(bank_card_storage, 'GetRecurrentTokens', {BankCardID}),
Tokens;
{exception, #customer_BankCardNotFound{}} ->
[]
end.

-spec save_recurrent_token_by_card(
dmsl_domain_thrift:'PartyConfigRef'(),
token(),
{dmsl_domain_thrift:'PaymentRoute'(), token()}
) -> recurrent_token().
save_recurrent_token_by_card(
PartyConfigRef,
BankCardToken,
{#domain_PaymentRoute{provider = ProviderRef, terminal = TerminalRef}, RecToken}
) ->
#customer_BankCard{id = BankCardID} = find_or_create_bank_card(PartyConfigRef, BankCardToken),
{ok, SavedToken} = call(
bank_card_storage,
'AddRecurrentToken',
{#customer_RecurrentTokenParams{
bank_card_id = BankCardID,
provider_ref = ProviderRef,
terminal_ref = TerminalRef,
token = RecToken
}}
),
SavedToken.

-spec tokens_to_map([recurrent_token()]) -> cascade_tokens().
tokens_to_map(Tokens) ->
lists:foldl(fun token_to_map_entry/2, #{}, Tokens).

%% Customer operations

-spec create_customer(dmsl_domain_thrift:'PartyConfigRef'()) -> dmsl_customer_thrift:'Customer'().
create_customer(PartyConfigRef) ->
{ok, Customer} = call(customer_management, 'Create', {#customer_CustomerParams{party_ref = PartyConfigRef}}),
Customer.
Comment on lines +87 to +88
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ключа идемпотентности нет, в параметрах создания нет привязки, значит если что то пойдет не так - у тебя будет миллиард пустых кастумеров

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Например создание и сразу привязка к платежу? А если платеж не успешен? Я думал чтобы список платежей в кастомере был списком успешных платежей

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это все верно, но после создания может же быть проблема - а можно делать чтобы у тебя в случае если не было кастумера и нужно создать ты мог в рамках транзакции создать, добавить карту и добавить реккурент - при этом проверяя не было ли уже их - чтобы не было дублей?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Карты и токены добавляются идемпотентно, в этом плане проблем нет

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Идемпотентностью создания самого кастомера (это будет происходить в капи) займется бендер на основе ExternalID

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а этот метод тут тогда нужен?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это для тестов, не вижу смысла ради этого метода рожать отдельный модуль

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

может коммент тогда докинуть? или в иф деф обернуть ?


-spec get_by_parent_payment(invoice_id(), payment_id()) ->
{ok, dmsl_customer_thrift:'CustomerState'()} | {exception, term()}.
get_by_parent_payment(InvoiceID, PaymentID) ->
call(customer_management, 'GetByParentPayment', {InvoiceID, PaymentID}).

-spec get_recurrent_tokens(invoice_id(), payment_id()) -> [recurrent_token()].
get_recurrent_tokens(InvoiceID, PaymentID) ->
case call(customer_management, 'GetByParentPayment', {InvoiceID, PaymentID}) of
{ok, #customer_CustomerState{bank_card_refs = BankCardRefs}} ->
lists:flatmap(fun collect_bank_card_tokens/1, BankCardRefs);
{exception, #customer_CustomerNotFound{}} ->
[];
{exception, #customer_InvalidRecurrentParent{}} ->
[]
end.

-spec add_payment(dmsl_customer_thrift:'CustomerID'(), invoice_id(), payment_id()) -> ok.
add_payment(CustomerID, InvoiceID, PaymentID) ->
{ok, ok} = call(customer_management, 'AddPayment', {CustomerID, InvoiceID, PaymentID}),
ok.

-spec link_bank_card(dmsl_customer_thrift:'CustomerID'(), token()) -> ok.
link_bank_card(CustomerID, BankCardToken) ->
{ok, _} = call(
customer_management,
'AddBankCard',
{CustomerID, #customer_BankCardParams{bank_card_token = BankCardToken}}
),
ok.

%% Internal

find_bank_card(PartyConfigRef, BankCardToken) ->
SearchParams = #customer_BankCardSearchParams{
bank_card_token = BankCardToken,
party_ref = PartyConfigRef
},
call(bank_card_storage, 'Find', {SearchParams}).

collect_bank_card_tokens(#customer_BankCardRef{id = BankCardID}) ->
{ok, Tokens} = call(bank_card_storage, 'GetRecurrentTokens', {BankCardID}),
Tokens.

token_to_map_entry(
#customer_RecurrentToken{
provider_ref = ProviderRef,
terminal_ref = TerminalRef,
token = Token
},
Acc
) ->
Key = #customer_ProviderTerminalKey{
provider_ref = ProviderRef,
terminal_ref = TerminalRef
},
Acc#{Key => Token}.

call(ServiceName, Function, Args) ->
Service = hg_proto:get_service(ServiceName),
Opts = hg_woody_wrapper:get_service_options(ServiceName),
WoodyContext =
try
hg_context:get_woody_context(hg_context:load())
catch
error:badarg -> woody_context:new()
end,
Request = {Service, Function, Args},
woody_client:call(
Request,
Opts#{
event_handler => {
scoper_woody_event_handler,
genlib_app:env(hellgate, scoper_event_handler_options, #{})
}
},
WoodyContext
).
Loading
Loading