Bug: [BUG] [AUTHORIZEDOTNET] Connector Audit



### Bug Description

Authorizedotnet Connector Audit fixes.
1. Production endpoint is wrong
2. Connector Transaction ID is not passed in 2XX Error Response
3. Default case handling in code

### Expected Behavior

Authorizedotnet Connector Audit fixes.
1. Production endpoint should be https://api.authorize.net/xml/v1/request.api.
2. Connector Transaction ID should be passed to 2XX Error Response.
3. Default case handling should not be present in code.

### Actual Behavior

Authorizedotnet Connector Audit fixes.
1. Production endpoint is wrong
2. Connector Transaction ID is not passed in 2XX Error Response
3. Default case handling in code

### Steps To Reproduce

Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'


### Context For The Bug

_No response_

### Environment

Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.

If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``


### Have you spent some time checking if this bug has been raised before?

- [X] I checked and didn't find a similar issue

### Have you read the Contributing Guidelines?

- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)

### Are you willing to submit a PR?

Yes, I am willing to submit a PR!
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 892f11e9415..6bfcad3ad50 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -21,7 +21,7 @@ adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpaymen
 adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/"
 airwallex.base_url = "https://api-demo.airwallex.com/"
 applepay.base_url = "https://apple-pay-gateway.apple.com/"
-authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
+authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api"
 bambora.base_url = "https://api.na.bambora.com"
 bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/"
 bitpay.base_url = "https://bitpay.com"
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 0aba48fa5e5..be02b4524f8 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -685,8 +685,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
         let intermediate_response =
             bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
 
-        let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response
-            .parse_struct("AuthorizedotnetSyncResponse")
+        let response: authorizedotnet::AuthorizedotnetRSyncResponse = intermediate_response
+            .parse_struct("AuthorizedotnetRSyncResponse")
             .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
         event_builder.map(|i| i.set_response_body(&response));
         router_env::logger::info!(connector_response=?response);
@@ -872,11 +872,17 @@ impl api::IncomingWebhook for Authorizedotnet {
                     ),
                 ))
             }
-            _ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
-                api_models::payments::PaymentIdType::ConnectorTransactionId(
-                    authorizedotnet::get_trans_id(&details)?,
-                ),
-            )),
+            authorizedotnet::AuthorizedotnetWebhookEvent::AuthorizationCreated
+            | authorizedotnet::AuthorizedotnetWebhookEvent::PriorAuthCapture
+            | authorizedotnet::AuthorizedotnetWebhookEvent::AuthCapCreated
+            | authorizedotnet::AuthorizedotnetWebhookEvent::CaptureCreated
+            | authorizedotnet::AuthorizedotnetWebhookEvent::VoidCreated => {
+                Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+                    api_models::payments::PaymentIdType::ConnectorTransactionId(
+                        authorizedotnet::get_trans_id(&details)?,
+                    ),
+                ))
+            }
         }
     }
 
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 5d3a7d0054f..4a79b179b84 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -190,44 +190,48 @@ fn get_pm_and_subsequent_auth_detail(
                 }
             }
         }
-        _ => match item.router_data.request.payment_method_data {
-            api::PaymentMethodData::Card(ref ccard) => {
-                Ok((
-                    PaymentDetails::CreditCard(CreditCardDetails {
-                        card_number: (*ccard.card_number).clone(),
-                        // expiration_date: format!("{expiry_year}-{expiry_month}").into(),
-                        expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
-                        card_code: Some(ccard.card_cvc.clone()),
-                    }),
-                    Some(ProcessingOptions {
-                        is_subsequent_auth: true,
-                    }),
+        Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
+            match item.router_data.request.payment_method_data {
+                api::PaymentMethodData::Card(ref ccard) => {
+                    Ok((
+                        PaymentDetails::CreditCard(CreditCardDetails {
+                            card_number: (*ccard.card_number).clone(),
+                            // expiration_date: format!("{expiry_year}-{expiry_month}").into(),
+                            expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+                            card_code: Some(ccard.card_cvc.clone()),
+                        }),
+                        Some(ProcessingOptions {
+                            is_subsequent_auth: true,
+                        }),
+                        None,
+                    ))
+                }
+                api::PaymentMethodData::Wallet(ref wallet_data) => Ok((
+                    get_wallet_data(
+                        wallet_data,
+                        &item.router_data.request.complete_authorize_url,
+                    )?,
+                    None,
                     None,
-                ))
+                )),
+                api::PaymentMethodData::CardRedirect(_)
+                | api::PaymentMethodData::PayLater(_)
+                | api::PaymentMethodData::BankRedirect(_)
+                | api::PaymentMethodData::BankDebit(_)
+                | api::PaymentMethodData::BankTransfer(_)
+                | api::PaymentMethodData::Crypto(_)
+                | api::PaymentMethodData::MandatePayment
+                | api::PaymentMethodData::Reward
+                | api::PaymentMethodData::Upi(_)
+                | api::PaymentMethodData::Voucher(_)
+                | api::PaymentMethodData::GiftCard(_)
+                | api::PaymentMethodData::CardToken(_) => {
+                    Err(errors::ConnectorError::NotImplemented(
+                        utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
+                    ))?
+                }
             }
-            api::PaymentMethodData::Wallet(ref wallet_data) => Ok((
-                get_wallet_data(
-                    wallet_data,
-                    &item.router_data.request.complete_authorize_url,
-                )?,
-                None,
-                None,
-            )),
-            api::PaymentMethodData::CardRedirect(_)
-            | api::PaymentMethodData::PayLater(_)
-            | api::PaymentMethodData::BankRedirect(_)
-            | api::PaymentMethodData::BankDebit(_)
-            | api::PaymentMethodData::BankTransfer(_)
-            | api::PaymentMethodData::Crypto(_)
-            | api::PaymentMethodData::MandatePayment
-            | api::PaymentMethodData::Reward
-            | api::PaymentMethodData::Upi(_)
-            | api::PaymentMethodData::Voucher(_)
-            | api::PaymentMethodData::GiftCard(_)
-            | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
-                utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
-            ))?,
-        },
+        }
     }
 }
 
@@ -382,7 +386,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
                 country: address.country,
             });
         let transaction_request = TransactionRequest {
-            transaction_type: TransactionType::from(item.router_data.request.capture_method),
+            transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
             amount: item.amount,
             currency_code: item.router_data.request.currency.to_string(),
             payment: payment_details,
@@ -662,7 +666,7 @@ impl<F, T>
                         reason: None,
                         status_code: item.http_code,
                         attempt_status: None,
-                        connector_transaction_id: None,
+                        connector_transaction_id: Some(transaction_response.transaction_id.clone()),
                     })
                 });
                 let metadata = transaction_response
@@ -740,7 +744,7 @@ impl<F, T>
                         reason: None,
                         status_code: item.http_code,
                         attempt_status: None,
-                        connector_transaction_id: None,
+                        connector_transaction_id: Some(transaction_response.transaction_id.clone()),
                     })
                 });
                 let metadata = transaction_response
@@ -886,7 +890,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundRespons
                 reason: None,
                 status_code: item.http_code,
                 attempt_status: None,
-                connector_transaction_id: None,
+                connector_transaction_id: Some(transaction_response.transaction_id.clone()),
             })
         });
 
@@ -976,6 +980,15 @@ pub enum SyncStatus {
     FDSPendingReview,
 }
 
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RSyncStatus {
+    RefundSettledSuccessfully,
+    RefundPendingSettlement,
+    Declined,
+    GeneralError,
+}
+
 #[derive(Debug, Deserialize, Serialize)]
 #[serde(rename_all = "camelCase")]
 pub struct SyncTransactionResponse {
@@ -990,14 +1003,18 @@ pub struct AuthorizedotnetSyncResponse {
     messages: ResponseMessages,
 }
 
-impl From<SyncStatus> for enums::RefundStatus {
-    fn from(transaction_status: SyncStatus) -> Self {
-        match transaction_status {
-            SyncStatus::RefundSettledSuccessfully => Self::Success,
-            SyncStatus::RefundPendingSettlement => Self::Pending,
-            _ => Self::Failure,
-        }
-    }
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RSyncTransactionResponse {
+    #[serde(rename = "transId")]
+    transaction_id: String,
+    transaction_status: RSyncStatus,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct AuthorizedotnetRSyncResponse {
+    transaction: Option<RSyncTransactionResponse>,
+    messages: ResponseMessages,
 }
 
 impl From<SyncStatus> for enums::AttemptStatus {
@@ -1017,13 +1034,23 @@ impl From<SyncStatus> for enums::AttemptStatus {
     }
 }
 
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>>
+impl From<RSyncStatus> for enums::RefundStatus {
+    fn from(transaction_status: RSyncStatus) -> Self {
+        match transaction_status {
+            RSyncStatus::RefundSettledSuccessfully => Self::Success,
+            RSyncStatus::RefundPendingSettlement => Self::Pending,
+            RSyncStatus::Declined | RSyncStatus::GeneralError => Self::Failure,
+        }
+    }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>>
     for types::RefundsRouterData<api::RSync>
 {
     type Error = error_stack::Report<errors::ConnectorError>;
 
     fn try_from(
-        item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>,
+        item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>,
     ) -> Result<Self, Self::Error> {
         match item.response.transaction {
             Some(transaction) => {
@@ -1108,11 +1135,24 @@ fn construct_refund_payment_details(masked_number: String) -> PaymentDetails {
     })
 }
 
-impl From<Option<enums::CaptureMethod>> for TransactionType {
-    fn from(capture_method: Option<enums::CaptureMethod>) -> Self {
+impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
+    type Error = error_stack::Report<errors::ConnectorError>;
+    fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> {
         match capture_method {
-            Some(enums::CaptureMethod::Manual) => Self::Authorization,
-            _ => Self::Payment,
+            Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization),
+            Some(enums::CaptureMethod::Automatic) | None => Ok(Self::Payment),
+            Some(enums::CaptureMethod::ManualMultiple) => {
+                Err(utils::construct_not_supported_error_report(
+                    enums::CaptureMethod::ManualMultiple,
+                    "authorizedotnet",
+                ))?
+            }
+            Some(enums::CaptureMethod::Scheduled) => {
+                Err(utils::construct_not_supported_error_report(
+                    enums::CaptureMethod::Scheduled,
+                    "authorizedotnet",
+                ))?
+            }
         }
     }
 }
@@ -1359,9 +1399,19 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterD
                 .change_context(errors::ConnectorError::ResponseDeserializationFailed)?
                 .payer_id;
         let transaction_type = match item.router_data.request.capture_method {
-            Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization,
-            _ => TransactionType::ContinueCapture,
-        };
+            Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization),
+            Some(enums::CaptureMethod::Automatic) | None => Ok(TransactionType::ContinueCapture),
+            Some(enums::CaptureMethod::ManualMultiple) => {
+                Err(errors::ConnectorError::NotSupported {
+                    message: enums::CaptureMethod::ManualMultiple.to_string(),
+                    connector: "authorizedotnet",
+                })
+            }
+            Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported {
+                message: enums::CaptureMethod::Scheduled.to_string(),
+                connector: "authorizedotnet",
+            }),
+        }?;
         let transaction_request = TransactionConfirmRequest {
             transaction_type,
             payment: PaypalPaymentConfirm {

## Type of Change
<!-- Put an `x` in the boxes that apply -->

- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD

## Description
<!-- Describe your changes in detail -->
Authorizedotnet Connector Audit fixes:

1. Production endpoint fixed.
2. Connector Transaction ID added to 2XX Error Response
3. Default case handling removed

### Additional Changes

- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables

<!--
Provide links to the files with corresponding changes.

Following are the paths where you can find config files:
1. `config`
4. `crates/router/src/configs`
5. `loadtest/config`
-->


## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.

If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4036

## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Testing needs to be done by creating a 2XX error for a payment via authorizedotnet.
2XX error can be generated by doing 2 back to back transactions with same request body which will trigger a dupliacte transaction error at connector end.
Request: 
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_5WytrFNU7ci62yt6DYvmVVcyVdMG6s92tlbiS9vWLsWgdud2qIDqvPhvfquNza5X' \
--data '{
    "amount": 1234,
    "currency": "USD",
    "confirm": true,
    "capture_method": "automatic",
    "customer_id": "StripeCustomer",
    "payment_method": "card",
    "payment_method_type": "credit",
    "payment_method_data": {
        "card": {
            "card_number": "5424000000000015",
            "card_exp_month": "02",
            "card_exp_year": "35",
            "card_holder_name": "John Doe",
            "card_cvc": "123"
        }
    },
    "billing": {
        "address": {
            "first_name": "John",
            "last_name": "Doe",
            "line1": "Harrison Street",
            "city": "San Francisco",
            "state": "California",
            "zip": "94016",
            "country": "US"
        }
    },
    "setup_future_usage": "on_session"
}'
```
Failure Response:
```json
{
    "payment_id": "pay_2LFVZlFX0KHdneXkkZSp",
    "merchant_id": "merchant_1709720492",
    "status": "failed",
    "amount": 1234,
    "net_amount": 1234,
    "amount_capturable": 0,
    "amount_received": null,
    "connector": "authorizedotnet",
    "client_secret": "pay_2LFVZlFX0KHdneXkkZSp_secret_34pXGRBkphSF4qARev7i",
    "created": "2024-03-11T13:54:27.251Z",
    "currency": "USD",
    "customer_id": "StripeCustomer",
    "description": null,
    "refunds": null,
    "disputes": null,
    "mandate_id": null,
    "mandate_data": null,
    "setup_future_usage": "on_session",
    "off_session": null,
    "capture_on": null,
    "capture_method": "automatic",
    "payment_method": "card",
    "payment_method_data": {
        "card": {
            "last4": "0015",
            "card_type": null,
            "card_network": null,
            "card_issuer": null,
            "card_issuing_country": null,
            "card_isin": "542400",
            "card_extended_bin": "54240000",
            "card_exp_month": "02",
            "card_exp_year": "35",
            "card_holder_name": "John Doe"
        },
        "billing": null
    },
    "payment_token": null,
    "shipping": null,
    "billing": {
        "address": {
            "city": "San Francisco",
            "country": "US",
            "line1": "Harrison Street",
            "line2": null,
            "line3": null,
            "zip": "94016",
            "state": "California",
            "first_name": "John",
            "last_name": "Doe"
        },
        "phone": {
            "number": null,
            "country_code": null
        },
        "email": null
    },
    "order_details": null,
    "email": null,
    "name": null,
    "phone": null,
    "return_url": null,
    "authentication_type": "no_three_ds",
    "statement_descriptor_name": null,
    "statement_descriptor_suffix": null,
    "next_action": null,
    "cancellation_reason": null,
    "error_code": "11",
    "error_message": "A duplicate transaction has been submitted.",
    "unified_code": null,
    "unified_message": null,
    "payment_experience": null,
    "payment_method_type": "credit",
    "connector_label": null,
    "business_country": null,
    "business_label": "default",
    "business_sub_label": null,
    "allowed_payment_method_types": null,
    "ephemeral_key": {
        "customer_id": "StripeCustomer",
        "created_at": 1710165267,
        "expires": 1710168867,
        "secret": "epk_e39c6817cc0c4abdb7cb8081cf601417"
    },
    "manual_retry_allowed": true,
    "connector_transaction_id": "0",
    "frm_message": null,
    "metadata": null,
    "connector_metadata": null,
    "feature_metadata": null,
    "reference_id": null,
    "payment_link": null,
    "profile_id": "pro_4aXJeUeyy9BzdhcV9Xue",
    "surcharge_details": null,
    "attempt_count": 1,
    "merchant_decision": null,
    "merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D",
    "incremental_authorization_allowed": false,
    "authorization_count": null,
    "incremental_authorizations": null,
    "external_authentication_details": null,
    "request_external_3ds_authentication": null,
    "expires_on": "2024-03-11T14:09:27.251Z",
    "fingerprint": null,
    "payment_method_id": null,
    "payment_method_status": null
}
```

Now check in DB whether connector_transaction_id is getting populated for the failure scenario:
<img width="435" alt="Screenshot 2024-03-11 at 7 30 05 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/42843ae3-cc0e-4323-81a5-641c4dc38d5b">


## Checklist
<!-- Put an `x` in the boxes that apply -->

- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
