repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch
migrations/2024-05-31-074402_add_acquirer_country_code_in_authentication/up.sql
.sql
-- Your SQL goes here ALTER TABLE authentication ADD COLUMN IF NOT EXISTS acquirer_country_code VARCHAR(64);
23
700
hyperswitch
migrations/2024-05-31-074402_add_acquirer_country_code_in_authentication/down.sql
.sql
ALTER TABLE authentication DROP COLUMN IF EXISTS acquirer_country_code;
12
701
hyperswitch
migrations/2023-01-12-084710_update_merchant_routing_algorithm/up.sql
.sql
-- Your SQL goes here ALTER TABLE merchant_account DROP COLUMN routing_algorithm; ALTER TABLE merchant_account DROP COLUMN custom_routing_rules; ALTER TABLE merchant_account ADD COLUMN routing_algorithm JSON; DROP TYPE "RoutingAlgorithm";
41
702
hyperswitch
migrations/2023-01-12-084710_update_merchant_routing_algorithm/down.sql
.sql
-- This file should undo anything in `up.sql` CREATE TYPE "RoutingAlgorithm" AS ENUM ( 'round_robin', 'max_conversion', 'min_cost', 'custom' ); ALTER TABLE merchant_account DROP COLUMN routing_algorithm; ALTER TABLE merchant_account ADD COLUMN custom_routing_rules JSON; ALTER TABLE merchant_account ADD COLUMN routing_algorithm "RoutingAlgorithm";
73
703
hyperswitch
migrations/2023-01-12-140107_drop_temp_card/up.sql
.sql
DROP TABLE temp_card;
5
704
hyperswitch
migrations/2023-01-12-140107_drop_temp_card/down.sql
.sql
CREATE TABLE temp_card ( id SERIAL PRIMARY KEY, date_created TIMESTAMP NOT NULL, txn_id VARCHAR(255), card_info JSON ); CREATE INDEX temp_card_txn_id_index ON temp_card (txn_id);
47
705
hyperswitch
migrations/2023-04-26-090005_remove_default_created_at_modified_at/up.sql
.sql
-- Merchant Account ALTER TABLE merchant_account ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE merchant_account ALTER COLUMN created_at DROP DEFAULT; -- Merchant Connector Account ALTER TABLE merchant_connector_account ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE merchant_connector_account ALTER COLUMN created_at DROP DEFAULT; -- Customers ALTER TABLE customers ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE customers ALTER COLUMN created_at DROP DEFAULT; -- Address ALTER TABLE address ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE address ALTER COLUMN created_at DROP DEFAULT; -- Refunds ALTER TABLE refund ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE refund ALTER COLUMN created_at DROP DEFAULT; -- Connector Response ALTER TABLE connector_response ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE connector_response ALTER COLUMN created_at DROP DEFAULT; -- Payment methods ALTER TABLE payment_methods ALTER COLUMN created_at DROP DEFAULT; -- Payment Intent ALTER TABLE payment_intent ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE payment_intent ALTER COLUMN created_at DROP DEFAULT; --- Payment Attempt ALTER TABLE payment_attempt ALTER COLUMN modified_at DROP DEFAULT; ALTER TABLE payment_attempt ALTER COLUMN created_at DROP DEFAULT;
235
706
hyperswitch
migrations/2023-04-26-090005_remove_default_created_at_modified_at/down.sql
.sql
-- Merchant Account ALTER TABLE merchant_account ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE merchant_account ALTER COLUMN created_at SET DEFAULT now(); -- Merchant Connector Account ALTER TABLE merchant_connector_account ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE merchant_connector_account ALTER COLUMN created_at SET DEFAULT now(); -- Customers ALTER TABLE customers ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE customers ALTER COLUMN created_at SET DEFAULT now(); -- Address ALTER TABLE address ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE address ALTER COLUMN created_at SET DEFAULT now(); -- Refunds ALTER TABLE refund ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE refund ALTER COLUMN created_at SET DEFAULT now(); -- Connector Response ALTER TABLE connector_response ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE connector_response ALTER COLUMN created_at SET DEFAULT now(); -- Payment methods ALTER TABLE payment_methods ALTER COLUMN created_at SET DEFAULT now(); -- Payment Intent ALTER TABLE payment_intent ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE payment_intent ALTER COLUMN created_at SET DEFAULT now(); --- Payment Attempt ALTER TABLE payment_attempt ALTER COLUMN modified_at SET DEFAULT now(); ALTER TABLE payment_attempt ALTER COLUMN created_at SET DEFAULT now();
252
707
hyperswitch
migrations/2024-08-12-130304_add_translations_table/up.sql
.sql
CREATE TABLE IF NOT EXISTS unified_translations ( unified_code VARCHAR(255) NOT NULL, unified_message VARCHAR(1024) NOT NULL, locale VARCHAR(255) NOT NULL , translation VARCHAR(1024) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, last_modified_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (unified_code,unified_message,locale) );
99
708
hyperswitch
migrations/2024-08-12-130304_add_translations_table/down.sql
.sql
-- This file should undo anything in `up.sql` DROP TABLE IF EXISTS unified_translations;
19
709
hyperswitch
migrations/2022-11-25-121143_add_paypal_pmt/up.sql
.sql
-- Your SQL goes here ALTER TYPE "PaymentMethodType" ADD VALUE 'paypal' after 'pay_later';
24
710
hyperswitch
migrations/2022-11-25-121143_add_paypal_pmt/down.sql
.sql
-- This file should undo anything in `up.sql` DELETE FROM pg_enum WHERE enumlabel = 'paypal' AND enumtypid = ( SELECT oid FROM pg_type WHERE typname = 'PaymentMethodType' )
45
711
hyperswitch
migrations/2025-03-20-085151_force-3ds-challenge-triggered/up.sql
.sql
-- Your SQL goes here ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS force_3ds_challenge_trigger boolean DEFAULT false;
26
712
hyperswitch
migrations/2025-03-20-085151_force-3ds-challenge-triggered/down.sql
.sql
-- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS force_3ds_challenge_trigger;
27
713
hyperswitch
migrations/2024-04-23-061745_add_pm_collect_link_config_to_merchant_account/up.sql
.sql
ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS pm_collect_link_config JSONB NULL; ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS payout_link_config JSONB NULL;
35
714
hyperswitch
migrations/2024-04-23-061745_add_pm_collect_link_config_to_merchant_account/down.sql
.sql
ALTER TABLE merchant_account DROP COLUMN IF EXISTS pm_collect_link_config; ALTER TABLE business_profile DROP COLUMN IF EXISTS payout_link_config;
27
715
hyperswitch
migrations/2024-07-05-115837_add_shipping_details_in_payment_intent/up.sql
.sql
-- Your SQL goes here ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS shipping_details BYTEA DEFAULT NULL;
22
716
hyperswitch
migrations/2024-07-05-115837_add_shipping_details_in_payment_intent/down.sql
.sql
-- This file should undo anything in `up.sql` ALTER TABLE payment_intent DROP COLUMN IF EXISTS shipping_details;
22
717
hyperswitch
v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql
.sql
-- Drop not null constraints on not null columns of v1 which are either dropped or made nullable in v2. ------------------------ Organization ----------------------- ALTER TABLE organization DROP CONSTRAINT organization_pkey, ALTER COLUMN org_id DROP NOT NULL; -- Create index on org_id in organization table -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_organization_org_id ON organization (org_id); ------------------------ Merchant Account ------------------- -- Drop not null in merchant_account table for v1 columns that are dropped in v2 ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey, ALTER COLUMN merchant_id DROP NOT NULL, ALTER COLUMN primary_business_details DROP NOT NULL, ALTER COLUMN is_recon_enabled DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_account_merchant_id ON merchant_account (merchant_id); ------------------------ Business Profile ------------------- ALTER TABLE business_profile DROP CONSTRAINT business_profile_pkey, ALTER COLUMN profile_id DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_business_profile_profile_id ON business_profile (profile_id); ---------------- Merchant Connector Account ----------------- ALTER TABLE merchant_connector_account DROP CONSTRAINT merchant_connector_account_pkey, ALTER COLUMN merchant_connector_id DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_merchant_connector_account_merchant_connector_id ON merchant_connector_account (merchant_connector_id); ------------------------ Customers -------------------------- ALTER TABLE customers DROP CONSTRAINT customers_pkey, ALTER COLUMN customer_id DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_customers_merchant_id_customer_id ON customers (merchant_id, customer_id); ---------------------- Payment Intent ----------------------- ALTER TABLE payment_intent DROP CONSTRAINT payment_intent_pkey, ALTER COLUMN payment_id DROP NOT NULL, ALTER COLUMN active_attempt_id DROP NOT NULL, ALTER COLUMN active_attempt_id DROP DEFAULT; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_payment_intent_payment_id_merchant_id ON payment_intent (payment_id, merchant_id); ---------------------- Payment Attempt ---------------------- ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey, ALTER COLUMN attempt_id DROP NOT NULL, ALTER COLUMN amount DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_payment_attempt_attempt_id_merchant_id ON payment_attempt (attempt_id, merchant_id); ---------------------- Payment Methods ---------------------- ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey, ALTER COLUMN payment_method_id DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_payment_methods_payment_method_id ON payment_methods (payment_method_id); ---------------------- Refunds ---------------------- ALTER TABLE refund DROP CONSTRAINT refund_pkey, ALTER COLUMN refund_id DROP NOT NULL; -- This is done to mullify the effects of droping primary key for v1 CREATE INDEX idx_refund_refund_id_merchant_id ON refund (refund_id, merchant_id);
676
718
hyperswitch
v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql
.sql
------------------------ Organization ----------------------- -- Drop index on org_id in organization table DROP INDEX IF EXISTS idx_organization_org_id; -- Re-add primary key constraint on `organization` ALTER TABLE organization ADD CONSTRAINT organization_pkey PRIMARY KEY (org_id), ALTER COLUMN org_id SET NOT NULL; ------------------------ Merchant Account ------------------- DROP INDEX IF EXISTS idx_merchant_account_merchant_id; ALTER TABLE merchant_account ADD PRIMARY KEY (merchant_id), ALTER COLUMN primary_business_details SET NOT NULL, ALTER COLUMN is_recon_enabled SET NOT NULL, ALTER COLUMN is_recon_enabled SET DEFAULT FALSE; ------------------------ Business Profile ------------------- DROP INDEX IF EXISTS idx_business_profile_profile_id; ALTER TABLE business_profile ADD PRIMARY KEY (profile_id); ---------------- Merchant Connector Account ----------------- DROP INDEX IF EXISTS idx_merchant_connector_account_merchant_connector_id; ALTER TABLE merchant_connector_account ADD PRIMARY KEY (merchant_connector_id); ------------------------ Customers -------------------------- DROP INDEX IF EXISTS idx_customers_merchant_id_customer_id; ALTER TABLE customers ADD PRIMARY KEY (merchant_id, customer_id); ---------------------- Payment Intent ----------------------- DROP INDEX IF EXISTS idx_payment_intent_payment_id_merchant_id; ALTER TABLE payment_intent ADD PRIMARY KEY (payment_id, merchant_id), ALTER COLUMN active_attempt_id SET NOT NULL, ALTER COLUMN active_attempt_id SET DEFAULT 'xxx'; ---------------------- Payment Attempt ---------------------- DROP INDEX IF EXISTS idx_payment_attempt_attempt_id_merchant_id; ALTER TABLE payment_attempt ADD PRIMARY KEY (attempt_id, merchant_id), ALTER COLUMN amount SET NOT NULL; ---------------------- Payment Methods ---------------------- DROP INDEX IF EXISTS idx_payment_methods_payment_method_id; ALTER TABLE payment_methods ADD PRIMARY KEY (payment_method_id); ---------------------- Refunds ---------------------- DROP INDEX IF EXISTS idx_refund_refund_id_merchant_id; ALTER TABLE refund ADD PRIMARY KEY (refund_id,merchant_id);
385
719
hyperswitch
v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/up.sql
.sql
-- Your SQL goes here CREATE TYPE "DeleteStatus" AS ENUM ('active', 'redacted');
21
720
hyperswitch
v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/down.sql
.sql
-- This file should undo anything in `up.sql` DROP TYPE "DeleteStatus";
17
721
hyperswitch
v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql
.sql
-- This file contains queries to re-create the `id` column as a `VARCHAR` column instead of `SERIAL` column for tables that already have it. -- It must be ensured that the deployed version of the application does not include the `id` column in any of its queries. -- Drop the id column as this will be used later as the primary key with a different type ------------------------ Customers ----------------------- ALTER TABLE customers ADD COLUMN IF NOT EXISTS id VARCHAR(64); ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS id VARCHAR(64); ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS id VARCHAR(64); ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS id VARCHAR(64);
169
722
hyperswitch
v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/down.sql
.sql
-- This file contains queries to create the `id` column as a `SERIAL` column instead of `VARCHAR` column for tables that already have it. -- This is to revert the `id` columns to the previous state. ALTER TABLE customers DROP COLUMN IF EXISTS id; ALTER TABLE payment_intent DROP COLUMN IF EXISTS id; ALTER TABLE payment_attempt DROP COLUMN IF EXISTS id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id;
92
723
hyperswitch
v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql
.sql
-- This file contains all new columns being added as part of v2 refactoring. -- The new columns added should work with both v1 and v2 applications. ALTER TABLE customers ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS default_billing_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS default_shipping_address BYTEA DEFAULT NULL, ADD COLUMN IF NOT EXISTS status "DeleteStatus"; CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); ALTER TABLE business_profile ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL, ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL, ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL, ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL, ADD COLUMN default_fallback_routing JSONB DEFAULT NULL, ADD COLUMN three_ds_decision_manager_config jsonb, -- Intentionally not adding a default value here since we would have to -- check if any merchants have enabled this from configs table, -- before filling data for this column. -- If no merchants have enabled this, then we can use `false` as the default value -- when adding the column, later we can drop the default added for the column -- so that we ensure new records inserted always have a value for the column. ADD COLUMN should_collect_cvv_during_payment BOOLEAN; ALTER TABLE payment_intent ADD COLUMN merchant_reference_id VARCHAR(64), ADD COLUMN billing_address BYTEA DEFAULT NULL, ADD COLUMN shipping_address BYTEA DEFAULT NULL, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN authentication_type "AuthenticationType", ADD COLUMN amount_to_capture bigint, ADD COLUMN prerouting_algorithm JSONB, ADD COLUMN surcharge_amount bigint, ADD COLUMN tax_on_surcharge bigint, ADD COLUMN frm_merchant_decision VARCHAR(64), ADD COLUMN statement_descriptor VARCHAR(255), ADD COLUMN enable_payment_link BOOLEAN, ADD COLUMN apply_mit_exemption BOOLEAN, ADD COLUMN customer_present BOOLEAN, ADD COLUMN routing_algorithm_id VARCHAR(64), ADD COLUMN payment_link_config JSONB; ALTER TABLE payment_attempt ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN connector_payment_id VARCHAR(128), ADD COLUMN payment_method_subtype VARCHAR(64), ADD COLUMN routing_result JSONB, ADD COLUMN authentication_applied "AuthenticationType", ADD COLUMN external_reference_id VARCHAR(128), ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA, ADD COLUMN redirection_data JSONB, ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS feature_metadata JSONB; ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); ALTER TABLE refund ADD COLUMN IF NOT EXISTS id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
708
724
hyperswitch
v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql
.sql
-- This file drops all new columns being added as part of v2 refactoring. -- These migrations can be run as long as there's no v2 application running. ALTER TABLE customers DROP COLUMN IF EXISTS merchant_reference_id, DROP COLUMN IF EXISTS default_billing_address, DROP COLUMN IF EXISTS default_shipping_address, DROP COLUMN IF EXISTS status; ALTER TABLE business_profile DROP COLUMN routing_algorithm_id, DROP COLUMN order_fulfillment_time, DROP COLUMN order_fulfillment_time_origin, DROP COLUMN frm_routing_algorithm_id, DROP COLUMN payout_routing_algorithm_id, DROP COLUMN default_fallback_routing, DROP COLUMN should_collect_cvv_during_payment, DROP COLUMN three_ds_decision_manager_config; DROP TYPE "OrderFulfillmentTimeOrigin"; -- Revert renaming of field, ALTER TABLE payment_intent DROP COLUMN merchant_reference_id, DROP COLUMN billing_address, DROP COLUMN shipping_address, DROP COLUMN capture_method, DROP COLUMN authentication_type, DROP COLUMN amount_to_capture, DROP COLUMN prerouting_algorithm, DROP COLUMN surcharge_amount, DROP COLUMN tax_on_surcharge, DROP COLUMN frm_merchant_decision, DROP COLUMN statement_descriptor, DROP COLUMN enable_payment_link, DROP COLUMN apply_mit_exemption, DROP COLUMN customer_present, DROP COLUMN routing_algorithm_id, DROP COLUMN payment_link_config; ALTER TABLE payment_attempt DROP COLUMN payment_method_type_v2, DROP COLUMN connector_payment_id, DROP COLUMN payment_method_subtype, DROP COLUMN routing_result, DROP COLUMN authentication_applied, DROP COLUMN external_reference_id, DROP COLUMN tax_on_surcharge, DROP COLUMN payment_method_billing_address, DROP COLUMN redirection_data, DROP COLUMN connector_payment_data, DROP COLUMN connector_token_details; ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS feature_metadata; ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_fingerprint_id, DROP COLUMN IF EXISTS payment_method_type_v2, DROP COLUMN IF EXISTS payment_method_subtype; ALTER TABLE refund DROP COLUMN IF EXISTS id, DROP COLUMN IF EXISTS merchant_reference_id, DROP COLUMN IF EXISTS connector_id;
432
725
hyperswitch
v2_migrations/2025-02-10-101458_create_index_payment_attempt_payment_id/up.sql
.sql
-- Your SQL goes here DROP INDEX IF EXISTS payment_attempt_payment_id_merchant_id_index; CREATE INDEX IF NOT EXISTS payment_attempt_payment_id_index ON payment_attempt (payment_id);
36
726
hyperswitch
v2_migrations/2025-02-10-101458_create_index_payment_attempt_payment_id/down.sql
.sql
-- This file should undo anything in `up.sql` DROP INDEX IF EXISTS payment_attempt_payment_id_index; CREATE INDEX IF NOT EXISTS payment_attempt_payment_id_merchant_id_index ON payment_attempt (payment_id, merchant_id);
44
727
hyperswitch
v2_migrations/2025-02-24-053820_add_billing_processor_value_to_connector_type_enum/up.sql
.sql
-- Your SQL goes here ALTER TYPE "ConnectorType" ADD VALUE If NOT EXISTS 'billing_processor';
21
728
hyperswitch
v2_migrations/2025-02-24-053820_add_billing_processor_value_to_connector_type_enum/down.sql
.sql
-- This file should undo anything in `up.sql` SELECT 1;
15
729
hyperswitch
v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/up.sql
.sql
-- Your SQL goes here ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL;
19
730
hyperswitch
v2_migrations/2025-03-25-074512_payment-method-subtype-mandatory/down.sql
.sql
-- This file should undo anything in `up.sql` ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL;
24
731
hyperswitch
v2_migrations/2025-04-02-051959_add_network_error_info_in_payment_attempt/up.sql
.sql
ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS network_advice_code VARCHAR(32) DEFAULT NULL, ADD COLUMN IF NOT EXISTS network_decline_code VARCHAR(32) DEFAULT NULL, ADD COLUMN IF NOT EXISTS network_error_message TEXT DEFAULT NULL;
51
732
hyperswitch
v2_migrations/2025-04-02-051959_add_network_error_info_in_payment_attempt/down.sql
.sql
ALTER TABLE payment_attempt DROP COLUMN IF EXISTS network_advice_code, DROP COLUMN IF EXISTS networ_decline_code, DROP COLUMN IF EXISTS network_error_message;
32
733
hyperswitch
v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql
.sql
-- This file contains queries to drop columns no longer used by the v2 application. -- It is safer to take a backup of the database before running these queries as they're destructive in nature. -- These queries should only be run when we're sure that data inserted by the v1 application is no longer required. ALTER TABLE ORGANIZATION DROP COLUMN org_id, DROP COLUMN org_name; -- Note: This query should not be run on higher environments as this leads to data loss -- The application will work fine even without these queries not being run ALTER TABLE merchant_account DROP COLUMN merchant_id, DROP COLUMN return_url, DROP COLUMN enable_payment_response_hash, DROP COLUMN payment_response_hash_key, DROP COLUMN redirect_to_merchant_with_http_post, DROP COLUMN sub_merchants_enabled, DROP COLUMN parent_merchant_id, DROP COLUMN primary_business_details, DROP COLUMN locker_id, DROP COLUMN intent_fulfillment_time, DROP COLUMN default_profile, DROP COLUMN payment_link_config, DROP COLUMN pm_collect_link_config, DROP COLUMN is_recon_enabled, DROP COLUMN webhook_details, DROP COLUMN routing_algorithm, DROP COLUMN frm_routing_algorithm, DROP COLUMN payout_routing_algorithm; -- Note: This query should not be run on higher environments as this leads to data loss. -- The application will work fine even without these queries being run. ALTER TABLE business_profile DROP COLUMN profile_id, DROP COLUMN routing_algorithm, DROP COLUMN intent_fulfillment_time, DROP COLUMN frm_routing_algorithm, DROP COLUMN payout_routing_algorithm; -- This migration is to remove the fields that are no longer used by the v1 application, or some type changes. ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS business_country, DROP COLUMN IF EXISTS business_label, DROP COLUMN IF EXISTS business_sub_label, DROP COLUMN IF EXISTS test_mode, DROP COLUMN IF EXISTS merchant_connector_id, DROP COLUMN IF EXISTS frm_configs; -- Run this query only when V1 is deprecated ALTER TABLE customers DROP COLUMN customer_id, DROP COLUMN address_id; -- Run below queries only when V1 is deprecated ALTER TABLE payment_intent DROP COLUMN payment_id, DROP COLUMN connector_id, DROP COLUMN shipping_address_id, DROP COLUMN billing_address_id, DROP COLUMN shipping_details, DROP COLUMN billing_details, DROP COLUMN statement_descriptor_suffix, DROP COLUMN business_country, DROP COLUMN business_label, DROP COLUMN incremental_authorization_allowed, DROP COLUMN fingerprint_id, DROP COLUMN merchant_decision, DROP COLUMN statement_descriptor_name, DROP COLUMN amount_to_capture, DROP COLUMN off_session, DROP COLUMN payment_confirm_source, DROP COLUMN merchant_order_reference_id, DROP COLUMN is_payment_processor_token_flow, DROP COLUMN charges; -- Run below queries only when V1 is deprecated ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN amount, DROP COLUMN currency, DROP COLUMN save_to_locker, DROP COLUMN offer_amount, DROP COLUMN payment_method, DROP COLUMN connector_transaction_id, DROP COLUMN connector_transaction_data, DROP COLUMN processor_transaction_data, DROP COLUMN capture_method, DROP COLUMN capture_on, DROP COLUMN mandate_id, DROP COLUMN payment_method_type, DROP COLUMN business_sub_label, DROP COLUMN mandate_details, DROP COLUMN mandate_data, DROP COLUMN tax_amount, DROP COLUMN straight_through_algorithm, DROP COLUMN confirm, DROP COLUMN authentication_data, DROP COLUMN payment_method_billing_address_id, DROP COLUMN connector_mandate_detail, DROP COLUMN charge_id, DROP COLUMN issuer_error_code, DROP COLUMN issuer_error_message; ALTER TABLE payment_methods DROP COLUMN IF EXISTS payment_method_id, DROP COLUMN IF EXISTS accepted_currency, DROP COLUMN IF EXISTS scheme, DROP COLUMN IF EXISTS token, DROP COLUMN IF EXISTS cardholder_name, DROP COLUMN IF EXISTS issuer_name, DROP COLUMN IF EXISTS issuer_country, DROP COLUMN IF EXISTS payer_country, DROP COLUMN IF EXISTS is_stored, DROP COLUMN IF EXISTS direct_debit_token, DROP COLUMN IF EXISTS swift_code, DROP COLUMN IF EXISTS payment_method_issuer, DROP COLUMN IF EXISTS payment_method_issuer_code, DROP COLUMN IF EXISTS metadata, DROP COLUMN IF EXISTS payment_method, DROP COLUMN IF EXISTS payment_method_type; DROP TYPE IF EXISTS "PaymentMethodIssuerCode"; -- Run below queries only when V1 is deprecated ALTER TABLE refund DROP COLUMN connector_refund_data, DROP COLUMN connector_transaction_data, DROP COLUMN issuer_error_code, DROP COLUMN issuer_error_message; -- Run below queries only when V1 is deprecated ALTER TABLE captures DROP COLUMN connector_capture_data; -- Run below queries only when V1 is deprecated ALTER TABLE refund DROP COLUMN IF EXISTS internal_reference_id, DROP COLUMN IF EXISTS refund_id, DROP COLUMN IF EXISTS merchant_connector_id;
993
734
hyperswitch
v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql
.sql
ALTER TABLE ORGANIZATION ADD COLUMN org_id VARCHAR(32), ADD COLUMN org_name TEXT; ALTER TABLE merchant_account ADD COLUMN merchant_id VARCHAR(64), ADD COLUMN return_url VARCHAR(255), ADD COLUMN enable_payment_response_hash BOOLEAN DEFAULT FALSE, ADD COLUMN payment_response_hash_key VARCHAR(255), ADD COLUMN redirect_to_merchant_with_http_post BOOLEAN DEFAULT FALSE, ADD COLUMN sub_merchants_enabled BOOLEAN DEFAULT FALSE, ADD COLUMN parent_merchant_id VARCHAR(64), ADD COLUMN locker_id VARCHAR(64), ADD COLUMN intent_fulfillment_time BIGINT, ADD COLUMN default_profile VARCHAR(64), ADD COLUMN payment_link_config JSONB NULL, ADD COLUMN pm_collect_link_config JSONB NULL, ADD COLUMN is_recon_enabled BOOLEAN, ADD COLUMN webhook_details JSON NULL, ADD COLUMN routing_algorithm JSON, ADD COLUMN frm_routing_algorithm JSONB, ADD COLUMN payout_routing_algorithm JSONB; -- The default value is for temporary purpose only ALTER TABLE merchant_account ADD COLUMN primary_business_details JSON; ALTER TABLE business_profile ADD COLUMN profile_id VARCHAR(64), ADD COLUMN routing_algorithm JSON DEFAULT NULL, ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS business_country "CountryAlpha2", ADD COLUMN IF NOT EXISTS business_label VARCHAR(255), ADD COLUMN IF NOT EXISTS business_sub_label VARCHAR(64), ADD COLUMN IF NOT EXISTS test_mode BOOLEAN, ADD COLUMN IF NOT EXISTS frm_configs jsonb, ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(128); ALTER TABLE customers ADD COLUMN customer_id VARCHAR(64), ADD COLUMN address_id VARCHAR(64); ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS payment_id VARCHAR(64), ADD COLUMN connector_id VARCHAR(64), ADD COLUMN shipping_address_id VARCHAR(64), ADD COLUMN billing_address_id VARCHAR(64), ADD COLUMN shipping_details BYTEA, ADD COLUMN billing_details BYTEA, ADD COLUMN statement_descriptor_suffix VARCHAR(255), ADD COLUMN business_country "CountryAlpha2", ADD COLUMN business_label VARCHAR(64), ADD COLUMN incremental_authorization_allowed BOOLEAN, ADD COLUMN merchant_decision VARCHAR(64), ADD COLUMN fingerprint_id VARCHAR(64), ADD COLUMN statement_descriptor_name VARCHAR(255), ADD COLUMN amount_to_capture BIGINT, ADD COLUMN off_session BOOLEAN, ADD COLUMN payment_confirm_source "PaymentSource", ADD COLUMN merchant_order_reference_id VARCHAR(255), ADD COLUMN is_payment_processor_token_flow BOOLEAN, ADD COLUMN charges jsonb; ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64), ADD COLUMN amount bigint, ADD COLUMN currency "Currency", ADD COLUMN save_to_locker BOOLEAN, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(128), ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN processor_transaction_data text, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), ADD COLUMN payment_method_type VARCHAR(64), ADD COLUMN business_sub_label VARCHAR(64), ADD COLUMN mandate_details JSONB, ADD COLUMN mandate_data JSONB, ADD COLUMN tax_amount bigint, ADD COLUMN straight_through_algorithm JSONB, ADD COLUMN confirm BOOLEAN, ADD COLUMN authentication_data JSON, ADD COLUMN payment_method_billing_address_id VARCHAR(64), ADD COLUMN connector_mandate_detail JSONB, ADD COLUMN charge_id VARCHAR(64); -- Create the index which was dropped because of dropping the column CREATE INDEX payment_attempt_connector_transaction_id_merchant_id_index ON payment_attempt (connector_transaction_id, merchant_id); CREATE UNIQUE INDEX payment_attempt_payment_id_merchant_id_attempt_id_index ON payment_attempt (payment_id, merchant_id, attempt_id); -- Payment Methods CREATE TYPE "PaymentMethodIssuerCode" AS ENUM ( 'jp_hdfc', 'jp_icici', 'jp_googlepay', 'jp_applepay', 'jp_phonepe', 'jp_wechat', 'jp_sofort', 'jp_giropay', 'jp_sepa', 'jp_bacs' ); ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS payment_method_id VARCHAR(64), ADD COLUMN IF NOT EXISTS accepted_currency "Currency" [ ], ADD COLUMN IF NOT EXISTS scheme VARCHAR(32), ADD COLUMN IF NOT EXISTS token VARCHAR(128), ADD COLUMN IF NOT EXISTS cardholder_name VARCHAR(255), ADD COLUMN IF NOT EXISTS issuer_name VARCHAR(64), ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(64), ADD COLUMN IF NOT EXISTS payer_country TEXT [ ], ADD COLUMN IF NOT EXISTS is_stored BOOLEAN, ADD COLUMN IF NOT EXISTS direct_debit_token VARCHAR(128), ADD COLUMN IF NOT EXISTS swift_code VARCHAR(32), ADD COLUMN IF NOT EXISTS payment_method_issuer VARCHAR(128), ADD COLUMN IF NOT EXISTS metadata JSON, ADD COLUMN IF NOT EXISTS payment_method VARCHAR, ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_issuer_code "PaymentMethodIssuerCode"; ALTER TABLE refund ADD COLUMN connector_refund_data VARCHAR(512), ADD COLUMN connector_transaction_data VARCHAR(512); ALTER TABLE captures ADD COLUMN connector_capture_data VARCHAR(512); ALTER TABLE refund ADD COLUMN IF NOT EXISTS internal_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS refund_id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_connector_id VARCHAR(64);
1,245
735
hyperswitch
v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/up.sql
.sql
-- This file contains queries to update the primary key constraints suitable to the v2 application. -- This also has queries to update other constraints and indexes on tables where applicable. ------------------------ Organization ----------------------- -- Update null id and organization_name fields UPDATE ORGANIZATION SET id = org_id WHERE id IS NULL; UPDATE ORGANIZATION SET organization_name = org_name WHERE organization_name IS NULL AND org_name IS NOT NULL; -- Alter queries for organization table ALTER TABLE ORGANIZATION ADD CONSTRAINT organization_pkey_id PRIMARY KEY (id); ALTER TABLE ORGANIZATION ADD CONSTRAINT organization_organization_name_key UNIQUE (organization_name); ------------------------ Merchant Account ----------------------- -- Backfill id column with merchant_id values UPDATE merchant_account SET id = merchant_id WHERE id IS NULL; -- Add primary key constraint ALTER TABLE merchant_account ADD PRIMARY KEY (id); ------------------------ Business Profile ----------------------- -- Backfill id column with profile_id values UPDATE business_profile SET id = profile_id WHERE id IS NULL; -- Add primary key constraint ALTER TABLE business_profile ADD PRIMARY KEY (id); ------------------------ Merchant Connector Account ----------------------- -- Backfill id column with merchant_connector_id values UPDATE merchant_connector_account SET id = merchant_connector_id WHERE id IS NULL; -- Add primary key constraint ALTER TABLE merchant_connector_account ADD PRIMARY KEY (id); -- Create index on profile_id CREATE INDEX IF NOT EXISTS merchant_connector_account_profile_id_index ON merchant_connector_account (profile_id); ------------------------ Customers ----------------------- -- Backfill id column with customer_id values UPDATE customers SET id = customer_id WHERE id IS NULL; -- Add primary key constraint ALTER TABLE customers ADD PRIMARY KEY (id); ------------------------ Payment Intent ----------------------- -- Add primary key constraint ALTER TABLE payment_intent ADD PRIMARY KEY (id); ------------------------ Payment Attempt ----------------------- -- Add primary key constraint ALTER TABLE payment_attempt ADD PRIMARY KEY (id); ------------------------ Payment Methods ----------------------- -- Add primary key constraint ALTER TABLE payment_methods ADD PRIMARY KEY (id); ------------------------ Refunds ----------------------- -- Add primary key constraint ALTER TABLE refund ADD PRIMARY KEY (id);
441
736
hyperswitch
v2_migrations/2024-08-28-081838_update_v2_primary_key_constraints/down.sql
.sql
-- Backfill for organization table ------------------------ Organization ----------------------- UPDATE ORGANIZATION SET org_id = id WHERE org_id IS NULL; ALTER TABLE ORGANIZATION DROP CONSTRAINT organization_pkey_id; ALTER TABLE ORGANIZATION DROP CONSTRAINT organization_organization_name_key; -- Backfill UPDATE ORGANIZATION SET org_name = organization_name WHERE org_name IS NULL AND organization_name IS NOT NULL; ------------------------ Merchant Account ----------------------- -- The new primary key for v2 merchant account will be `id` ALTER TABLE merchant_account DROP CONSTRAINT merchant_account_pkey; ALTER TABLE merchant_account ALTER COLUMN id DROP NOT NULL; -- Backfill the id, a simple strategy will be to copy the values of id to merchant_id UPDATE merchant_account SET merchant_id = id WHERE merchant_id IS NULL; ------------------------ Business Profile ----------------------- ALTER TABLE business_profile DROP CONSTRAINT business_profile_pkey; ALTER TABLE business_profile ALTER COLUMN id DROP NOT NULL; UPDATE business_profile SET profile_id = id WHERE profile_id IS NULL; ------------------------ Merchant Connector Account ----------------------- ALTER TABLE merchant_connector_account DROP CONSTRAINT merchant_connector_account_pkey; ALTER TABLE merchant_connector_account ALTER COLUMN id DROP NOT NULL; UPDATE merchant_connector_account SET merchant_connector_id = id WHERE merchant_connector_id IS NULL; DROP INDEX IF EXISTS merchant_connector_account_profile_id_index; ------------------------ Customers ----------------------- -- Run this query only when V1 is deprecated ALTER TABLE customers DROP CONSTRAINT customers_pkey; ALTER TABLE customers ALTER COLUMN id DROP NOT NULL; -- Backfill before making it primary key UPDATE customers SET customer_id = id WHERE customer_id IS NULL; ------------------------ Payment Intent ----------------------- ALTER TABLE payment_intent DROP CONSTRAINT payment_intent_pkey; ALTER TABLE payment_intent ALTER COLUMN id DROP NOT NULL; UPDATE payment_intent SET payment_id = id WHERE payment_id IS NULL; ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP CONSTRAINT payment_attempt_pkey; ALTER TABLE payment_attempt ALTER COLUMN id DROP NOT NULL; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP CONSTRAINT payment_methods_pkey; ALTER TABLE payment_methods ALTER COLUMN id DROP NOT NULL; ------------------------ Refunds ----------------------- ALTER TABLE refund DROP CONSTRAINT refund_pkey; ALTER TABLE refund ALTER COLUMN id DROP NOT NULL;
451
737
hyperswitch
v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/up.sql
.sql
-- Your SQL goes here ALTER TABLE customers ALTER COLUMN status SET NOT NULL, ALTER COLUMN status SET DEFAULT 'active'; -- This migration is to make profile_id mandatory in mca table ALTER TABLE merchant_connector_account ALTER COLUMN profile_id SET NOT NULL; -- This migration is to make fields mandatory in payment_intent table ALTER TABLE payment_intent ALTER COLUMN profile_id SET NOT NULL, ALTER COLUMN currency SET NOT NULL, ALTER COLUMN client_secret SET NOT NULL, ALTER COLUMN session_expiry SET NOT NULL; -- This migration is to make fields mandatory in payment_attempt table ALTER TABLE payment_attempt ALTER COLUMN net_amount SET NOT NULL, ALTER COLUMN authentication_type SET NOT NULL, ALTER COLUMN payment_method_type_v2 SET NOT NULL, ALTER COLUMN payment_method_subtype SET NOT NULL; -- This migration is to make fields mandatory in refund table ALTER TABLE refund ALTER COLUMN merchant_reference_id SET NOT NULL;
193
738
hyperswitch
v2_migrations/2024-08-28-081837_add_not_null_constraints_to_v2_columns/down.sql
.sql
-- This file should undo anything in `up.sql` ALTER TABLE customers ALTER COLUMN status DROP NOT NULL, ALTER COLUMN status DROP DEFAULT; ALTER TABLE merchant_connector_account ALTER COLUMN profile_id DROP NOT NULL; ALTER TABLE payment_intent ALTER COLUMN profile_id DROP NOT NULL, ALTER COLUMN currency DROP NOT NULL, ALTER COLUMN client_secret DROP NOT NULL, ALTER COLUMN session_expiry DROP NOT NULL; ALTER TABLE payment_attempt ALTER COLUMN net_amount DROP NOT NULL; -- This migration is to make fields mandatory in payment_attempt table ALTER TABLE payment_attempt ALTER COLUMN net_amount DROP NOT NULL, ALTER COLUMN authentication_type DROP NOT NULL, ALTER COLUMN payment_method_type_v2 DROP NOT NULL, ALTER COLUMN payment_method_subtype DROP NOT NULL; ALTER TABLE refund ALTER COLUMN merchant_reference_id DROP NOT NULL;
171
739
hyperswitch
v2_migrations/2025-03-19-080705_payment-method-subtype-optional/up.sql
.sql
-- Your SQL goes here ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype DROP NOT NULL;
19
740
hyperswitch
v2_migrations/2025-03-19-080705_payment-method-subtype-optional/down.sql
.sql
ALTER TABLE payment_attempt ALTER COLUMN payment_method_subtype SET NOT NULL;
13
741
hyperswitch
v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/up.sql
.sql
ALTER TABLE payment_attempt ADD COLUMN feature_metadata JSONB;
12
742
hyperswitch
v2_migrations/2025-01-17-042122_add_feature_metadata_in_payment_attempt/down.sql
.sql
ALTER TABLE payment_attempt DROP COLUMN IF EXISTS feature_metadata;
12
743
hyperswitch
loadtest/Dockerfile
none
FROM rust:latest AS builder WORKDIR /app COPY . . RUN cargo install diesel_cli && cargo build --bin router --release FROM rust:latest AS runtime WORKDIR /app COPY --from=builder /app/migrations migrations COPY --from=builder /app/target/release/router router COPY --from=builder /usr/local/cargo/bin/diesel diesel
79
744
hyperswitch
loadtest/docker-compose.yaml
.yaml
version: "2" networks: loadtest_net: services: db: image: postgres restart: always environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: loadtest_router networks: - loadtest_net healthcheck: test: [ "CMD-SHELL", "pg_isready -U postgres" ] interval: 5s timeout: 5s retries: 5 stripe-mock: image: heyrutvik/stripe-mock:latest networks: - loadtest_net redis-queue: image: redis:7 networks: - loadtest_net router-server: build: context: .. dockerfile: ./loadtest/Dockerfile cpuset: "0" volumes: - ./config:/config - ./logs.tmp:/app/logs command: - /bin/bash - -c - | ./diesel migration run ./router -f /config/development.toml ports: - "8080" environment: DATABASE_URL: postgres://postgres:postgres@db/loadtest_router RUST_LOG: INFO RUN_ENV: development OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317 networks: - loadtest_net healthcheck: test: curl --fail http://router-server:8080/health || exit 1 interval: 5s timeout: 5s retries: 5 depends_on: db: condition: service_healthy stripe-mock: condition: service_started redis-queue: condition: service_started influxdb: condition: service_started otel-collector: condition: service_started tempo: condition: service_started grafana: condition: service_started k6: image: loadimpact/k6:latest volumes: - ./k6:/scripts command: run /scripts/${LOADTEST_K6_SCRIPT} networks: - loadtest_net environment: - LOADTEST_RUN_NAME=${LOADTEST_RUN_NAME} - K6_OUT=influxdb=http://influxdb:8086/scripts depends_on: router-server: condition: service_healthy influxdb: image: influxdb:1.8 networks: - loadtest_net environment: - INFLUXDB_DB=scripts otel-collector: image: otel/opentelemetry-collector:latest command: --config=/etc/otel-collector.yaml networks: - loadtest_net volumes: - ./config/otel-collector.yaml:/etc/otel-collector.yaml tempo: image: grafana/tempo:latest command: -config.file=/etc/tempo.yaml volumes: - ./config/tempo.yaml:/etc/tempo.yaml - ./tempo.tmp:/tmp/tempo networks: - loadtest_net grafana: image: grafana/grafana:latest ports: - "3002:3000" networks: - loadtest_net environment: - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin - GF_AUTH_ANONYMOUS_ENABLED=true - GF_AUTH_BASIC_ENABLED=false volumes: - ./grafana/dashboards:/var/lib/grafana/dashboards - ./grafana/grafana-dashboard.yaml:/etc/grafana/provisioning/dashboards/dashboard.yaml - ./grafana/grafana-datasource.yaml:/etc/grafana/provisioning/datasources/datasource.yaml
836
745
hyperswitch
loadtest/README.md
.md
## Performance Benchmarking Setup The setup uses docker compose to get the required components up and running. It also handles running database migration and starts [K6 load testing](https://k6.io/docs/) script at the end. The metrics are visible in the console as well as through Grafana dashboard. We have added a callback at the end of the script to compare result with existing baseline values. The env variable `LOADTEST_RUN_NAME` can be used to change the name of the run which will be used to create json, result summary and diff benchmark files. The default value is "baseline", and diff will be created by comparing new results against baseline. See 'How to run' section. ### Structure/Files `config`: contains router toml file to change settings. Also setting files for other components like Tempo etc. `grafana`: data source and dashboard files `k6`: K6 load testing tool scripts. The `setup.js` contain common functions like creating merchant api key etc. Each js files will contain load testing scenario of each APIs. Currently, we have `health.js` and `payment-confirm.js`. `.env`: It provide default value to docker compose file. Developer can specify which js script they want to run using env variable called `LOADTEST_K6_SCRIPT`. The default script is `health.js`. See 'How to run' section. ### How to run Build image of checked out branch. ```bash docker compose build ``` Run default (`health.js`) script. It will generate baseline result. ```bash bash loadtest.sh ``` The `loadtest.sh` script takes following flags, `-c`: _compare_ with baseline results [without argument] auto assign run name based on current commit number `-r`: takes _run name_ as argument (default: baseline) `-s`: _script name_ exists in `k6` directory without the file extension as argument (default: health) `-a`: run loadtest for _all scripts_ existing in `k6` directory [without argument] For example, to run the baseline for `payment-confirm.js` script. ```bash bash loadtest.sh -s payment-confirm ``` The run name could be anything. It will be used to prefix benchmarking files, stored at `./k6/benchmark`. For example, ```bash bash loadtest.sh -r made_calls_asyns -s payment-confirm ``` A preferred way to compare new changes with the baseline is using the `-c` flag. It automatically assigns commit numbers to easily match different results. ```bash bash loadtest.sh -c -s payment-confirm ``` Assuming there is baseline files for all the script, following command will compare them with new changes, ```bash bash loadtest.sh -ca ``` It uses `-c` compare flag and `-a` run loadtest using all the scripts. Developer can observe live metrics using [K6 Load Testing Dashboard](http://localhost:3002/d/k6/k6-load-testing-results?orgId=1&refresh=5s&from=now-1m&to=now) in Grafana. The [Tempo datasource](http://localhost:3002/explore?orgId=1&left=%7B%22datasource%22:%22P214B5B846CF3925F%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22queryType%22:%22nativeSearch%22%7D%5D,%22range%22:%7B%22from%22:%22now-1m%22,%22to%22:%22now%22%7D%7D) is available to inspect tracing of individual requests. ### Notes 1. The script will first "down" the already running docker compose to run loadtest on freshly created database. 2. Make sure that the Rust compiler is happy with your changes before you start running a performance test. This will save a lot of your time. 3. If the project image is available locally then `docker compose up` won't take your new changes into account. Either first do `docker compose build` or `docker compose up --build k6`. 4. For baseline, make sure you in the right branch and have build the image before running the loadtest script.
955
746
hyperswitch
loadtest/loadtest.sh
.sh
#!/bin/bash run_loadtest() { docker compose down docker compose up k6 } print_details() { echo "-----------------------------------" echo "RUN NAME: $1" echo " SCRIPT: $2" echo "-----------------------------------" } exit_if_baseline_file_not_exist() { if ! [ -e "./k6/benchmark/baseline_$1.json" ] then echo "baseline_$1.json file not exist to compare." exit 1 fi } while getopts r:s:ca flag do case "${flag}" in r) run_name=${OPTARG};; s) script=${OPTARG};; c) compare=true;; a) all_script=true;; *) echo "usage: $0 [-r] [-c] [-s]" >&2 exit 1;; esac done # if script is empty, `-s` not specified, use "health" if [ -z "$script" ] then script=health fi if ! [ -e "./k6/$script.js" ] && [ -z "$all_script" ] then echo "$script.js not exist." exit 1 fi # if compare is specified using `-c` flag, create run name using commit number if [ "$compare" = true ] then run_name=$(git show -s --format=%h) # make sure baseline file exist for specified parameter before starting the loadtest if [ "$all_script" = true ] then for scriptname in ./k6/*.js do filename=$(basename "$scriptname" | cut -f 1 -d '.') exit_if_baseline_file_not_exist "$filename" done else exit_if_baseline_file_not_exist "$script" fi else # if run name is empty, `-r` not specified, use "baseline" if [ -z "$run_name" ] then run_name=baseline fi fi export LOADTEST_RUN_NAME=$run_name if [ "$all_script" = true ] then for script in ./k6/*.js do script=$(basename "$script") print_details "$run_name" "$script" export LOADTEST_K6_SCRIPT=$script run_loadtest done else print_details "$run_name" "$script.js" export LOADTEST_K6_SCRIPT="$script.js" run_loadtest fi
532
747
hyperswitch
loadtest/k6/payment-confirm.js
.js
import http from "k6/http"; import { sleep, check } from "k6"; import { Counter } from "k6/metrics"; import { setup_merchant_apikey } from "./helper/setup.js"; import { random_string } from "./helper/misc.js"; import { readBaseline, storeResult } from "./helper/compare-result.js"; export const requests = new Counter("http_reqs"); const baseline = readBaseline("payment-confirm"); export const options = { stages: [ { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds ], thresholds: { 'http_req_duration': ['p(90) < 500'], // 90% of requests must finish within 500ms. }, }; export function setup() { return setup_merchant_apikey(); } export default function (data) { let payload = { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": random_string(), "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "setup_future_usage": "on_session", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } }, "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }; let res = http.post("http://router-server:8080/payments", JSON.stringify(payload), { "headers": { "Content-Type": "application/json", "api-key" : data.api_key }, }); check(res, { "confirm payment status 200": (r) => r.status === 200, }); } export function handleSummary(data) { return storeResult("payment-confirm", baseline, data) }
682
748
hyperswitch
loadtest/k6/payment-create-and-confirm.js
.js
import http from "k6/http"; import { sleep, check } from "k6"; import { Counter } from "k6/metrics"; import { setup_merchant_apikey } from "./helper/setup.js"; import { random_string } from "./helper/misc.js"; import { readBaseline, storeResult } from "./helper/compare-result.js"; export const requests = new Counter("http_reqs"); const baseline = readBaseline("payment-create-and-confirm"); export const options = { stages: [ { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds ], thresholds: { 'http_req_duration': ['p(90) < 500'], // 90% of requests must finish within 500ms. }, }; export function setup() { return setup_merchant_apikey(); } export default function(data) { const create_payment_payload = { "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": random_string(), "description": "Its my first payment request", "return_url": "http://example.com/payments", "authentication_type": "three_ds", "payment_method": "card", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router" }; let create_payment_res = http.post("http://router-server:8080/payments", JSON.stringify(create_payment_payload), { "headers": { "Content-Type": "application/json", "api-key" : data.api_key }, }); check(create_payment_res, { "create payment status 200": (r) => r.status === 200, }); const payment_id = create_payment_res.json().payment_id; const confirm_payment_payload = { "return_url": "http://example.com/payments", "setup_future_usage": "off_session", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "35", "card_holder_name": "John Doe", "card_cvc": "123" } } }; let confirm_payment_res = http.post(`http://router-server:8080/payments/${payment_id}/confirm`, JSON.stringify(confirm_payment_payload), { "headers": { "Content-Type": "application/json", "api-key" : data.api_key }, }); check(confirm_payment_res, { "confirm payment status 200": (r) => r.status === 200, }); }; export function handleSummary(data) { return storeResult("payment-create-and-confirm", baseline, data) }
745
749
hyperswitch
loadtest/k6/health.js
.js
import http from "k6/http"; import { sleep, check } from "k6"; import { Counter } from "k6/metrics"; import { readBaseline, storeResult } from "./helper/compare-result.js"; export const requests = new Counter('http_reqs'); const baseline = readBaseline("health"); export const options = { stages: [ { duration: "10s", target: 25 }, // ramp up users to 25 in 10 seconds { duration: "10s", target: 25 }, // maintain 25 users for 10 seconds { duration: "10s", target: 0 } // ramp down to 0 users in 10 seconds ], thresholds: { "http_req_duration": ["p(90) < 15"], // 90% of requests must finish within 15ms. }, }; export default function () { const res = http.get("http://router-server:8080/health"); check(res, { "health status 200": (r) => r.status === 200, }); } export function handleSummary(data) { return storeResult("health", baseline, data) }
274
750
hyperswitch
loadtest/k6/rps.js
.js
import { group } from 'k6'; import { Counter } from "k6/metrics"; import { readBaseline, storeResult } from "./helper/compare-result.js"; import { setup_merchant_apikey } from "./helper/setup.js"; import paymentCreateAndConfirmFunc from './payment-create-and-confirm.js'; import paymentConfirmFunc from './payment-confirm.js'; export const requests = new Counter("http_reqs"); const baseline = readBaseline("rps"); export const options = { scenarios: { contacts: { executor: 'per-vu-iterations', vus: 10, iterations: 100, maxDuration: '5m', }, }, }; export function setup() { return setup_merchant_apikey() } export default function (data) { group("create payment and confirm", function() { paymentCreateAndConfirmFunc(data) }); group("create confirmed payment", function() { paymentConfirmFunc(data) }); } export function handleSummary(data) { return storeResult("rps", baseline, data) }
223
751
hyperswitch
loadtest/k6/helper/setup.js
.js
import http from "k6/http"; import { check } from "k6"; export function setup_merchant_apikey() { let params = { "headers": { "Content-Type": "application/json", "api-key" : "test_admin" } }; let merchant_account_payload = { "merchant_id":`merchant_${Date.now()}`, "merchant_name":"NewAge Retailer", "merchant_details":{ "primary_contact_person":"John Test", "primary_email":"JohnTest@test.com", "primary_phone":"sunt laborum", "secondary_contact_person":"John Test2", "secondary_email":"JohnTest2@test.com", "secondary_phone":"cillum do dolor id", "website":"www.example.com", "about_business":"Online Retail with a wide selection of organic products for North America", "address":{ "line1":"Vivamus vitae", "line2":"Libero eget", "line3":"Cras ultrices", "city":"Nascetur", "state":"Purus", "zip":"010101", "country":"ZX" } }, "return_url":"www.example.com/success", "webhook_details":{ "webhook_version":"1.0.1", "webhook_username":"wh_store", "webhook_password":"pwd_wh@101", "payment_created_enabled":true, "payment_succeeded_enabled":true, "payment_failed_enabled":true }, "routing_algorithm": { "type": "single", "data": "checkout" }, "sub_merchants_enabled":false, "metadata":{ "city":"NY", "unit":"245" } } let ma_res = http.post("http://router-server:8080/accounts", JSON.stringify(merchant_account_payload), params); let json = ma_res.json(); let merchant_id = json.merchant_id; let api_key = json.api_key; let connector_account_payload = { "connector_type":"fiz_operations", "connector_name":"stripe", "connector_account_details":{ "auth_type":"HeaderKey", "api_key":"Bearer sk_test_123" }, "test_mode":false, "disabled":false, "payment_methods_enabled":[ { "payment_method":"wallet", "payment_method_types":[ "upi_collect", "upi_intent" ], "payment_method_issuers":[ "labore magna ipsum", "aute" ], "payment_schemes":[ "Discover", "Discover" ], "accepted_currencies":[ "AED", "AED" ], "accepted_countries":[ "in", "us" ], "minimum_amount":1, "maximum_amount":68607706, "recurring_enabled":true, "installment_payment_enabled":true } ], "metadata":{ "city":"NY", "unit":"245" } } let ca_res = http.post(`http://router-server:8080/account/${merchant_id}/connectors`, JSON.stringify(connector_account_payload), params); let update_merchant_account_payload = { "merchant_id":merchant_id, "merchant_name":"NewAge Retailer", "merchant_details":{ "primary_contact_person":"John Test", "primary_email":"JohnTest@test.com", "primary_phone":"veniam aute officia ullamco esse", "secondary_contact_person":"John Test2", "secondary_email":"JohnTest2@test.com", "secondary_phone":"proident adipisicing officia nulla", "website":"www.example.com", "about_business":"Online Retail with a wide selection of organic products for North America", "address":{ "line1":"Vivamus vitae", "line2":"Libero eget", "line3":"Cras ultrices", "city":"Nascetur", "state":"Purus", "zip":"010101", "country":"ZX" } }, "return_url":"www.example.com/success", "webhook_details":{ "webhook_version":"1.0.1", "webhook_username":"wh_store", "webhook_password":"pwd_wh@101", "payment_created_enabled":true, "payment_succeeded_enabled":true, "payment_failed_enabled":true }, "routing_algorithm": { "type": "single", "data": "stripe" }, "metadata":{ "city":"NY", "unit":"245" } } let uma_res = http.post(`http://router-server:8080/accounts/${merchant_id}`, JSON.stringify(update_merchant_account_payload), params); return { "api_key": api_key } }
1,069
752
hyperswitch
loadtest/k6/helper/k6-summary.js
.js
var forEach = function (obj, callback) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback(key, obj[key])) { break } } } } var palette = { bold: 1, faint: 2, red: 31, green: 32, cyan: 36, //TODO: add others? } var groupPrefix = '█' var detailsPrefix = '↳' var succMark = '✓' var failMark = '✗' var defaultOptions = { indent: ' ', enableColors: true, summaryTimeUnit: null, summaryTrendStats: null, } // strWidth tries to return the actual width the string will take up on the // screen, without any terminal formatting, unicode ligatures, etc. function strWidth(s) { // TODO: determine if NFC or NFKD are not more appropriate? or just give up? https://hsivonen.fi/string-length/ var data = s.normalize('NFKC') // This used to be NFKD in Go, but this should be better var inEscSeq = false var inLongEscSeq = false var width = 0 for (var char of data) { if (char.done) { break } // Skip over ANSI escape codes. if (char == '\x1b') { inEscSeq = true continue } if (inEscSeq && char == '[') { inLongEscSeq = true continue } if (inEscSeq && inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x7e) { inEscSeq = false inLongEscSeq = false continue } if (inEscSeq && !inLongEscSeq && char.charCodeAt(0) >= 0x40 && char.charCodeAt(0) <= 0x5f) { inEscSeq = false continue } if (!inEscSeq && !inLongEscSeq) { width++ } } return width } function summarizeCheck(indent, check, decorate) { if (check.fails == 0) { return decorate(indent + succMark + ' ' + check.name, palette.green) } var succPercent = Math.floor((100 * check.passes) / (check.passes + check.fails)) return decorate( indent + failMark + ' ' + check.name + '\n' + indent + ' ' + detailsPrefix + ' ' + succPercent + '% — ' + succMark + ' ' + check.passes + ' / ' + failMark + ' ' + check.fails, palette.red ) } function summarizeGroup(indent, group, decorate) { var result = [] if (group.name != '') { result.push(indent + groupPrefix + ' ' + group.name + '\n') indent = indent + ' ' } for (var i = 0; i < group.checks.length; i++) { result.push(summarizeCheck(indent, group.checks[i], decorate)) } if (group.checks.length > 0) { result.push('') } for (var i = 0; i < group.groups.length; i++) { Array.prototype.push.apply(result, summarizeGroup(indent, group.groups[i], decorate)) } return result } function displayNameForMetric(name) { var subMetricPos = name.indexOf('{') if (subMetricPos >= 0) { return '{ ' + name.substring(subMetricPos + 1, name.length - 1) + ' }' } return name } function indentForMetric(name) { if (name.indexOf('{') >= 0) { return ' ' } return '' } function humanizeBytes(bytes) { var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var base = 1000 if (bytes < 10) { return bytes + ' B' } var e = Math.floor(Math.log(bytes) / Math.log(base)) var suffix = units[e | 0] var val = Math.floor((bytes / Math.pow(base, e)) * 10 + 0.5) / 10 return val.toFixed(val < 10 ? 1 : 0) + ' ' + suffix } var unitMap = { s: { unit: 's', coef: 0.001 }, ms: { unit: 'ms', coef: 1 }, us: { unit: 'µs', coef: 1000 }, } function toFixedNoTrailingZeros(val, prec) { // TODO: figure out something better? return parseFloat(val.toFixed(prec)).toString() } function toFixedNoTrailingZerosTrunc(val, prec) { var mult = Math.pow(10, prec) return toFixedNoTrailingZeros(Math.trunc(mult * val) / mult, prec) } function humanizeGenericDuration(duration) { if (duration === 0) { return '0s' } if (duration < 0.001) { // smaller than a microsecond, print nanoseconds return Math.trunc(duration * 1000000) + 'ns' } if (duration < 1) { // smaller than a millisecond, print microseconds return toFixedNoTrailingZerosTrunc(duration * 1000, 2) + 'µs' } if (duration < 1000) { // duration is smaller than a second return toFixedNoTrailingZerosTrunc(duration, 2) + 'ms' } var result = toFixedNoTrailingZerosTrunc((duration % 60000) / 1000, duration > 60000 ? 0 : 2) + 's' var rem = Math.trunc(duration / 60000) if (rem < 1) { // less than a minute return result } result = (rem % 60) + 'm' + result rem = Math.trunc(rem / 60) if (rem < 1) { // less than an hour return result } return rem + 'h' + result } function humanizeDuration(duration, timeUnit) { if (timeUnit !== '' && unitMap.hasOwnProperty(timeUnit)) { return (duration * unitMap[timeUnit].coef).toFixed(2) + unitMap[timeUnit].unit } return humanizeGenericDuration(duration) } function humanizeValue(val, metric, timeUnit) { if (metric.type == 'rate') { // Truncate instead of round when decreasing precision to 2 decimal places return (Math.trunc(val * 100 * 100) / 100).toFixed(2) + '%' } switch (metric.contains) { case 'data': return humanizeBytes(val) case 'time': return humanizeDuration(val, timeUnit) default: return toFixedNoTrailingZeros(val, 6) } } function nonTrendMetricValueForSum(metric, timeUnit) { switch (metric.type) { case 'counter': return [ humanizeValue(metric.values.count, metric, timeUnit), humanizeValue(metric.values.rate, metric, timeUnit) + '/s', ] case 'gauge': return [ humanizeValue(metric.values.value, metric, timeUnit), 'min=' + humanizeValue(metric.values.min, metric, timeUnit), 'max=' + humanizeValue(metric.values.max, metric, timeUnit), ] case 'rate': return [ humanizeValue(metric.values.rate, metric, timeUnit), succMark + ' ' + metric.values.passes, failMark + ' ' + metric.values.fails, ] default: return ['[no data]'] } } function summarizeMetrics(options, data, decorate) { var indent = options.indent + ' ' var result = [] var names = [] var nameLenMax = 0 var nonTrendValues = {} var nonTrendValueMaxLen = 0 var nonTrendExtras = {} var nonTrendExtraMaxLens = [0, 0] var trendCols = {} var numTrendColumns = options.summaryTrendStats.length var trendColMaxLens = new Array(numTrendColumns).fill(0) forEach(data.metrics, function (name, metric) { names.push(name) // When calculating widths for metrics, account for the indentation on submetrics. var displayName = indentForMetric(name) + displayNameForMetric(name) var displayNameWidth = strWidth(displayName) if (displayNameWidth > nameLenMax) { nameLenMax = displayNameWidth } if (metric.type == 'trend') { var cols = [] for (var i = 0; i < numTrendColumns; i++) { var tc = options.summaryTrendStats[i] var value = metric.values[tc] if (tc === 'count') { value = value.toString() } else { value = humanizeValue(value, metric, options.summaryTimeUnit) } var valLen = strWidth(value) if (valLen > trendColMaxLens[i]) { trendColMaxLens[i] = valLen } cols[i] = value } trendCols[name] = cols return } var values = nonTrendMetricValueForSum(metric, options.summaryTimeUnit) nonTrendValues[name] = values[0] var valueLen = strWidth(values[0]) if (valueLen > nonTrendValueMaxLen) { nonTrendValueMaxLen = valueLen } nonTrendExtras[name] = values.slice(1) for (var i = 1; i < values.length; i++) { var extraLen = strWidth(values[i]) if (extraLen > nonTrendExtraMaxLens[i - 1]) { nonTrendExtraMaxLens[i - 1] = extraLen } } }) // sort all metrics but keep sub metrics grouped with their parent metrics names.sort(function (metric1, metric2) { var parent1 = metric1.split('{', 1)[0] var parent2 = metric2.split('{', 1)[0] var result = parent1.localeCompare(parent2) if (result !== 0) { return result } var sub1 = metric1.substring(parent1.length) var sub2 = metric2.substring(parent2.length) return sub1.localeCompare(sub2) }) var getData = function (name) { if (trendCols.hasOwnProperty(name)) { var cols = trendCols[name] var tmpCols = new Array(numTrendColumns) for (var i = 0; i < cols.length; i++) { tmpCols[i] = options.summaryTrendStats[i] + '=' + decorate(cols[i], palette.cyan) + ' '.repeat(trendColMaxLens[i] - strWidth(cols[i])) } return tmpCols.join(' ') } var value = nonTrendValues[name] var fmtData = decorate(value, palette.cyan) + ' '.repeat(nonTrendValueMaxLen - strWidth(value)) var extras = nonTrendExtras[name] if (extras.length == 1) { fmtData = fmtData + ' ' + decorate(extras[0], palette.cyan, palette.faint) } else if (extras.length > 1) { var parts = new Array(extras.length) for (var i = 0; i < extras.length; i++) { parts[i] = decorate(extras[i], palette.cyan, palette.faint) + ' '.repeat(nonTrendExtraMaxLens[i] - strWidth(extras[i])) } fmtData = fmtData + ' ' + parts.join(' ') } return fmtData } for (var name of names) { var metric = data.metrics[name] var mark = ' ' var markColor = function (text) { return text } // noop if (metric.thresholds) { mark = succMark markColor = function (text) { return decorate(text, palette.green) } forEach(metric.thresholds, function (name, threshold) { if (!threshold.ok) { mark = failMark markColor = function (text) { return decorate(text, palette.red) } return true // break } }) } var fmtIndent = indentForMetric(name) var fmtName = displayNameForMetric(name) fmtName = fmtName + decorate( '.'.repeat(nameLenMax - strWidth(fmtName) - strWidth(fmtIndent) + 3) + ':', palette.faint ) result.push(indent + fmtIndent + markColor(mark) + ' ' + fmtName + ' ' + getData(name)) } return result } function generateTextSummary(data, options) { var mergedOpts = Object.assign({}, defaultOptions, data.options, options) var lines = [] // TODO: move all of these functions into an object with methods? var decorate = function (text) { return text } if (mergedOpts.enableColors) { decorate = function (text, color /*, ...rest*/) { var result = '\x1b[' + color for (var i = 2; i < arguments.length; i++) { result += ';' + arguments[i] } return result + 'm' + text + '\x1b[0m' } } Array.prototype.push.apply( lines, summarizeGroup(mergedOpts.indent + ' ', data.root_group, decorate) ) Array.prototype.push.apply(lines, summarizeMetrics(mergedOpts, data, decorate)) return lines.join('\n') } exports.humanizeValue = humanizeValue exports.textSummary = generateTextSummary var replacements = { '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;', } function escapeHTML(str) { // TODO: something more robust? return str.replace(/[&<>'"]/g, function (char) { return replacements[char] }) } function generateJUnitXML(data, options) { var failures = 0 var cases = [] forEach(data.metrics, function (metricName, metric) { if (!metric.thresholds) { return } forEach(metric.thresholds, function (thresholdName, threshold) { if (threshold.ok) { cases.push( '<testcase name="' + escapeHTML(metricName) + ' - ' + escapeHTML(thresholdName) + '" />' ) } else { failures++ cases.push( '<testcase name="' + escapeHTML(metricName) + ' - ' + escapeHTML(thresholdName) + '"><failure message="failed" /></testcase>' ) } }) }) var name = options && options.name ? escapeHTML(options.name) : 'k6 thresholds' return ( '<?xml version="1.0"?>\n<testsuites tests="' + cases.length + '" failures="' + failures + '">\n' + '<testsuite name="' + name + '" tests="' + cases.length + '" failures="' + failures + '">' + cases.join('\n') + '\n</testsuite >\n</testsuites >' ) } exports.jUnit = generateJUnitXML
3,545
753
hyperswitch
loadtest/k6/helper/compare-result.js
.js
import { textSummary } from "./k6-summary.js"; function compute(baseline, result) { return ((1 - (result/baseline)) * -100).toFixed(2) } function buildResult(baseline, data) { return function(metrics, fields) { const result = {} metrics.forEach(metric => { result[metric] = {} fields.forEach(field => { let a = baseline.metrics[metric]["values"][field] let b = data.metrics[metric]["values"][field] result[metric][field] = compute(a, b) + "%" }) }) return result } } function compareResult(baseline, data) { // note: we can add more metrics. we grouped them based on the field they contain. // todo: add validation whether threshold/check are being matched or vus are the same as baseline run. const computeResult = buildResult(baseline, data) const group1 = ["http_req_duration"] const group1_fields = data.options.summaryTrendStats const group1_result = computeResult(group1, group1_fields) const group2 = ["http_reqs"] const group2_fields = ["rate"] const group2_result = computeResult(group2, group2_fields) return Object.assign(group1_result, group2_result) } export function readBaseline(scenario) { let baseline = null; if (__ENV.LOADTEST_RUN_NAME != "baseline") { baseline = JSON.parse(open(`./benchmark/baseline_${scenario}.json`, "r")) } return baseline } export function storeResult(scenario, baseline, data) { const file = `/scripts/benchmark/${__ENV.LOADTEST_RUN_NAME}_${scenario}` const summary = textSummary(data, { indent: ' ', enableColors: false }) const result = { [`${file}.json`]: JSON.stringify(data, null, 2), [`${file}.summary`]: summary } if (baseline != null) { const diff = JSON.stringify(compareResult(baseline, data), null, 2) result[`${file}.diff`] = diff result["stdout"] = diff } else { result["stdout"] = summary } return result }
484
754
hyperswitch
loadtest/k6/helper/misc.js
.js
export function random_string() { return Math.random().toString(36).slice(-5) }
21
755
hyperswitch
loadtest/config/development.toml
.toml
[log.file] enabled = false [log.console] enabled = false [log.telemetry] traces_enabled = true metrics_enabled = true ignore_errors = false [key_manager] url = "http://localhost:5000" [master_database] username = "postgres" password = "postgres" host = "db" port = 5432 dbname = "loadtest_router" pool_size = 20 connection_timeout = 10 [server] host = "0.0.0.0" [redis] host = "redis-queue" [secrets] admin_api_key = "test_admin" jwt_secret = "secret" [user] password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" force_two_factor_auth = false force_cookies = true [locker] host = "" host_rs = "" mock_locker = true basilisk_host = "" locker_enabled = true ttl_for_storage_in_secs = 220752000 [forex_api] api_key = "" fallback_api_key = "" data_expiration_delay_in_seconds = 21600 redis_lock_timeout_in_seconds = 100 redis_ttl_in_seconds = 172800 [eph_key] validity = 1 [refund] max_attempts = 10 max_age = 365 [jwekey] vault_encryption_key = "" rust_locker_encryption_key = "" vault_private_key = "" [webhooks] outgoing_enabled = true [api_keys] hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" [connectors] aci.base_url = "https://eu-test.oppwa.com/" adyen.base_url = "https://checkout-test.adyen.com/" adyenplatform.base_url = "https://balanceplatform-api-test.adyen.com/" adyen.payout_base_url = "https://pal-test.adyen.com/" adyen.dispute_base_url = "https://ca-test.adyen.com/" airwallex.base_url = "https://api-demo.airwallex.com/" amazonpay.base_url = "https://pay-api.amazon.com/v2" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api" bambora.base_url = "https://api.na.bambora.com" bamboraapac.base_url = "https://demo.ippayments.com.au/interface/api" bankofamerica.base_url = "https://apitest.merchant-services.bankofamerica.com/" billwerk.base_url = "https://api.reepay.com/" billwerk.secondary_base_url = "https://card.reepay.com/" bitpay.base_url = "https://test.bitpay.com" bluesnap.base_url = "https://sandbox.bluesnap.com/" bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/" boku.base_url = "https://country-api4-stage.boku.com" braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql" cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" coingate.base_url = "https://api-sandbox.coingate.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" datatrans.secondary_base_url = "https://pay.sandbox.datatrans.com/" deutschebank.base_url = "https://testmerch.directpos.de/rest-api" digitalvirgo.base_url = "https://dcb-integration-service-sandbox-external.staging.digitalvirgo.pl" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" elavon.base_url = "https://api.demo.convergepay.com/VirtualMerchantDemo/" facilitapay.base_url = "https://sandbox-api.facilitapay.com/api/v1" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" fiuu.secondary_base_url = "https://sandbox.merchant.razer.com/" fiuu.third_base_url = "https://api.merchant.razer.com/" forte.base_url = "https://sandbox.forte.net/api/v3" getnet.base_url = "https://api-test.getneteurope.com/engine/rest" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" gocardless.base_url = "https://api-sandbox.gocardless.com" gpayments.base_url = "https://{{merchant_endpoint_prefix}}-test.api.as1.gpayments.net" helcim.base_url = "https://api.helcim.com/" hipay.base_url = "https://stage-secure-gateway.hipay-tpp.com/rest/" hipay.secondary_base_url = "https://stage-secure2-vault.hipay-tpp.com/rest/" hipay.third_base_url = "https://stage-api-gateway.hipay.com/" iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1" inespay.base_url = "https://apiflow.inespay.com/san/v21" itaubank.base_url = "https://sandbox.devportal.itau.com.br/" jpmorgan.base_url = "https://api-mock.payments.jpmorgan.com/api/v2" juspaythreedsserver.base_url = "http://localhost:8000" jpmorgan.secondary_base_url = "https://id.payments.jpmorgan.com" klarna.base_url = "https://api{{klarna_region}}.playground.klarna.com/" mifinity.base_url = "https://demo.mifinity.com/" mollie.base_url = "https://api.mollie.com/v2/" moneris.base_url = "https://api.sb.moneris.io" mollie.secondary_base_url = "https://api.cc.mollie.com/v1/" multisafepay.base_url = "https://testapi.multisafepay.com/" netcetera.base_url = "https://{{merchant_endpoint_prefix}}.3ds-server.prev.netcetera-cloud-payment.ch" nexinets.base_url = "https://apitest.payengine.de/v1" nexixpay.base_url = "https://xpaysandbox.nexigroup.com/api/phoenix-0.0/psp/api/v1" nmi.base_url = "https://secure.nmi.com/" nomupay.base_url = "https://payout-api.sandbox.nomupay.com" noon.base_url = "https://api-test.noonpayments.com/" noon.key_mode = "Test" novalnet.base_url = "https://payport.novalnet.de/v2" nuvei.base_url = "https://ppp-test.nuvei.com/" opayo.base_url = "https://pi-test.sagepay.com/" opennode.base_url = "https://dev-api.opennode.com" paybox.base_url = "https://preprod-ppps.paybox.com/PPPS.php" paybox.secondary_base_url = "https://preprod-tpeweb.paybox.com/" payeezy.base_url = "https://api-cert.payeezy.com/" payme.base_url = "https://sandbox.payme.io/" payone.base_url = "https://payment.preprod.payone.com/" paypal.base_url = "https://api-m.sandbox.paypal.com/" paystack.base_url = "https://api.paystack.co" payu.base_url = "https://secure.snd.payu.com/" placetopay.base_url = "https://test.placetopay.com/rest/gateway" plaid.base_url = "https://sandbox.plaid.com" powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" recurly.base_url = "https://v3.recurly.com" redsys.base_url = "https://sis-t.redsys.es:25443" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" square.base_url = "https://connect.squareupsandbox.com/" square.secondary_base_url = "https://pci-connect.squareupsandbox.com/" stax.base_url = "https://apiprod.fattlabs.com/" stripe.base_url = "https://api.stripe.com/" stripebilling.base_url = "https://api.stripe.com/" taxjar.base_url = "https://api.sandbox.taxjar.com/v2/" threedsecureio.base_url = "https://service.sandbox.3dsecure.io" thunes.base_url = "https://api.limonetikqualif.com/" stripe.base_url_file_upload = "https://files.stripe.com/" trustpay.base_url = "https://test-tpgw.trustpay.eu/" trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/" tsys.base_url = "https://stagegw.transnox.com/" unified_authentication_service.base_url = "http://localhost:8000" volt.base_url = "https://api.sandbox.volt.io/" wellsfargo.base_url = "https://apitest.cybersource.com/" wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/" worldline.base_url = "https://eu.sandbox.api-ingenico.com/" worldpay.base_url = "https://try.access.worldpay.com/" xendit.base_url = "https://api.xendit.co" wise.base_url = "https://api.sandbox.transferwise.tech/" zen.base_url = "https://api.zen-test.com/" zen.secondary_base_url = "https://secure.zen-test.com/" zsl.base_url = "https://api.sitoffalb.net/" [pm_filters.default] apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } [connectors.supported] wallets = ["klarna", "mifinity", "braintree", "applepay"] rewards = ["cashtocode", "zen"] cards = [ "aci", "adyen", "adyenplatform", "airwallex", "amazonpay", "authorizedotnet", "bambora", "bamboraapac", "bankofamerica", "billwerk", "bitpay", "bluesnap", "boku", "braintree", "checkout", "coinbase", "coingate", "cryptopay", "ctp_visa", "cybersource", "datatrans", "deutschebank", "digitalvirgo", "dlocal", "dummyconnector", "ebanx", "elavon", "facilitapay", "fiserv", "fiservemea", "fiuu", "forte", "getnet", "globalpay", "globepay", "gocardless", "gpayments", "helcim", "hipay", "iatapay", "inespay", "itaubank", "jpmorgan", "juspaythreedsserver", "mollie", "moneris", "multisafepay", "netcetera", "nexinets", "nexixpay", "nmi", "noon", "novalnet", "nuvei", "opayo", "opennode", "paybox", "payeezy", "payme", "payone", "paypal", "paystack", "payu", "placetopay", "plaid", "powertranz", "prophetpay", "redsys", "shift4", "square", "stax", "stripe", "stripebilling", "taxjar", "threedsecureio", "thunes", "trustpay", "tsys", "unified_authentication_service", "volt", "wellsfargo", "wellsfargopayout", "wise", "worldline", "worldpay", "xendit", "zen", "zsl", ] [pm_filters.dlocal] credit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" } debit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" } [pm_filters.mollie] credit = { not_available_flows = { capture_method = "manual" } } debit = { not_available_flows = { capture_method = "manual" } } eps = { country = "AT", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } przelewy24 = { country = "PL", currency = "PLN,EUR" } [pm_filters.mifinity] mifinity = { country = "BR,CN,SG,MY,DE,CH,DK,GB,ES,AD,GI,FI,FR,GR,HR,IT,JP,MX,AR,CO,CL,PE,VE,UY,PY,BO,EC,GT,HN,SV,NI,CR,PA,DO,CU,PR,NL,NO,PL,PT,SE,RU,TR,TW,HK,MO,AX,AL,DZ,AS,AO,AI,AG,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BE,BZ,BJ,BM,BT,BQ,BA,BW,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CX,CC,KM,CG,CK,CI,CW,CY,CZ,DJ,DM,EG,GQ,ER,EE,ET,FK,FO,FJ,GF,PF,TF,GA,GM,GE,GH,GL,GD,GP,GU,GG,GN,GW,GY,HT,HM,VA,IS,IN,ID,IE,IM,IL,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LI,LT,LU,MK,MG,MW,MV,ML,MT,MH,MQ,MR,MU,YT,FM,MD,MC,MN,ME,MS,MA,MZ,NA,NR,NP,NC,NZ,NE,NG,NU,NF,MP,OM,PK,PW,PS,PG,PH,PN,QA,RE,RO,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SX,SK,SI,SB,SO,ZA,GS,KR,LK,SR,SJ,SZ,TH,TL,TG,TK,TO,TT,TN,TM,TC,TV,UG,UA,AE,UZ,VU,VN,VG,VI,WF,EH,ZM", currency = "AUD,CAD,CHF,CNY,CZK,DKK,EUR,GBP,INR,JPY,NOK,NZD,PLN,RUB,SEK,ZAR,USD,EGP,UYU,UZS" } [pm_filters.volt] open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" } [pm_filters.trustpay] instant_bank_transfer = { country = "CZ,SK,GB,AT,DE,IT", currency = "CZK, EUR, GBP" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,GB", currency = "EUR" } [pm_filters.razorpay] upi_collect = { country = "IN", currency = "INR" } [pm_filters.adyen] boleto = { country = "BR", currency = "BRL" } sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" } paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" } ideal = { country = "NL", currency = "EUR" } [pm_filters.bambora] credit = { country = "US,CA", currency = "USD" } debit = { country = "US,CA", currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } debit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU,AU,BR,US", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } [pm_filters.square] credit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } debit = { country = "AU,CA,FR,IE,JP,ES,GB,US", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLE,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } [pm_filters.iatapay] upi_collect = { country = "IN", currency = "INR" } upi_intent = { country = "IN", currency = "INR" } ideal = { country = "NL", currency = "EUR" } local_bank_redirect = { country = "AT,BE,EE,FI,FR,DE,IE,IT,LV,LT,LU,NL,PT,ES,GB,IN,HK,SG,TH,BR,MX,GH,VN,MY,PH,JO,AU,CO", currency = "EUR,GBP,INR,HKD,SGD,THB,BRL,MXN,GHS,VND,MYR,PHP,JOD,AUD,COP" } duit_now = { country = "MY", currency = "MYR" } fps = { country = "GB", currency = "GBP" } prompt_pay = { country = "TH", currency = "THB" } viet_qr = { country = "VN", currency = "VND" } [pm_filters.coinbase] crypto_currency = { country = "ZA,US,BR,CA,TR,SG,VN,GB,DE,FR,ES,PT,IT,NL,AU" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } debit = { not_available_flows = { capture_method = "manual" } } boleto = { country = "BR", currency = "BRL" } efecty = { country = "CO", currency = "COP" } multibanco = { country = "PT", currency = "EUR" } pago_efectivo = { country = "PE", currency = "PEN" } pse = { country = "CO", currency = "COP" } pix = { country = "BR", currency = "BRL" } red_compra = { country = "CL", currency = "CLP" } red_pagos = { country = "UY", currency = "UYU" } [pm_filters.globalpay] credit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } debit = { country = "AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BQ,BA,BW,BV,BR,IO,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CW,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,SZ,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,VA,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,NC,NZ,NI,NE,NG,NU,NF,MP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,PR,QA,RE,RO,RU,RW,BL,SH,KN,LC,MF,PM,VC,WS,SM,ST,SA,SN,RS,SC,SL,SG,SX,SK,SI,SB,SO,ZA,GS,SS,ES,LK,SD,SR,SJ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UM,UY,UZ,VU,VE,VN,VG,VI,WF,EH,YE,ZM,ZW", currency = "AFN,DZD,ARS,AMD,AWG,AUD,AZN,BSD,BHD,THB,PAB,BBD,BYN,BZD,BMD,BOB,BRL,BND,BGN,BIF,CVE,CAD,CLP,COP,KMF,CDF,NIO,CRC,CUP,CZK,GMD,DKK,MKD,DJF,DOP,VND,XCD,EGP,SVC,ETB,EUR,FKP,FJD,HUF,GHS,GIP,HTG,PYG,GNF,GYD,HKD,UAH,ISK,INR,IRR,IQD,JMD,JOD,KES,PGK,HRK,KWD,AOA,MMK,LAK,GEL,LBP,ALL,HNL,SLL,LRD,LYD,SZL,LSL,MGA,MWK,MYR,MUR,MXN,MDL,MAD,MZN,NGN,ERN,NAD,NPR,ANG,ILS,TWD,NZD,BTN,KPW,NOK,TOP,PKR,MOP,UYU,PHP,GBP,BWP,QAR,GTQ,ZAR,OMR,KHR,RON,MVR,IDR,RUB,RWF,SHP,SAR,RSD,SCR,SGD,PEN,SBD,KGS,SOS,TJS,SSP,LKR,SDG,SRD,SEK,CHF,SYP,BDT,WST,TZS,KZT,TTD,MNT,TND,TRY,TMT,AED,UGX,USD,UZS,VUV,KRW,YER,JPY,CNY,ZMW,ZWL,PLN,CLF,STD,CUC" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } sofort = { country = "AT,BE,DE,ES,IT,NL", currency = "EUR" } [pm_filters.rapyd] apple_pay = { country = "AL,AS,AD,AR,AM,AU,AT,AZ,BH,BE,BM,BA,BR,BG,CA,KH,KY,CL,CO,CR,HR,CY,CZ,DK,DO,EC,SV,EE,FO,FI,FR,GE,DE,GI,GR,GL,GU,GT,GG,HN,HK,HU,IS,IE,IM,IL,IT,JP,KZ,KG,KW,LV,LI,LT,LU,MO,MY,MT,MX,MD,MC,ME,MA,NL,NZ,NI,MK,MP,NO,PA,PY,PR,PE,PL,PT,QA,RO,SM,RS,SG,SK,SI,ZA,ES,SE,CH,TW,TJ,TH,UA,AE,GB,US,UY,VI,VN", currency = "EUR,GBP,ISK,USD" } google_pay = { country = "AM,AT,AU,AZ,BA,BE,BG,BY,CA,CH,CL,CN,CO,CR,CY,CZ,DE,DK,DO,EC,EE,EG,ES,FI,FR,GB,GE,GL,GR,GT,HK,HN,HR,HU,IE,IL,IM,IS,IT,JE,JP,JO,KZ,KW,LA,LI,LT,LU,LV,MA,MC,MD,ME,MO,MN,MT,MX,MY,NC,NL,NO,NZ,OM,PA,PE,PL,PR,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,SV,TH,TW,UA,US,UY,VA,VN,ZA", currency = "EUR,GBP,ISK,USD" } credit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" } debit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" } [pm_filters.bamboraapac] credit = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CV,CY,CZ,DE,DK,DJ,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FM,FR,GA,GB,GD,GE,GG,GH,GM,GN,GQ,GR,GT,GW,GY,HN,HR,HT,HU,ID,IE,IL,IN,IS,IT,JM,JP,JO,KE,KG,KH,KI,KM,KN,KR,KW,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MR,MT,MU,MV,MW,MX,MY,MZ,NA,NE,NG,NI,NL,NO,NP,NR,NZ,OM,PA,PE,PG,PH,PK,PL,PS,PT,PW,PY,QA,RO,RS,RW,SA,SB,SC,SE,SG,SI,SK,SL,SM,SN,SO,SR,SS,ST,SV,SZ,TD,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VN,VU,WS,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" } debit = { country = "AD,AE,AG,AL,AM,AO,AR,AT,AU,AZ,BA,BB,BD,BE,BG,BH,BI,BJ,BN,BO,BR,BS,BT,BW,BY,BZ,CA,CD,CF,CG,CH,CI,CL,CM,CN,CO,CR,CV,CY,CZ,DE,DK,DJ,DM,DO,DZ,EC,EE,EG,ER,ES,ET,FI,FJ,FM,FR,GA,GB,GD,GE,GG,GH,GM,GN,GQ,GR,GT,GW,GY,HN,HR,HT,HU,ID,IE,IL,IN,IS,IT,JM,JP,JO,KE,KG,KH,KI,KM,KN,KR,KW,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,MA,MC,MD,ME,MG,MH,MK,ML,MM,MN,MR,MT,MU,MV,MW,MX,MY,MZ,NA,NE,NG,NI,NL,NO,NP,NR,NZ,OM,PA,PE,PG,PH,PK,PL,PS,PT,PW,PY,QA,RO,RS,RW,SA,SB,SC,SE,SG,SI,SK,SL,SM,SN,SO,SR,SS,ST,SV,SZ,TD,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TZ,UA,UG,US,UY,UZ,VA,VC,VE,VN,VU,WS,ZA,ZM,ZW", currency = "AED,AUD,BDT,BGN,BND,BOB,BRL,BWP,CAD,CHF,CNY,COP,CZK,DKK,EGP,EUR,FJD,GBP,GEL,GHS,HKD,HRK,HUF,IDR,ILS,INR,IQD,IRR,ISK,JPY,KES,KRW,KWD,KZT,LAK,LKR,MAD,MDL,MMK,MOP,MXN,MYR,MZN,NAD,NGN,NOK,NPR,NZD,PEN,PHP,PKR,PLN,QAR,RON,RSD,RUB,RWF,SAR,SCR,SEK,SGD,SLL,THB,TRY,TWD,TZS,UAH,UGX,USD,UYU,VND,XAF,XOF,ZAR,ZMW,MWK" } [pm_filters.gocardless] ach = { country = "US", currency = "USD" } becs = { country = "AU", currency = "AUD" } sepa = { country = "AU,AT,BE,BG,CA,HR,CY,CZ,DK,FI,FR,DE,HU,IT,LU,MT,NL,NZ,NO,PL,PT,IE,RO,SK,SI,ZA,ES,SE,CH,GB", currency = "GBP,EUR,SEK,DKK,AUD,NZD,CAD" } [pm_filters.powertranz] credit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "BBD,BMD,BSD,CRC,GTQ,HNL,JMD,KYD,TTD,USD" } debit = { country = "AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "BBD,BMD,BSD,CRC,GTQ,HNL,JMD,KYD,TTD,USD" } [pm_filters.worldline] giropay = { country = "DE", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } [pm_filters.shift4] eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE", currency = "CHF,EUR" } credit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } debit = { country = "AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW", currency = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTN,BWP,BYN,BZD,CAD,CDF,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ERN,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK,HTG,HUF,IDR,ILS,INR,IQD,IRR,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK,SGD,SHP,SLL,SOS,SRD,SSP,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW,ZWL" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } mollie = { long_lived_token = false, payment_method = "card" } braintree = { long_lived_token = false, payment_method = "card" } gocardless = { long_lived_token = true, payment_method = "bank_debit" } billwerk = { long_lived_token = false, payment_method = "card" } [connector_customer] connector_list = "gocardless,stax,stripe" payout_connector_list = "nomupay,wise" [dummy_connector] enabled = true payment_ttl = 172800 payment_duration = 1000 payment_tolerance = 100 payment_retrieve_duration = 500 payment_retrieve_tolerance = 100 payment_complete_duration = 500 payment_complete_tolerance = 100 refund_ttl = 172800 refund_duration = 1000 refund_tolerance = 100 refund_retrieve_duration = 500 refund_retrieve_tolerance = 100 authorize_ttl = 36000 assets_base_url = "https://app.hyperswitch.io/assets/TestProcessor/" default_return_url = "https://app.hyperswitch.io/" slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg" discord_invite_url = "https://discord.gg/wJZ7DVW8mm" [payouts] payout_eligibility = true [mandates.supported_payment_methods] bank_debit.ach = { connector_list = "gocardless,adyen,stripe" } bank_debit.becs = { connector_list = "gocardless,stripe,adyen" } bank_debit.bacs = { connector_list = "stripe,gocardless" } bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" } card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal,xendit" pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet" wallet.samsung_pay.connector_list = "cybersource" wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet" wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal" wallet.momo.connector_list = "adyen" wallet.kakao_pay.connector_list = "adyen" wallet.go_pay.connector_list = "adyen" wallet.gcash.connector_list = "adyen" wallet.dana.connector_list = "adyen" wallet.twint.connector_list = "adyen" wallet.vipps.connector_list = "adyen" bank_redirect.ideal.connector_list = "stripe,adyen,globalpay,multisafepay,nexinets" bank_redirect.sofort.connector_list = "stripe,globalpay" bank_redirect.giropay.connector_list = "globalpay,multisafepay,nexinets" bank_redirect.bancontact_card.connector_list = "adyen,stripe" bank_redirect.trustly.connector_list = "adyen" bank_redirect.open_banking_uk.connector_list = "adyen" bank_redirect.eps.connector_list = "globalpay,nexinets" [cors] max_age = 30 origins = "http://localhost:8080" allowed_methods = "GET,POST,PUT,DELETE" wildcard_origin = false [mandates.update_mandate_supported] card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } [network_transaction_id_supported_connectors] connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [analytics] source = "sqlx" [analytics.sqlx] username = "db_user" password = "db_pass" host = "localhost" port = 5432 dbname = "hyperswitch_db" pool_size = 5 connection_timeout = 10 [kv_config] ttl = 300 # 5 * 60 seconds [frm] enabled = true [connector_onboarding.paypal] client_id = "" client_secret = "" partner_id = "" [unmasked_headers] keys = "accept-language,user-agent,x-profile-id" [multitenancy] enabled = false global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "" } [multitenancy.tenants.public] base_url = "http://localhost:8080" schema = "public" accounts_schema = "public" redis_key_prefix = "" clickhouse_database = "default" [multitenancy.tenants.public.user] control_center_url = "http://localhost:9000" [email] sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 active_email_client = "NO_EMAIL_CLIENT" recon_recipient_email = "recon@example.com" prod_intent_recipient_email = "business@example.com" [email.aws_ses] email_role_arn = "" sts_role_session_name = "" [temp_locker_enable_config] paybox = { payment_method = "card" } redsys = { payment_method = "card" } [billing_connectors_payment_sync] billing_connectors_which_require_payment_sync = "stripebilling, recurly"
17,119
756
hyperswitch
loadtest/config/otel-collector.yaml
.yaml
receivers: otlp: protocols: grpc: exporters: otlp: endpoint: tempo:4317 tls: insecure: true service: pipelines: traces: receivers: [otlp] exporters: [otlp]
62
757
hyperswitch
loadtest/config/tempo.yaml
.yaml
server: http_listen_port: 3200 distributor: receivers: otlp: protocols: grpc: ingester: trace_idle_period: 10s # the length of time after a trace has not received spans to consider it complete and flush it max_block_bytes: 1_000_000 # cut the head block when it hits this size or ... max_block_duration: 5m # this much time passes compactor: compaction: compaction_window: 1h # blocks in this time window will be compacted together max_block_bytes: 100_000_000 # maximum size of compacted blocks block_retention: 1h compacted_block_retention: 10m storage: trace: backend: local # backend configuration to use block: bloom_filter_false_positive: .05 # bloom filter false positive rate. lower values create larger filters but fewer false positives index_downsample_bytes: 1000 # number of bytes per index record encoding: zstd # block encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2 wal: path: /tmp/tempo/wal # where to store the wal locally encoding: snappy # wal encoding/compression. options: none, gzip, lz4-64k, lz4-256k, lz4-1M, lz4, snappy, zstd, s2 local: path: /tmp/tempo/blocks pool: max_workers: 100 # worker pool determines the number of parallel requests to the object store backend queue_depth: 10000 search_enabled: true
429
758
hyperswitch
loadtest/grafana/grafana-dashboard.yaml
.yaml
apiVersion: 1 providers: - name: 'default' org_id: 1 folder: '' type: 'file' options: path: /var/lib/grafana/dashboards
47
759
hyperswitch
loadtest/grafana/grafana-datasource.yaml
.yaml
apiVersion: 1 datasources: - name: K6InfluxDB type: influxdb access: proxy database: scripts url: http://influxdb:8086 isDefault: false - name: Tempo type: tempo access: proxy url: http://tempo:3200 isDefault: true editable: true
95
760
hyperswitch
loadtest/grafana/dashboards/k6-load-testing-results_rev3.json
.json
{ "__inputs": [ { "name": "DS_K6", "label": "k6", "description": "", "type": "datasource", "pluginId": "influxdb", "pluginName": "InfluxDB" } ], "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "4.4.1" }, { "type": "panel", "id": "graph", "name": "Graph", "version": "" }, { "type": "panel", "id": "heatmap", "name": "Heatmap", "version": "" }, { "type": "datasource", "id": "influxdb", "name": "InfluxDB", "version": "1.0.0" }, { "type": "panel", "id": "singlestat", "name": "Singlestat", "version": "" } ], "annotations": { "list": [] }, "description": "A dashboard for visualizing results from the k6.io load testing tool, using the InfluxDB exporter", "editable": true, "gnetId": 2587, "graphTooltip": 2, "hideControls": false, "id": null, "uid": "k6", "links": [], "refresh": "5s", "rows": [ { "collapse": false, "height": "250px", "panels": [ { "aliasColors": {}, "bars": true, "dashLength": 10, "dashes": false, "datasource": "K6InfluxDB", "fill": 1, "id": 1, "interval": ">1s", "legend": { "alignAsTable": true, "avg": false, "current": false, "max": true, "min": true, "show": true, "total": false, "values": true }, "lines": false, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "span": 3, "stack": false, "steppedLine": false, "targets": [ { "alias": "Active VUs", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "vus", "orderByTime": "ASC", "policy": "default", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": [], "timeFrom": null, "timeShift": null, "title": "Virtual Users", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ] }, { "aliasColors": {}, "bars": true, "dashLength": 10, "dashes": false, "datasource": "K6InfluxDB", "fill": 1, "id": 17, "interval": "1s", "legend": { "alignAsTable": true, "avg": true, "current": false, "max": true, "min": false, "rightSide": false, "show": true, "total": false, "values": true }, "lines": false, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "span": 3, "stack": false, "steppedLine": false, "targets": [ { "alias": "Requests per Second", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "measurement": "http_reqs", "orderByTime": "ASC", "policy": "default", "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "sum" } ] ], "tags": [] } ], "thresholds": [], "timeFrom": null, "timeShift": null, "title": "Requests per Second", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ] }, { "aliasColors": {}, "bars": true, "dashLength": 10, "dashes": false, "datasource": "K6InfluxDB", "fill": 1, "id": 7, "interval": "1s", "legend": { "alignAsTable": true, "avg": true, "current": false, "max": false, "min": false, "show": true, "total": true, "values": true }, "lines": false, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [ { "alias": "Num Errors", "color": "#BF1B00" } ], "spaceLength": 10, "span": 3, "stack": true, "steppedLine": false, "targets": [ { "alias": "Num Errors", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "errors", "orderByTime": "ASC", "policy": "default", "refId": "C", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "count" } ] ], "tags": [] } ], "thresholds": [], "timeFrom": null, "timeShift": null, "title": "Errors Per Second", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ] }, { "aliasColors": {}, "bars": true, "dashLength": 10, "dashes": false, "datasource": "K6InfluxDB", "fill": 1, "id": 10, "interval": ">1s", "legend": { "alignAsTable": true, "avg": true, "current": false, "max": false, "min": false, "show": true, "total": true, "values": true }, "lines": false, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [ { "alias": "Num Errors", "color": "#BF1B00" } ], "spaceLength": 10, "span": 3, "stack": true, "steppedLine": false, "targets": [ { "alias": "$tag_check", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "check" ], "type": "tag" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "checks", "orderByTime": "ASC", "policy": "default", "refId": "C", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "sum" } ] ], "tags": [] } ], "thresholds": [], "timeFrom": null, "timeShift": null, "title": "Checks Per Second", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "none", "label": null, "logBase": 1, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ] } ], "repeat": null, "repeatIteration": null, "repeatRowId": null, "showTitle": false, "title": "Dashboard Row", "titleSize": "h6" }, { "collapse": false, "height": "", "panels": [ { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 11, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT mean(\"value\") FROM $Measurement WHERE $timeFilter ", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (mean)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "avg" }, { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 14, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT max(\"value\") FROM $Measurement WHERE $timeFilter", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (max)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "avg" }, { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 15, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT median(\"value\") FROM $Measurement WHERE $timeFilter", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (med)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "avg" }, { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 16, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT min(\"value\") FROM $Measurement WHERE $timeFilter and value > 0", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (min)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "current" }, { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 12, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT percentile(\"value\", 90) FROM $Measurement WHERE $timeFilter", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (p90)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "avg" }, { "cacheTimeout": null, "colorBackground": false, "colorValue": false, "colors": [ "rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)" ], "datasource": "K6InfluxDB", "decimals": 2, "format": "ms", "gauge": { "maxValue": 100, "minValue": 0, "show": false, "thresholdLabels": false, "thresholdMarkers": true }, "height": "50px", "id": 13, "interval": null, "links": [], "mappingType": 1, "mappingTypes": [ { "name": "value to text", "value": 1 }, { "name": "range to text", "value": 2 } ], "maxDataPoints": 100, "nullPointMode": "connected", "nullText": null, "postfix": "", "postfixFontSize": "50%", "prefix": "", "prefixFontSize": "50%", "rangeMaps": [ { "from": "null", "text": "N/A", "to": "null" } ], "span": 2, "sparkline": { "fillColor": "rgba(31, 118, 189, 0.18)", "full": false, "lineColor": "rgb(31, 120, 193)", "show": false }, "tableColumn": "", "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "orderByTime": "ASC", "policy": "default", "query": "SELECT percentile(\"value\", 95) FROM $Measurement WHERE $timeFilter ", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "thresholds": "", "title": "$Measurement (p95)", "type": "singlestat", "valueFontSize": "80%", "valueMaps": [ { "op": "=", "text": "N/A", "value": "null" } ], "valueName": "avg" }, { "aliasColors": {}, "bars": false, "dashLength": 10, "dashes": false, "datasource": "K6InfluxDB", "description": "Grouped by 1 sec intervals", "fill": 1, "height": "250px", "id": 5, "interval": ">1s", "legend": { "alignAsTable": false, "avg": false, "current": false, "max": false, "min": false, "show": true, "total": false, "values": false }, "lines": true, "linewidth": 1, "links": [], "nullPointMode": "null", "percentage": false, "pointradius": 5, "points": false, "renderer": "flot", "seriesOverrides": [], "spaceLength": 10, "span": 6, "stack": false, "steppedLine": false, "targets": [ { "alias": "max", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "/^$Measurement$/", "orderByTime": "ASC", "policy": "default", "query": "SELECT max(\"value\") FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)", "rawQuery": true, "refId": "C", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "max" } ] ], "tags": [] }, { "alias": "p95", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "/^$Measurement$/", "orderByTime": "ASC", "policy": "default", "query": "SELECT percentile(\"value\", 95) FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)", "rawQuery": true, "refId": "D", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [ 95 ], "type": "percentile" } ] ], "tags": [] }, { "alias": "p90", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "/^$Measurement$/", "orderByTime": "ASC", "policy": "default", "query": "SELECT percentile(\"value\", 90) FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [ "90" ], "type": "percentile" } ] ], "tags": [] }, { "alias": "min", "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "none" ], "type": "fill" } ], "measurement": "/^$Measurement$/", "orderByTime": "ASC", "policy": "default", "query": "SELECT min(\"value\") FROM /^$Measurement$/ WHERE $timeFilter and value > 0 GROUP BY time($__interval) fill(none)", "rawQuery": true, "refId": "E", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "min" } ] ], "tags": [] } ], "thresholds": [], "timeFrom": null, "timeShift": null, "title": "$Measurement (over time)", "tooltip": { "shared": true, "sort": 0, "value_type": "individual" }, "type": "graph", "xaxis": { "buckets": null, "mode": "time", "name": null, "show": true, "values": [] }, "yaxes": [ { "format": "ms", "label": null, "logBase": 2, "max": null, "min": null, "show": true }, { "format": "short", "label": null, "logBase": 1, "max": null, "min": null, "show": true } ] }, { "cards": { "cardPadding": null, "cardRound": null }, "color": { "cardColor": "rgb(0, 234, 255)", "colorScale": "sqrt", "colorScheme": "interpolateRdYlGn", "exponent": 0.5, "mode": "spectrum" }, "dataFormat": "timeseries", "datasource": "K6InfluxDB", "heatmap": {}, "height": "250px", "highlightCards": true, "id": 8, "interval": ">1s", "links": [], "span": 6, "targets": [ { "dsType": "influxdb", "groupBy": [ { "params": [ "$__interval" ], "type": "time" }, { "params": [ "null" ], "type": "fill" } ], "measurement": "http_req_duration", "orderByTime": "ASC", "policy": "default", "query": "SELECT \"value\" FROM $Measurement WHERE $timeFilter and value > 0", "rawQuery": true, "refId": "A", "resultFormat": "time_series", "select": [ [ { "params": [ "value" ], "type": "field" }, { "params": [], "type": "mean" } ] ], "tags": [] } ], "title": "$Measurement (over time)", "tooltip": { "show": true, "showHistogram": true }, "tooltipDecimals": null, "type": "heatmap", "xAxis": { "show": true }, "xBucketNumber": null, "xBucketSize": null, "yAxis": { "decimals": null, "format": "ms", "logBase": 2, "max": null, "min": null, "show": true, "splitFactor": null }, "yBucketNumber": null, "yBucketSize": null } ], "repeat": "Measurement", "repeatIteration": null, "repeatRowId": null, "showTitle": true, "title": "$Measurement", "titleSize": "h6" }, { "collapse": false, "height": 250, "panels": [], "repeat": null, "repeatIteration": null, "repeatRowId": null, "showTitle": false, "title": "Dashboard Row", "titleSize": "h6" } ], "schemaVersion": 14, "style": "dark", "tags": [], "templating": { "list": [ { "allValue": null, "current": { "selected": true, "tags": [], "text": "http_req_duration", "value": [ "http_req_duration" ] }, "hide": 0, "includeAll": true, "label": null, "multi": true, "name": "Measurement", "options": [ { "selected": false, "text": "All", "value": "$__all" }, { "selected": true, "text": "http_req_duration", "value": "http_req_duration" }, { "selected": false, "text": "http_req_blocked", "value": "http_req_blocked" }, { "selected": false, "text": "http_req_connecting", "value": "http_req_connecting" }, { "selected": false, "text": "http_req_looking_up", "value": "http_req_looking_up" }, { "selected": false, "text": "http_req_receiving", "value": "http_req_receiving" }, { "selected": false, "text": "http_req_sending", "value": "http_req_sending" }, { "selected": false, "text": "http_req_waiting", "value": "http_req_waiting" } ], "query": "http_req_duration,http_req_blocked,http_req_connecting,http_req_looking_up,http_req_receiving,http_req_sending,http_req_waiting", "type": "custom" } ] }, "time": { "from": "now-3m", "to": "now" }, "timepicker": { "refresh_intervals": [ "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d" ], "time_options": [ "5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d" ] }, "timezone": "browser", "title": "k6 Load Testing Results", "version": 22 }
9,505
761
hyperswitch
docs/try_local_system.md
.md
# Try out hyperswitch on your system The simplest way to run hyperswitch locally is [with Docker Compose](#run-hyperswitch-using-docker-compose) by pulling the latest images from Docker Hub. However, if you're willing to modify the code and run it, or are a developer contributing to hyperswitch, then you can either [set up a development environment using Docker Compose](#set-up-a-development-environment-using-docker-compose), or [set up a Rust environment on your system](#set-up-a-rust-environment-and-other-dependencies). Check the Table Of Contents to jump to the relevant section. **Table Of Contents:** - [Run hyperswitch using Docker Compose](#run-hyperswitch-using-docker-compose) - [Running additional services](#running-additional-services) - [Set up a development environment using Docker Compose](#set-up-a-development-environment-using-docker-compose) - [Set up a Nix development environment](#set-up-a-nix-development-environment) - [Install Nix](#install-nix) - [Using external services through Nix](#using-external-services-through-nix) - [Develop in a Nix environment (coming soon)](#develop-in-a-nix-environment-coming-soon) - [Set up a Rust environment and other dependencies](#set-up-a-rust-environment-and-other-dependencies) - [Set up dependencies on Ubuntu-based systems](#set-up-dependencies-on-ubuntu-based-systems) - [Set up dependencies on Windows (Ubuntu on WSL2)](#set-up-dependencies-on-windows-ubuntu-on-wsl2) - [Set up dependencies on Windows](#set-up-dependencies-on-windows) - [Set up dependencies on MacOS](#set-up-dependencies-on-macos) - [Set up the database](#set-up-the-database) - [Configure the application](#configure-the-application) - [Run the application](#run-the-application) - [Try out our APIs](#try-out-our-apis) - [Set up your merchant account](#set-up-your-merchant-account) - [Create an API key](#create-an-api-key) - [Set up a payment connector account](#set-up-a-payment-connector-account) - [Create a Payment](#create-a-payment) - [Create a Refund](#create-a-refund) ## Run hyperswitch using Docker Compose 1. Install [Docker Compose][docker-compose-install] or [Podman Compose][podman-compose-install]. 2. Clone the repository and switch to the project directory: ```shell git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch ``` 3. (Optional) Configure the application using the [`config/docker_compose.toml`][docker-compose-config] file. The provided configuration should work as is. If you do update the `docker_compose.toml` file, ensure to also update the corresponding values in the [`docker-compose.yml`][docker-compose-yml] file. 4. Start all the services using below script: ```shell scripts/setup.sh ``` You will get prompts to select your preferred setup option. [docker-compose-install]: https://docs.docker.com/compose/install/ [podman-compose-install]: https://podman.io/docs/installation [docker-compose-config]: /config/docker_compose.toml [docker-compose-yml]: /docker-compose.yml [architecture]: /docs/architecture.md [data-docs]: /crates/analytics/docs/README.md ## Set up a development environment using Docker Compose 1. Install [Docker Compose][docker-compose-install]. 2. Clone the repository and switch to the project directory: ```shell git clone https://github.com/juspay/hyperswitch cd hyperswitch ``` 3. (Optional) Configure the application using the [`config/docker_compose.toml`][docker-compose-config] file. The provided configuration should work as is. If you do update the `docker_compose.toml` file, ensure to also update the corresponding values in the [`docker-compose.yml`][docker-compose-yml] file. 4. Start all the services using Docker Compose: ```shell docker compose --file docker-compose-development.yml up -d ``` This will compile the payments router, the primary component within hyperswitch and then start it. Depending on the specifications of your machine, **compilation can take around 30 minutes**. 5. (Optional) You can also choose to [start the scheduler and/or monitoring services](#running-additional-services) in addition to the payments router. 6. Verify that the server is up and running by hitting the health endpoint: ```shell curl --head --request GET 'http://localhost:8080/health' ``` If the command returned a `200 OK` status code, proceed with [trying out our APIs](#try-out-our-apis). ## Set up a Nix development environment A Nix development environment simplifies the setup of required project dependencies. This is available for MacOS, Linux and WSL2 users. ### Install nix We recommend that you install Nix using [the DetSys nix-installer][detsys-nixos-installer], which automatically enables flakes. As an **optional** next step, if you are interested in using Nix to manage your dotfiles and local packages, you can setup [nixos-unified-template][nixos-unified-template-repo]. ### Using external services through Nix Once Nix is installed, you can use it to manage external services via `flakes`. More services will be added soon. - Run below command in hyperswitch directory ```shell nix run .#ext-services ``` This will start the following services using `process-compose` - PostgreSQL - Creates database and an user to be used by the application - Redis ### Develop in a Nix environment (coming soon) Nix development environment ensures all the required project dependencies, including both the tools and services are readily available, eliminating the need for manual setup. Run below command in hyperswitch directory ```shell nix develop ``` **NOTE:** This is a work in progress, and only a selected commands are available at the moment. Look in `flake.nix` (hyperswitch-shell) for a full list of packages. ## Set up a Rust environment and other dependencies If you are using `nix`, please skip the setup dependencies step and jump to [Set up the database](#set-up-the-database). ### Set up dependencies on Ubuntu-based systems This section of the guide provides instructions to install dependencies on Ubuntu-based systems. If you're running another Linux distribution, install the corresponding packages for your distribution and follow along. 1. Install the stable Rust toolchain using `rustup`: ```shell curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` When prompted, proceed with the `default` profile, which installs the stable toolchain. Optionally, verify that the Rust compiler and `cargo` are successfully installed: ```shell rustc --version ``` _Be careful when running shell scripts downloaded from the Internet. We only suggest running this script as there seems to be no `rustup` package available in the Ubuntu package repository._ 2. Install PostgreSQL and start the `postgresql` systemd service: ```shell sudo apt update sudo apt install postgresql postgresql-contrib libpq-dev systemctl start postgresql.service ``` If you're running any other distribution than Ubuntu, you can follow the installation instructions on the [PostgreSQL documentation website][postgresql-install] to set up PostgreSQL on your system. 3. Install Redis and start the `redis` systemd service: ```shell sudo apt install redis-server systemctl start redis.service ``` If you're running a distribution other than Ubuntu, you can follow the installation instructions on the [Redis website][redis-install] to set up Redis on your system. 4. Install `diesel_cli` using `cargo`: ```shell cargo install diesel_cli --no-default-features --features postgres ``` 5. Make sure your system has the `pkg-config` package and OpenSSL installed ```shell sudo apt install pkg-config libssl-dev ``` Once you're done with setting up the dependencies, proceed with [setting up the database](#set-up-the-database). [postgresql-install]: https://www.postgresql.org/download/ [redis-install]: https://redis.io/docs/getting-started/installation/ [wsl-config]: https://learn.microsoft.com/en-us/windows/wsl/wsl-config/ ### Set up dependencies on Windows (Ubuntu on WSL2) This section of the guide provides instructions to install dependencies on Ubuntu on WSL2. If you prefer running another Linux distribution, install the corresponding packages for your distribution and follow along. 1. Install Ubuntu on WSL: ```shell wsl --install -d Ubuntu ``` Refer to the [official installation docs][wsl-install] for more information. Launch the WSL instance and set up your username and password. The following steps assume that you are running the commands within the WSL shell environment. > Note that a `SIGKILL` error may occur when compiling certain crates if WSL is unable to use sufficient memory. It may be necessary to allow up to 24GB of memory, but your mileage may vary. You may increase the amount of memory WSL can use via a `.wslconfig` file in your Windows user folder, or by creating a swap file in WSL itself. Refer to the [WSL configuration documentation][wsl-config] for more information. 2. Install the stable Rust toolchain using `rustup`: ```shell curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` When prompted, proceed with the `default` profile, which installs the stable toolchain. Optionally, verify that the Rust compiler and `cargo` are successfully installed: ```shell rustc --version ``` _Be careful when running shell scripts downloaded from the Internet. We only suggest running this script as there seems to be no `rustup` package available in the Ubuntu package repository._ 3. Install PostgreSQL and start the `postgresql` service: ```shell sudo apt update sudo apt install postgresql postgresql-contrib libpq-dev sudo service postgresql start ``` For more information, refer to the docs for [installing PostgreSQL on WSL][postgresql-install-wsl]. If you're running any other distribution than Ubuntu, you can follow the installation instructions on the [PostgreSQL documentation website][postgresql-install] to set up PostgreSQL on your system. 4. Install Redis and start the `redis-server` service: ```shell sudo apt install redis-server sudo service redis-server start ``` For more information, refer to the docs for [installing Redis on WSL][redis-install-wsl]. If you're running a distribution other than Ubuntu, you can follow the installation instructions on the [Redis website][redis-install] to set up Redis on your system. 5. Make sure your system has the packages necessary for compiling Rust code: ```shell sudo apt install build-essential ``` 6. Install `diesel_cli` using `cargo`: ```shell cargo install diesel_cli --no-default-features --features postgres ``` 7. Make sure your system has the `pkg-config` package and OpenSSL installed: ```shell sudo apt install pkg-config libssl-dev ``` Once you're done with setting up the dependencies, proceed with [setting up the database](#set-up-the-database). [wsl-install]: https://learn.microsoft.com/en-us/windows/wsl/install [postgresql-install-wsl]: https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-database#install-postgresql [redis-install-wsl]: https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-database#install-redis ### Set up dependencies on Windows We'll be using [`winget`][winget] in this section of the guide, where possible. You can opt to use your favorite package manager instead. 1. Install PostgreSQL database, following the [official installation docs][postgresql-install-windows]. 2. Install Redis, following the [official installation docs][redis-install-windows]. 3. Install rust with `winget`: ```shell winget install -e --id Rustlang.Rust.GNU ``` 4. Install `diesel_cli` using `cargo`: ```shell cargo install diesel_cli --no-default-features --features postgres ``` 5. Install OpenSSL with `winget`: ```shell winget install openssl ``` Once you're done with setting up the dependencies, proceed with [setting up the database](#set-up-the-database). [winget]: https://github.com/microsoft/winget-cli [postgresql-install-windows]: https://www.postgresql.org/download/windows/ [redis-install-windows]: https://redis.io/docs/getting-started/installation/install-redis-on-windows ### Set up dependencies on MacOS We'll be using [Homebrew][homebrew] in this section of the guide. You can opt to use your favorite package manager instead. 1. Install the stable Rust toolchain using `rustup`: ```shell brew install rustup rustup default stable ``` Optionally, verify that the Rust compiler and `cargo` are successfully installed: ```shell rustc --version ``` 2. Install PostgreSQL and start the `postgresql` service: ```shell brew install postgresql@14 brew services start postgresql@14 ``` If a `postgres` database user was not already created, you may have to create one: ```shell createuser -s postgres ``` 3. Install Redis and start the `redis` service: ```shell brew install redis brew services start redis ``` 4. Install `diesel_cli` using `cargo`: ```shell cargo install diesel_cli --no-default-features --features postgres ``` If linking `diesel_cli` fails due to missing `libpq` (if the error message is along the lines of `cannot find -lpq`), you may also have to install `libpq` and reinstall `diesel_cli`: ```shell brew install libpq export PQ_LIB_DIR="$(brew --prefix libpq)/lib" cargo install diesel_cli --no-default-features --features postgres ``` You may also choose to persist the value of `PQ_LIB_DIR` in your shell startup file like so: ```shell echo 'PQ_LIB_DIR="$(brew --prefix libpq)/lib"' >> ~/.zshrc ``` 5. Install a command runner called `just`: In order to make running migrations easier, you can use a command runner called just ```shell cargo install just ``` Once you're done with setting up the dependencies, proceed with [setting up the database](#set-up-the-database). [homebrew]: https://brew.sh/ ### Set up the database 1. Create the database and database users, modifying the database user credentials and database name as required. ```shell export DB_USER="db_user" export DB_PASS="db_pass" export DB_NAME="hyperswitch_db" ``` On Ubuntu-based systems (also applicable for Ubuntu on WSL2): ```shell sudo -u postgres psql -e -c \ "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;" sudo -u postgres psql -e -c \ "CREATE DATABASE $DB_NAME;" ``` On MacOS: ```shell psql -e -U postgres -c \ "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;" psql -e -U postgres -c \ "CREATE DATABASE $DB_NAME" ``` 2. Clone the repository and switch to the project directory: ```shell git clone https://github.com/juspay/hyperswitch cd hyperswitch ``` 3. Run database migrations: Export the `DATABASE_URL` env variable ```shell export DATABASE_URL=postgres://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME ``` Run the migrations - If you have just installed ```shell just migrate ``` - Using the diesel-cli command ```shell diesel migration run ``` Once you're done with setting up the database, proceed with [configuring the application](#configure-the-application). ### Configure the application The application configuration files are present under the [`config`][config-directory] directory. The configuration file read varies with the environment: - Development: [`config/development.toml`][config-development] - Sandbox: `config/sandbox.toml` - Production: `config/production.toml` Refer to [`config.example.toml`][config-example] for all the available configuration options. Refer to [`development.toml`][config-development] for the recommended defaults for local development. Ensure to update the [`development.toml`][config-development] file if you opted to use different database credentials as compared to the sample ones included in this guide. Once you're done with configuring the application, proceed with [running the application](#run-the-application). [config-directory]: /config [config-development]: /config/development.toml [config-example]: /config/config.example.toml [config-docker-compose]: /config/docker_compose.toml ### Run the application 1. Compile and run the application using `cargo`: ```shell cargo run ``` If you are using `nix`, you can compile and run the application using `nix`: ```shell nix run ``` 2. Verify that the server is up and running by hitting the health endpoint: ```shell curl --head --request GET 'http://localhost:8080/health' ``` If the command returned a `200 OK` status code, proceed with [trying out our APIs](#try-out-our-apis). ## Try out our APIs ### Set up your merchant account 1. Sign up or sign in to [Postman][postman]. 2. Open our [Postman collection][postman-collection] and switch to the ["Variables" tab][variables]. Update the value under the "current value" column for the `baseUrl` variable to have the hostname and port of the locally running server (`http://localhost:8080` by default). 3. While on the "Variables" tab, add the admin API key you configured in the application configuration under the "current value" column for the `admin_api_key` variable. 1. If you're running Docker Compose, you can find the configuration file at [`config/docker_compose.toml`][config-docker-compose], search for `admin_api_key` to find the admin API key. 2. If you set up the dependencies locally, you can find the configuration file at [`config/development.toml`][config-development], search for `admin_api_key` to find the admin API key 4. Open the ["Quick Start" folder][quick-start] in the collection. 5. Open the ["Merchant Account - Create"][merchant-account-create] request, switch to the "Body" tab and update any request parameters as required. - If you want to use a different connector for making payments with than the provided default, update the `data` field present in the `routing_algorithm` field to your liking. Click on the "Send" button to create a merchant account (You may need to "create a fork" to fork this collection to your own workspace to send a request). You should obtain a response containing most of the data included in the request, along with some additional fields. Store the merchant ID and publishable key returned in the response. ### Create an API key 1. Open the ["API Key - Create"][api-key-create] request, switch to the "Body" tab and update any request parameters as required. Click on the "Send" button to create an API key. You should obtain a response containing the data included in the request, along with the plaintext API key. Store the API key returned in the response securely. ### Set up a payment connector account 1. Sign up on the payment connector's (say Stripe, Adyen, etc.) dashboard and store your connector API key (and any other necessary secrets) securely. 2. Open the ["Payment Connector - Create"][payment-connector-create] request, switch to the "Body" tab and update any request parameters as required. - Pay special attention to the `connector_name` and `connector_account_details` fields and update them. You can find connector-specific details to be included in this [spreadsheet][connector-specific-details]. - Open the ["Variables" tab][variables] in the [Postman collection][postman-collection] and set the `connector_api_key` variable to your connector's API key. Click on the "Send" button to create a payment connector account. You should obtain a response containing most of the data included in the request, along with some additional fields. 3. Follow the above steps if you'd like to add more payment connector accounts. ### Create a Payment Ensure that you have [set up your merchant account](#set-up-your-merchant-account) and [set up at least one payment connector account](#set-up-a-payment-connector-account) before trying to create a payment. 1. Open the ["Payments - Create"][payments-create] request, switch to the "Body" tab and update any request parameters as required. Click on the "Send" button to create a payment. If all goes well and you had provided the correct connector credentials, the payment should be created successfully. You should see the `status` field of the response body having a value of `succeeded` in this case. - If the `status` of the payment created was `requires_confirmation`, set `confirm` to `true` in the request body and send the request again. 2. Open the ["Payments - Retrieve"][payments-retrieve] request and click on the "Send" button (without modifying anything). This should return the payment object for the payment created in Step 2. ### Create a Refund 1. Open the ["Refunds - Create"][refunds-create] request in the ["Quick Start" folder][quick-start] folder and switch to the "Body" tab. Update the amount to be refunded, if required, and click on the "Send" button. This should create a refund against the last payment made for the specified amount. Check the `status` field of the response body to verify that the refund hasn't failed. 2. Open the ["Refunds - Retrieve"][refunds-retrieve] request and switch to the "Params" tab. Set the `id` path variable in the "Path Variables" table to the `refund_id` value returned in the response during the previous step. This should return the refund object for the refund created in the previous step. That's it! Hope you got a hang of our APIs. To explore more of our APIs, please check the remaining folders in the [Postman collection][postman-collection]. [postman]: https://www.postman.com [postman-collection]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/collection/25176162-630b5353-7002-44d1-8ba1-ead6c230f2e3 [variables]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/collection/25176162-630b5353-7002-44d1-8ba1-ead6c230f2e3?tab=variables [quick-start]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/folder/25176162-0f61a2bb-f9d5-4c60-8b73-9b677bf8ebbc [merchant-account-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-3c5d5282-931b-4adc-a651-f88c8697ebcb [api-key-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-98ce39af-0dbc-4583-8c22-dcaa801851e0 [payment-connector-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-295d83c8-957a-4524-95c8-589a26d751cf [payments-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-ee0549bf-dd38-41fd-9a8a-de74879f3cda [payments-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-8baf2590-d2af-44d0-ba37-e9cab7ef891a [refunds-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-4d1315c6-ac61-4411-8f7d-15d4e4e736a1 [refunds-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-137d6260-24f7-4752-9e69-26b61b83df0d [connector-specific-details]: https://docs.google.com/spreadsheets/d/e/2PACX-1vQWHLza9m5iO4Ol-tEBx22_Nnq8Mb3ISCWI53nrinIGLK8eHYmHGnvXFXUXEut8AFyGyI9DipsYaBLG/pubhtml?gid=748960791&single=true [detsys-nixos-installer]: https://nixos.asia/en/install [nixos-unified-template-repo]: https://github.com/juspay/nixos-unified-template#on-non-nixos
6,078
762
hyperswitch
docs/SECURITY.md
.md
# Security Policy ## Reporting a security issue The hyperswitch project team welcomes security reports and is committed to providing prompt attention to security issues. Security issues should be reported privately via the [advisories page on GitHub][report-vulnerability] or by email at [hyperswitch@juspay.in](mailto:hyperswitch@juspay.in). Security issues should not be reported via the public GitHub Issue tracker. [report-vulnerability]: https://github.com/juspay/hyperswitch/security/advisories/new
116
763
hyperswitch
docs/try_sandbox.md
.md
# Try out hyperswitch sandbox environment **Table Of Contents:** - [Set up your accounts](#set-up-your-accounts) - [Try out our APIs](#try-out-our-apis) - [Create a payment](#create-a-payment) - [Create a refund](#create-a-refund) ## Set up your accounts 1. Sign up on the payment connector's (say Stripe, Adyen, etc.) dashboard and store your connector API key (and any other necessary secrets) securely. 2. Sign up on our [dashboard][dashboard]. 3. Create a merchant account on our dashboard and generate your API keys. Ensure to save the merchant ID, API key and publishable key displayed on the dashboard securely. 4. Configure the merchant return URL and the webhooks URL, which will be used on completion of payments and for sending webhooks, respectively. 5. Create a payments connector account by selecting a payment connector among the options displayed and fill in the connector credentials you obtained in Step 1. 6. Sign up or sign in to [Postman][postman]. 7. Open our [Postman collection][postman-collection] and switch to the ["Variables" tab][variables]. Add the API key received in Step 3 under the "current value" column for the `api_key` variable. ## Try out our APIs ### Create a payment 1. Open the ["Quick Start" folder][quick-start] in the collection. 2. Open the ["Payments - Create"][payments-create] request, switch to the "Body" tab and update any request parameters as required. Click on the "Send" button to create a payment. If all goes well and you had provided the correct connector credentials, the payment should be created successfully. You should see the `status` field of the response body having a value of `succeeded` in this case. - If the `status` of the payment created was `requires_confirmation`, set `confirm` to `true` in the request body and send the request again. 3. Open the ["Payments - Retrieve"][payments-retrieve] request and click on the "Send" button (without modifying anything). This should return the payment object for the payment created in Step 2. ### Create a refund 1. Open the ["Refunds - Create"][refunds-create] request in the ["Quick Start" folder][quick-start] folder and switch to the "Body" tab. Update the amount to be refunded, if required, and click on the "Send" button. This should create a refund against the last payment made for the specified amount. Check the `status` field of the response body to verify that the refund hasn't failed. 2. Open the ["Refunds - Retrieve"][refunds-retrieve] request and switch to the "Params" tab. Set the `id` path variable in the "Path Variables" table to the `refund_id` value returned in the response during the previous step. This should return the refund object for the refund created in the previous step. That's it! Hope you got a hang of our APIs. To explore more of our APIs, please check the remaining folders in the [Postman collection][postman-collection]. [dashboard]: https://app.hyperswitch.io [postman]: https://www.postman.com [postman-collection]: https://www.postman.com/hyperswitch/workspace/hyperswitch/collection/25176183-e36f8e3d-078c-4067-a273-f456b6b724ed [variables]: https://www.postman.com/hyperswitch/workspace/hyperswitch/collection/25176183-e36f8e3d-078c-4067-a273-f456b6b724ed?tab=variables [quick-start]: https://www.postman.com/hyperswitch/workspace/hyperswitch/folder/25176183-0103918c-6611-459b-9faf-354dee8e4437 [payments-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-9b4ad6a8-fbdd-4919-8505-c75c83bdf9d6 [payments-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-11995c9b-8a34-4afd-a6ce-e8645693929b [refunds-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-5b15d068-db9e-48a5-9ee9-3a70c0aac944 [refunds-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch/request/25176183-c50c32af-5ceb-4ab6-aca7-85f6b32df9d3
1,178
764
hyperswitch
docs/CONTRIBUTING.md
.md
# Contributing to hyperswitch :tada: First off, thanks for taking the time to contribute! We are so happy to have you! :tada: There are opportunities to contribute to hyperswitch at any level. It doesn't matter if you are just getting started with Rust or are the most weathered expert, we can use your help. **No contribution is too small and all contributions are valued.** This guide will help you get started. **Do not let this guide intimidate you.** It should be considered a map to help you navigate the process. You can also get help with contributing on our [Discord server][discord], [Slack workspace][slack], or [Discussions][discussions] space. Please join us! [discord]: https://discord.gg/wJZ7DVW8mm [slack]: https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg [discussions]: https://github.com/juspay/hyperswitch/discussions ## Table of Contents - [Code of Conduct](#code-of-conduct) - [What's Included?](#whats-included) - [Repositories](#repositories) - [Files Tree Layout](#files-tree-layout) - [Contributing in Issues](#contributing-in-issues) - [Asking for General Help](#asking-for-general-help) - [Submitting a Bug Report](#submitting-a-bug-report) - [Triaging a Bug Report](#triaging-a-bug-report) - [Resolving a Bug Report](#resolving-a-bug-report) - [Pull Requests](#pull-requests) - [Cargo Commands](#cargo-commands) - [Code Coverage](#code-coverage) - [Commits](#commits) - [Opening the Pull Request](#opening-the-pull-request) - [Discuss and update](#discuss-and-update) - [Commit Squashing](#commit-squashing) - [Reviewing Pull Requests](#reviewing-pull-requests) - [Review a bit at a time](#review-a-bit-at-a-time) - [Be aware of the person behind the code](#be-aware-of-the-person-behind-the-code) - [Abandoned or Stalled Pull Requests](#abandoned-or-stalled-pull-requests) - [Keeping track of issues and PRs](#keeping-track-of-issues-and-prs) - [Area](#area) - [Category](#category) - [Calls for participation](#calls-for-participation) - [Metadata](#metadata) - [Priority](#priority) - [RFCs](#rfcs) - [Status](#status) ## Code of Conduct The hyperswitch project adheres to the [Rust Code of Conduct][coc]. This describes the _minimum_ behavior expected from all contributors. [coc]: https://www.rust-lang.org/policies/code-of-conduct ## What's Included❓ ### Repositories The current setup contains three different repositories, corresponding to the different Hyperswitch components. - [App Server][app-server] - The core payments engine responsible for managing payment flows, payment unification and smart routing. App server is maintained in this repo itself. - [Web Client (SDK)][web-client] - An inclusive, consistent and blended payment experience optimized for the best payment conversions. - [Control center][control-center] - A dashboard for payment analytics and operations, managing payment processors or payment methods and configuring payment routing rules. [app-server]: https://github.com/juspay/hyperswitch [web-client]: https://github.com/juspay/hyperswitch-web [control-center]: https://github.com/juspay/hyperswitch-control-center ### Files Tree Layout Within the repositories, you'll find the following directories and files, logically grouping common assets and providing both compiled and minified variations. <!-- FIXME: this table should either be generated by a script or smoke test should be introduced, checking it agrees with the actual structure --> ```text . ├── config : Initial startup config files for the router ├── connector-template : boilerplate code for connectors ├── crates : sub-crates │ ├── api_models : Request/response models for the `router` crate │ ├── cards : Types to handle card masking and validation │ ├── common_enums : Enums shared across the request/response types and database types │ ├── common_utils : Utilities shared across `router` and other crates │ ├── data_models : Represents the data/domain models used by the business/domain layer │ ├── diesel_models : Database models shared across `router` and other crates │ ├── drainer : Application that reads Redis streams and executes queries in database │ ├── external_services : Interactions with external systems like emails, AWS KMS, etc. │ ├── masking : Personal Identifiable Information protection │ ├── redis_interface : A user-friendly interface to Redis │ ├── router : Main crate of the project │ ├── router_derive : Utility macros for the `router` crate │ ├── router_env : Environment of payment router: logger, basic config, its environment awareness │ ├── scheduler : Scheduling and executing deferred tasks like mail scheduling │ ├── storage_impl : Storage backend implementations for data structures & objects │ └── test_utils : Utilities to run Postman and connector UI tests ├── docs : hand-written documentation ├── loadtest : performance benchmarking setup ├── migrations : diesel DB setup ├── monitoring : Grafana & Loki monitoring related configuration files ├── openapi : automatically generated OpenAPI spec ├── postman : postman scenarios API └── scripts : automation, testing, and other utility scripts ``` ## Contributing in Issues For any issue, there are fundamentally three ways an individual can contribute: 1. By opening the issue for discussion: For instance, if you believe that you have discovered a bug in hyperswitch, creating a new issue in [the juspay/hyperswitch issue tracker][issue] is the way to report it. 2. By helping to triage the issue: This can be done by providing supporting details (a test case that demonstrates a bug), providing suggestions on how to address the issue, or ensuring that the issue is tagged correctly. 3. By helping to resolve the issue: Typically this is done either in the form of demonstrating that the issue reported is not a problem after all, or more often, by opening a Pull Request that changes some bit of something in hyperswitch in a concrete and reviewable manner. [issue]: https://github.com/juspay/hyperswitch/issues **Anybody can participate in any stage of contribution**. We urge you to participate in the discussion around bugs and participate in reviewing PRs. ### Asking for General Help If you have reviewed existing documentation and still have questions or are having problems, you can [open a discussion] asking for help. In exchange for receiving help, we ask that you contribute back a documentation PR that helps others avoid the problems that you encountered. [open a discussion]: https://github.com/juspay/hyperswitch/discussions/new/choose ### Submitting a Bug Report When opening a new issue in the hyperswitch issue tracker, you will be presented with a basic template that should be filled in. If you believe that you have uncovered a bug, please fill out this form, following the template to the best of your ability. Do not worry if you cannot answer every detail, just fill in what you can. The two most important pieces of information we need in order to properly evaluate the report is a description of the behavior you are seeing and a simple test case we can use to recreate the problem on our own. If we cannot recreate the issue, it becomes impossible for us to fix. See [How to create a Minimal, Complete, and Verifiable example][mcve]. [mcve]: https://stackoverflow.com/help/mcve ### Triaging a Bug Report Once an issue has been opened, it is not uncommon for there to be discussion around it. Some contributors may have differing opinions about the issue, including whether the behavior being seen is a bug or a feature. This discussion is part of the process and should be kept focused, helpful, and professional. Short, clipped responses — that provide neither additional context nor supporting detail — are not helpful or professional. To many, such responses are simply annoying and unfriendly. Contributors are encouraged to help one another make forward progress as much as possible, empowering one another to solve issues collaboratively. If you choose to comment on an issue that you feel either is not a problem that needs to be fixed, or if you encounter information in an issue that you feel is incorrect, explain why you feel that way with additional supporting context, and be willing to be convinced that you may be wrong. By doing so, we can often reach the correct outcome much faster. ### Resolving a Bug Report In the majority of cases, issues are resolved by opening a Pull Request. The process for opening and reviewing a Pull Request is similar to that of opening and triaging issues, but carries with it a necessary review and approval workflow that ensures that the proposed changes meet the minimal quality and functional guidelines of the hyperswitch project. ## Pull Requests Pull Requests are the way concrete changes are made to the code, documentation, and dependencies in the hyperswitch repository. Even tiny pull requests (e.g., one character pull request fixing a typo in API documentation) are greatly appreciated. Before making a large change, it is usually a good idea to first open an issue describing the change to solicit feedback and guidance. This will increase the likelihood of the PR getting merged. ### Cargo Commands Due to the extensive use of features in hyperswitch, you will often need to add extra arguments to many common cargo commands. This section lists some commonly needed commands. Some commands just need the `--all-features` argument: ```shell cargo check --all-features cargo clippy --all-features cargo test --all-features ``` The `cargo fmt` command requires the nightly toolchain, as we use a few of the unstable features: ```shell cargo +nightly fmt ``` ### Code Coverage We appreciate well-tested code, so feel free to add tests when you can. To generate code coverage using the cypress tests, follow these steps: 0. Make sure `grcov` and `llvm-tools-preview` are installed ```shell rustup component add llvm-tools-preview cargo install grcov ``` 1. Build the project with the `-Cinstrument-coverage` flag: ```shell RUSTFLAGS="-Cinstrument-coverage" cargo build --bin=router --package=router ``` Several `.profraw` files will be generated. (Due to the execution of build scripts) 2. Execute the binary: ```shell LLVM_PROFILE_FILE="coverage.profraw" target/debug/router ``` 3. Open a separate terminal tab and run the cypress tests, following the [README][cypress-v2-readme] 4. After the tests have finished running, stop the `router` process using `Ctrl+C` The generated `coverage.profraw` file will contain the code coverage data for `router` 5. Generate an html report from the data: ```shell grcov . --source-dir . --output-type html --binary-path ./target/debug ``` 6. A folder named `html` will be generated, containing the report. You can view it using: ```shell cd html && python3 -m http.server 8000 ``` 7. You can delete the generated `.profraw` files: ```shell rm **/*.profraw ``` Note: - It is necessary to stop the `router` process to generate the coverage file - Branch coverage generation requires nightly and currently `grcov` crashes while trying to include branch coverage. (Checked using `--log-level` parameter in `grcov`) #### Integration with VSCode You can also visualize code coverage in VSCode using the [coverage-gutters](https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters) extension. You need to generate an `lcov.info` file in the directory root. After following till step 4 above: ```shell grcov . -s . -t lcov --output-path lcov.info --binary-path ./target/debug --keep-only "crates/*" ``` This will generate an `lcov.info` file that can be read by the extension. [cypress-v2-readme]: /cypress-tests-v2/README.md ### Commits It is a recommended best practice to keep your changes as logically grouped as possible within individual commits. There is no limit to the number of commits any single Pull Request may have, and many contributors find it easier to review changes that are split across multiple commits. Please adhere to the general guideline that you should never force push to a publicly shared branch. Once you have opened your pull request, you should consider your branch publicly shared. Instead of force pushing you can just add incremental commits; this is generally easier on your reviewers. If you need to pick up changes from main, you can merge main into your branch. A reviewer might ask you to rebase a long-running pull request in which case force pushing is okay for that request. Note that squashing at the end of the review process should also not be done, that can be done when the pull request is integrated via GitHub. #### Commit message guidelines Each commit message consists of a header, an optional body, and an optional footer. ```text <header> <BLANK LINE> <optional body> <BLANK LINE> <optional footer> ``` The `header` is mandatory and must conform to the [commit message header](#commit-message-header) format. The `body` is optional. When the body is present it must be at least 20 characters long and must conform to the [commit message body](#commit-message-body) format. The `footer` is optional. The [commit message footer](#commit-message-footer) format describes what the footer is used for and the structure it must have. ##### Commit message header ```text <type>(<scope>): <short summary> │ │ │ │ │ └── Summary in present tense. | | Not capitalized. | | No period at the end. │ │ │ └── Commit Scope: crate name | changelog | config | migrations | | openapi | postman │ └── Commit Type: build | chore | ci | docs | feat | fix | perf | refactor | test ``` The `<type>` and `<summary>` fields are mandatory, the (`<scope>`) field is optional. `<type>` must be one of the following: - `build`: Changes that affect the build system or external dependencies (example scopes: `deps`, `dev-deps`, `metadata`) - `chore`: Changes such as fixing formatting or addressing warnings or lints, or other maintenance changes - `ci`: Changes to our CI configuration files and scripts (examples: `workflows`, `dependabot`, `renovate`) - `docs`: Documentation only changes - `feat`: A new feature - `fix`: A bug fix - `perf`: A code change that improves performance - `refactor`: A code change that neither fixes a bug nor adds a feature - `test`: Adding missing tests or correcting existing tests `<scope>` should be the name of the crate affected (as perceived by the person reading the changelog generated from commit messages). The scope can be more specific if the changes are targeted towards the main crate in the repository (`router`). The following is the list of supported scopes: - `masking` - `router` - `router_derive` - `router_env` There are currently a few exceptions to the "use crate name" rule: - `changelog`: Used for updating the release notes in the `CHANGELOG.md` file. Commonly used with the `docs` commit type (e.g. `docs(changelog): generate release notes for v0.4.0 release`). - `config`: Used for changes which affect the configuration files of any of the services. - `migrations`: Used for changes to the database migration scripts. - `openapi`: Used for changes to the OpenAPI specification file. - `postman`: Used for changes to the Postman collection file. - none/empty string: Useful for test and refactor changes that are done across all crates (e.g. `test: add missing unit tests`) and for docs changes that are not related to a specific crate (e.g. `docs: fix typo in tutorial`). Use the `<summary>` field to provide a succinct description of the change: - Use the imperative, present tense: "change" not "changed" nor "changes". - Don't capitalize the first letter. - No period (.) at the end. ##### Commit message body Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes". Explain the motivation for the change in the commit message body. This commit message should explain why you are making the change. You can include a comparison of the previous behavior with the new behavior in order to illustrate the impact of the change. ##### Commit message footer The footer can contain information about breaking changes and deprecations and is also the place to reference GitHub issues, Jira tickets, and other PRs that this commit closes or is related to. For example: ```text BREAKING CHANGE: <breaking change summary> <BLANK LINE> <breaking change description + migration instructions> <BLANK LINE> <BLANK LINE> Fixes #<issue number> ``` or ```text DEPRECATED: <what is deprecated> <BLANK LINE> <deprecation description + recommended update path> <BLANK LINE> <BLANK LINE> Closes #<PR number> ``` Breaking Change section should start with the phrase "BREAKING CHANGE: " followed by a summary of the breaking change, a blank line, and a detailed description of the breaking change that also includes migration instructions. Similarly, a Deprecation section should start with "DEPRECATED: " followed by a short description of what is deprecated, a blank line, and a detailed description of the deprecation that also mentions the recommended update path. If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. The content of the commit message body should contain: - Information about the SHA of the commit being reverted in the following format: `This reverts commit <SHA>`. - A clear description of the reason for reverting the commit message. Sample commit messages: 1. ```text feat(router): add 3ds support to payments core flow Implement Redirection flow support. This can be used by any flow that requires redirection. Fixes #123 ``` 2. ```text chore: run formatter ``` 3. ```text fix(config): fix binary name displayed in help message ``` _Adapted from the [Angular Commit Message convention][angular commit message]._ [angular commit message]: https://github.com/angular/angular/blob/d684148f93837cf0e4e37146a8df17dc70403558/CONTRIBUTING.md#-commit-message-format ### Opening the Pull Request From within GitHub, opening a new Pull Request will present you with a [template] that should be filled out. Please try to do your best at filling out the details, but feel free to skip parts if you're not sure what to put. [template]: /.github/PULL_REQUEST_TEMPLATE.md ### Discuss and update You will probably get feedback or requests for changes to your Pull Request. This is a big part of the submission process so don't be discouraged! Some contributors may sign off on the Pull Request right away, others may have more detailed comments or feedback. This is a necessary part of the process in order to evaluate whether the changes are correct and necessary. **Any community member can review a PR and you might get conflicting feedback**. Keep an eye out for comments from code owners to provide guidance on conflicting feedback. **Once the PR is open, do not rebase the commits**. See [Commit Squashing](#commit-squashing) for more details. ### Commit Squashing In most cases, **do not squash commits that you add to your Pull Request during the review process**. When the commits in your Pull Request land, they may be squashed into one commit per logical change. Metadata will be added to the commit message (including links to the Pull Request, links to relevant issues, and the names of the reviewers). The commit history of your Pull Request, however, will stay intact on the Pull Request page. ## Reviewing Pull Requests **Any hyperswitch community member is welcome to review any pull request**. All hyperswitch contributors who choose to review and provide feedback on Pull Requests have a responsibility to both the project and the individual making the contribution. Reviews and feedback must be helpful, insightful, and geared towards improving the contribution as opposed to simply blocking it. If there are reasons why you feel the PR should not land, explain what those are. Do not expect to be able to block a Pull Request from advancing simply because you say "No" without giving an explanation. Be open to having your mind changed. Be open to working with the contributor to make the Pull Request better. Reviews that are dismissive or disrespectful of the contributor or any other reviewers are strictly counter to the Code of Conduct. When reviewing a Pull Request, the primary goals are for the codebase to improve and for the person submitting the request to succeed. **Even if a Pull Request does not land, the submitters should come away from the experience feeling like their effort was not wasted or unappreciated**. Every Pull Request from a new contributor is an opportunity to grow the community. ### Review a bit at a time Do not overwhelm new contributors. It is tempting to micro-optimize and make everything about relative performance, perfect grammar, or exact style matches. Do not succumb to that temptation. Focus first on the most significant aspects of the change: 1. Does this change make sense for hyperswitch? 2. Does this change make hyperswitch better, even if only incrementally? 3. Are there clear bugs or larger scale issues that need attending to? 4. Is the commit message readable and correct? If it contains a breaking change is it clear enough? Note that only **incremental** improvement is needed to land a PR. This means that the PR does not need to be perfect, only better than the status quo. Follow up PRs may be opened to continue iterating. When changes are necessary, _request_ them, do not _demand_ them, and **do not assume that the submitter already knows how to add a test or run a benchmark**. Specific performance optimization techniques, coding styles and conventions change over time. The first impression you give to a new contributor never does. Nits (requests for small changes that are not essential) are fine, but try to avoid stalling the Pull Request. Most nits can typically be fixed by the hyperswitch collaborator landing the Pull Request but they can also be an opportunity for the contributor to learn a bit more about the project. It is always good to clearly indicate nits when you comment: e.g. `Nit: change foo() to bar(). But this is not blocking.` If your comments were addressed but were not folded automatically after new commits or if they proved to be mistaken, please, [hide them][hiding-a-comment] with the appropriate reason to keep the conversation flow concise and relevant. ### Be aware of the person behind the code Be aware that _how_ you communicate requests and reviews in your feedback can have a significant impact on the success of the Pull Request. Yes, we may land a particular change that makes hyperswitch better, but the individual might just not want to have anything to do with hyperswitch ever again. The goal is not just having good code. ### Abandoned or Stalled Pull Requests If a Pull Request appears to be abandoned or stalled, it is polite to first check with the contributor to see if they intend to continue the work before checking if they would mind if you took it over (especially if it just has nits left). When doing so, it is courteous to give the original contributor credit for the work they started (either by preserving their name and email address in the commit log, or by using an `Author:` meta-data tag in the commit. _Adapted from the [Node.js contributing guide][node]_. [node]: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md [hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment ## Keeping track of issues and PRs The hyperswitch GitHub repository has a lot of issues and PRs to keep track of. This section explains the meaning of various labels, as well as our [GitHub project][project]. The section is primarily targeted at maintainers. Most contributors aren't able to set these labels. ### Area The area label describes the area relevant to this issue or PR. - **A-CI-CD**: This issue/PR concerns our CI/CD setup. - **A-connector-compatibility**: This issue/PR concerns connector compatibility code. - **A-connector-integration**: This issue/PR concerns connector integrations. - **A-core**: This issue/PR concerns the core flows. - **A-dependencies**: The issue/PR concerns one or more of our dependencies. - **A-drainer**: The issue/PR concerns the drainer code. - **A-errors**: The issue/PR concerns error messages, error structure or error logging. - **A-framework**: The issue/PR concerns code to interact with other systems or services such as database, Redis, connector APIs, etc. - **A-infra**: This issue/PR concerns deployments, Dockerfiles, Docker Compose files, etc. - **A-macros**: This issue/PR concerns the `router_derive` crate. - **A-payment-methods**: This issue/PR concerns the integration of new or existing payment methods. - **A-process-tracker**: This issue/PR concerns the process tracker code. ### Category - **C-bug**: This issue is a bug report or this PR is a bug fix. - **C-doc**: This issue/PR concerns changes to the documentation. - **C-feature**: This issue is a feature request or this PR adds new features. - **C-refactor**: This issue/PR concerns a refactor of existing behavior. - **C-tracking-issue**: This is a tracking issue for a proposal or for a category of bugs. ### Calls for participation - **E-easy**: This is easy, ranging from quick documentation fixes to stuff you can do after getting a basic idea about our product. - **E-medium**: This is not `E-easy` or `E-hard`. - **E-hard**: This either involves very tricky code, is something we don't know how to solve, or is difficult for some other reason. ### Metadata The metadata label describes additional metadata that are important for sandbox or production deployments of our application. - **M-api-contract-changes**: This PR involves API contract changes. - **M-configuration-changes**: This PR involves configuration changes. - **M-database-changes**: This PR involves database schema changes. ### Priority - **P-low**: This is a low priority issue. - **P-medium**: This is not `P-low` or `P-high`. - **P-high**: This is a high priority issue and must be addressed quickly. ### RFCs - **RFC-in-progress**: This RFC involves active discussion regarding substantial design changes. - **RFC-resolved**: This RFC has been resolved. ### Status The status label provides information about the status of the issue or PR. - **S-awaiting-triage**: This issue or PR is relatively new and has not been addressed yet. - **S-blocked**: This issue or PR is blocked on something else, or other implementation work. - **S-design**: This issue or PR involves a problem without an obvious solution; or the proposed solution raises other questions. - **S-in-progress**: The implementation relevant to this issue/PR is underway. - **S-invalid**: This is an invalid issue. - **S-needs-conflict-resolution**: This PR requires merge conflicts to be resolved by the author. - **S-needs-reproduction-steps**: This behavior hasn't been reproduced by the team. - **S-unactionable**: There is not enough information to act on this problem. - **S-unassigned**: This issue has no one assigned to address it. - **S-waiting-on-author**: This PR is incomplete or the author needs to address review comments. - **S-waiting-on-reporter**: Awaiting response from the issue author. - **S-waiting-on-review**: This PR has been implemented and needs to be reviewed. - **S-wont-fix**: The proposal in this issue was rejected and will not be implemented. Any label not listed here is not in active use. [project]: https://github.com/orgs/juspay/projects/3
6,405
765
hyperswitch
docs/TERMS_OF_CONTEST.md
.md
## Terms and Conditions Juspay Technologies Private Limited (Juspay) is the problem statement issuer for the contest and this contest is subject to the below stated terms and conditions. **Hyperswitch** is Juspay's open source full stack payment infrastructure solution to embrace diversity, reduce payment friction and manage compliance. By participating in this contest, Participants agree to the following terms and conditions: 1. Eligibility: Participants must comply with all applicable laws and regulations. Juspay solely reserves the right to disqualify any participant or withhold prizes if participation or prize distribution if in Juspay's opinion the participant by its acts or omission violates or may violate any applicable laws. The discretionary rights for the same at all times shall remain with Juspay. 2. Sanctions Compliance: Participants warrant that they are not located in any country subject to U.S. trade and economic sanctions, including but not limited to Cuba, Iran, North Korea, Syria, and the Crimea region of Ukraine. Participants also warrant that they are not listed on any U.S. list of prohibited parties, including the Treasury Department's List of Specially Designated Nationals (SDN List) or Sectoral Sanctions List (SSI List). 3. Prize Distribution: Juspay will make reasonable efforts to distribute prizes to eligible winners. However, Juspay shall not be liable if prize distribution is impossible due to sanctions, export controls, or other legal restrictions. In such cases, the prize may be forfeited without any liability to Juspay. Juspay reserves the right to withhold any prize or disqualify any participant from the contest if in Juspay's opinion the participant has violated any rules of the contest. 4. Participant Responsibility: Juspay is not responsible for any taxes, duties, or other costs associated with prize acceptance or use. 5. Liability: To the fullest extent permitted by law, Juspay disclaims all liability for any issues arising from contest participation, including but not limited to inability to distribute prizes due to legal restrictions. Participants acknowledge that they enter the contest at their own risk and agree to indemnify and hold Juspay harmless from any claims, losses, liabilities or damages arising from their participation in the contest. 6. Intellectual Property Rights: Juspay will solely retain ownership of the submissions by the participant. Juspay shall have the full right to use, modify, reproduce, distribute, and otherwise exploit the submission, in whole or in part, for any purpose whatsoever, without any additional permission of the participant.  7. Modifications: Juspay reserves the exclusive right to modify the terms and conditions, suspend, or terminate the contest at its sole discretion and at any time. 8. Governing Law: These terms shall be governed by and construed in accordance with the laws of India, without regard to its conflict of law provisions and in the matters of any dispute between Juspay and the participant , the courts of Bangalore shall have exclusive jurisdiction.  9. By participating in this contest, Participant acknowledge that Participant have read, understood, and agree to be bound by these terms and conditions.
644
766
hyperswitch
docs/CODE_OF_CONDUCT.md
.md
# Code of Conduct The hyperswitch project adheres to the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). This describes the minimum behavior expected from all contributors.
44
767
hyperswitch
docs/building_docker_images.md
.md
# Building Docker Images ## Cargo Features The Hyperswitch application server makes extensive use of [Cargo features][cargo-features] to selectively toggle certain features and integrations. The list of features can be found in the `[features]` section in the [`crates/router/Cargo.toml`][router-manifest] file. Of these features, the noteworthy ones are the `default` and `release` features: - `default`: This feature set enables a basic set of necessary features for both development and production environments, such as the transactional APIs, APIs used by the control center, Stripe compatibility, automatic payment retries, in-memory caching, etc. - `release`: This feature set enables some additional features that are suitable for production environments, such as AWS KMS integration, AWS S3 integration, AWS SES integration, etc. Refer to the [documentation on cargo features][cargo-features] to understand how to select features with Cargo, when building the application server. ## Building with the Dockerfile The Docker images for the application server and other components can be built using the [`Dockerfile`][dockerfile] using the below commands, substituting the Docker image tags with suitable values: - router: ```shell docker build \ --load \ --file Dockerfile \ --build-arg "BINARY=router" \ --tag hyperswitch-router \ . ``` - consumer: ```shell docker build \ --load \ --file Dockerfile \ --build-arg "BINARY=scheduler" \ --build-arg "SCHEDULER_FLOW=consumer" \ --tag hyperswitch-consumer \ . ``` - producer: ```shell docker build \ --load \ --file Dockerfile \ --build-arg "BINARY=scheduler" \ --build-arg "SCHEDULER_FLOW=producer" \ --tag hyperswitch-producer \ . ``` - drainer: ```shell docker build \ --load \ --file Dockerfile \ --build-arg "BINARY=drainer" \ --tag hyperswitch-drainer \ . ``` When our Docker images are built using the [`Dockerfile`][dockerfile], the `cargo` command being run is: ```shell cargo build --release --features release ${EXTRA_FEATURES} ``` - The `--release` flag specifies that optimized release binaries must be built. Refer to the [`cargo build` manual page][cargo-build-manual-page] for more information. - The `--features release` flag specifies that the `release` feature set must be enabled for the build. Since we do not specify the `--no-default-features` flag to the `cargo build` command, the build would have the `default` and `release` features enabled. - In case you create your own features sets and want to enable them, you can use the `${EXTRA_FEATURES}` build argument to specify any additional features that would have to be passed to the `cargo build` command. The build argument could look as follows: `EXTRA_FEATURES="--features feature1,feature2,feature3"`, with actual feature names substituted in the command. ## Image Variants on Docker Hub As of writing this document, we have two image variants available on our Docker Hub repositories: - release: These images contain only the tag that was built, and no other suffixes, like the `v1.105.1` and `v1.107.0` Docker images. - standalone: These images contain the tag that was built with a `standalone` suffix, like the `v1.105.1-standalone` and `v1.107.0-standalone` Docker images. The primary difference is that our standalone Docker images do not have some features enabled by default in order to support hosting of Hyperswitch outside AWS. As of writing this document, the standalone images exclude the `email` and `recon` features from the `release` feature set, while the release images are built from the Dockerfile without any changes to the codebase after the tag is checked out. If you are building custom images and would like to mirror the behavior of our standalone images, then you'd have to remove the `email` and `recon` features from the `release` feature set. ## Frequently Asked Questions ### What machine specifications would I need to build release images? Building release (optimized) images needs significant amount of resources, and we'd recommend using a machine with at least 8 cores and 16 GB of RAM for this purpose. Rust is known to have long compile times, and a codebase of this size will require a significant time to build, around 45-60 minutes for the above configuration. ### Build seems to be stuck at "Compiling router/scheduler/analytics/..." The compilation process involves compiling all of our dependencies and then compiling our workspace (first-party) crates, among which the biggest one (in terms of lines of code) is the `router` crate. Once all the dependencies of the `router` crate have been built, one of the last ones being built is the `router` crate itself. As mentioned above, building release images takes a significant amount of time. It is normal to see nothing else being printed after a line which says `Compiling router / scheduler / analytics / ...`. We'd suggest waiting for a while. If you're still concerned that the compilation process has been stuck for far too long, you can check if at least one CPU is being utilized by `cargo` / `docker` using a tool like `htop` (if you can access the machine which is building the code). Worst case, you can proceed to kill the compilation process and try again. [cargo-features]: https://doc.rust-lang.org/cargo/reference/features.html [router-manifest]: https://github.com/juspay/hyperswitch/blob/main/crates/router/Cargo.toml [dockerfile]: https://github.com/juspay/hyperswitch/blob/main/Dockerfile [cargo-build-manual-page]: https://doc.rust-lang.org/cargo/commands/cargo-build.html
1,362
768
hyperswitch
docs/architecture.md
.md
# HyperSwitch Architecture - [Introduction](#introduction) - [Router](#router) - [Scheduler](#scheduler) - [Producer (Job scheduler)](#producer-job-scheduler) - [Consumer (Job executor)](#consumer-job-executor) - [Database](#database) - [Postgres](#postgres) - [Redis](#redis) - [Locker](#locker) - [Monitoring](#monitoring) ## Introduction Hyperswitch comprises two distinct app services: **Router** and **Scheduler** which in turn consists of **Producer** and **Consumer**, where each service has its specific responsibilities to process payment-related tasks efficiently. <p align="center"> <img src="../docs/imgs/hyperswitch-architecture.png" alt="HyperSwitch Architecture" style="width:60%"> <p align="center"><b>Fig.1 - Typical Deployment</b></p> </p> ## Router The Router is the main component of Hyperswitch, serving as the primary crate where all the core payment functionalities are implemented. It is a crucial component responsible for managing and coordinating different aspects of the payment processing system. Within the Router, the core payment flows serve as the central hub through which all payment activities are directed. When a payment request is received, it goes through the Router, which handles important processing and routing tasks. ## Scheduler Suppose a scenario where a customer has saved their card details in your application, but for security reasons, you want to remove the saved card information after a certain period. To automate this process, Scheduler comes into picture. It schedules a task with a specific time for execution and stores it in the database. When the scheduled time arrives, the job associated with the task starts executing, here in this case, allowing the saved card details to be deleted automatically. One other situation in which we use this service in Hyperswitch is when we want to notify the merchant that their api key is about to expire. ### Producer (Job scheduler) The Producer is one of the components responsible for the Scheduler's functionality. Its primary responsibility is to handle the tracking of tasks which are yet to be executed. When the Router Service inserts a new task into the database, specifying a scheduled time, the producer retrieves the task from the database when the scheduled time is up and proceeds to group or batch these tasks together. These batches of tasks are then stored in a Redis queue, ready for execution, which will be picked up by consumer service. ### Consumer (Job executor) The Consumer is another key component of the Scheduler. Its main role is to retrieve batches of tasks from the Redis queue for processing, which were previously added by the Producer. Once the tasks are retrieved, the Consumer executes them. It ensures that the tasks within the batches are handled promptly and in accordance with the required processing logic. ## Database ### Postgres The application relies on a PostgreSQL database for storing various types of data, including customer information, merchant details, payment-related data, and other relevant information. The application maintains a master-database and replica-database setup to optimize read and write operations. ### Redis In addition to the database, Hyperswitch incorporates Redis for two main purposes. It is used to **cache** frequently accessed data in order to decrease the application latencies and reduce the load on the database. It is also used as a **queuing mechanism** by the Scheduler. ## Locker The application utilizes a Rust locker built with a GDPR compliant PII (personal identifiable information) storage. It also uses secure encryption algorithms to be fully compliant with **PCI DSS** (Payment Card Industry Data Security Standard) requirements, this ensures that all payment-related data is handled and stored securely. You can find the source code of locker [here](https://github.com/juspay/hyperswitch-card-vault). ## Monitoring <p align="center"> <img src="../docs/imgs/hyperswitch-monitoring-architecture.png" alt="HyperSwitch Monitoring Architecture" style="width:70%"> <p align="center"><b>Fig.2 - HyperSwitch Monitoring Architecture</b></p> </p> The monitoring services in Hyperswitch ensure the effective collection and analysis of metrics to monitor the system's performance. Hyperswitch pushes the metrics and traces in **OTLP** format to the [OpenTelemetry collector]. [Prometheus] utilizes a pull-based model, where it periodically retrieves application metrics from the OpenTelemetry collector. [Promtail] scrapes application logs from the router, which in turn are pushed to the [Loki] instance. Users can query and visualize the logs in Grafana through Loki. [Tempo] is used for querying the application traces. Except for the OpenTelemetry collector, all other monitoring services like Loki, Tempo, Prometheus can be easily replaced with a preferred equivalent, with minimal to no code changes. [OpenTelemetry collector]: https://opentelemetry.io/docs/collector/ [Prometheus]: https://prometheus.io/docs/introduction/overview/ [Promtail]: https://grafana.com/docs/loki/latest/clients/promtail/ [Loki]: https://grafana.com/docs/loki/latest/ [Tempo]: https://grafana.com/docs/tempo/latest/
1,074
769
hyperswitch
docs/CONTRIBUTOR_LICENSE_AGREEMENT.md
.md
# Contributor License Agreement You accept and agree to the following terms and conditions for Your present and future Contributions submitted to Juspay Technologies Private Limited, Except for the license granted herein to Juspay Technologies Private Limited and recipients of software distributed by Juspay Technologies Private Limited, You reserve all right, title, and interest in and to Your Contributions. 1. **Definitions:** 1. "You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with Juspay Technologies Private Limited. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 2. "Contribution" shall mean the code, documentation or other original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to Juspay Technologies Private Limited for inclusion in, or documentation of, any of the products owned or managed by Juspay Technologies Private Limited (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to Juspay Technologies Private Limited or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, Juspay Technologies Private Limited for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution." 2. **Grant of Copyright License:** Subject to the terms and conditions of this Agreement, You hereby grant to Juspay Technologies Private Limited and to recipients of software distributed by Juspay Technologies Private Limited a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. 3. **Grant of Patent License:** Subject to the terms and conditions of this Agreement, You hereby grant to Juspay Technologies Private Limited and to recipients of software distributed by Juspay Technologies Private Limited a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed. 4. You represent that You are legally entitled to grant the above license. You represent further that each of Your employees is authorized to submit Contributions on Your behalf, but excluding employees that are designated in writing by You as "Not authorized to submit Contributions on behalf of [name of Your corporation here]." Such designations of exclusion for unauthorized employees are to be submitted via email to Juspay Technologies Private Limited. In case of Individual, if your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to Juspay Technologies Private Limited, or that your employer has executed a separate Corporate CLA with Juspay Technologies Private Limited. 5. You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions. 6. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. 7. Should You wish to submit work that is not Your original creation, You may submit it to Juspay Technologies Private Limited separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [Juspay Technologies Private Limited]". You agree to notify Juspay Technologies Private Limited of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. It is Your responsibility to notify Juspay Technologies Private Limited when any change is required to the list of designated employees excluded from submitting Contributions on Your behalf. Such notification should be sent via email to Juspay Technologies Private Limited. This text is licensed to Juspay Technologies Private Limited and the original source is the [Juspay license](/LICENSE).
1,363
770
hyperswitch
docs/one_click_setup.md
.md
# One-Click Docker Setup Guide This document provides detailed information about the one-click setup script for Hyperswitch. ## Overview The `setup.sh` script simplifies the process of setting up Hyperswitch in a local development or testing environment. It provides an interactive setup experience that handles checking prerequisites, configuring the environment, and starting the necessary services. ## Features - **Prerequisite Checking**: Verifies Docker/Podman and Docker/Podman Compose installation. - **Port Availability Check**: Ensures required ports are available to avoid conflicts. - **Configuration Management**: Automatically sets up necessary configuration files. - **Multiple Deployment Profiles**: Choose the right setup for your needs. - **Health Checking**: Verifies services are running and healthy. - **Detailed Feedback**: Provides clear output and helpful error messages. ## Deployment Profiles The script offers four deployment profiles to match your needs: ### 1. Standard (Recommended) - **Services**: App server + Control Center + Web SDK (includes PostgreSQL, Redis) - **Best for**: General development and testing - **Resources required**: Medium ### 2. Full - **Services**: Standard + Monitoring (Grafana, Prometheus) + Scheduler - **Best for**: Complete system testing - **Resources required**: Higher ### 3. Standalone App Server - **Services**: Hyperswitch server, PostgreSQL, Redis - **Best for**: Testing basic API functionality - **Resources required**: Lower ## Troubleshooting ### Common Issues 1. **Docker not running** - **Error**: "Cannot connect to the Docker/Podman daemon" - **Solution**: Start the Docker daemon/Docker Desktop or Use Orbstack. 2. **Port conflicts** - **Error**: "The following ports are already in use: [port list]" - **Solution**: Stop services using those ports or choose different ports. 3. **Server not becoming healthy** - **Error**: "Hyperswitch server did not become healthy in the expected time." - **Solution**: Check logs with `docker compose logs hyperswitch-server` or `podman compose logs hyperswitch-server`. ### Viewing Logs To view logs for any service: ``` docker compose logs -f [service-name] ``` Common service names: - `hyperswitch-server` - `pg` (PostgreSQL) - `redis-standalone` - `hyperswitch-control-center` ## Advanced Usage ### Environment Variables You can set these environment variables before running the script: - `DRAINER_INSTANCE_COUNT`: Number of drainer instances (default: 1) - `REDIS_CLUSTER_COUNT`: Number of Redis cluster nodes (default: 3) Example: ``` export DRAINER_INSTANCE_COUNT=2 ./setup.sh ``` ### Manual Service Control After setup, you can manually control services: - Stop all services: `docker/podman compose down` - Start specific services: `docker/podman compose up -d [service-name]` - Restart a service: `docker/podman compose restart [service-name]` ## Next Steps After running the setup script: 1. Verify the server is running: `curl --head --request GET 'http://localhost:8080/health'`. 2. Access the Control Center at `http://localhost:9000`. 3. Configure payment connectors in the Control Center. 4. Try a test payment using the demo store.
715
771
hyperswitch
docs/rfcs/guidelines.md
.md
# Hyperswitch RFC Process Hyperswitch welcomes contributions from anyone in the open-source community. Although some contributions can be easily reviewed and implemented through regular GitHub pull requests, larger changes that require design decisions will require more discussion and collaboration within the community. To facilitate this process, Hyperswitch has adopted the RFC (Request for Comments) process from other successful open-source projects like Rust and React. The RFC process is designed to encourage community-driven change and ensure that everyone has a voice in the decision-making process, including both core and non-core contributors. Here are the steps involved: 1. Prepare an RFC Proposal 2. Submit Proposal 3. Complete Initial Review 4. Initiate RFC Discussion 5. Finalize Proposal 6. Complete Implementation 7. Close RFC **Prepare an RFC Proposal:** Anyone interested in proposing a change to Hyperswitch should first create an RFC(in the format given below) that outlines the proposed change. This document should describe the problem the proposal is trying to solve, the proposed solution, and any relevant technical details. The document should also include any potential drawbacks or alternative solutions that were considered. **Submit Proposal:** Once the RFC document is complete, the proposer should submit it to the Hyperswitch community for review. The proposal can be submitted either as a pull request to the RFC Documents folder or as a GitHub Issue. **Complete Initial Review:** After the proposal is submitted, the Hyperswitch core team would review it and provide feedback. Feedback can include suggestions for improvements, questions about the proposal, or concerns about its potential impact. **Initiate RFC Discussion:** If the initial review results in interest from the community, a discussion should be opened to debate the proposal. The discussion can take place on GitHub or on Hyperswitch’s Slack & Discord servers. The discussion timeframe would be one week unless specified otherwise by the proposer or the core team. **Finalize Proposal:** During the discussion phase, the proposer should work with the community to refine the proposal based on feedback and input. Once the proposal is deemed mature enough, a final version should be submitted for community review and acceptance. If the proposal is accepted, the proposed changes can be implemented. If the proposal is rejected, the proposer can either abandon the proposal or rework it based on community feedback and resubmit it for another round of review. **Complete Implementation:** Once the proposal is accepted, the proposer or a designated contributor can implement the changes to the repository. The implementation should follow the design outlined in the RFC document and adhere to any relevant coding standards and guidelines. **Close RFC:** After the proposal is implemented, the RFC process would be closed by marking the proposal as completed. The RFC document would be kept for future reference, and any feedback received during the process can be used to inform future RFCs. This RFC process for Hyperswitch is intended to encourage collaboration and communication within the community and ensure that proposed changes to the platform are thoroughly evaluated before implementation. Please note that ​​a lack of response from others is assumed to be positive indifference. ## Templates: ### Issuing an RFC ```text **Title** **Objective** A clear and concise title for the RFC **Proposal** A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered **Open Questions** Any questions or concerns that are still open for discussion and debate within the community **Additional Context / Previous Improvements** Any relevant external resources or references like slack / discord threads that support the proposal ``` ### Resolving an RFC ```text **Title** The title of the resolved RFC **Status** The final status of the RFC (Accepted / Rejected) **Resolution** A description of the final resolution of the RFC, including any modifications or adjustments made during the discussion and review process **Implementation** A description of how the resolution will be implemented, including any relevant future scope for the solution **Acknowledgements** Any final thoughts or acknowledgements for the community and contributors who participated in the RFC process ```
826
772
hyperswitch
docs/rfcs/000-issuing-template.md
.md
## RFC 000: [Title] ### I. Objective A clear and concise title for the RFC ### II. Proposal A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered ### III. Open Questions Any questions or concerns that are still open for discussion and debate within the community ### IV. Additional Context / Previous Improvements Any relevant external resources or references like slack / discord threads that support the proposal
100
773
hyperswitch
docs/rfcs/000-resolution-template.md
.md
## RFC 000: [Title] ### I. Status The final status of the RFC (Accepted / Rejected) ### II. Resolution A description of the final resolution of the RFC, including any modifications or adjustments made during the discussion and review process ### III. Implementation A description of how the resolution will be implemented, including any relevant future scope for the solution ### IV. Acknowledgements Any final thoughts or acknowledgements for the community and contributors who participated in the RFC process
103
774
hyperswitch
docs/rfcs/text/001-compile-time-perf.md
.md
## RFC 001: Hyperswitch compile time optimization ### I. Objective Optimizing the compile time of Hyperswitch while preserving (and/or improving) the runtime performance. This would ensure accessibility across machines and improve developer experience for the community ### II. Proposal While the Rust compiler provides various options like zero-cost abstractions or compiler code optimizations, there is always a trade-off between compile time and runtime performance. Through this RFC, we intend to improve the compile time without losing any runtime performance. Compile time enhances developer experience by improving iteration speed and hence developer productivity. It enables machines with limited computing resources (especially machines with 4 GB RAMs) to work on Hyperswitch. Currently the target directory occupies ~6.4 GB of disk space for debug builds and checks. The focus of this RFC is on external dependencies and the dependency tree which has a significant impact on the compilation time. Sometimes adding redundant features to dependencies can also have a severe impact on the compilation time, one such improvement is mentioned in the Past Improvements section. Dependencies might be repeated or be present with different versions. Reduced compile time also implies faster deployment and lower cost incurred for compiling the project on a sandbox / production environment. Another area for optimization is code generation. Rust provides means to extend the existing functionality of the code with constructs like `monomorphization` and `proc_macros`. These patterns help the developer reduce code repetition but it comes at the cost of compile time. Adding to this, there are some data structures in the codebase which might have redundant `derive` implementations, which could also contribute to code generation, i.e. generating redundant code which isn't used. ### III. Open Questions * How can we reduce the depth of the crate dependency tree? * Can we remove some of the procedural macros used, for an OOTB (out of the box) solution available? * Are there any other features in the overall dependencies which could be removed? * Which `derive` macros can be removed to reduce code generation? ### IV. Past Improvements Below mentioned are some of the PR's that were intended to improve the performance of the codebase: * [#40](http://github.com/juspay/hyperswitch/pull/40): move `serde` implementations and date-time utils to `common_utils` crate * [#356](http://github.com/juspay/hyperswitch/pull/356): cleanup unused `ApplicationError` variants * [#413](http://github.com/juspay/hyperswitch/pull/413): Reusing request client for significant performance boost on the connector side. * [#753](http://github.com/juspay/hyperswitch/pull/753): Removing redundant and unnecessary logs * [#775](http://github.com/juspay/hyperswitch/pull/775): Removing unused features from diesel to improve the compile time: This is an example that was mentioned in the Proposal section that illustrated the performance boost from a relatively small change. Prior to this change diesel contributed a whopping *59.17s* to the compile time, though there are crates compiling alongside diesel, for the longest of time only diesel was compiling even after all the dependencies were compiled. ![pre-opt](../assets/rfc-001-perf-before.png) After removing a redundant feature flag used for diesel in various crates, the performance boost was visibly significant, the compile time taken by diesel was a measly *4.8s*. This provided a *37.65%* improvement in the overall compile time. ![post-opt](../assets/rfc-001-perf-after.png) Note: these benchmarks were performed on an M1 pro chip with a ~250 Mbps connection.
793
775
hyperswitch
crates/diesel_models/Cargo.toml
.toml
[package] name = "diesel_models" description = "Database types shared across `router` and other crates" version = "0.1.0" edition.workspace = true rust-version.workspace = true readme = "README.md" license.workspace = true [features] default = ["kv_store"] kv_store = [] v1 = ["common_utils/v1", "common_types/v1"] v2 = ["common_utils/v2", "common_types/v2"] customer_v2 = [] payment_methods_v2 = [] refunds_v2 = [] [dependencies] async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } diesel = { version = "2.2.3", features = ["postgres", "serde_json", "time", "128-column-tables"] } error-stack = "0.4.1" rustc-hash = "1.1.0" serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } # First party crates common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } common_types = { version = "0.1.0", path = "../common_types" } masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } [lints] workspace = true
484
780
hyperswitch
crates/diesel_models/README.md
.md
# Storage Models Database models shared across `router` and other crates.
15
782
hyperswitch
crates/diesel_models/src/payment_link.rs
.rs
use common_utils::types::MinorUnit; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payment_link}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_link, primary_key(payment_link_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentLink { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = payment_link)] pub struct PaymentLinkNew { pub payment_link_id: String, pub payment_id: common_utils::id_type::PaymentId, pub link_to_pay: String, pub merchant_id: common_utils::id_type::MerchantId, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_modified_at: Option<PrimitiveDateTime>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub fulfilment_time: Option<PrimitiveDateTime>, pub custom_merchant_name: Option<String>, pub payment_link_config: Option<serde_json::Value>, pub description: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub secure_link: Option<String>, }
574
783
hyperswitch
crates/diesel_models/src/query.rs
.rs
pub mod address; pub mod api_keys; pub mod blocklist_lookup; pub mod business_profile; mod capture; pub mod cards_info; pub mod configs; pub mod authentication; pub mod authorization; pub mod blocklist; pub mod blocklist_fingerprint; pub mod callback_mapper; pub mod customers; pub mod dashboard_metadata; pub mod dispute; pub mod dynamic_routing_stats; pub mod events; pub mod file; pub mod fraud_check; pub mod generic_link; pub mod generics; pub mod gsm; pub mod locker_mock_up; pub mod mandate; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_key_store; pub mod organization; pub mod payment_attempt; pub mod payment_intent; pub mod payment_link; pub mod payment_method; pub mod payout_attempt; pub mod payouts; pub mod process_tracker; pub mod refund; pub mod relay; pub mod reverse_lookup; pub mod role; pub mod routing_algorithm; pub mod unified_translations; pub mod user; pub mod user_authentication_method; pub mod user_key_store; pub mod user_role;
217
784
hyperswitch
crates/diesel_models/src/merchant_account.rs
.rs
use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_account; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account; /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v1")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v1")] pub struct MerchantAccountSetter { pub merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v1")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: Some(item.merchant_id.clone()), merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, primary_business_details: item.primary_business_details, intent_fulfillment_time: item.intent_fulfillment_time, created_at: item.created_at, modified_at: item.modified_at, frm_routing_algorithm: item.frm_routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, } } } /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, router_derive::DebugAsDisplay, Selectable, )] #[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: item.id, merchant_name: item.merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, metadata: item.metadata, created_at: item.created_at, modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, } } } #[cfg(feature = "v2")] pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, } impl MerchantAccount { #[cfg(feature = "v1")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.id } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub id: common_utils::id_type::MerchantId, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub recon_status: Option<storage_enums::ReconStatus>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, publishable_key, storage_scheme, metadata, modified_at, organization_id, recon_status, is_platform_account, product_type, } = self; MerchantAccount { merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), metadata: metadata.or(source.metadata), created_at: source.created_at, modified_at, organization_id: organization_id.unwrap_or(source.organization_id), recon_status: recon_status.unwrap_or(source.recon_status), version: source.version, id: source.id, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), product_type: product_type.or(source.product_type), } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: Option<serde_json::Value>, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub is_recon_enabled: Option<bool>, pub default_profile: Option<Option<common_utils::id_type::ProfileId>>, pub recon_status: Option<storage_enums::ReconStatus>, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v1")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, return_url, webhook_details, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, storage_scheme, locker_id, metadata, routing_algorithm, primary_business_details, modified_at, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, organization_id, is_recon_enabled, default_profile, recon_status, payment_link_config, pm_collect_link_config, is_platform_account, product_type, } = self; MerchantAccount { merchant_id: source.merchant_id, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), webhook_details: webhook_details.or(source.webhook_details), sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled), parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), locker_id: locker_id.or(source.locker_id), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), primary_business_details: primary_business_details .unwrap_or(source.primary_business_details), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), created_at: source.created_at, modified_at, frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), organization_id: organization_id.unwrap_or(source.organization_id), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), default_profile: default_profile.unwrap_or(source.default_profile), recon_status: recon_status.unwrap_or(source.recon_status), payment_link_config: payment_link_config.or(source.payment_link_config), pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), version: source.version, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), } } }
3,931
785
hyperswitch
crates/diesel_models/src/payment_intent.rs
.rs
use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::RequestExtendedAuthorizationBool; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_intent; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent; #[cfg(feature = "v2")] use crate::types::{FeatureMetadata, OrderDetailsWithAmount}; use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums}; #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub customer_present: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, /// merchant display logo pub logo: Option<String>, /// Custom merchant name for payment link pub seller_name: Option<String>, /// Custom layout for sdk pub sdk_layout: Option<String>, /// Display only the sdk for payment link pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details pub key: String, /// Value for the transaction details pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI pub position: Option<i8>, /// Whether the key should be bold pub is_key_bold: Option<bool>, /// Whether the value should be bold pub is_value_bold: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration); #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct TaxDetails { /// This is the tax related information that is calculated irrespective of any payment method. /// This is calculated when the order is created with shipping details pub default: Option<DefaultTax>, /// This is the tax related information that is calculated based on the payment method /// This is calculated when calling the /calculate_tax API pub payment_method_type: Option<PaymentMethodTypeTax>, } impl TaxDetails { /// Get the tax amount /// If default tax is present, return the default tax amount /// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> { self.payment_method_type .as_ref() .zip(payment_method) .filter(|(payment_method_type_tax, payment_method)| { payment_method_type_tax.pmt == *payment_method }) .map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount) .or_else(|| self.get_default_tax_amount()) } /// Get the default tax amount pub fn get_default_tax_amount(&self) -> Option<MinorUnit> { self.default .as_ref() .map(|default_tax_details| default_tax_details.order_tax_amount) } } common_utils::impl_to_sql_from_sql_json!(TaxDetails); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentMethodTypeTax { pub order_tax_amount: MinorUnit, pub pmt: PaymentMethodType, } #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTax { pub order_tax_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub client_secret: common_utils::types::ClientSecret, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { /// Update the payment intent details on payment intent confirmation, before calling the connector ConfirmIntent { status: storage_enums::IntentStatus, active_attempt_id: common_utils::id_type::GlobalAttemptId, updated_by: String, }, /// Update the payment intent details on payment intent confirmation, after calling the connector ConfirmIntentPostUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<common_utils::id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { status: storage_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: storage_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: Option<bool>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<storage_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address: Option<Encryption>, pub billing_address: Option<Encryption>, pub return_url: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub is_payment_processor_token_flow: Option<bool>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub status: Option<storage_enums::IntentStatus>, pub prerouting_algorithm: Option<serde_json::Value>, pub amount_captured: Option<MinorUnit>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>, pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub surcharge_applicable: Option<bool>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub customer_present: Option<bool>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub apply_mit_exemption: Option<bool>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), amount_captured: amount_captured.or(source.amount_captured), customer_id: customer_id.or(source.customer_id), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), off_session: off_session.or(source.off_session), metadata: metadata.or(source.metadata), billing_address_id: billing_address_id.or(source.billing_address_id), shipping_address_id: shipping_address_id.or(source.shipping_address_id), modified_at: common_utils::date_time::now(), active_attempt_id: active_attempt_id.unwrap_or(source.active_attempt_id), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), description: description.or(source.description), statement_descriptor_name: statement_descriptor_name .or(source.statement_descriptor_name), statement_descriptor_suffix: statement_descriptor_suffix .or(source.statement_descriptor_suffix), order_details: order_details.or(source.order_details), attempt_count: attempt_count.unwrap_or(source.attempt_count), merchant_decision: merchant_decision.or(source.merchant_decision), payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), billing_details: billing_details.or(source.billing_details), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), shipping_details: shipping_details.or(source.shipping_details), is_payment_processor_token_flow: is_payment_processor_token_flow .or(source.is_payment_processor_token_flow), tax_details: tax_details.or(source.tax_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), ..source } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: value.return_url, business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, amount_captured: None, off_session: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, attempt_count: None, merchant_decision: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: None, force_3ds_challenge: value.force_3ds_challenge, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, return_url: None, modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, customer_id: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable, updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { shipping_address_id, amount: None, tax_details: Some(tax_details), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details, is_payment_processor_token_flow: None, force_3ds_challenge: None, }, } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", "amount": 10000, "currency": "USD", "amount_captured": null, "customer_id": "cust_123456", "description": "Test Payment", "return_url": "https://example.com/return", "metadata": null, "connector_id": "connector_001", "shipping_address_id": null, "billing_address_id": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "created_at": "2024-02-01T12:00:00Z", "modified_at": "2024-02-01T12:00:00Z", "last_synced": null, "setup_future_usage": null, "off_session": null, "client_secret": "sec_abcdef1234567890", "active_attempt_id": "attempt_123", "business_country": "US", "business_label": null, "order_details": null, "allowed_payment_method_types": "credit", "connector_metadata": null, "feature_metadata": null, "attempt_count": 1, "profile_id": null, "merchant_decision": null, "payment_link_id": null, "payment_confirm_source": null, "updated_by": "admin", "surcharge_applicable": null, "request_incremental_authorization": null, "incremental_authorization_allowed": null, "authorization_count": null, "session_expiry": null, "fingerprint_id": null, "frm_metadata": null }"#; let deserialized_payment_intent = serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); assert!(deserialized_payment_intent.is_ok()); } }
12,381
786
hyperswitch
crates/diesel_models/src/refund.rs
.rs
use common_utils::{ pii, types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums as storage_enums; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] use crate::schema::refund; #[cfg(all(feature = "v2", feature = "refunds_v2"))] use crate::schema_v2::refund; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub internal_reference_id: String, pub refund_id: String, //merchant_reference id pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, /// INFO: This field is deprecated and replaced by processor_refund_data pub connector_refund_data: Option<String>, /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub payment_id: common_utils::id_type::GlobalPaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: common_utils::id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub updated_by: String, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub id: common_utils::id_type::GlobalRefundId, pub merchant_reference_id: common_utils::id_type::RefundReferenceId, pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub refund_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub internal_reference_id: String, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub merchant_reference_id: common_utils::id_type::RefundReferenceId, pub payment_id: common_utils::id_type::GlobalPaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub id: common_utils::id_type::GlobalRefundId, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: common_utils::id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub updated_by: String, pub connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, issuer_error_code, issuer_error_message, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, issuer_error_code, issuer_error_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, issuer_error_code, issuer_error_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), issuer_error_code: issuer_error_code.or(source.issuer_error_code), issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), ..source } } } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: self.payment_id.clone(), refund_id: self.id.clone(), }) } } impl ConnectorTransactionIdTrait for Refund { fn get_optional_connector_refund_id(&self) -> Option<&String> { match self .connector_refund_id .as_ref() .map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref())) .transpose() { Ok(refund_id) => refund_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self .connector_refund_id .as_ref() .map(|txn_id| txn_id.get_id()), } } fn get_connector_transaction_id(&self) -> &String { match self .connector_transaction_id .get_txn_id(self.processor_transaction_data.as_ref()) { Ok(txn_id) => txn_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self.connector_transaction_id.get_id(), } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_refund = r#"{ "internal_reference_id": "internal_ref_123", "refund_id": "refund_456", "payment_id": "payment_789", "merchant_id": "merchant_123", "connector_transaction_id": "connector_txn_789", "connector": "stripe", "connector_refund_id": null, "external_reference_id": null, "refund_type": "instant_refund", "total_amount": 10000, "currency": "USD", "refund_amount": 9500, "refund_status": "Success", "sent_to_gateway": true, "refund_error_message": null, "metadata": null, "refund_arn": null, "created_at": "2024-02-26T12:00:00Z", "updated_at": "2024-02-26T12:00:00Z", "description": null, "attempt_id": "attempt_123", "refund_reason": null, "refund_error_code": null, "profile_id": null, "updated_by": "admin", "merchant_connector_id": null, "charges": null, "connector_transaction_data": null "unified_code": null, "unified_message": null, "processor_transaction_data": null, }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); assert!(deserialized.is_ok()); } }
6,326
787
hyperswitch
crates/diesel_models/src/schema_v2.rs
.rs
// @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Varchar, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Varchar, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>, #[max_length = 64] frm_routing_algorithm_id -> Nullable<Varchar>, #[max_length = 64] payout_routing_algorithm_id -> Nullable<Varchar>, default_fallback_routing -> Nullable<Jsonb>, three_ds_decision_manager_config -> Nullable<Jsonb>, should_collect_cvv_during_payment -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { id -> Int4, #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (id) { #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, default_billing_address -> Nullable<Bytea>, default_shipping_address -> Nullable<Bytea>, status -> DeleteStatus, #[max_length = 64] id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (id) { id -> Int4, #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (id) { merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] organization_id -> Varchar, recon_status -> ReconStatus, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Varchar, #[max_length = 64] product_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, disabled -> Nullable<Bool>, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Varchar, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (id) { organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Varchar, organization_name -> Nullable<Text>, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> AttemptStatus, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, surcharge_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, authentication_type -> AuthenticationType, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Int8, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, payment_method_type_v2 -> Varchar, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Varchar, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] external_reference_id -> Nullable<Varchar>, tax_on_surcharge -> Nullable<Int8>, payment_method_billing_address -> Nullable<Bytea>, redirection_data -> Nullable<Jsonb>, connector_payment_data -> Nullable<Text>, connector_token_details -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, #[max_length = 32] network_advice_code -> Nullable<Varchar>, #[max_length = 32] network_decline_code -> Nullable<Varchar>, network_error_message -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (id) { #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Currency, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, #[max_length = 128] client_secret -> Varchar, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_link_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, authorization_count -> Nullable<Int4>, session_expiry -> Timestamp, request_external_three_ds_authentication -> Nullable<Bool>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, prerouting_algorithm -> Nullable<Jsonb>, surcharge_amount -> Nullable<Int8>, tax_on_surcharge -> Nullable<Int8>, #[max_length = 64] frm_merchant_decision -> Nullable<Varchar>, #[max_length = 255] statement_descriptor -> Nullable<Varchar>, enable_payment_link -> Nullable<Bool>, apply_mit_exemption -> Nullable<Bool>, customer_present -> Nullable<Bool>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Nullable<Varchar>, #[max_length = 64] id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] id -> Varchar, #[max_length = 64] merchant_reference_id -> Varchar, #[max_length = 64] connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, incremental_authorization, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, themes, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
11,404
788
hyperswitch
crates/diesel_models/src/organization.rs
.rs
use common_utils::{id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; #[cfg(feature = "v1")] use crate::schema::organization; #[cfg(feature = "v2")] use crate::schema_v2::organization; pub trait OrganizationBridge { fn get_organization_id(&self) -> id_type::OrganizationId; fn get_organization_name(&self) -> Option<String>; fn set_organization_name(&mut self, organization_name: String); } #[cfg(feature = "v1")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(org_id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { org_id: id_type::OrganizationId, org_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, #[allow(dead_code)] id: Option<id_type::OrganizationId>, #[allow(dead_code)] organization_name: Option<String>, pub version: common_enums::ApiVersion, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel( table_name = organization, primary_key(id), check_for_backend(diesel::pg::Pg) )] pub struct Organization { pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, id: id_type::OrganizationId, organization_name: Option<String>, pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { org_id, org_name, organization_details, metadata, created_at, modified_at, id: _, organization_name: _, version, } = org_new; Self { id: Some(org_id.clone()), organization_name: org_name.clone(), org_id, org_name, organization_details, metadata, created_at, modified_at, version, } } } #[cfg(feature = "v2")] impl Organization { pub fn new(org_new: OrganizationNew) -> Self { let OrganizationNew { id, organization_name, organization_details, metadata, created_at, modified_at, version, } = org_new; Self { id, organization_name, organization_details, metadata, created_at, modified_at, version, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(org_id))] pub struct OrganizationNew { org_id: id_type::OrganizationId, org_name: Option<String>, id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(id))] pub struct OrganizationNew { id: id_type::OrganizationId, organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] impl OrganizationNew { pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { Self { org_id: id.clone(), org_name: organization_name.clone(), id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, } } } #[cfg(feature = "v2")] impl OrganizationNew { pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { Self { id, organization_name, organization_details: None, metadata: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), version: common_types::consts::API_VERSION, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { org_name: Option<String>, organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, } pub enum OrganizationUpdate { Update { organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, }, } #[cfg(feature = "v1")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, } => Self { org_name: organization_name.clone(), organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), }, } } } #[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { organization_name, organization_details, metadata, } => Self { organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), }, } } } #[cfg(feature = "v1")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v1")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.org_id.clone() } fn get_organization_name(&self) -> Option<String> { self.org_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.org_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for Organization { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } } #[cfg(feature = "v2")] impl OrganizationBridge for OrganizationNew { fn get_organization_id(&self) -> id_type::OrganizationId { self.id.clone() } fn get_organization_name(&self) -> Option<String> { self.organization_name.clone() } fn set_organization_name(&mut self, organization_name: String) { self.organization_name = Some(organization_name); } }
1,773
789
hyperswitch
crates/diesel_models/src/capture.rs
.rs
use common_utils::types::{ConnectorTransactionId, MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::captures}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))] pub struct Capture { pub capture_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub connector: String, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub tax_amount: Option<MinorUnit>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, // reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, pub processor_capture_data: Option<String>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = captures)] pub struct CaptureNew { pub capture_id: String, pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::CaptureStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub connector: String, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub tax_amount: Option<MinorUnit>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, pub connector_response_reference_id: Option<String>, /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, pub processor_capture_data: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum CaptureUpdate { ResponseUpdate { status: storage_enums::CaptureStatus, connector_capture_id: Option<ConnectorTransactionId>, connector_response_reference_id: Option<String>, processor_capture_data: Option<String>, }, ErrorUpdate { status: storage_enums::CaptureStatus, error_code: Option<String>, error_message: Option<String>, error_reason: Option<String>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = captures)] pub struct CaptureUpdateInternal { pub status: Option<storage_enums::CaptureStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub error_reason: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub connector_capture_id: Option<ConnectorTransactionId>, pub connector_response_reference_id: Option<String>, pub processor_capture_data: Option<String>, } impl CaptureUpdate { pub fn apply_changeset(self, source: Capture) -> Capture { let CaptureUpdateInternal { status, error_message, error_code, error_reason, modified_at: _, connector_capture_id, connector_response_reference_id, processor_capture_data, } = self.into(); Capture { status: status.unwrap_or(source.status), error_message: error_message.or(source.error_message), error_code: error_code.or(source.error_code), error_reason: error_reason.or(source.error_reason), modified_at: common_utils::date_time::now(), connector_capture_id: connector_capture_id.or(source.connector_capture_id), connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), processor_capture_data: processor_capture_data.or(source.processor_capture_data), ..source } } } impl From<CaptureUpdate> for CaptureUpdateInternal { fn from(payment_attempt_child_update: CaptureUpdate) -> Self { let now = Some(common_utils::date_time::now()); match payment_attempt_child_update { CaptureUpdate::ResponseUpdate { status, connector_capture_id: connector_transaction_id, connector_response_reference_id, processor_capture_data, } => Self { status: Some(status), connector_capture_id: connector_transaction_id, modified_at: now, connector_response_reference_id, processor_capture_data, ..Self::default() }, CaptureUpdate::ErrorUpdate { status, error_code, error_message, error_reason, } => Self { status: Some(status), error_code, error_message, error_reason, modified_at: now, ..Self::default() }, } } }
1,196
790
hyperswitch
crates/diesel_models/src/enums.rs
.rs
#[doc(hidden)] pub mod diesel_exports { pub use super::{ DbApiVersion as ApiVersion, DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, DbCardDiscovery as CardDiscovery, DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDeleteStatus as DeleteStatus, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource, DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRelayStatus as RelayStatus, DbRelayType as RelayType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, DbScaExemptionType as ScaExemptionType, DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; use common_utils::pii; use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Jsonb}; use router_derive::diesel_enum; use time::PrimitiveDateTime; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EventObjectType { PaymentDetails, RefundDetails, DisputeDetails, MandateDetails, PayoutDetails, } // Refund #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundType { InstantRefund, #[default] RegularRefund, RetryRefund, } // Mandate #[derive( Clone, Copy, Debug, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum MandateType { SingleUse, #[default] MultiUse, } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } common_utils::impl_to_sql_from_sql_json!(MandateDetails); #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] #[diesel(sql_type = Jsonb)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } common_utils::impl_to_sql_from_sql_json!(MandateDataType); #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: common_utils::types::MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckType { PreFrm, PostFrm, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "text")] #[strum(serialize_all = "snake_case")] pub enum FraudCheckLastStep { #[default] Processing, CheckoutOrSale, TransactionOrRecordRefund, Fulfillment, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserStatus { Active, #[default] InvitationSent, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] #[router_derive::diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DashboardMetadata { ProductionAgreement, SetupProcessor, ConfigureEndpoint, SetupComplete, FirstProcessorConnected, SecondProcessorConnected, ConfiguredRouting, TestPayment, IntegrationMethod, ConfigurationType, IntegrationCompleted, StripeConnected, PaypalConnected, SpRoutingConfigured, Feedback, ProdIntent, SpTestPayment, DownloadWoocom, ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, IsChangePasswordRequired, OnboardingSurvey, ReconStatus, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TotpStatus { Set, InProgress, #[default] NotSet, } #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::EnumString, strum::Display, )] #[diesel_enum(storage_type = "db_enum")] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum UserRoleVersion { #[default] V1, V2, }
1,814
791
hyperswitch
crates/diesel_models/src/kv.rs
.rs
use error_stack::ResultExt; use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use crate::payment_attempt::PaymentAttemptUpdateInternal; #[cfg(feature = "v1")] use crate::payment_intent::PaymentIntentUpdate; #[cfg(feature = "v2")] use crate::payment_intent::PaymentIntentUpdateInternal; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate}, payment_intent::PaymentIntentNew, payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate}, payouts::{Payouts, PayoutsNew, PayoutsUpdate}, refund::{Refund, RefundNew, RefundUpdate}, reverse_lookup::{ReverseLookup, ReverseLookupNew}, Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew, PaymentMethodUpdateInternal, PgPooledConn, }; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "db_op", content = "data")] pub enum DBOperation { Insert { insertable: Box<Insertable> }, Update { updatable: Box<Updateable> }, } impl DBOperation { pub fn operation<'a>(&self) -> &'a str { match self { Self::Insert { .. } => "insert", Self::Update { .. } => "update", } } pub fn table<'a>(&self) -> &'a str { match self { Self::Insert { insertable } => match **insertable { Insertable::PaymentIntent(_) => "payment_intent", Insertable::PaymentAttempt(_) => "payment_attempt", Insertable::Refund(_) => "refund", Insertable::Address(_) => "address", Insertable::Payouts(_) => "payouts", Insertable::PayoutAttempt(_) => "payout_attempt", Insertable::Customer(_) => "customer", Insertable::ReverseLookUp(_) => "reverse_lookup", Insertable::PaymentMethod(_) => "payment_method", Insertable::Mandate(_) => "mandate", }, Self::Update { updatable } => match **updatable { Updateable::PaymentIntentUpdate(_) => "payment_intent", Updateable::PaymentAttemptUpdate(_) => "payment_attempt", Updateable::RefundUpdate(_) => "refund", Updateable::CustomerUpdate(_) => "customer", Updateable::AddressUpdate(_) => "address", Updateable::PayoutsUpdate(_) => "payouts", Updateable::PayoutAttemptUpdate(_) => "payout_attempt", Updateable::PaymentMethodUpdate(_) => "payment_method", Updateable::MandateUpdate(_) => " mandate", }, } } } #[derive(Debug)] pub enum DBResult { PaymentIntent(Box<PaymentIntent>), PaymentAttempt(Box<PaymentAttempt>), Refund(Box<Refund>), Address(Box<Address>), Customer(Box<Customer>), ReverseLookUp(Box<ReverseLookup>), Payouts(Box<Payouts>), PayoutAttempt(Box<PayoutAttempt>), PaymentMethod(Box<PaymentMethod>), Mandate(Box<Mandate>), } #[derive(Debug, Serialize, Deserialize)] pub struct TypedSql { #[serde(flatten)] pub op: DBOperation, } impl DBOperation { pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> { Ok(match self { Self::Insert { insertable } => match *insertable { Insertable::PaymentIntent(a) => { DBResult::PaymentIntent(Box::new(a.insert(conn).await?)) } Insertable::PaymentAttempt(a) => { DBResult::PaymentAttempt(Box::new(a.insert(conn).await?)) } Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)), Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)), Insertable::Customer(cust) => { DBResult::Customer(Box::new(cust.insert(conn).await?)) } Insertable::ReverseLookUp(rev) => { DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?)) } Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)), Insertable::PayoutAttempt(rev) => { DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?)) } Insertable::PaymentMethod(rev) => { DBResult::PaymentMethod(Box::new(rev.insert(conn).await?)) } Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)), }, Self::Update { updatable } => match *updatable { #[cfg(feature = "v1")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v1")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v2")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig .update_with_attempt_id( conn, PaymentAttemptUpdateInternal::from(a.update_data), ) .await?, )), #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(all(feature = "v2", feature = "refunds_v2"))] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?)) } Updateable::AddressUpdate(a) => { DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutsUpdate(a) => { DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig .update_with_payment_method_id(conn, v.update_data) .await?, )), #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig.update_with_id(conn, v.update_data).await?, )), Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new( Mandate::update_by_merchant_id_mandate_id( conn, &m.orig.merchant_id, &m.orig.mandate_id, m.update_data, ) .await?, )), #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_customer_id_merchant_id( conn, cust.orig.customer_id.clone(), cust.orig.merchant_id.clone(), cust.update_data, ) .await?, )), #[cfg(all(feature = "v2", feature = "customer_v2"))] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?, )), }, }) } } impl TypedSql { pub fn to_field_value_pairs( &self, request_id: String, global_id: String, ) -> crate::StorageResult<Vec<(&str, String)>> { let pushed_at = common_utils::date_time::now_unix_timestamp(); Ok(vec![ ( "typed_sql", serde_json::to_string(self) .change_context(errors::DatabaseError::QueryGenerationFailed)?, ), ("global_id", global_id), ("request_id", request_id), ("pushed_at", pushed_at.to_string()), ]) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Insertable { PaymentIntent(Box<PaymentIntentNew>), PaymentAttempt(Box<PaymentAttemptNew>), Refund(RefundNew), Address(Box<AddressNew>), Customer(CustomerNew), ReverseLookUp(ReverseLookupNew), Payouts(PayoutsNew), PayoutAttempt(PayoutAttemptNew), PaymentMethod(PaymentMethodNew), Mandate(MandateNew), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Updateable { PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), RefundUpdate(Box<RefundUpdateMems>), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), PayoutAttemptUpdate(PayoutAttemptUpdateMems), PaymentMethodUpdate(Box<PaymentMethodUpdateMems>), MandateUpdate(MandateUpdateMems), } #[derive(Debug, Serialize, Deserialize)] pub struct CustomerUpdateMems { pub orig: Customer, pub update_data: CustomerUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct AddressUpdateMems { pub orig: Address, pub update_data: AddressUpdateInternal, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct RefundUpdateMems { pub orig: Refund, pub update_data: RefundUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutsUpdateMems { pub orig: Payouts, pub update_data: PayoutsUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutAttemptUpdateMems { pub orig: PayoutAttempt, pub update_data: PayoutAttemptUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentMethodUpdateMems { pub orig: PaymentMethod, pub update_data: PaymentMethodUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct MandateUpdateMems { pub orig: Mandate, pub update_data: MandateUpdateInternal, }
2,575
792
hyperswitch
crates/diesel_models/src/authorization.rs
.rs
use common_utils::types::MinorUnit; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::incremental_authorization}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, )] #[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Authorization { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationNew { pub authorization_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, pub amount: MinorUnit, pub status: storage_enums::AuthorizationStatus, pub error_code: Option<String>, pub error_message: Option<String>, pub connector_authorization_id: Option<String>, pub previously_authorized_amount: MinorUnit, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AuthorizationUpdate { StatusUpdate { status: storage_enums::AuthorizationStatus, error_code: Option<String>, error_message: Option<String>, connector_authorization_id: Option<String>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = incremental_authorization)] pub struct AuthorizationUpdateInternal { pub status: Option<storage_enums::AuthorizationStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: Option<PrimitiveDateTime>, pub connector_authorization_id: Option<String>, } impl AuthorizationUpdateInternal { pub fn create_authorization(self, source: Authorization) -> Authorization { Authorization { status: self.status.unwrap_or(source.status), error_code: self.error_code.or(source.error_code), error_message: self.error_message.or(source.error_message), modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), connector_authorization_id: self .connector_authorization_id .or(source.connector_authorization_id), ..source } } } impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); match authorization_child_update { AuthorizationUpdate::StatusUpdate { status, error_code, error_message, connector_authorization_id, } => Self { status: Some(status), error_code, error_message, connector_authorization_id, modified_at: now, }, } } }
742
793
hyperswitch
crates/diesel_models/src/file.rs
.rs
use common_utils::custom_serde; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::{Deserialize, Serialize}; use crate::schema::file_metadata; #[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)] #[diesel(table_name = file_metadata)] #[serde(deny_unknown_fields)] pub struct FileMetadataNew { pub file_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub file_name: Option<String>, pub file_size: i32, pub file_type: String, pub provider_file_id: Option<String>, pub file_upload_provider: Option<common_enums::FileUploadProvider>, pub available: bool, pub connector_label: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Deserialize, Serialize, Identifiable, Queryable, Selectable)] #[diesel(table_name = file_metadata, primary_key(file_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct FileMetadata { #[serde(skip_serializing)] pub file_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub file_name: Option<String>, pub file_size: i32, pub file_type: String, pub provider_file_id: Option<String>, pub file_upload_provider: Option<common_enums::FileUploadProvider>, pub available: bool, #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, pub connector_label: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug)] pub enum FileMetadataUpdate { Update { provider_file_id: Option<String>, file_upload_provider: Option<common_enums::FileUploadProvider>, available: bool, profile_id: Option<common_utils::id_type::ProfileId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } #[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = file_metadata)] pub struct FileMetadataUpdateInternal { provider_file_id: Option<String>, file_upload_provider: Option<common_enums::FileUploadProvider>, available: bool, profile_id: Option<common_utils::id_type::ProfileId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } impl From<FileMetadataUpdate> for FileMetadataUpdateInternal { fn from(merchant_account_update: FileMetadataUpdate) -> Self { match merchant_account_update { FileMetadataUpdate::Update { provider_file_id, file_upload_provider, available, profile_id, merchant_connector_id, } => Self { provider_file_id, file_upload_provider, available, profile_id, merchant_connector_id, }, } } }
676
794
hyperswitch
crates/diesel_models/src/authentication.rs
.rs
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use serde_json; use crate::schema::authentication; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))] pub struct Authentication { pub authentication_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: String, pub connector_authentication_id: Option<String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, } impl Authentication { pub fn is_separate_authn_required(&self) -> bool { self.maximum_supported_version .as_ref() .is_some_and(|version| version.get_major() == 2) } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)] #[diesel(table_name = authentication)] pub struct AuthenticationNew { pub authentication_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: String, pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, } #[derive(Debug)] pub enum AuthenticationUpdate { PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version: common_utils::types::SemanticVersion, message_version: common_utils::types::SemanticVersion, }, PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, connector_metadata: Option<serde_json::Value>, }, PreAuthenticationUpdate { threeds_server_transaction_id: String, maximum_supported_3ds_version: common_utils::types::SemanticVersion, connector_authentication_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, message_version: common_utils::types::SemanticVersion, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, directory_server_id: Option<String>, acquirer_country_code: Option<String>, }, AuthenticationUpdate { authentication_value: Option<String>, trans_status: common_enums::TransactionStatus, authentication_type: common_enums::DecoupledAuthenticationType, acs_url: Option<String>, challenge_request: Option<String>, acs_reference_number: Option<String>, acs_trans_id: Option<String>, acs_signed_content: Option<String>, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, ds_trans_id: Option<String>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, authentication_value: Option<String>, eci: Option<String>, authentication_status: common_enums::AuthenticationStatus, }, ErrorUpdate { error_message: Option<String>, error_code: Option<String>, authentication_status: common_enums::AuthenticationStatus, connector_authentication_id: Option<String>, }, PostAuthorizationUpdate { authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, }, AuthenticationStatusUpdate { trans_status: common_enums::TransactionStatus, authentication_status: common_enums::AuthenticationStatus, }, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)] #[diesel(table_name = authentication)] pub struct AuthenticationUpdateInternal { pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: Option<common_enums::AuthenticationStatus>, pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>, pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, } impl Default for AuthenticationUpdateInternal { fn default() -> Self { Self { connector_authentication_id: Default::default(), payment_method_id: Default::default(), authentication_type: Default::default(), authentication_status: Default::default(), authentication_lifecycle_status: Default::default(), modified_at: common_utils::date_time::now(), error_message: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), maximum_supported_version: Default::default(), threeds_server_transaction_id: Default::default(), cavv: Default::default(), authentication_flow_type: Default::default(), message_version: Default::default(), eci: Default::default(), trans_status: Default::default(), acquirer_bin: Default::default(), acquirer_merchant_id: Default::default(), three_ds_method_data: Default::default(), three_ds_method_url: Default::default(), acs_url: Default::default(), challenge_request: Default::default(), acs_reference_number: Default::default(), acs_trans_id: Default::default(), acs_signed_content: Default::default(), ds_trans_id: Default::default(), directory_server_id: Default::default(), acquirer_country_code: Default::default(), service_details: Default::default(), } } } impl AuthenticationUpdateInternal { pub fn apply_changeset(self, source: Authentication) -> Authentication { let Self { connector_authentication_id, payment_method_id, authentication_type, authentication_status, authentication_lifecycle_status, modified_at: _, error_code, error_message, connector_metadata, maximum_supported_version, threeds_server_transaction_id, cavv, authentication_flow_type, message_version, eci, trans_status, acquirer_bin, acquirer_merchant_id, three_ds_method_data, three_ds_method_url, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, ds_trans_id, directory_server_id, acquirer_country_code, service_details, } = self; Authentication { connector_authentication_id: connector_authentication_id .or(source.connector_authentication_id), payment_method_id: payment_method_id.unwrap_or(source.payment_method_id), authentication_type: authentication_type.or(source.authentication_type), authentication_status: authentication_status.unwrap_or(source.authentication_status), authentication_lifecycle_status: authentication_lifecycle_status .unwrap_or(source.authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_code: error_code.or(source.error_code), error_message: error_message.or(source.error_message), connector_metadata: connector_metadata.or(source.connector_metadata), maximum_supported_version: maximum_supported_version .or(source.maximum_supported_version), threeds_server_transaction_id: threeds_server_transaction_id .or(source.threeds_server_transaction_id), cavv: cavv.or(source.cavv), authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type), message_version: message_version.or(source.message_version), eci: eci.or(source.eci), trans_status: trans_status.or(source.trans_status), acquirer_bin: acquirer_bin.or(source.acquirer_bin), acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id), three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data), three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url), acs_url: acs_url.or(source.acs_url), challenge_request: challenge_request.or(source.challenge_request), acs_reference_number: acs_reference_number.or(source.acs_reference_number), acs_trans_id: acs_trans_id.or(source.acs_trans_id), acs_signed_content: acs_signed_content.or(source.acs_signed_content), ds_trans_id: ds_trans_id.or(source.ds_trans_id), directory_server_id: directory_server_id.or(source.directory_server_id), acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code), service_details: service_details.or(source.service_details), ..source } } } impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { fn from(auth_update: AuthenticationUpdate) -> Self { match auth_update { AuthenticationUpdate::ErrorUpdate { error_message, error_code, authentication_status, connector_authentication_id, } => Self { error_code, error_message, authentication_status: Some(authentication_status), connector_authentication_id, authentication_type: None, authentication_lifecycle_status: None, modified_at: common_utils::date_time::now(), payment_method_id: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PostAuthorizationUpdate { authentication_lifecycle_status, } => Self { connector_authentication_id: None, payment_method_id: None, authentication_type: None, authentication_status: None, authentication_lifecycle_status: Some(authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_message: None, error_code: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PreAuthenticationUpdate { threeds_server_transaction_id, maximum_supported_3ds_version, connector_authentication_id, three_ds_method_data, three_ds_method_url, message_version, connector_metadata, authentication_status, acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), maximum_supported_version: Some(maximum_supported_3ds_version), connector_authentication_id: Some(connector_authentication_id), three_ds_method_data, three_ds_method_url, message_version: Some(message_version), connector_metadata, authentication_status: Some(authentication_status), acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, ..Default::default() }, AuthenticationUpdate::AuthenticationUpdate { authentication_value, trans_status, authentication_type, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status, ds_trans_id, } => Self { cavv: authentication_value, trans_status: Some(trans_status), authentication_type: Some(authentication_type), acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status: Some(authentication_status), ds_trans_id, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, authentication_value, eci, authentication_status, } => Self { trans_status: Some(trans_status), cavv: authentication_value, eci, authentication_status: Some(authentication_status), ..Default::default() }, AuthenticationUpdate::PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version, message_version, } => Self { maximum_supported_version: Some(maximum_supported_3ds_version), message_version: Some(message_version), ..Default::default() }, AuthenticationUpdate::PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id, three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, ..Default::default() }, AuthenticationUpdate::AuthenticationStatusUpdate { trans_status, authentication_status, } => Self { trans_status: Some(trans_status), authentication_status: Some(authentication_status), ..Default::default() }, } } }
3,598
795
hyperswitch
crates/diesel_models/src/unified_translations.rs
.rs
//! Translations use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::schema::unified_translations; #[derive(Clone, Debug, Queryable, Selectable, Identifiable)] #[diesel(table_name = unified_translations, primary_key(unified_code, unified_message, locale), check_for_backend(diesel::pg::Pg))] pub struct UnifiedTranslations { pub unified_code: String, pub unified_message: String, pub locale: String, pub translation: String, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, Insertable)] #[diesel(table_name = unified_translations)] pub struct UnifiedTranslationsNew { pub unified_code: String, pub unified_message: String, pub locale: String, pub translation: String, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, } #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = unified_translations)] pub struct UnifiedTranslationsUpdateInternal { pub translation: Option<String>, pub last_modified_at: PrimitiveDateTime, } #[derive(Debug)] pub struct UnifiedTranslationsUpdate { pub translation: Option<String>, } impl From<UnifiedTranslationsUpdate> for UnifiedTranslationsUpdateInternal { fn from(value: UnifiedTranslationsUpdate) -> Self { let now = common_utils::date_time::now(); let UnifiedTranslationsUpdate { translation } = value; Self { translation, last_modified_at: now, } } }
331
796
hyperswitch
crates/diesel_models/src/schema.rs
.rs
// @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Varchar, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (merchant_id, fingerprint) { #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (profile_id) { #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, routing_algorithm -> Nullable<Json>, intent_fulfillment_time -> Nullable<Int8>, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, #[max_length = 512] connector_capture_data -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (customer_id, merchant_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (card_id) { #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (merchant_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 255] return_url -> Nullable<Varchar>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, webhook_details -> Nullable<Json>, sub_merchants_enabled -> Nullable<Bool>, #[max_length = 64] parent_merchant_id -> Nullable<Varchar>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, #[max_length = 64] locker_id -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, primary_business_details -> Json, intent_fulfillment_time -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, is_recon_enabled -> Bool, #[max_length = 64] default_profile -> Nullable<Varchar>, recon_status -> ReconStatus, payment_link_config -> Nullable<Jsonb>, pm_collect_link_config -> Nullable<Jsonb>, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Nullable<Varchar>, #[max_length = 64] product_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (merchant_connector_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, test_mode -> Nullable<Bool>, disabled -> Nullable<Bool>, #[max_length = 128] merchant_connector_id -> Varchar, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 255] business_label -> Nullable<Varchar>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, frm_configs -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (org_id) { #[max_length = 32] org_id -> Varchar, org_name -> Nullable<Text>, organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Nullable<Varchar>, organization_name -> Nullable<Text>, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, status -> AttemptStatus, amount -> Int8, currency -> Nullable<Currency>, save_to_locker -> Nullable<Bool>, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, offer_amount -> Nullable<Int8>, surcharge_amount -> Nullable<Int8>, tax_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, payment_method -> Nullable<Varchar>, #[max_length = 128] connector_transaction_id -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, capture_on -> Nullable<Timestamp>, confirm -> Bool, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, #[max_length = 64] mandate_id -> Nullable<Varchar>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, straight_through_algorithm -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, mandate_details -> Nullable<Jsonb>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, authentication_data -> Nullable<Json>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, mandate_data -> Nullable<Jsonb>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_billing_address_id -> Nullable<Varchar>, #[max_length = 64] charge_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, connector_mandate_detail -> Nullable<Jsonb>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (payment_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, #[max_length = 64] connector_id -> Nullable<Varchar>, #[max_length = 64] shipping_address_id -> Nullable<Varchar>, #[max_length = 64] billing_address_id -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_name -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_suffix -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, off_session -> Nullable<Bool>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 64] active_attempt_id -> Varchar, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] merchant_decision -> Nullable<Varchar>, #[max_length = 255] payment_link_id -> Nullable<Varchar>, payment_confirm_source -> Nullable<PaymentSource>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, incremental_authorization_allowed -> Nullable<Bool>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, request_external_three_ds_authentication -> Nullable<Bool>, charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, billing_details -> Nullable<Bytea>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, shipping_details -> Nullable<Bytea>, is_payment_processor_token_flow -> Nullable<Bool>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (payment_method_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, accepted_currency -> Nullable<Array<Nullable<Currency>>>, #[max_length = 32] scheme -> Nullable<Varchar>, #[max_length = 128] token -> Nullable<Varchar>, #[max_length = 255] cardholder_name -> Nullable<Varchar>, #[max_length = 64] issuer_name -> Nullable<Varchar>, #[max_length = 64] issuer_country -> Nullable<Varchar>, payer_country -> Nullable<Array<Nullable<Text>>>, is_stored -> Nullable<Bool>, #[max_length = 32] swift_code -> Nullable<Varchar>, #[max_length = 128] direct_debit_token -> Nullable<Varchar>, created_at -> Timestamp, last_modified -> Timestamp, payment_method -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 128] payment_method_issuer -> Nullable<Varchar>, payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (merchant_id, refund_id) { #[max_length = 64] internal_reference_id -> Varchar, #[max_length = 64] refund_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 512] connector_refund_data -> Nullable<Varchar>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, incremental_authorization, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, themes, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
12,084
797
hyperswitch
crates/diesel_models/src/api_keys.rs
.rs
use diesel::{AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::schema::api_keys; #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, Identifiable, Queryable, Selectable, )] #[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))] pub struct ApiKey { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, pub hashed_api_key: HashedApiKey, pub prefix: String, pub created_at: PrimitiveDateTime, pub expires_at: Option<PrimitiveDateTime>, pub last_used: Option<PrimitiveDateTime>, } #[derive(Debug, Insertable)] #[diesel(table_name = api_keys)] pub struct ApiKeyNew { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub name: String, pub description: Option<String>, pub hashed_api_key: HashedApiKey, pub prefix: String, pub created_at: PrimitiveDateTime, pub expires_at: Option<PrimitiveDateTime>, pub last_used: Option<PrimitiveDateTime>, } #[derive(Debug)] pub enum ApiKeyUpdate { Update { name: Option<String>, description: Option<String>, expires_at: Option<Option<PrimitiveDateTime>>, last_used: Option<PrimitiveDateTime>, }, LastUsedUpdate { last_used: PrimitiveDateTime, }, } #[derive(Debug, AsChangeset)] #[diesel(table_name = api_keys)] pub(crate) struct ApiKeyUpdateInternal { pub name: Option<String>, pub description: Option<String>, pub expires_at: Option<Option<PrimitiveDateTime>>, pub last_used: Option<PrimitiveDateTime>, } impl From<ApiKeyUpdate> for ApiKeyUpdateInternal { fn from(api_key_update: ApiKeyUpdate) -> Self { match api_key_update { ApiKeyUpdate::Update { name, description, expires_at, last_used, } => Self { name, description, expires_at, last_used, }, ApiKeyUpdate::LastUsedUpdate { last_used } => Self { last_used: Some(last_used), name: None, description: None, expires_at: None, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Text)] pub struct HashedApiKey(String); impl HashedApiKey { pub fn into_inner(self) -> String { self.0 } } impl From<String> for HashedApiKey { fn from(hashed_api_key: String) -> Self { Self(hashed_api_key) } } mod diesel_impl { use diesel::{ backend::Backend, deserialize::FromSql, serialize::{Output, ToSql}, sql_types::Text, Queryable, }; impl<DB> ToSql<Text, DB> for super::HashedApiKey where DB: Backend, String: ToSql<Text, DB>, { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { self.0.to_sql(out) } } impl<DB> FromSql<Text, DB> for super::HashedApiKey where DB: Backend, String: FromSql<Text, DB>, { fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { Ok(Self(String::from_sql(bytes)?)) } } impl<DB> Queryable<Text, DB> for super::HashedApiKey where DB: Backend, Self: FromSql<Text, DB>, { type Row = Self; fn build(row: Self::Row) -> diesel::deserialize::Result<Self> { Ok(row) } } } // Tracking data by process_tracker #[derive(Default, Debug, Deserialize, Serialize, Clone)] pub struct ApiKeyExpiryTrackingData { pub key_id: common_utils::id_type::ApiKeyId, pub merchant_id: common_utils::id_type::MerchantId, pub api_key_name: String, pub prefix: String, pub api_key_expiry: Option<PrimitiveDateTime>, // Days on which email reminder about api_key expiry has to be sent, prior to it's expiry. pub expiry_reminder_days: Vec<u8>, }
1,006
798
hyperswitch
crates/diesel_models/src/relay.rs
.rs
use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::relay}; #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = relay)] pub struct Relay { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = relay)] pub struct RelayNew { pub id: common_utils::id_type::RelayId, pub connector_resource_id: String, pub connector_id: common_utils::id_type::MerchantConnectorAccountId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub relay_type: storage_enums::RelayType, pub request_data: Option<pii::SecretSerdeValue>, pub status: storage_enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = relay)] pub struct RelayUpdateInternal { pub connector_reference_id: Option<String>, pub status: Option<storage_enums::RelayStatus>, pub error_code: Option<String>, pub error_message: Option<String>, pub modified_at: PrimitiveDateTime, }
629
799
hyperswitch
crates/diesel_models/src/user.rs
.rs
use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users}; pub mod dashboard_metadata; pub mod sample_data; pub mod theme; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] #[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct User { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)] pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, } #[derive( router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, )] #[diesel(table_name = users)] pub struct UserNew { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, pub totp_status: TotpStatus, pub totp_secret: Option<Encryption>, pub totp_recovery_codes: Option<Vec<Secret<String>>>, pub last_password_modified_at: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = users)] pub struct UserUpdateInternal { name: Option<String>, password: Option<Secret<String>>, is_verified: Option<bool>, last_modified_at: PrimitiveDateTime, totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, last_password_modified_at: Option<PrimitiveDateTime>, } #[derive(Debug)] pub enum UserUpdate { VerifyUser, AccountUpdate { name: Option<String>, is_verified: Option<bool>, }, TotpUpdate { totp_status: Option<TotpStatus>, totp_secret: Option<Encryption>, totp_recovery_codes: Option<Vec<Secret<String>>>, }, PasswordUpdate { password: Secret<String>, }, } impl From<UserUpdate> for UserUpdateInternal { fn from(user_update: UserUpdate) -> Self { let last_modified_at = common_utils::date_time::now(); match user_update { UserUpdate::VerifyUser => Self { name: None, password: None, is_verified: Some(true), last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, }, UserUpdate::AccountUpdate { name, is_verified } => Self { name, password: None, is_verified, last_modified_at, totp_status: None, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: None, }, UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => Self { name: None, password: None, is_verified: None, last_modified_at, totp_status, totp_secret, totp_recovery_codes, last_password_modified_at: None, }, UserUpdate::PasswordUpdate { password } => Self { name: None, password: Some(password), is_verified: None, last_modified_at, last_password_modified_at: Some(last_modified_at), totp_status: None, totp_secret: None, totp_recovery_codes: None, }, } } }
891
800
hyperswitch
crates/diesel_models/src/address.rs
.rs
use common_utils::{crypto, encryption::Encryption}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums, schema::address}; #[derive(Clone, Debug, Insertable, Serialize, Deserialize, router_derive::DebugAsDisplay)] #[diesel(table_name = address)] pub struct AddressNew { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, } #[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)] #[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub updated_by: String, pub email: Option<Encryption>, } #[derive(Clone)] // Intermediate struct to convert HashMap to Address pub struct EncryptableAddress { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = address)] pub struct AddressUpdateInternal { pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, pub line1: Option<Encryption>, pub line2: Option<Encryption>, pub line3: Option<Encryption>, pub state: Option<Encryption>, pub zip: Option<Encryption>, pub first_name: Option<Encryption>, pub last_name: Option<Encryption>, pub phone_number: Option<Encryption>, pub country_code: Option<String>, pub modified_at: PrimitiveDateTime, pub updated_by: String, pub email: Option<Encryption>, } impl AddressUpdateInternal { pub fn create_address(self, source: Address) -> Address { Address { city: self.city, country: self.country, line1: self.line1, line2: self.line2, line3: self.line3, state: self.state, zip: self.zip, first_name: self.first_name, last_name: self.last_name, phone_number: self.phone_number, country_code: self.country_code, modified_at: self.modified_at, updated_by: self.updated_by, ..source } } }
910
801
hyperswitch
crates/diesel_models/src/callback_mapper.rs
.rs
use common_utils::pii; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, pub type_: String, pub data: pii::SecretSerdeValue, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, }
127
802
hyperswitch
crates/diesel_models/src/locker_mock_up.rs
.rs
use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::locker_mock_up; #[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)] #[diesel(table_name = locker_mock_up, primary_key(card_id), check_for_backend(diesel::pg::Pg))] pub struct LockerMockUp { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub duplicate: Option<bool>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub enc_card_data: Option<String>, } #[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = locker_mock_up)] pub struct LockerMockUpNew { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub nickname: Option<String>, pub enc_card_data: Option<String>, }
371
803
hyperswitch
crates/diesel_models/src/routing_algorithm.rs
.rs
use common_utils::id_type; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use crate::{enums, schema::routing_algorithm}; #[derive(Clone, Debug, Identifiable, Insertable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = routing_algorithm, primary_key(algorithm_id), check_for_backend(diesel::pg::Pg))] pub struct RoutingAlgorithm { pub algorithm_id: id_type::RoutingId, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub algorithm_data: serde_json::Value, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } pub struct RoutingAlgorithmMetadata { pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, } pub struct RoutingProfileMetadata { pub profile_id: id_type::ProfileId, pub algorithm_id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub kind: enums::RoutingAlgorithmKind, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub algorithm_for: enums::TransactionType, }
341
804