%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/emergentqj/actioncivile/pre-auth/.4cc3a2e1590a4463a5f392ddcc26929e/static/js/sagas/
Upload File :
Create Path :
Current File : /home/emergentqj/actioncivile/pre-auth/.4cc3a2e1590a4463a5f392ddcc26929e/static/js/sagas/registerPayment.js

import { put, call, takeEvery } from "redux-saga/effects";
import i18n from "i18next";
import configFunc from "config/config";
import { getUniversalCookies } from "utils/cookies";
import { trackMixpanelActions } from "utils/mixpanel";
import { isEmpty } from "lodash";
import { DIRECT_DEBIT_ERRORS } from "constants/errors";
import LIST_ACTIONS from "../constants/action_types";
import { getDataAction, postDataAction } from "../common/actions";
import { isDomEnabled } from "../utils";
import { showAlert, showAlertModal } from "../actions/list_actions";
import MIXPANEL_ACTIONS from "../constants/mixpanel_actions";

const mixpanel = isDomEnabled ? require("mixpanel-browser") : null;

const config = configFunc();

function* runRegisterPayment(dispatch, action) {
  // TODO if (action.payload && action.payload.sepa) { is it in use?
  if (action.payload && action.payload.sepa) {
    const registerSepaPaymentUrl = `${
      config.apiUrl
    }billingaccount/${
      action.payload.sepa.billingAccountId
    }/paymentdevice/sepa`;
    const data = {
      bic: action.payload.sepa.bic,
      iban: action.payload.sepa.iban,
      firstName: action.payload.sepa.firstName,
      lastName: action.payload.sepa.lastName,
      email: action.payload.sepa.email,
    };
    try {
      const payload = yield call(
        postDataAction(registerSepaPaymentUrl, data, true),
      );
      yield put({
        type: LIST_ACTIONS.GET_PAYMENT_DEVICE_REQUEST,
        payload,
      });
    } catch (e) {
      yield put(
        showAlert({
          icon: "error",
          show: true,
          title: i18n.t("sweet-alert.sorry"),
          text: e.data.message,
        }),
      );
    }
  } else if (action.payload && action.payload.afterPay) {
    const registerAfterPayPaymentUrl = `${
      config.apiUrl
    }billingaccount/changedistributiontype/afterpay`;
    try {
      const payload = yield call(
        postDataAction(
          registerAfterPayPaymentUrl,
          action.payload.afterPay,
          true,
        ),
      );
      yield put({
        type: LIST_ACTIONS.GET_PAYMENT_DEVICE_REQUEST,
        payload,
      });
    } catch (e) {
      yield put(
        showAlert({
          icon: "error",
          show: true,
          title: i18n.t("sweet-alert.sorry"),
          text: e.data.message.userErrorString,
        }),
      );
    }
  } else {
    const { currentUser } = action.payload;
    const { selectedMethod } = action.payload;
    const registerPaymentUrl = `${
      config.apiUrl
    }billingaccount/${
      currentUser.id
    }/registerPayment/${
      selectedMethod.id
    }?returnUrl=${
      window.location.href
    }`;
    const isSafari = navigator.userAgent.toLowerCase().indexOf("safari") !== -1
      && navigator.userAgent.toLowerCase().indexOf("chrome") === -1;

    try {
      const payload = yield call(getDataAction(registerPaymentUrl, null, true));
      if (
        /^([a-z|A-Z])+?:\/\/([^\/]+[.])?(easyparksystem[.]net)?(\/.*)?$/.test(
          payload.headers.location,
        ) === true
        || /^([a-z|A-Z])+?:\/\/([^\/]+[.])?(epinternal[.]net)?(\/.*)?$/.test(
          payload.headers.location,
        ) === true
        || /^([a-z|A-Z])+?:\/\/([^\/]+[.])?(paypal[.]com)?(\/.*)?$/.test(
          payload.headers.location,
        ) === true
      ) {
        yield put({
          type: LIST_ACTIONS.REGISTER_PAYMENT_SUCCESS,
          payload,
        });
        if (payload.data.redirect) {
          const performanceCookie = document.cookie
            .split("; ")
            .find(
              (c) => c.startsWith("userConsent") && c.includes("performance"),
            ) || "={}";
          const isPerformanceAllowed = JSON.parse(
            decodeURIComponent(performanceCookie.split("=").pop()),
          ).performance;
          if (mixpanel && isPerformanceAllowed) {
            mixpanel.track(MIXPANEL_ACTIONS.REDIRECTED_TO_PAYPAL, {
              channel: "DesktopWeb",
            });
          }
          window.location.href = payload.headers.location;
        } else if (isSafari && payload.headers.location) {
          if (payload.headers.location.indexOf("v1") >= 0) {
            window.location.href = payload.headers.location;
          } else {
            window.open(payload.headers.location);
          }
        }
      } else {
        yield put({
          type: LIST_ACTIONS.REGISTER_PAYMENT_ERROR,
          function() {
            return "Url is not whitelisted";
          },
        });
      }
    } catch (e) {
      yield put({
        type: LIST_ACTIONS.REGISTER_PAYMENT_ERROR,
        e,
      });
    }
  }
}

function* runRegisterSepaPayment(dispatch, action) {
  const registerSepaPaymentUrl = `${
    config.b2bApiUrl
  }billinggroup/${
    action.payload.billingAccount.id
  }/registerPaymentDevice?paymentMethodId=${
    action.payload.paymentMethodId
  }&companyid=${
    action.payload.customer.id
  }&registration=true`;
  const data = {
    bic: action.payload.sepa.sepaBic,
    iban: action.payload.sepa.sepaIban,
    firstName: action.payload.sepa.sepaFirstName,
    lastName: action.payload.sepa.sepaLastName,
    email: action.payload.sepa.sepaEmail,
    address: {
      street: action.payload.sepa.street,
      city: action.payload.sepa.city,
      postalCode: action.payload.sepa.postalCode,
      countryCode: action.payload.sepa.countryCode,
    },
  };
  try {
    const payload = yield call(
      postDataAction(registerSepaPaymentUrl, data, true),
    );
    yield put({
      type: LIST_ACTIONS.REGISTER_SEPA_PAYMENT_SUCCESS,
      payload,
    });
  } catch (e) {
    trackMixpanelActions(
      MIXPANEL_ACTIONS.BUSINESS_REGISTRATION_V2_PAYMENT_METHOD_ERROR,
      {
        error: e,
        data,
      },
    );
    yield put({
      type: LIST_ACTIONS.REGISTER_SEPA_PAYMENT_ERROR,
      error: e.response.data.message,
    });
    yield put(
      showAlert({
        icon: "error",
        show: true,
        title: i18n.t("sweet-alert.sorry"),
        text: e.response.data.message,
      }),
    );
  }
}

function* runCompleteSepaPaymentSetUp(dispatch, action) {
  const completeSepaPaymentUrl = `${
    config.b2bApiUrl
  }billinggroup/${
    action.payload.accountId
  }/complete/sepa`;
  const epSsAuthToken = getUniversalCookies().get("epSsAuthToken");
  const data = {
    ...action.payload,
    authToken: epSsAuthToken,
  };

  try {
    const payload = yield call(
      postDataAction(completeSepaPaymentUrl, data, true),
    );
    yield put({
      type: LIST_ACTIONS.REGISTER_SEPA_PAYMENT_SUCCESS,
      payload,
    });
  } catch (e) {
    yield put({
      type: LIST_ACTIONS.REGISTER_SEPA_PAYMENT_ERROR,
      error: e.response.data.userErrorString,
    });
  }
}

export const getDirectDebitErrorText = (errors) => {
  const errorMessages = new Set();
  if (!isEmpty(errors)) {
    errors.forEach((error) => {
      switch (error.userErrorKey) {
        case DIRECT_DEBIT_ERRORS.CUSTOMER_TOO_YOUNG:
          errorMessages.add(i18n.t("errors.directDebit.customerTooYoung"));
          break;
        case DIRECT_DEBIT_ERRORS.B2B_NOT_ALLOWED:
        case DIRECT_DEBIT_ERRORS.COUNTRY_UNSUPPORTED:
        case DIRECT_DEBIT_ERRORS.NOT_AVAILABLE:
        case DIRECT_DEBIT_ERRORS.NEGATIVE_CUSTOMER_SCORE:
          errorMessages.add(i18n.t("errors.directDebit.paymentMethodUnavailable"));
          break;
        case DIRECT_DEBIT_ERRORS.ADDRESS_MISMATCH:
          errorMessages.add(i18n.t("errors.directDebit.addressMismatch"));
          break;
        case DIRECT_DEBIT_ERRORS.BILLING_ADDRESS_NOT_VALID:
          errorMessages.add(i18n.t("errors.directDebit.billingAddressNotValid"));
          break;
        case DIRECT_DEBIT_ERRORS.DELIVERY_ADDRESS_NOT_VALID:
          errorMessages.add(i18n.t("errors.directDebit.deliveryAddressNotValid"));
          break;
        case DIRECT_DEBIT_ERRORS.INVALID_BANK_ACCOUNT:
          errorMessages.add(i18n.t("errors.directDebit.invalidBankAccount"));
          break;
        case DIRECT_DEBIT_ERRORS.ACCOUNT_NUMBER_NOT_SUPPORTED:
          errorMessages.add(
            i18n.t("errors.directDebit.accountNumberNotSupportedForCountry"),
          );
          break;
        case DIRECT_DEBIT_ERRORS.STRONG_AUTH_NEEDED:
          errorMessages.add(i18n.t("errors.directDebit.strongAuthNeeded"));
          break;
        case DIRECT_DEBIT_ERRORS.AGREEMENT_NOT_FOUND:
          errorMessages.add(i18n.t("errors.directDebit.agreementNotFound"));
          break;
        case DIRECT_DEBIT_ERRORS.UNPAID_INVOICES:
          errorMessages.add(i18n.t("errors.directDebit.unpaidInvoices"));
          break;
        case DIRECT_DEBIT_ERRORS.VALUE_REQUIRED:
          errorMessages.add(
            `${i18n.t("errors.directDebit.valueRequired")} (${error.fieldReference}).`,
          );
          break;
        case DIRECT_DEBIT_ERRORS.VALUE_OUT_OF_RANGE:
          errorMessages.add(
            `${i18n.t("errors.directDebit.valueOutOfRange")} (${error.fieldReference}).`,
          );
          break;
        case DIRECT_DEBIT_ERRORS.VALUE_TOO_LONG:
          errorMessages.add(
            `${i18n.t("errors.directDebit.valueLengthExceeded")} (${error.fieldReference}).`,
          );
          break;
        case DIRECT_DEBIT_ERRORS.VALUE_FORMAT_INVALID:
          errorMessages.add(
            `${i18n.t("errors.directDebit.valueFormatInvalid")} (${error.fieldReference}).`,
          );
          break;
        default:
          errorMessages.add(i18n.t("errors.unknownError"));
      }
    });
    return [...errorMessages].join(" ");
  }

  return i18n.t("directDebit.errorMessage2");
};

function* runRegisterDirectDebit(dispatch, action) {
  const registerPaymentUrl = `${
    config.apiUrl
  }billing/registerPayment/${
    action.payload.billingAccountId
  }/directDebit`;
  const returnUrl = `?merchantUrl=${
    window.location.href.split("?")[0]
  }/final?billingAccountId=${action.payload.billingAccountId}`;
  const { data } = action.payload;
  try {
    const payload = yield call(
      postDataAction(registerPaymentUrl, data, true, {
        "Content-Type": "application/json",
      }),
    );
    if (payload.data.success === false) {
      throw payload.data.errors;
    }
    yield put({
      type: LIST_ACTIONS.REGISTER_DIRECT_DEBIT_SUCCESS,
      payload,
    });
    trackMixpanelActions(
      MIXPANEL_ACTIONS.REDIRECTED_TO_AFTER_PAY_DIRECT_DEBIT,
      {
        channel: "DesktopWeb",
      },
    );
    window.location.href = `${payload.data.redirectUrl}${returnUrl}`;
  } catch (e) {
    yield put({
      type: LIST_ACTIONS.REGISTER_DIRECT_DEBIT_ERROR,
      error: e,
    });

    yield put(
      showAlertModal({
        type: "error",
        show: true,
        title: i18n.t("directDebit.setUp"),
        text1: i18n.t("directDebit.errorMessage1"),
        text2: getDirectDebitErrorText(e),
        confirmButtonText: i18n.t("general-ok"),
      }),
    );
  }
}

function* runCheckDirectDebitStatus(dispatch, action) {
  const checkDirectDebitStatusUrl = `${
    config.apiUrl
  }billing/registerPayment/${
    action.payload
  }/directDebit/status`;
  try {
    const payload = yield call(
      getDataAction(checkDirectDebitStatusUrl, null, true),
    );
    if (payload.data.status !== "accepted") {
      throw payload.data.errors;
    }

    yield put({
      type: LIST_ACTIONS.CHECK_DIRECT_DEBIT_STATUS_SUCCESS,
      payload,
    });
    yield put(
      showAlertModal({
        type: "success",
        show: true,
        title: i18n.t("directDebit.setUp"),
        text1: i18n.t("directDebit.successMessage"),
        confirmButtonText: i18n.t("general-ok"),
      }),
    );
    trackMixpanelActions(
      MIXPANEL_ACTIONS.BUSINESS_REGISTRATION_V2_PAYMENT_METHOD_SUCCESS,
      {
        category: "Selfservice",
        channel: "DesktopWeb",
        eventType: "click",
        label: MIXPANEL_ACTIONS.BUSINESS_REGISTRATION_V2_PAYMENT_METHOD_SUCCESS,
        formData: "AFTER_PAY_DIRECT_DEBIT",
      },
    );
  } catch (e) {
    trackMixpanelActions(
      MIXPANEL_ACTIONS.BUSINESS_REGISTRATION_V2_PAYMENT_METHOD_ERROR,
      {
        "Card Type": "AFTER_PAY_DIRECT_DEBIT",
      },
    );
    yield put({
      type: LIST_ACTIONS.CHECK_DIRECT_DEBIT_STATUS_ERROR,
      error: e,
    });
    yield put(
      showAlertModal({
        type: "error",
        show: true,
        title: i18n.t("directDebit.setUp"),
        text1: i18n.t("directDebit.errorMessage1"),
        text2: i18n.t("directDebit.errorMessage2"),
        confirmButtonText: i18n.t("general-ok"),
      }),
    );
  }
}

export function* registerPayment(dispatch) {
  yield takeEvery(
    LIST_ACTIONS.REGISTER_PAYMENT_REQUEST,
    runRegisterPayment,
    dispatch,
  );
}

export function* registerSepaPayment(dispatch) {
  yield takeEvery(
    LIST_ACTIONS.REGISTER_SEPA_PAYMENT_REQUEST,
    runRegisterSepaPayment,
    dispatch,
  );
}

export function* registerDirectDebit(dispatch) {
  yield takeEvery(
    LIST_ACTIONS.REGISTER_DIRECT_DEBIT_REQUEST,
    runRegisterDirectDebit,
    dispatch,
  );
}

export function* checkDirectDebitStatus(dispatch) {
  yield takeEvery(
    LIST_ACTIONS.CHECK_DIRECT_DEBIT_STATUS_REQUEST,
    runCheckDirectDebitStatus,
    dispatch,
  );
}

export function* completeSepaPaymentSetUp(dispatch) {
  yield takeEvery(
    LIST_ACTIONS.COMPLETE_SEPA_PAYMENT,
    runCompleteSepaPaymentSetUp,
    dispatch,
  );
}

Zerion Mini Shell 1.0