index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountExtractBatchJobItemProcessor.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.sellers.bankaccountextraction.services.strategies.HyperWalletBankAccountStrategyExecutor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Component;
/**
* Bank account extract batch job item processor for creating the bank accounts in HW
*/
@Component
public class BankAccountExtractBatchJobItemProcessor
implements BatchJobItemProcessor<BatchJobContext, BankAccountExtractJobItem> {
private final HyperWalletBankAccountStrategyExecutor hyperWalletBankAccountStrategyExecutor;
private final TokenSynchronizationService<SellerModel> bankAccountTokenSynchronizationService;
public BankAccountExtractBatchJobItemProcessor(
final HyperWalletBankAccountStrategyExecutor hyperWalletBankAccountStrategyExecutor,
final TokenSynchronizationService<SellerModel> bankAccountTokenSynchronizationService) {
this.hyperWalletBankAccountStrategyExecutor = hyperWalletBankAccountStrategyExecutor;
this.bankAccountTokenSynchronizationService = bankAccountTokenSynchronizationService;
}
/**
* Processes the {@link BankAccountExtractJobItem} with the
* {@link HyperWalletBankAccountStrategyExecutor}
* @param ctx The {@link BatchJobContext}
* @param jobItem The {@link BankAccountExtractJobItem}
*/
@Override
public void processItem(final BatchJobContext ctx, final BankAccountExtractJobItem jobItem) {
final SellerModel synchronizedSellerModel = bankAccountTokenSynchronizationService
.synchronizeToken(jobItem.getItem());
hyperWalletBankAccountStrategyExecutor.execute(synchronizedSellerModel);
}
}
| 4,900 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountExtractBatchJob.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractExtractBatchJob;
import org.springframework.stereotype.Component;
/**
* Extract bank account job for extracting Mirakl sellers data and populate it on
* HyperWallet as users
*/
@Component
public class BankAccountExtractBatchJob extends AbstractExtractBatchJob<BatchJobContext, BankAccountExtractJobItem> {
private final BankAccountExtractBatchJobItemProcessor bankAccountExtractBatchJobItemProcessor;
private final BankAccountExtractBatchJobItemsExtractor bankAccountExtractBatchJobItemsExtractor;
public BankAccountExtractBatchJob(
final BankAccountExtractBatchJobItemProcessor bankAccountExtractBatchJobItemProcessor,
final BankAccountExtractBatchJobItemsExtractor bankAccountExtractBatchJobItemsExtractor) {
this.bankAccountExtractBatchJobItemProcessor = bankAccountExtractBatchJobItemProcessor;
this.bankAccountExtractBatchJobItemsExtractor = bankAccountExtractBatchJobItemsExtractor;
}
/**
* Retrieves the bank account batch job item processor
* @return the {@link BatchJobItemProcessor} for {@link BankAccountExtractJobItem}
*/
@Override
protected BatchJobItemProcessor<BatchJobContext, BankAccountExtractJobItem> getBatchJobItemProcessor() {
return this.bankAccountExtractBatchJobItemProcessor;
}
/**
* Retrieves the bank account batch job items extractor
* @return the {@link BatchJobItemsExtractor} for {@link BankAccountExtractJobItem}
*/
@Override
protected BatchJobItemsExtractor<BatchJobContext, BankAccountExtractJobItem> getBatchJobItemsExtractor() {
return this.bankAccountExtractBatchJobItemsExtractor;
}
}
| 4,901 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountRetryBatchJobItemsExtractor.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobfailures.services.BatchJobFailedItemService;
import com.paypal.jobsystem.batchjobfailures.services.cache.BatchJobFailedItemCacheService;
import com.paypal.jobsystem.batchjobfailures.support.AbstractCachingFailedItemsBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Extract bank accounts for retry from the failed items cache.
*/
@Component
public class BankAccountRetryBatchJobItemsExtractor
extends AbstractCachingFailedItemsBatchJobItemsExtractor<BatchJobContext, BankAccountExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
protected BankAccountRetryBatchJobItemsExtractor(final BatchJobFailedItemService batchJobFailedItemService,
final BatchJobFailedItemCacheService batchJobFailedItemCacheService,
final MiraklSellersExtractService miraklSellersExtractService) {
super(BankAccountExtractJobItem.class, BankAccountExtractJobItem.ITEM_TYPE, batchJobFailedItemService,
batchJobFailedItemCacheService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
@Override
protected Collection<BankAccountExtractJobItem> getItems(final List<String> ids) {
//@formatter:off
return miraklSellersExtractService.extractSellers(ids)
.stream()
.map(BankAccountExtractJobItem::new)
.collect(Collectors.toList());
//@formatter:on
}
}
| 4,902 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountRetryBatchJob.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractRetryBatchJob;
import org.springframework.stereotype.Component;
/**
* Retries items that have failed during the bank account extract job
*/
@Component
public class BankAccountRetryBatchJob extends AbstractRetryBatchJob<BatchJobContext, BankAccountExtractJobItem> {
private final BankAccountExtractBatchJobItemProcessor bankAccountExtractBatchJobItemProcessor;
private final BankAccountRetryBatchJobItemsExtractor bankAccountRetryBatchJobItemsExtractor;
public BankAccountRetryBatchJob(
final BankAccountExtractBatchJobItemProcessor bankAccountExtractBatchJobItemProcessor,
final BankAccountRetryBatchJobItemsExtractor bankAccountRetryBatchJobItemsExtractor) {
this.bankAccountExtractBatchJobItemProcessor = bankAccountExtractBatchJobItemProcessor;
this.bankAccountRetryBatchJobItemsExtractor = bankAccountRetryBatchJobItemsExtractor;
}
@Override
protected BatchJobItemProcessor<BatchJobContext, BankAccountExtractJobItem> getBatchJobItemProcessor() {
return bankAccountExtractBatchJobItemProcessor;
}
@Override
protected BatchJobItemsExtractor<BatchJobContext, BankAccountExtractJobItem> getBatchJobItemsExtractor() {
return bankAccountRetryBatchJobItemsExtractor;
}
}
| 4,903 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountExtractBatchJobItemsExtractor.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobaudit.services.BatchJobTrackingService;
import com.paypal.jobsystem.batchjobsupport.support.AbstractDynamicWindowDeltaBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The extractor class for retrieving all the sellers within a delta time from mirakl
*/
@Component
public class BankAccountExtractBatchJobItemsExtractor
extends AbstractDynamicWindowDeltaBatchJobItemsExtractor<BatchJobContext, BankAccountExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
public BankAccountExtractBatchJobItemsExtractor(final MiraklSellersExtractService miraklSellersExtractService,
final BatchJobTrackingService batchJobTrackingService) {
super(batchJobTrackingService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
/**
* Retrieves all the sellers modified since the {@code delta} time and returns them as
* a {@link BankAccountExtractJobItem}
* @param delta the cut-out {@link Date}
* @return a {@link Collection} of {@link BankAccountExtractJobItem}
*/
@Override
protected Collection<BankAccountExtractJobItem> getItems(final BatchJobContext ctx, final Date delta) {
final Collection<BankAccountExtractJobItem> individualBankAccounts = miraklSellersExtractService
.extractIndividuals(delta).stream().map(BankAccountExtractJobItem::new).collect(Collectors.toList());
final Collection<BankAccountExtractJobItem> professionalBankAccounts = miraklSellersExtractService
.extractProfessionals(delta).stream().map(BankAccountExtractJobItem::new).collect(Collectors.toList());
return Stream.concat(individualBankAccounts.stream(), professionalBankAccounts.stream())
.collect(Collectors.toList());
}
}
| 4,904 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/batchjobs/BankAccountExtractJobItem.java | package com.paypal.sellers.bankaccountextraction.batchjobs;
import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem;
import com.paypal.jobsystem.batchjob.model.BatchJobItem;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
/**
* Class that holds the needed information for processing a bank account job.
*/
public class BankAccountExtractJobItem extends AbstractBatchJobItem<SellerModel> {
public static final String ITEM_TYPE = "BankAccount";
protected static final String BATCH_JOB_ITEM_EMPTY_ID = "empty";
public BankAccountExtractJobItem(final SellerModel item) {
super(item);
}
/**
* Returns the {@code clientUserId} of a {@link SellerModel}
* @return the {@link String} clientUserId
*/
@Override
public String getItemId() {
return getItem().getClientUserId();
}
/**
* Returns the type as {@link String} of the {@link BatchJobItem}
* @return {@code BankAccount}
*/
@Override
public String getItemType() {
return ITEM_TYPE;
}
}
| 4,905 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/IBANBankAccountModel.java | package com.paypal.sellers.bankaccountextraction.model;
import lombok.Getter;
import java.util.Objects;
/**
* Creates an object of type {@link IBANBankAccountModel}
*/
@Getter
public class IBANBankAccountModel extends BankAccountModel {
private final String bankBic;
public IBANBankAccountModel(final Builder builder) {
super(builder);
bankBic = builder.bankBic;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final IBANBankAccountModel that = (IBANBankAccountModel) o;
return Objects.equals(bankBic, that.bankBic);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bankBic);
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
//@formatter:off
return IBANBankAccountModel.builder()
.buildTransferMethodCountry(transferMethodCountry)
.buildTransferMethodCurrency(transferMethodCurrency)
.transferType(transferType)
.type(type)
.bankAccountNumber(bankAccountNumber)
.businessName(businessName)
.firstName(firstName)
.lastName(lastName)
.buildCountry(country)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.postalCode(postalCode)
.token(token)
.hyperwalletProgram(hyperwalletProgram)
.bankBic(bankBic);
//@formatter:on
}
public static class Builder extends BankAccountModel.Builder<Builder> {
private String bankBic;
@Override
public Builder getThis() {
return this;
}
public Builder bankBic(final String bankBIC) {
bankBic = bankBIC;
return getThis();
}
@Override
public IBANBankAccountModel build() {
return new IBANBankAccountModel(this);
}
}
}
| 4,906 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/BankAccountModel.java | package com.paypal.sellers.bankaccountextraction.model;
import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue;
import com.paypal.infrastructure.support.countries.CountriesUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javax.money.Monetary;
import javax.money.UnknownCurrencyException;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import static com.paypal.sellers.sellerextractioncommons.model.SellerModelConstants.*;
/**
* Creates an object of type {@link BankAccountModel}
*/
@Slf4j
@Getter
public class BankAccountModel {
protected final String transferMethodCountry;
protected final String transferMethodCurrency;
protected final TransferType transferType;
protected final BankAccountType type;
protected final String bankAccountNumber;
protected final String businessName;
protected final String firstName;
protected final String lastName;
protected final String country;
protected final String addressLine1;
protected final String addressLine2;
protected final String city;
protected final String stateProvince;
protected final String postalCode;
protected final String token;
protected final String hyperwalletProgram;
protected BankAccountModel(final Builder<?> builder) {
transferMethodCountry = builder.transferMethodCountry;
transferMethodCurrency = builder.transferMethodCurrency;
transferType = builder.transferType;
type = builder.type;
bankAccountNumber = builder.bankAccountNumber;
businessName = builder.businessName;
addressLine1 = builder.addressLine1;
addressLine2 = builder.addressLine2;
firstName = builder.firstName;
lastName = builder.lastName;
city = builder.city;
stateProvince = builder.stateProvince;
country = builder.country;
postalCode = builder.postalCode;
token = builder.token;
hyperwalletProgram = builder.hyperwalletProgram;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BankAccountModel)) {
return false;
}
final BankAccountModel that = (BankAccountModel) o;
//@formatter:off
return Objects.equals(getTransferMethodCountry(), that.getTransferMethodCountry())
&& Objects.equals(getTransferMethodCurrency(), that.getTransferMethodCurrency())
&& getTransferType() == that.getTransferType() && getType() == that.getType()
&& Objects.equals(getBankAccountNumber(), that.getBankAccountNumber())
&& Objects.equals(getBusinessName(), that.getBusinessName())
&& Objects.equals(getFirstName(), that.getFirstName())
&& Objects.equals(getLastName(), that.getLastName())
&& Objects.equals(getCountry(), that.getCountry())
&& Objects.equals(getAddressLine1(), that.getAddressLine1())
&& Objects.equals(getAddressLine2(), that.getAddressLine2())
&& Objects.equals(getCity(), that.getCity())
&& Objects.equals(getStateProvince(), that.getStateProvince())
&& Objects.equals(getPostalCode(), that.getPostalCode())
&& Objects.equals(getToken(), that.getToken())
&& Objects.equals(getHyperwalletProgram(), that.getHyperwalletProgram());
//@formatter:on
}
@Override
public int hashCode() {
return Objects.hash(getTransferMethodCountry(), getTransferMethodCurrency(), getTransferType(), getType(),
getBankAccountNumber(), getBusinessName(), getFirstName(), getLastName(), getCountry(),
getAddressLine1(), getAddressLine2(), getCity(), getStateProvince(), getPostalCode(), getToken());
}
@SuppressWarnings("java:S3740")
public Builder toBuilder() {
//@formatter:off
return BankAccountModel.builder()
.buildTransferMethodCountry(transferMethodCountry)
.buildTransferMethodCurrency(transferMethodCurrency)
.transferType(transferType)
.type(type)
.bankAccountNumber(bankAccountNumber)
.businessName(businessName)
.firstName(firstName)
.lastName(lastName)
.buildCountry(country)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.postalCode(postalCode)
.token(token)
.hyperwalletProgram(hyperwalletProgram);
//@formatter:on
}
@SuppressWarnings("java:S3740")
public static Builder builder() {
return new Builder() {
@Override
public Builder getThis() {
return this;
}
};
}
public abstract static class Builder<T extends Builder<T>> {
protected String transferMethodCountry;
protected String transferMethodCurrency;
protected TransferType transferType;
protected BankAccountType type;
protected String bankAccountNumber;
protected String businessName;
protected String firstName;
protected String lastName;
protected String country;
protected String addressLine1;
protected String addressLine2;
protected String city;
protected String stateProvince;
protected String postalCode;
protected String token;
protected String hyperwalletProgram;
public abstract T getThis();
public T transferMethodCountry(final String transferMethodCountry) {
final Locale countryLocale = CountriesUtil.getLocaleByIsocode(transferMethodCountry)
.orElseThrow(() -> new IllegalStateException(
"Country with isocode: [%s] not valid".formatted(transferMethodCountry)));
this.transferMethodCountry = countryLocale.getCountry();
return getThis();
}
protected T buildTransferMethodCountry(final String transferMethodCountry) {
this.transferMethodCountry = transferMethodCountry;
return getThis();
}
public T transferMethodCurrency(final String transferMethodCurrency) {
try {
Optional.of(Monetary.getCurrency(transferMethodCurrency))
.ifPresent(currency -> this.transferMethodCurrency = currency.getCurrencyCode());
}
catch (final UnknownCurrencyException ex) {
throw new IllegalStateException(
"Transfer method currency with code: [%s] not valid".formatted(transferMethodCurrency), ex);
}
return getThis();
}
protected T buildTransferMethodCurrency(final String transferMethodCurrency) {
this.transferMethodCurrency = transferMethodCurrency;
return getThis();
}
public T transferType(final TransferType type) {
transferType = type;
return getThis();
}
public T type(final BankAccountType type) {
this.type = type;
return getThis();
}
public T bankAccountNumber(final String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
return getThis();
}
public T businessName(final String businessName) {
this.businessName = businessName;
return getThis();
}
public T firstName(final String firstName) {
this.firstName = firstName;
return getThis();
}
public T lastName(final String lastName) {
this.lastName = lastName;
return getThis();
}
public T country(final String country) {
final Locale countryLocale = CountriesUtil.getLocaleByIsocode(country).orElseThrow(
() -> new IllegalStateException("Country with isocode: [%s] not valid".formatted(country)));
this.country = countryLocale.getCountry();
return getThis();
}
protected T buildCountry(final String country) {
this.country = country;
return getThis();
}
public T addressLine1(final String addressLine1) {
this.addressLine1 = addressLine1;
return getThis();
}
public T addressLine2(final String addressLine2) {
this.addressLine2 = addressLine2;
return getThis();
}
public T city(final String city) {
this.city = city;
return getThis();
}
public T stateProvince(final List<MiraklAdditionalFieldValue> fieldValues) {
stateProvince = getMiraklStringCustomFieldValue(fieldValues, HYPERWALLET_BANK_ACCOUNT_STATE).orElse(null);
return getThis();
}
public T stateProvince(final String stateProvince) {
this.stateProvince = stateProvince;
return getThis();
}
public T postalCode(final String postalCode) {
this.postalCode = postalCode;
return getThis();
}
public T token(final List<MiraklAdditionalFieldValue> fieldValues) {
token = getMiraklStringCustomFieldValue(fieldValues, HYPERWALLET_BANK_ACCOUNT_TOKEN).orElse(null);
return getThis();
}
public T token(final String token) {
this.token = token;
return getThis();
}
public T hyperwalletProgram(final String hyperwalletProgram) {
this.hyperwalletProgram = hyperwalletProgram;
return getThis();
}
public T hyperwalletProgram(final List<MiraklAdditionalFieldValue> fields) {
getMiraklSingleValueListCustomFieldValue(fields, HYPERWALLET_PROGRAM)
.ifPresent(hyperwalletProgramValue -> this.hyperwalletProgram = hyperwalletProgramValue);
return getThis();
}
public BankAccountModel build() {
return new BankAccountModel(this);
}
private Optional<String> getMiraklStringCustomFieldValue(final List<MiraklAdditionalFieldValue> fields,
final String customFieldCode) {
//@formatter:off
return fields.stream().filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::cast)
.findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue);
//@formatter:on
}
private Optional<String> getMiraklSingleValueListCustomFieldValue(final List<MiraklAdditionalFieldValue> fields,
final String customFieldCode) {
//@formatter:off
return fields.stream()
.filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::cast).findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue);
//@formatter:on
}
}
}
| 4,907 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/BankAccountType.java | package com.paypal.sellers.bankaccountextraction.model;
public enum BankAccountType {
IBAN, ABA, CANADIAN, UK
}
| 4,908 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/UKBankAccountModel.java | package com.paypal.sellers.bankaccountextraction.model;
import lombok.Getter;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Creates an object of type {@link UKBankAccountModel}
*/
@Getter
public class UKBankAccountModel extends BankAccountModel {
private final String bankAccountId;
public UKBankAccountModel(final UKBankAccountModel.Builder builder) {
super(builder);
bankAccountId = builder.bankAccountId;
}
public static UKBankAccountModel.Builder builder() {
return new UKBankAccountModel.Builder();
}
@Override
public Builder toBuilder() {
//@formatter:off
return UKBankAccountModel.builder()
.buildTransferMethodCountry(transferMethodCountry)
.buildTransferMethodCurrency(transferMethodCurrency)
.transferType(transferType)
.type(type)
.bankAccountNumber(bankAccountNumber)
.businessName(businessName)
.firstName(firstName)
.lastName(lastName)
.buildCountry(country)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.postalCode(postalCode)
.token(token)
.hyperwalletProgram(hyperwalletProgram)
.bankAccountId(bankAccountId);
//@formatter:on
}
@Override
public boolean equals(final Object o) {
if (super.equals(o)) {
final UKBankAccountModel that = (UKBankAccountModel) o;
return this.getBankAccountId().equals(that.getBankAccountId());
}
return false;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public static class Builder extends BankAccountModel.Builder<UKBankAccountModel.Builder> {
private String bankAccountId;
@Override
public UKBankAccountModel.Builder getThis() {
return this;
}
public UKBankAccountModel.Builder bankAccountId(final String bankAccountId) {
this.bankAccountId = bankAccountId;
return getThis();
}
@Override
public UKBankAccountModel build() {
return new UKBankAccountModel(this);
}
}
}
| 4,909 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/BankAccountPurposeType.java | package com.paypal.sellers.bankaccountextraction.model;
public enum BankAccountPurposeType {
CHECKING
}
| 4,910 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/CanadianBankAccountModel.java | package com.paypal.sellers.bankaccountextraction.model;
import lombok.Getter;
import java.util.Objects;
/**
* Creates an object of type {@link CanadianBankAccountModel}
*/
@Getter
public class CanadianBankAccountModel extends BankAccountModel {
private final String bankId;
private final String branchId;
public CanadianBankAccountModel(final Builder builder) {
super(builder);
bankId = builder.bankId;
branchId = builder.branchId;
}
public static CanadianBankAccountModel.Builder builder() {
return new CanadianBankAccountModel.Builder();
}
@Override
public Builder toBuilder() {
//@formatter:off
return CanadianBankAccountModel.builder()
.buildTransferMethodCountry(transferMethodCountry)
.buildTransferMethodCurrency(transferMethodCurrency)
.transferType(transferType)
.type(type)
.bankAccountNumber(bankAccountNumber)
.businessName(businessName)
.firstName(firstName)
.lastName(lastName)
.buildCountry(country)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.postalCode(postalCode)
.token(token)
.hyperwalletProgram(hyperwalletProgram)
.bankId(bankId)
.branchId(branchId);
//@formatter:on
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final CanadianBankAccountModel that = (CanadianBankAccountModel) o;
return Objects.equals(bankId, that.bankId) && Objects.equals(branchId, that.branchId);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bankId, branchId);
}
public static class Builder extends BankAccountModel.Builder<CanadianBankAccountModel.Builder> {
private String bankId;
private String branchId;
@Override
public CanadianBankAccountModel.Builder getThis() {
return this;
}
public CanadianBankAccountModel.Builder branchId(final String branchId) {
this.branchId = branchId;
return getThis();
}
public CanadianBankAccountModel.Builder bankId(final String bankId) {
this.bankId = bankId;
return getThis();
}
@Override
public CanadianBankAccountModel build() {
return new CanadianBankAccountModel(this);
}
}
}
| 4,911 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/ABABankAccountModel.java | package com.paypal.sellers.bankaccountextraction.model;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
/**
* Creates an object of type {@link ABABankAccountModel}
*/
@Slf4j
@Getter
public class ABABankAccountModel extends BankAccountModel {
private final String branchId;
private final String bankAccountPurpose;
public ABABankAccountModel(final Builder builder) {
super(builder);
branchId = builder.branchId;
bankAccountPurpose = builder.bankAccountPurpose;
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
//@formatter:off
return ABABankAccountModel.builder()
.buildTransferMethodCountry(transferMethodCountry)
.buildTransferMethodCurrency(transferMethodCurrency)
.transferType(transferType)
.type(type)
.bankAccountNumber(bankAccountNumber)
.businessName(businessName)
.firstName(firstName)
.lastName(lastName)
.buildCountry(country)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.postalCode(postalCode)
.token(token)
.hyperwalletProgram(hyperwalletProgram)
.branchId(branchId)
.bankAccountPurpose(bankAccountPurpose);
//@formatter:on
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final ABABankAccountModel that = (ABABankAccountModel) o;
return Objects.equals(branchId, that.branchId) && Objects.equals(bankAccountPurpose, that.bankAccountPurpose);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), branchId, bankAccountPurpose);
}
public static class Builder extends BankAccountModel.Builder<Builder> {
private String branchId;
private String bankAccountPurpose;
@Override
public Builder getThis() {
return this;
}
public Builder branchId(final String branchId) {
this.branchId = branchId;
return getThis();
}
public Builder bankAccountPurpose(final String bankAccountPurpose) {
this.bankAccountPurpose = bankAccountPurpose;
return getThis();
}
@Override
public ABABankAccountModel build() {
return new ABABankAccountModel(this);
}
}
}
| 4,912 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/model/TransferType.java | package com.paypal.sellers.bankaccountextraction.model;
public enum TransferType {
BANK_ACCOUNT, WIRE_ACCOUNT
}
| 4,913 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/jobs/BankAccountExtractJob.java | package com.paypal.sellers.bankaccountextraction.jobs;
import com.paypal.jobsystem.quartzadapter.support.AbstractBatchJobSupportQuartzJob;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobAdapterFactory;
import com.paypal.sellers.bankaccountextraction.batchjobs.BankAccountExtractBatchJob;
import org.quartz.*;
/**
* Quartz Job for executing the {@link BankAccountExtractBatchJob}.
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BankAccountExtractJob extends AbstractBatchJobSupportQuartzJob implements Job {
private final BankAccountExtractBatchJob bankAccountExtractBatchJob;
public BankAccountExtractJob(final QuartzBatchJobAdapterFactory quartzBatchJobAdapterFactory,
final BankAccountExtractBatchJob bankAccountExtractBatchJob) {
super(quartzBatchJobAdapterFactory);
this.bankAccountExtractBatchJob = bankAccountExtractBatchJob;
}
/**
* {@inheritDoc}
*/
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
executeBatchJob(bankAccountExtractBatchJob, context);
}
}
| 4,914 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/controllers/BankAccountExtractJobController.java | package com.paypal.sellers.bankaccountextraction.controllers;
import com.paypal.jobsystem.quartzintegration.controllers.AbstractJobController;
import com.paypal.sellers.bankaccountextraction.jobs.BankAccountExtractJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@Slf4j
@RestController
@RequestMapping("/job")
public class BankAccountExtractJobController extends AbstractJobController {
private static final String DEFAULT_BANK_ACCOUNT_EXTRACT_JOB_NAME = "BankAccountExtractJobSingleExecution";
/**
* Triggers the {@link BankAccountExtractJob} with the {@code delta} time to retrieve
* shops created or updated since that {@code delta} and schedules the job with the
* {@code name} provided
* @param delta the {@link Date} in {@link DateTimeFormat.ISO}
* @param name the job name in {@link String}
* @return a {@link ResponseEntity <String>} with the name of the job scheduled
* @throws SchedulerException if quartz {@link org.quartz.Scheduler} fails
*/
@PostMapping("/bank-accounts-extract")
public ResponseEntity<String> runJob(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final Date delta,
@RequestParam(required = false, defaultValue = DEFAULT_BANK_ACCOUNT_EXTRACT_JOB_NAME) final String name)
throws SchedulerException {
runSingleJob(name, BankAccountExtractJob.class, delta);
return ResponseEntity.accepted().body(name);
}
}
| 4,915 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/BankAccountTokenSynchronizationServiceImpl.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.HyperwalletException;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.hyperwallet.clientsdk.model.HyperwalletList;
import com.mirakl.client.core.exception.MiraklApiException;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.support.exceptions.HMCHyperwalletAPIException;
import com.paypal.infrastructure.support.exceptions.HMCMiraklAPIException;
import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
/**
* Class that implements the {@link TokenSynchronizationService} interface for the
* synchronization of tokens for bank accounts
*/
@Slf4j
@Service("bankAccountTokenSynchronizationService")
public class BankAccountTokenSynchronizationServiceImpl implements TokenSynchronizationService<SellerModel> {
private final UserHyperwalletSDKService userHyperwalletSDKService;
private final MiraklBankAccountExtractService miraklBankAccountExtractService;
private final HyperwalletMiraklBankAccountMatcher hyperwalletMiraklBankAccountMatcher;
public BankAccountTokenSynchronizationServiceImpl(final UserHyperwalletSDKService userHyperwalletSDKService,
final MiraklBankAccountExtractService miraklBankAccountExtractService,
final HyperwalletMiraklBankAccountMatcher hyperwalletMiraklBankAccountMatcher) {
this.userHyperwalletSDKService = userHyperwalletSDKService;
this.miraklBankAccountExtractService = miraklBankAccountExtractService;
this.hyperwalletMiraklBankAccountMatcher = hyperwalletMiraklBankAccountMatcher;
}
public SellerModel synchronizeToken(final SellerModel miraklSeller) {
final BankAccountModel miraklBankAccount = miraklSeller.getBankAccountDetails();
if (miraklBankAccount == null || StringUtils.isBlank(miraklBankAccount.getBankAccountNumber())) {
log.debug("Not bank account for client user id [{}], synchronization not needed",
miraklSeller.getClientUserId());
return miraklSeller;
}
// If not exact match or compatible bank account is found, the bank account token
// in Mirakl will be updated with a null value, forcing the bank account to be
// created again
// in Hyperwallet
final List<HyperwalletBankAccount> hyperwalletBankAccounts = getHwBankAccountByClientUserId(miraklSeller);
final HyperwalletBankAccount matchedHyperwalletBankAccount = hyperwalletMiraklBankAccountMatcher
.findExactOrCompatibleMatch(hyperwalletBankAccounts, miraklBankAccount)
.orElse(new HyperwalletBankAccount());
if (!Objects.equals(miraklBankAccount.getToken(), matchedHyperwalletBankAccount.getToken())) {
updateMiraklBankAccountToken(miraklSeller, matchedHyperwalletBankAccount);
}
return updateSellerBankAccountWithHyperwalletToken(miraklSeller, matchedHyperwalletBankAccount);
}
private List<HyperwalletBankAccount> getHwBankAccountByClientUserId(final SellerModel sellerModel) {
final Hyperwallet hyperwalletSDK = userHyperwalletSDKService
.getHyperwalletInstanceByProgramToken(sellerModel.getProgramToken());
try {
final HyperwalletList<HyperwalletBankAccount> bankAccounts = hyperwalletSDK
.listBankAccounts(sellerModel.getToken());
return bankAccounts != null && bankAccounts.getData() != null ? bankAccounts.getData() : List.of();
}
catch (final HyperwalletException exception) {
log.error(
String.format("Error while getting Hyperwallet bank account by clientUserId [%s].%n%s",
sellerModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(exception)),
exception);
throw new HMCHyperwalletAPIException(exception);
}
}
private void updateMiraklBankAccountToken(final SellerModel miraklSeller,
final HyperwalletBankAccount hyperwalletBankAccount) {
try {
miraklBankAccountExtractService.updateBankAccountToken(miraklSeller, hyperwalletBankAccount);
}
catch (final MiraklApiException exception) {
log.error("Error while updating Mirakl bank account by clientUserId [{}]", miraklSeller.getClientUserId(),
exception);
throw new HMCMiraklAPIException(exception);
}
}
private SellerModel updateSellerBankAccountWithHyperwalletToken(final SellerModel sellerModel,
final HyperwalletBankAccount hyperwalletBankAccount) {
return sellerModel.toBuilder().bankAccountDetails(
sellerModel.getBankAccountDetails().toBuilder().token(hyperwalletBankAccount.getToken()).build())
.build();
}
}
| 4,916 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/MiraklBankAccountExtractService.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
/**
* Service to manipulate bank account updates in Mirakl
*/
public interface MiraklBankAccountExtractService {
/**
* Updates the custom field {@code hw-bankaccount-token} with the token received after
* creation of the {@link HyperwalletBankAccount}
* @param sellerModel
* @param hyperwalletBankAccount
*/
void updateBankAccountToken(SellerModel sellerModel, HyperwalletBankAccount hyperwalletBankAccount);
}
| 4,917 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/HyperwalletMiraklBankAccountMatcher.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
//@formatter:off
@Component
public class HyperwalletMiraklBankAccountMatcher {
private final HyperwalletMiraklBankAccountCompatibilityChecker hyperwalletMiraklBankAccountCompatibilityChecker;
private final HyperwalletMiraklBankAccountEqualityChecker hyperwalletMiraklBankAccountEqualityChecker;
public HyperwalletMiraklBankAccountMatcher(final HyperwalletMiraklBankAccountCompatibilityChecker hyperwalletMiraklBankAccountCompatibilityChecker, final HyperwalletMiraklBankAccountEqualityChecker hyperwalletMiraklBankAccountEqualityChecker) {
this.hyperwalletMiraklBankAccountCompatibilityChecker = hyperwalletMiraklBankAccountCompatibilityChecker;
this.hyperwalletMiraklBankAccountEqualityChecker = hyperwalletMiraklBankAccountEqualityChecker;
}
public Optional<HyperwalletBankAccount> findExactOrCompatibleMatch(final List<HyperwalletBankAccount> hyperwalletCandidates, final BankAccountModel miraklBankAccount) {
return findSameTokenCompatibleBankAccount(hyperwalletCandidates, miraklBankAccount)
.or(() -> findExactBankAccount(hyperwalletCandidates, miraklBankAccount))
.or(() -> findCompatibleBankAccount(hyperwalletCandidates, miraklBankAccount));
}
private Optional<HyperwalletBankAccount> findExactBankAccount(final List<HyperwalletBankAccount> hyperwalletCandidates, final BankAccountModel miraklBankAccount) {
return hyperwalletCandidates.stream()
.filter(candidate -> hyperwalletMiraklBankAccountEqualityChecker.isSameBankAccount(candidate, miraklBankAccount))
.findFirst();
}
private Optional<HyperwalletBankAccount> findCompatibleBankAccount(final List<HyperwalletBankAccount> hyperwalletCandidates, final BankAccountModel miraklBankAccount) {
return hyperwalletCandidates.stream()
.filter(candidate -> hyperwalletMiraklBankAccountCompatibilityChecker.isBankAccountCompatible(candidate, miraklBankAccount))
.findFirst();
}
private Optional<HyperwalletBankAccount> findSameTokenCompatibleBankAccount(final List<HyperwalletBankAccount> hyperwalletCandidates, final BankAccountModel miraklBankAccount) {
return hyperwalletCandidates.stream()
.filter(candidate -> candidate.getToken().equals(miraklBankAccount.getToken()))
.filter(candidate -> hyperwalletMiraklBankAccountCompatibilityChecker.isBankAccountCompatible(candidate, miraklBankAccount))
.findFirst();
}
}
| 4,918 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/MiraklBankAccountExtractServiceImpl.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.mirakl.client.core.exception.MiraklApiException;
import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop;
import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest;
import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.mirakl.client.MiraklClient;
import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.paypal.sellers.sellerextractioncommons.model.SellerModelConstants.HYPERWALLET_BANK_ACCOUNT_TOKEN;
@Slf4j
@Service
public class MiraklBankAccountExtractServiceImpl implements MiraklBankAccountExtractService {
private final MiraklClient miraklOperatorClient;
private final MailNotificationUtil sellerMailNotificationUtil;
private static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further "
+ "information:\n";
public MiraklBankAccountExtractServiceImpl(final MiraklClient miraklOperatorClient,
final MailNotificationUtil sellerMailNotificationUtil) {
this.miraklOperatorClient = miraklOperatorClient;
this.sellerMailNotificationUtil = sellerMailNotificationUtil;
}
/**
* {@inheritDoc}
*/
@Override
public void updateBankAccountToken(final SellerModel sellerModel,
final HyperwalletBankAccount hyperwalletBankAccount) {
final MiraklUpdateShop miraklUpdateShop = new MiraklUpdateShop();
final String shopId = sellerModel.getClientUserId();
miraklUpdateShop.setShopId(Long.valueOf(shopId));
final MiraklSimpleRequestAdditionalFieldValue userTokenCustomField = new MiraklSimpleRequestAdditionalFieldValue();
userTokenCustomField.setCode(HYPERWALLET_BANK_ACCOUNT_TOKEN);
userTokenCustomField.setValue(hyperwalletBankAccount.getToken());
miraklUpdateShop.setAdditionalFieldValues(List.of(userTokenCustomField));
final MiraklUpdateShopsRequest request = new MiraklUpdateShopsRequest(List.of(miraklUpdateShop));
log.info("Updating bank account token for shop [{}]", shopId);
try {
miraklOperatorClient.updateShops(request);
log.info("Bank account token updated for shop [{}]", shopId);
}
catch (final MiraklApiException ex) {
log.error("Something went wrong updating information of shop [{}]", shopId);
sellerMailNotificationUtil.sendPlainTextEmail("Issue detected updating bank token in Mirakl",
(ERROR_MESSAGE_PREFIX + "Something went wrong updating bank token of shop [%s]%n%s")
.formatted(shopId, MiraklLoggingErrorsUtil.stringify(ex)));
}
}
}
| 4,919 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/HyperwalletMiraklBankAccountEqualityChecker.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.*;
import org.springframework.stereotype.Component;
@Component
public class HyperwalletMiraklBankAccountEqualityChecker {
public boolean isSameBankAccount(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel miraklBankAccount) {
if (!sameCountryAndCurrency(hyperwalletBankAccount, miraklBankAccount)
|| !sameBankAccountId(hyperwalletBankAccount, miraklBankAccount)) {
return false;
}
if (miraklBankAccount instanceof IBANBankAccountModel) {
return sameBankIdFields(hyperwalletBankAccount, (IBANBankAccountModel) miraklBankAccount);
}
else if (miraklBankAccount instanceof ABABankAccountModel) {
return sameBankIdFields(hyperwalletBankAccount, (ABABankAccountModel) miraklBankAccount);
}
else if (miraklBankAccount instanceof UKBankAccountModel) {
return sameBankIdFields(hyperwalletBankAccount, (UKBankAccountModel) miraklBankAccount);
}
else if (miraklBankAccount instanceof CanadianBankAccountModel) {
return sameBankIdFields(hyperwalletBankAccount, (CanadianBankAccountModel) miraklBankAccount);
}
else {
throw new IllegalArgumentException(
"Bank account type not supported: " + miraklBankAccount.getClass().getName());
}
}
private boolean sameCountryAndCurrency(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel bankAccountModel) {
return hyperwalletBankAccount.getTransferMethodCountry().equals(bankAccountModel.getTransferMethodCountry())
&& hyperwalletBankAccount.getTransferMethodCurrency()
.equals(bankAccountModel.getTransferMethodCurrency());
}
private boolean sameBankAccountId(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel miraklBankAccount) {
return compareObfuscatedBankAccountNumber(miraklBankAccount.getBankAccountNumber(),
hyperwalletBankAccount.getBankAccountId());
}
private boolean sameBankIdFields(final HyperwalletBankAccount hyperwalletBankAccount,
final IBANBankAccountModel ibanBankAccountModel) {
return hyperwalletBankAccount.getBankId().equals(ibanBankAccountModel.getBankBic());
}
private boolean sameBankIdFields(final HyperwalletBankAccount hyperwalletBankAccount,
final ABABankAccountModel abaBankAccountModel) {
return hyperwalletBankAccount.getBranchId().equals(abaBankAccountModel.getBranchId())
&& hyperwalletBankAccount.getBankAccountPurpose().equals(abaBankAccountModel.getBankAccountPurpose());
}
private boolean sameBankIdFields(final HyperwalletBankAccount hyperwalletBankAccount,
final UKBankAccountModel ukBankAccountModel) {
return hyperwalletBankAccount.getBankId().equals(ukBankAccountModel.getBankAccountId());
}
private boolean sameBankIdFields(final HyperwalletBankAccount hyperwalletBankAccount,
final CanadianBankAccountModel canadianBankAccountModel) {
return hyperwalletBankAccount.getBankId().equals(canadianBankAccountModel.getBankId())
&& hyperwalletBankAccount.getBranchId().equals(canadianBankAccountModel.getBranchId());
}
private boolean compareObfuscatedBankAccountNumber(final String plainBankAccountNumber,
final String obfuscatedBankAccountNumber) {
final String lastFourDigits = plainBankAccountNumber.substring(plainBankAccountNumber.length() - 4);
final String lastFourDigitsObfuscated = obfuscatedBankAccountNumber
.substring(obfuscatedBankAccountNumber.length() - 4);
return lastFourDigits.equals(lastFourDigitsObfuscated);
}
}
| 4,920 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/HyperwalletMiraklBankAccountCompatibilityChecker.java | package com.paypal.sellers.bankaccountextraction.services;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.services.converters.bankaccounttype.HyperwalletBankAccountTypeResolver;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class HyperwalletMiraklBankAccountCompatibilityChecker {
private final HyperwalletBankAccountTypeResolver hyperwalletBankAccountTypeResolver;
public HyperwalletMiraklBankAccountCompatibilityChecker(
final HyperwalletBankAccountTypeResolver hyperwalletBankAccountTypeResolver) {
this.hyperwalletBankAccountTypeResolver = hyperwalletBankAccountTypeResolver;
}
public boolean isBankAccountCompatible(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel miraklBankAccount) {
return hasSameBankAccountType(hyperwalletBankAccount, miraklBankAccount)
&& hasSameBankAccountCountry(hyperwalletBankAccount, miraklBankAccount);
}
private boolean hasSameBankAccountType(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel miraklBankAccount) {
return hyperwalletBankAccountTypeResolver.getBankAccountType(hyperwalletBankAccount) == miraklBankAccount
.getType();
}
private boolean hasSameBankAccountCountry(final HyperwalletBankAccount hyperwalletBankAccount,
final BankAccountModel miraklBankAccount) {
return Objects.equals(hyperwalletBankAccount.getTransferMethodCountry(),
miraklBankAccount.getTransferMethodCountry());
}
}
| 4,921 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/strategies/HyperWalletCreateBankAccountServiceStrategy.java | package com.paypal.sellers.bankaccountextraction.services.strategies;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.strategy.StrategyExecutor;
import com.paypal.sellers.bankaccountextraction.services.MiraklBankAccountExtractService;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Optional;
/**
* Strategy class that creates a new bank account into hyperwallet and updates the token
* in mirakl
*/
@Service
public class HyperWalletCreateBankAccountServiceStrategy extends AbstractHyperwalletBankAccountStrategy {
private final MiraklBankAccountExtractService miraklBankAccountExtractService;
protected HyperWalletCreateBankAccountServiceStrategy(
final StrategyExecutor<SellerModel, HyperwalletBankAccount> sellerModelToHyperwalletBankAccountStrategyExecutor,
final MiraklBankAccountExtractService miraklBankAccountExtractService,
final UserHyperwalletSDKService userHyperwalletSDKService,
final MailNotificationUtil mailNotificationUtil) {
super(sellerModelToHyperwalletBankAccountStrategyExecutor, userHyperwalletSDKService, mailNotificationUtil);
this.miraklBankAccountExtractService = miraklBankAccountExtractService;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<HyperwalletBankAccount> execute(final SellerModel seller) {
final Optional<HyperwalletBankAccount> hwBankAccountCreated = callSuperExecute(seller);
hwBankAccountCreated
.ifPresent(bankAccount -> miraklBankAccountExtractService.updateBankAccountToken(seller, bankAccount));
return hwBankAccountCreated;
}
@Override
protected HyperwalletBankAccount callHyperwalletAPI(final String hyperwalletProgram,
final HyperwalletBankAccount hyperwalletBankAccount) {
final Hyperwallet hyperwallet = userHyperwalletSDKService
.getHyperwalletInstanceByHyperwalletProgram(hyperwalletProgram);
return hyperwallet.createBankAccount(hyperwalletBankAccount);
}
/**
* Checks whether the strategy must be executed based on the {@code source}
* @param seller the source object
* @return returns whether the strategy is applicable or not
*/
@Override
public boolean isApplicable(final SellerModel seller) {
return Objects.isNull(seller.getBankAccountDetails().getToken());
}
protected Optional<HyperwalletBankAccount> callSuperExecute(final SellerModel seller) {
return super.execute(seller);
}
}
| 4,922 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/strategies/HyperWalletBankAccountStrategyExecutor.java | package com.paypal.sellers.bankaccountextraction.services.strategies;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.infrastructure.support.strategy.SingleAbstractStrategyExecutor;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Executor class that controls strategies to insert or update bank account information
* into Hyperwallet
*/
@Slf4j
@Service
public class HyperWalletBankAccountStrategyExecutor
extends SingleAbstractStrategyExecutor<SellerModel, Optional<HyperwalletBankAccount>> {
private final Set<Strategy<SellerModel, Optional<HyperwalletBankAccount>>> strategies;
public HyperWalletBankAccountStrategyExecutor(
final Set<Strategy<SellerModel, Optional<HyperwalletBankAccount>>> strategies) {
this.strategies = strategies;
}
@Override
protected Set<Strategy<SellerModel, Optional<HyperwalletBankAccount>>> getStrategies() {
return strategies;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<HyperwalletBankAccount> execute(final SellerModel seller) {
if (Objects.isNull(seller.getBankAccountDetails())) {
log.warn("No bank account info for shop code: [{}]", seller.getClientUserId());
return Optional.empty();
}
return callSuperExecute(seller);
}
protected Optional<HyperwalletBankAccount> callSuperExecute(final SellerModel seller) {
return super.execute(seller);
}
}
| 4,923 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/strategies/HyperWalletUpdateBankAccountServiceStrategy.java | package com.paypal.sellers.bankaccountextraction.services.strategies;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.strategy.StrategyExecutor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* Strategy class that updates an existing bank account into hyperwallet
*/
@Service
public class HyperWalletUpdateBankAccountServiceStrategy extends AbstractHyperwalletBankAccountStrategy {
protected HyperWalletUpdateBankAccountServiceStrategy(
final StrategyExecutor<SellerModel, HyperwalletBankAccount> sellerModelToHyperwalletBankAccountStrategyExecutor,
final UserHyperwalletSDKService userHyperwalletSDKService,
final MailNotificationUtil mailNotificationUtil) {
super(sellerModelToHyperwalletBankAccountStrategyExecutor, userHyperwalletSDKService, mailNotificationUtil);
}
/**
* Checks whether the strategy must be executed based on the {@code source}
* @param seller the source object
* @return returns whether the strategy is applicable or not
*/
@Override
public boolean isApplicable(final SellerModel seller) {
return Objects.nonNull(seller.getBankAccountDetails().getToken());
}
@Override
protected HyperwalletBankAccount callHyperwalletAPI(final String hyperwalletProgram,
final HyperwalletBankAccount hyperwalletBankAccount) {
final Hyperwallet hyperwallet = userHyperwalletSDKService
.getHyperwalletInstanceByHyperwalletProgram(hyperwalletProgram);
return hyperwallet.updateBankAccount(hyperwalletBankAccount);
}
}
| 4,924 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/strategies/AbstractHyperwalletBankAccountStrategy.java | package com.paypal.sellers.bankaccountextraction.services.strategies;
import com.hyperwallet.clientsdk.HyperwalletException;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.mirakl.client.core.exception.MiraklApiException;
import com.paypal.infrastructure.support.exceptions.HMCHyperwalletAPIException;
import com.paypal.infrastructure.support.exceptions.HMCMiraklAPIException;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.infrastructure.support.strategy.StrategyExecutor;
import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil;
import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
import java.util.Optional;
@Slf4j
public abstract class AbstractHyperwalletBankAccountStrategy
implements Strategy<SellerModel, Optional<HyperwalletBankAccount>> {
protected final StrategyExecutor<SellerModel, HyperwalletBankAccount> sellerModelToHyperwalletBankAccountStrategyExecutor;
protected final UserHyperwalletSDKService userHyperwalletSDKService;
protected final MailNotificationUtil mailNotificationUtil;
protected static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further "
+ "information:\n";
protected AbstractHyperwalletBankAccountStrategy(
final StrategyExecutor<SellerModel, HyperwalletBankAccount> sellerModelToHyperwalletBankAccountStrategyExecutor,
final UserHyperwalletSDKService userHyperwalletSDKService,
final MailNotificationUtil mailNotificationUtil) {
this.sellerModelToHyperwalletBankAccountStrategyExecutor = sellerModelToHyperwalletBankAccountStrategyExecutor;
this.userHyperwalletSDKService = userHyperwalletSDKService;
this.mailNotificationUtil = mailNotificationUtil;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<HyperwalletBankAccount> execute(final SellerModel seller) {
HyperwalletBankAccount hwCreatedBankAccount = null;
final HyperwalletBankAccount hwBankAccountRequest = sellerModelToHyperwalletBankAccountStrategyExecutor
.execute(seller);
if (Objects.nonNull(hwBankAccountRequest)) {
try {
hwCreatedBankAccount = callHyperwalletAPI(seller.getHyperwalletProgram(), hwBankAccountRequest);
log.info("Bank account created or updated for seller with clientId [{}]", seller.getClientUserId());
}
catch (final HyperwalletException e) {
mailNotificationUtil
.sendPlainTextEmail("Issue detected when creating or updating bank account in Hyperwallet",
String.format(ERROR_MESSAGE_PREFIX
+ "Bank account not created or updated for seller with clientId [%s]%n%s",
seller.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)));
log.error(String.format("Bank account not created or updated for seller with clientId [%s].%n%s",
seller.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)), e);
throw new HMCHyperwalletAPIException(e);
}
catch (final MiraklApiException e) {
log.error("Error while updating Mirakl bank account by clientUserId [{}]", seller.getClientUserId(), e);
log.error(MiraklLoggingErrorsUtil.stringify(e));
throw new HMCMiraklAPIException(e);
}
}
return Optional.ofNullable(hwCreatedBankAccount);
}
protected abstract HyperwalletBankAccount callHyperwalletAPI(final String hyperwalletProgram,
HyperwalletBankAccount hyperwalletBankAccount);
}
| 4,925 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/MiraklToBankAccountModelExecutor.java | package com.paypal.sellers.bankaccountextraction.services.converters;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.paypal.infrastructure.support.strategy.SingleAbstractStrategyExecutor;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Set;
@Slf4j
@Service
public class MiraklToBankAccountModelExecutor extends SingleAbstractStrategyExecutor<MiraklShop, BankAccountModel> {
private final Set<Strategy<MiraklShop, BankAccountModel>> strategies;
public MiraklToBankAccountModelExecutor(final Set<Strategy<MiraklShop, BankAccountModel>> strategies) {
this.strategies = strategies;
}
/**
* Returns the set converters from {@link MiraklShop} to {@link BankAccountModel}
* @return the set of converters
*/
@Override
protected Set<Strategy<MiraklShop, BankAccountModel>> getStrategies() {
return strategies;
}
/**
* {@inheritDoc}
*/
@Override
public BankAccountModel execute(final MiraklShop source) {
if (Objects.isNull(source.getPaymentInformation())) {
log.warn("No bank account info for shop code: [{}]", source.getId());
return null;
}
return callSuperExecute(source);
}
protected BankAccountModel callSuperExecute(final MiraklShop source) {
return super.execute(source);
}
}
| 4,926 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/SellerModelToHyperwalletBankAccountExecutor.java | package com.paypal.sellers.bankaccountextraction.services.converters;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.infrastructure.support.strategy.SingleAbstractStrategyExecutor;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class SellerModelToHyperwalletBankAccountExecutor
extends SingleAbstractStrategyExecutor<SellerModel, HyperwalletBankAccount> {
private final Set<Strategy<SellerModel, HyperwalletBankAccount>> strategies;
public SellerModelToHyperwalletBankAccountExecutor(
final Set<Strategy<SellerModel, HyperwalletBankAccount>> strategies) {
this.strategies = strategies;
}
/**
* Returns the set converters from {@link SellerModel} to
* {@link HyperwalletBankAccount}
* @return the set of converters
*/
@Override
protected Set<Strategy<SellerModel, HyperwalletBankAccount>> getStrategies() {
return strategies;
}
}
| 4,927 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/bankaccounttype/HyperwalletBankAccountTypeResolverImpl.java | package com.paypal.sellers.bankaccountextraction.services.converters.bankaccounttype;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.infrastructure.support.exceptions.HMCException;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyRestrictions;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class HyperwalletBankAccountTypeResolverImpl implements HyperwalletBankAccountTypeResolver {
private final HyperwalletBankAccountCurrencyRestrictions countryCurrencyConfiguration;
public HyperwalletBankAccountTypeResolverImpl(
final HyperwalletBankAccountCurrencyRestrictions countryCurrencyConfiguration) {
this.countryCurrencyConfiguration = countryCurrencyConfiguration;
}
@Override
public BankAccountType getBankAccountType(final HyperwalletBankAccount hyperwalletBankAccount) {
final HyperwalletBankAccount.Type type = hyperwalletBankAccount.getType();
final List<HyperwalletBankAccountCurrencyRestrictions.CountryCurrencyEntry> typeCandidates = countryCurrencyConfiguration
.getEntriesFor(hyperwalletBankAccount.getTransferMethodCountry(),
hyperwalletBankAccount.getTransferMethodCurrency(), TransferType.valueOf(type.name()));
if (typeCandidates.isEmpty()) {
throw new HMCException(String.format(
"No bank account type found for country %s, currency %s and transfer type %s",
hyperwalletBankAccount.getTransferMethodCountry(),
hyperwalletBankAccount.getTransferMethodCurrency(), hyperwalletBankAccount.getType().name()));
}
else {
return BankAccountType.valueOf(typeCandidates.get(0).getBankAccountType());
}
}
}
| 4,928 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/bankaccounttype/HyperwalletBankAccountTypeResolver.java | package com.paypal.sellers.bankaccountextraction.services.converters.bankaccounttype;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
public interface HyperwalletBankAccountTypeResolver {
BankAccountType getBankAccountType(HyperwalletBankAccount hyperwalletBankAccount);
}
| 4,929 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/hyperwallet/SellerModelToHyperWalletIBANBankAccount.java | package com.paypal.sellers.bankaccountextraction.services.converters.hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.IBANBankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* Class to convert from {@link IBANBankAccountModel} to {@link HyperwalletBankAccount}
*/
@Service
public class SellerModelToHyperWalletIBANBankAccount extends AbstractSellerModelToHyperwalletBankAccount {
@Override
public HyperwalletBankAccount execute(final SellerModel source) {
final var hyperwalletBankAccount = callSuperConvert(source);
final var bankAccountDetails = (IBANBankAccountModel) source.getBankAccountDetails();
hyperwalletBankAccount.setBankId(bankAccountDetails.getBankBic());
return hyperwalletBankAccount;
}
protected HyperwalletBankAccount callSuperConvert(final SellerModel source) {
return super.execute(source);
}
/**
* Returns true if bankAccountDetails of {@link SellerModel} is of type
* {@link IBANBankAccountModel}
* @param source the source object
* @return true if bankAccountDetails of {@link SellerModel} is of type
* {@link IBANBankAccountModel}, false otherwise
*/
@Override
public boolean isApplicable(final SellerModel source) {
return Objects.nonNull(source.getBankAccountDetails())
&& source.getBankAccountDetails() instanceof IBANBankAccountModel;
}
}
| 4,930 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/hyperwallet/SellerModelToHyperWalletCanadianBankAccount.java | package com.paypal.sellers.bankaccountextraction.services.converters.hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.CanadianBankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* Class to convert from {@link CanadianBankAccountModel} to
* {@link HyperwalletBankAccount}
*/
@Service
public class SellerModelToHyperWalletCanadianBankAccount extends AbstractSellerModelToHyperwalletBankAccount {
@Override
public HyperwalletBankAccount execute(final SellerModel source) {
final var hyperwalletBankAccount = callSuperConvert(source);
final var bankAccountDetails = (CanadianBankAccountModel) source.getBankAccountDetails();
hyperwalletBankAccount.setBankId(bankAccountDetails.getBankId());
hyperwalletBankAccount.setBranchId(bankAccountDetails.getBranchId());
return hyperwalletBankAccount;
}
protected HyperwalletBankAccount callSuperConvert(final SellerModel source) {
return super.execute(source);
}
/**
* Returns true if bankAccountDetails of {@link SellerModel} is of type
* {@link CanadianBankAccountModel}
* @param source the source object
* @return true if bankAccountDetails of {@link SellerModel} is of type
* {@link CanadianBankAccountModel}, false otherwise
*/
@Override
public boolean isApplicable(final SellerModel source) {
return Objects.nonNull(source.getBankAccountDetails())
&& source.getBankAccountDetails() instanceof CanadianBankAccountModel;
}
}
| 4,931 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/hyperwallet/AbstractSellerModelToHyperwalletBankAccount.java | package com.paypal.sellers.bankaccountextraction.services.converters.hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.hyperwallet.clientsdk.model.HyperwalletUser.ProfileType;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.IBANBankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerProfileType;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
/**
* Class to convert from {@link IBANBankAccountModel} to {@link HyperwalletBankAccount}
*/
@Slf4j
public abstract class AbstractSellerModelToHyperwalletBankAccount
implements Strategy<SellerModel, HyperwalletBankAccount> {
@Override
public HyperwalletBankAccount execute(final SellerModel source) {
final BankAccountModel bankAccountDetails = source.getBankAccountDetails();
if (Objects.isNull(bankAccountDetails)) {
return null;
}
final HyperwalletBankAccount hyperwalletBankAccount = new HyperwalletBankAccount();
hyperwalletBankAccount.setAddressLine1(bankAccountDetails.getAddressLine1());
hyperwalletBankAccount.setAddressLine2(bankAccountDetails.getAddressLine2());
hyperwalletBankAccount.setBankAccountId(bankAccountDetails.getBankAccountNumber());
hyperwalletBankAccount.setTransferMethodCountry(bankAccountDetails.getTransferMethodCountry());
hyperwalletBankAccount.setTransferMethodCurrency(bankAccountDetails.getTransferMethodCurrency());
hyperwalletBankAccount
.setType(HyperwalletBankAccount.Type.valueOf(bankAccountDetails.getTransferType().name()));
hyperwalletBankAccount.setCountry(bankAccountDetails.getCountry());
hyperwalletBankAccount.setCity(bankAccountDetails.getCity());
hyperwalletBankAccount.setUserToken(source.getToken());
hyperwalletBankAccount.setProfileType(ProfileType.valueOf(source.getProfileType().name()));
hyperwalletBankAccount.setToken(bankAccountDetails.getToken());
if (SellerProfileType.BUSINESS.equals(source.getProfileType())) {
fillProfessionalAttributes(hyperwalletBankAccount, source);
}
else {
fillIndividualAttributes(hyperwalletBankAccount, source);
}
return hyperwalletBankAccount;
}
private void fillIndividualAttributes(final HyperwalletBankAccount hyperwalletBankAccount,
final SellerModel source) {
final BankAccountModel bankAccountDetails = source.getBankAccountDetails();
hyperwalletBankAccount.setFirstName(bankAccountDetails.getFirstName());
hyperwalletBankAccount.setLastName(bankAccountDetails.getLastName());
}
private void fillProfessionalAttributes(final HyperwalletBankAccount hyperwalletBankAccount,
final SellerModel source) {
hyperwalletBankAccount.setBusinessName(source.getBusinessName());
}
}
| 4,932 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/hyperwallet/SellerModelToHyperWalletUKBankAccount.java | package com.paypal.sellers.bankaccountextraction.services.converters.hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.UKBankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* Class to convert from {@link UKBankAccountModel} to {@link HyperwalletBankAccount}
*/
@Service
public class SellerModelToHyperWalletUKBankAccount extends AbstractSellerModelToHyperwalletBankAccount {
@Override
public HyperwalletBankAccount execute(final SellerModel source) {
final var hyperwalletBankAccount = callSuperConvert(source);
final var bankAccountDetails = (UKBankAccountModel) source.getBankAccountDetails();
hyperwalletBankAccount.setBankId(bankAccountDetails.getBankAccountId());
return hyperwalletBankAccount;
}
protected HyperwalletBankAccount callSuperConvert(final SellerModel source) {
return super.execute(source);
}
/**
* Returns true if bankAccountDetails of {@link SellerModel} is of type
* {@link UKBankAccountModel}
* @param source the source object
* @return true if bankAccountDetails of {@link SellerModel} is of type
* {@link UKBankAccountModel}, false otherwise
*/
@Override
public boolean isApplicable(final SellerModel source) {
return Objects.nonNull(source.getBankAccountDetails())
&& source.getBankAccountDetails() instanceof UKBankAccountModel;
}
}
| 4,933 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/hyperwallet/SellerModelToHyperWalletABABankAccount.java | package com.paypal.sellers.bankaccountextraction.services.converters.hyperwallet;
import com.hyperwallet.clientsdk.model.HyperwalletBankAccount;
import com.paypal.sellers.bankaccountextraction.model.ABABankAccountModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* Class to convert from {@link ABABankAccountModel} to {@link HyperwalletBankAccount}
*/
@Service
public class SellerModelToHyperWalletABABankAccount extends AbstractSellerModelToHyperwalletBankAccount {
@Override
public HyperwalletBankAccount execute(final SellerModel source) {
final var hyperwalletBankAccount = callSuperConvert(source);
final var bankAccountDetails = (ABABankAccountModel) source.getBankAccountDetails();
hyperwalletBankAccount.setBranchId(bankAccountDetails.getBranchId());
hyperwalletBankAccount.setBankAccountPurpose(bankAccountDetails.getBankAccountPurpose());
hyperwalletBankAccount.setPostalCode(bankAccountDetails.getPostalCode());
hyperwalletBankAccount.setStateProvince(bankAccountDetails.getStateProvince());
return hyperwalletBankAccount;
}
protected HyperwalletBankAccount callSuperConvert(final SellerModel source) {
return super.execute(source);
}
/**
* Returns true if bankAccountDetails of {@link SellerModel} is of type
* {@link ABABankAccountModel}
* @param source the source object
* @return true if bankAccountDetails of {@link SellerModel} is of type
* {@link ABABankAccountModel}, false otherwise
*/
@Override
public boolean isApplicable(final SellerModel source) {
return Objects.nonNull(source.getBankAccountDetails())
&& source.getBankAccountDetails() instanceof ABABankAccountModel;
}
}
| 4,934 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyResolutionConfiguration.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Data
@Component
public class HyperwalletBankAccountCurrencyResolutionConfiguration {
@Value("${hmc.bankaccounts.enableAutomaticCurrencySelection}")
protected boolean enableAutomaticCurrencySelection;
@Value("${hmc.bankaccounts.allowWireAccountTransferType}")
protected boolean allowWireAccounts;
@Value("${hmc.bankaccounts.overrideCurrencySelectionPriority}")
protected boolean overrideCurrencySelectionPriority;
@Value("${hmc.bankaccounts.prioritizeBankAccountTypeOverCurrency}")
protected boolean prioritizeBankAccountTypeOverCurrency;
protected List<String> globalCurrencyPriority;
protected Map<String, List<String>> perCountryCurrencyPriority;
public HyperwalletBankAccountCurrencyResolutionConfiguration(
@Value("${hmc.bankaccounts.overriddenCurrencySelectionPriority}") final String overriddenCurrencySelectionPriority) {
this.globalCurrencyPriority = buildGlobalCurrencySelectionPriority(overriddenCurrencySelectionPriority);
this.perCountryCurrencyPriority = buildPerCountryCurrencyPriority(overriddenCurrencySelectionPriority);
}
protected Map<String, List<String>> buildPerCountryCurrencyPriority(
final String perCountryCurrencySelectionPriority) {
// Country and currency list separated by semicolons. Expected format:
// "US:USD,GBP;CA:CAD,USD"
return Stream.of(perCountryCurrencySelectionPriority.split(";")).map(it -> it.split(":"))
.filter(it -> it.length == 2)
.collect(Collectors.toMap(it -> it[0], it -> parseGlobalCurrencyPriority(it[1])));
}
protected List<String> buildGlobalCurrencySelectionPriority(final String perCountryCurrencySelectionPriority) {
// Country and currency list separated by semicolons. Expected format:
// "US:USD,GBP;CA:CAD,USD"
return Stream.of(perCountryCurrencySelectionPriority.split(";")).map(it -> it.split(":"))
.filter(it -> it.length == 1).findFirst().map(it -> parseGlobalCurrencyPriority(it[0]))
.orElse(List.of());
}
protected List<String> parseGlobalCurrencyPriority(final String currencySelectionPriority) {
// Currency list separated by comma. Expected format example: "USD,GBP"
return Stream.of(currencySelectionPriority.split(",")).map(String::trim).collect(Collectors.toList());
}
}
| 4,935 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyResolverImpl.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@Slf4j
@Component
public class HyperwalletBankAccountCurrencyResolverImpl implements HyperwalletBankAccountCurrencyResolver {
private final HyperwalletBankAccountCurrencyRestrictions hyperwalletBankAccountCurrencyRestrictions;
private final HyperwalletBankAccountCurrencyResolutionConfiguration hyperwalletBankAccountCurrencyResolutionConfiguration;
private final HyperwalletBankAccountCurrencyPriorityResolver hyperwalletBankAccountCurrencyPriorityResolver;
public HyperwalletBankAccountCurrencyResolverImpl(
final HyperwalletBankAccountCurrencyRestrictions hyperwalletBankAccountCurrencyRestrictions,
final HyperwalletBankAccountCurrencyResolutionConfiguration hyperwalletBankAccountCurrencyResolutionConfiguration,
final HyperwalletBankAccountCurrencyPriorityResolver hyperwalletBankAccountCurrencyPriorityResolver) {
this.hyperwalletBankAccountCurrencyRestrictions = hyperwalletBankAccountCurrencyRestrictions;
this.hyperwalletBankAccountCurrencyResolutionConfiguration = hyperwalletBankAccountCurrencyResolutionConfiguration;
this.hyperwalletBankAccountCurrencyPriorityResolver = hyperwalletBankAccountCurrencyPriorityResolver;
}
//@formatter:off
@Override
public HyperwalletBankAccountCurrencyInfo getCurrencyForCountry(final String bankAccountType, final String countryIsoCode, final String shopCurrency) {
if (!hyperwalletBankAccountCurrencyResolutionConfiguration.isEnableAutomaticCurrencySelection()) {
log.debug("Automatic currency selection is disabled. Falling back to shop currency {}", shopCurrency);
return createCurrencyWithDefaults(countryIsoCode, shopCurrency);
}
final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates =
hyperwalletBankAccountCurrencyRestrictions.getCurrenciesFor(bankAccountType, countryIsoCode);
final List<HyperwalletBankAccountCurrencyInfo> filteredCandidates =
filterUnsupportedCurrencyCandidates(currencyCandidates);
final List<HyperwalletBankAccountCurrencyInfo> sortedCurrencyCandidates =
hyperwalletBankAccountCurrencyPriorityResolver.sortCurrenciesByPriority(filteredCandidates);
return chooseCurrency(countryIsoCode, sortedCurrencyCandidates, shopCurrency);
}
private List<HyperwalletBankAccountCurrencyInfo> filterUnsupportedCurrencyCandidates(final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates) {
return currencyCandidates.stream().filter(this::supportedTransferType).collect(Collectors.toList());
}
private boolean supportedTransferType(final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo) {
return hyperwalletBankAccountCurrencyInfo.getTransferType().equals(TransferType.BANK_ACCOUNT)
|| hyperwalletBankAccountCurrencyResolutionConfiguration.isAllowWireAccounts();
}
private HyperwalletBankAccountCurrencyInfo chooseCurrency(
final String countryIsoCode, final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates, final String shopCurrency) {
if (currencyCandidates == null || currencyCandidates.isEmpty()) {
log.warn(String.format("There are no currency candidates for country %s. Falling back to shop currency %s",
countryIsoCode, shopCurrency));
return createCurrencyWithDefaults(countryIsoCode, shopCurrency);
}
final Optional<HyperwalletBankAccountCurrencyInfo> matchedCurrency =
matchBankAccountTypeAndShopCurrency(currencyCandidates, shopCurrency)
.or(matchShopCurrency(currencyCandidates, shopCurrency));
return matchedCurrency.orElse(CollectionUtils.isNotEmpty(currencyCandidates) ? currencyCandidates.get(0)
: createCurrencyWithDefaults(countryIsoCode, shopCurrency));
}
@NotNull
private static HyperwalletBankAccountCurrencyInfo createCurrencyWithDefaults(final String countryIsoCode, final String shopCurrency) {
return new HyperwalletBankAccountCurrencyInfo(countryIsoCode, shopCurrency, TransferType.BANK_ACCOUNT);
}
@NotNull
private Supplier<Optional<? extends HyperwalletBankAccountCurrencyInfo>> matchShopCurrency(final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates, final String shopCurrency) {
return () -> currencyCandidates.stream()
.filter(x -> hasSameCurrency(x, shopCurrency))
.findFirst();
}
@NotNull
private Optional<HyperwalletBankAccountCurrencyInfo> matchBankAccountTypeAndShopCurrency(final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates, final String shopCurrency) {
return currencyCandidates.stream()
.filter(x -> hasSameCurrencyAndBankAccountType(x, shopCurrency))
.findFirst();
}
private boolean hasSameCurrencyAndBankAccountType(
final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo, final String shopCurrency) {
return hyperwalletBankAccountCurrencyInfo.getTransferType().equals(TransferType.BANK_ACCOUNT)
&& hyperwalletBankAccountCurrencyInfo.getCurrency().equals(shopCurrency);
}
private boolean hasSameCurrency(final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo,
final String shopCurrency) {
return hyperwalletBankAccountCurrencyInfo.getCurrency().equals(shopCurrency);
}
}
| 4,936 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyPriorityResolver.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@Component
public class HyperwalletBankAccountCurrencyPriorityResolver {
private final HyperwalletBankAccountCurrencyResolutionConfiguration hyperwalletBankAccountCurrencyResolutionConfiguration;
private final List<TransferType> transferTypePriority = List.of(TransferType.BANK_ACCOUNT,
TransferType.WIRE_ACCOUNT);
public HyperwalletBankAccountCurrencyPriorityResolver(
final HyperwalletBankAccountCurrencyResolutionConfiguration hyperwalletBankAccountCurrencyResolutionConfiguration) {
this.hyperwalletBankAccountCurrencyResolutionConfiguration = hyperwalletBankAccountCurrencyResolutionConfiguration;
}
public List<HyperwalletBankAccountCurrencyInfo> sortCurrenciesByPriority(
final List<HyperwalletBankAccountCurrencyInfo> currencyCandidates) {
if (CollectionUtils.isEmpty(currencyCandidates)) {
return Collections.emptyList();
}
final List<HyperwalletBankAccountCurrencyInfo> sortedCurrencyCandidates = new ArrayList<>(currencyCandidates);
if (hyperwalletBankAccountCurrencyResolutionConfiguration.isOverrideCurrencySelectionPriority()) {
Collections.sort(sortedCurrencyCandidates,
Comparator.comparing(HyperwalletBankAccountCurrencyInfo::getCountry)
.thenComparing(this::compareCurrencyInfoPriority));
}
else if (hyperwalletBankAccountCurrencyResolutionConfiguration.isPrioritizeBankAccountTypeOverCurrency()) {
Collections.sort(sortedCurrencyCandidates,
Comparator.comparing(HyperwalletBankAccountCurrencyInfo::getCountry)
.thenComparing(this::compareTransferTypePriority));
}
else {
Collections.sort(sortedCurrencyCandidates,
Comparator.comparing(HyperwalletBankAccountCurrencyInfo::getCountry)
.thenComparing(this::compareTransferTypeOnlyForSameCurrencies));
}
return sortedCurrencyCandidates;
}
private int compareCurrencyInfoPriority(final HyperwalletBankAccountCurrencyInfo c1,
final HyperwalletBankAccountCurrencyInfo c2) {
// The compare algorithm is as follows:
// 1. If prioritizeBankAccountTypeOverCurrency is enabled, then:
// 1.1. we sort the currencies by transfer type, being BANK_ACCOUNT the one with
// the highest priority.
// 1.2. If the currencies have the same transfer type, then we sort them by
// priority.
// 2. If prioritizeBankAccountTypeOverCurrency is disabled, then:
// 2.1 we sort the currencies by priority.
// 2.2 If the currencies have the same priority, then we sort them by transfer
// type, being BANK_ACCUNT the one with the
// highest priority
if (hyperwalletBankAccountCurrencyResolutionConfiguration.isPrioritizeBankAccountTypeOverCurrency()) {
if (compareTransferTypePriority(c1, c2) == 0) {
return compareCurrencyPriority(c1, c2);
}
else {
return compareTransferTypePriority(c1, c2);
}
}
else {
if (compareCurrencyPriority(c1, c2) == 0) {
return compareTransferTypePriority(c1, c2);
}
else {
return compareCurrencyPriority(c1, c2);
}
}
}
private int compareTransferTypeOnlyForSameCurrencies(final HyperwalletBankAccountCurrencyInfo c1,
final HyperwalletBankAccountCurrencyInfo c2) {
if (c1.getCurrency().equals(c2.getCurrency())) {
return compareTransferTypePriority(c1, c2);
}
else {
return 0;
}
}
private int compareCurrencyPriority(final HyperwalletBankAccountCurrencyInfo c1,
final HyperwalletBankAccountCurrencyInfo c2) {
return Integer.compare(getCurrencyPriority(c1), getCurrencyPriority(c2));
}
private int getCurrencyPriority(final HyperwalletBankAccountCurrencyInfo currencyInfo) {
// The priority of a currency is defined by the index of the currency in the list
// of currencies.
// The currency with the highest priority is the one with the lowest index.
// Per country priority has a higher priority than the global priority.
// If the currency is not found in the list, then the priority is -1
final List<String> currencyPriorityPerCountry = hyperwalletBankAccountCurrencyResolutionConfiguration
.getPerCountryCurrencyPriority().get(currencyInfo.getCountry());
final List<String> globalCurrencyPriority = hyperwalletBankAccountCurrencyResolutionConfiguration
.getGlobalCurrencyPriority();
final String currency = currencyInfo.getCurrency();
if (CollectionUtils.isNotEmpty(currencyPriorityPerCountry) && currencyPriorityPerCountry.contains(currency)) {
return currencyPriorityPerCountry.indexOf(currency);
}
else if (CollectionUtils.isNotEmpty(globalCurrencyPriority) && globalCurrencyPriority.contains(currency)) {
return globalCurrencyPriority.indexOf(currency);
}
return Integer.MAX_VALUE;
}
private int compareTransferTypePriority(final HyperwalletBankAccountCurrencyInfo c1,
final HyperwalletBankAccountCurrencyInfo c2) {
// Currency Info with the higher transfer type priority should be first in the
// resulting list
return Integer.compare(getTransferTypePriority(c1), getTransferTypePriority(c2));
}
private int getTransferTypePriority(final HyperwalletBankAccountCurrencyInfo currencyInfo) {
return transferTypePriority.indexOf(currencyInfo.getTransferType());
}
}
| 4,937 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyRestrictions.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class HyperwalletBankAccountCurrencyRestrictions {
private final Map<String, CountryCurrencyEntry> countryCurrencies = new HashMap<>();
public HyperwalletBankAccountCurrencyRestrictions(final List<CountryCurrencyEntry> countryCurrencyEntries) {
countryCurrencyEntries.forEach(this::addCountryCurrencyEntry);
}
public List<HyperwalletBankAccountCurrencyInfo> getCurrenciesFor(final String bankAccountType,
final String bankAccountCountry) {
final CountryCurrencyEntry countryCurrencyEntry = countryCurrencies
.get(getKey(bankAccountType, bankAccountCountry));
return countryCurrencyEntry != null ? countryCurrencyEntry.getSupportedCurrencies() : List.of();
}
public List<CountryCurrencyEntry> getEntriesFor(final String country, final String currency,
final TransferType transferType) {
return countryCurrencies.values().stream()
.filter(countryCurrencyEntry -> countryCurrencyEntry.getCountry().equals(country))
.filter(countryCurrencyEntry -> countryCurrencyEntry.getSupportedCurrencies().stream()
.anyMatch(hyperwalletBankAccountCurrencyInfo -> hyperwalletBankAccountCurrencyInfo.getCurrency()
.equals(currency)
&& hyperwalletBankAccountCurrencyInfo.getTransferType().equals(transferType)))
.collect(Collectors.toList());
}
public int numEntries() {
return countryCurrencies.entrySet().size();
}
private void addCountryCurrencyEntry(final CountryCurrencyEntry countryCurrencyEntry) {
countryCurrencies.put(getKey(countryCurrencyEntry), countryCurrencyEntry);
}
private String getKey(final CountryCurrencyEntry countryCurrencyEntry) {
return getKey(countryCurrencyEntry.bankAccountType, countryCurrencyEntry.country);
}
private String getKey(final String bankAccountType, final String country) {
return bankAccountType.toUpperCase() + "-" + country.toUpperCase();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class CountryCurrencyEntry {
private String bankAccountType;
private String country;
private List<HyperwalletBankAccountCurrencyInfo> supportedCurrencies;
}
}
| 4,938 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyResolver.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
public interface HyperwalletBankAccountCurrencyResolver {
HyperwalletBankAccountCurrencyInfo getCurrencyForCountry(String bankAccountType, String countryIsoCode,
String shopCurrency);
}
| 4,939 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyRestrictionsLoader.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* This class creates an instance of {@link HyperwalletBankAccountCurrencyRestrictions} by
* reading a json containing details about the constraints between bank account types,
* countries and currency.
*/
//@formatter:off
@Configuration
public class HyperwalletBankAccountCurrencyRestrictionsLoader {
@Bean
public HyperwalletBankAccountCurrencyRestrictions countryCurrencyConfiguration() {
final List<HwBankAccountConstraintsJsonEntry> hyperwalletBankAccountRestrictionsJsonEntries
= loadConfigurationEntriesFromJson();
final List<HyperwalletBankAccountCurrencyRestrictions.CountryCurrencyEntry> countryCurrencyEntries
= toCountryCurrencyEntries(hyperwalletBankAccountRestrictionsJsonEntries);
return new HyperwalletBankAccountCurrencyRestrictions(countryCurrencyEntries);
}
private List<HyperwalletBankAccountCurrencyRestrictions.CountryCurrencyEntry> toCountryCurrencyEntries(
final List<HwBankAccountConstraintsJsonEntry> hyperwalletBankAccountRestrictionsJsonEntries) {
// Group hyperwalletBankAccountRestrictionsJsonEntries by country and bankAccountType
final Map<String, List<HwBankAccountConstraintsJsonEntry>> groupedByCountryBankAccountType
= hyperwalletBankAccountRestrictionsJsonEntries.stream()
.collect(Collectors.groupingBy(this::getGroupingKey));
return groupedByCountryBankAccountType.entrySet().stream()
.map(this::toCountryCurrencyEntry)
.collect(Collectors.toList());
}
private String getGroupingKey(final HwBankAccountConstraintsJsonEntry entry) {
return entry.getCountry() + "-" + entry.getBankAccountType();
}
private HyperwalletBankAccountCurrencyRestrictions.CountryCurrencyEntry toCountryCurrencyEntry(
final Map.Entry<String, List<HwBankAccountConstraintsJsonEntry>> countryCurrenciesMap) {
final String[] countryBankAccountType = countryCurrenciesMap.getKey().split("-");
return new HyperwalletBankAccountCurrencyRestrictions.CountryCurrencyEntry(
countryBankAccountType[1],
countryBankAccountType[0],
countryCurrenciesMap.getValue().stream()
.map(this::toCurrencyConfigurationInfo)
.collect(Collectors.toList()));
}
private HyperwalletBankAccountCurrencyInfo toCurrencyConfigurationInfo(
final HwBankAccountConstraintsJsonEntry hwBankAccountConstraintsJsonEntry) {
return new HyperwalletBankAccountCurrencyInfo(
hwBankAccountConstraintsJsonEntry.getCountry(),
hwBankAccountConstraintsJsonEntry.getCurrency(),
TransferType.valueOf(hwBankAccountConstraintsJsonEntry.getTransferType()));
}
private List<HwBankAccountConstraintsJsonEntry> loadConfigurationEntriesFromJson() {
try {
final ClassLoader classLoader = getClass().getClassLoader();
final InputStream inputStream = classLoader.getResourceAsStream("hwapi-bankaccount-constraints.json");
final String json = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
final ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final List<HwBankAccountConstraintsJsonEntry> hwBankAccountConstraintsJsonEntryList =
mapper.readValue(json, new TypeReference<>() { });
return filterUnsupportedConfigurations(hwBankAccountConstraintsJsonEntryList);
}
catch (final IOException e) {
throw new IllegalArgumentException("Hyperwallet API Country Currency constraints file couldn't be read", e);
}
}
private List<HwBankAccountConstraintsJsonEntry> filterUnsupportedConfigurations(
final List<HwBankAccountConstraintsJsonEntry> hyperwalletBankAccountRestrictionsJsonEntries) {
return hyperwalletBankAccountRestrictionsJsonEntries.stream()
.filter(this::isSupported)
.collect(Collectors.toList());
}
private boolean isSupported(final HwBankAccountConstraintsJsonEntry hwBankAccountConstraintsJsonEntry) {
return !Objects.equals("OTHER", hwBankAccountConstraintsJsonEntry.getBankAccountType());
}
@Data
@NoArgsConstructor
private static class HwBankAccountConstraintsJsonEntry {
private String bankAccountType;
private String country;
private String currency;
private String transferType;
}
}
| 4,940 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/currency/HyperwalletBankAccountCurrencyInfo.java | package com.paypal.sellers.bankaccountextraction.services.converters.currency;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
@AllArgsConstructor
public class HyperwalletBankAccountCurrencyInfo {
private String country;
private String currency;
private TransferType transferType;
}
| 4,941 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/mirakl/MiraklShopToUKBankAccountModelConverterStrategy.java | package com.paypal.sellers.bankaccountextraction.services.converters.mirakl;
import com.mirakl.client.mmp.domain.shop.MiraklContactInformation;
import com.mirakl.client.mmp.domain.shop.MiraklProfessionalInformation;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.mirakl.client.mmp.domain.shop.bank.MiraklPaymentInformation;
import com.mirakl.client.mmp.domain.shop.bank.MiraklUkBankAccountInformation;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
import com.paypal.sellers.bankaccountextraction.model.UKBankAccountModel;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyInfo;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyResolver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
/**
* Class to convert from {@link MiraklShop} to {@link UKBankAccountModel}
*/
@Service
public class MiraklShopToUKBankAccountModelConverterStrategy implements Strategy<MiraklShop, BankAccountModel> {
private final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver;
public MiraklShopToUKBankAccountModelConverterStrategy(
final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver) {
this.hyperwalletBankAccountCurrencyResolver = hyperwalletBankAccountCurrencyResolver;
}
/**
* {@inheritDoc}
*/
@Override
public BankAccountModel execute(final MiraklShop source) {
final MiraklPaymentInformation paymentInformation = source.getPaymentInformation();
final MiraklUkBankAccountInformation miraklUkBankAccountInformation = (MiraklUkBankAccountInformation) paymentInformation;
final MiraklContactInformation contactInformation = source.getContactInformation();
final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo = hyperwalletBankAccountCurrencyResolver
.getCurrencyForCountry(BankAccountType.UK.name(), Locale.UK.getCountry(),
source.getCurrencyIsoCode().name());
//@formatter:off
return UKBankAccountModel.builder()
.transferMethodCountry(Locale.UK.getCountry())
.transferMethodCurrency(hyperwalletBankAccountCurrencyInfo.getCurrency())
.transferType(hyperwalletBankAccountCurrencyInfo.getTransferType())
.type(BankAccountType.UK)
.bankAccountNumber(miraklUkBankAccountInformation.getBankAccountNumber())
.bankAccountId(miraklUkBankAccountInformation.getBankSortCode())
.businessName(Optional.ofNullable(source.getProfessionalInformation())
.map(MiraklProfessionalInformation::getCorporateName)
.orElse(null))
.firstName(contactInformation.getFirstname())
.lastName(contactInformation.getLastname())
.country(contactInformation.getCountry())
.addressLine1(contactInformation.getStreet1())
.addressLine2(Optional.ofNullable(contactInformation.getStreet2())
.orElse(StringUtils.EMPTY))
.city(miraklUkBankAccountInformation.getBankCity())
.stateProvince(source.getAdditionalFieldValues())
.token(source.getAdditionalFieldValues())
.hyperwalletProgram(source.getAdditionalFieldValues())
.build();
//@formatter:on
}
/**
* {@inheritDoc}
*/
@Override
public boolean isApplicable(final MiraklShop source) {
return Objects.nonNull(source.getPaymentInformation())
&& source.getPaymentInformation() instanceof MiraklUkBankAccountInformation;
}
}
| 4,942 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/mirakl/MiraklShopToABABankAccountModelConverterStrategy.java | package com.paypal.sellers.bankaccountextraction.services.converters.mirakl;
import com.mirakl.client.mmp.domain.shop.MiraklContactInformation;
import com.mirakl.client.mmp.domain.shop.MiraklProfessionalInformation;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.mirakl.client.mmp.domain.shop.bank.MiraklAbaBankAccountInformation;
import com.mirakl.client.mmp.domain.shop.bank.MiraklPaymentInformation;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.ABABankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.BankAccountPurposeType;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyInfo;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
/**
* Class to convert from {@link MiraklShop} to {@link ABABankAccountModel}
*/
@Slf4j
@Service
public class MiraklShopToABABankAccountModelConverterStrategy implements Strategy<MiraklShop, BankAccountModel> {
private final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver;
public MiraklShopToABABankAccountModelConverterStrategy(
final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver) {
this.hyperwalletBankAccountCurrencyResolver = hyperwalletBankAccountCurrencyResolver;
}
/**
* {@inheritDoc}
*/
@Override
public ABABankAccountModel execute(@NonNull final MiraklShop source) {
final MiraklPaymentInformation paymentInformation = source.getPaymentInformation();
final MiraklAbaBankAccountInformation miraklAbaBankAccountInformation = (MiraklAbaBankAccountInformation) paymentInformation;
final MiraklContactInformation contactInformation = source.getContactInformation();
final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo = hyperwalletBankAccountCurrencyResolver
.getCurrencyForCountry(BankAccountType.ABA.name(), Locale.US.getCountry(),
source.getCurrencyIsoCode().name());
//@formatter:off
return ABABankAccountModel.builder()
.transferMethodCountry(Locale.US.getCountry())
.branchId(miraklAbaBankAccountInformation.getRoutingNumber())
.bankAccountPurpose(BankAccountPurposeType.CHECKING.name())
.transferMethodCurrency(hyperwalletBankAccountCurrencyInfo.getCurrency())
.transferType(hyperwalletBankAccountCurrencyInfo.getTransferType())
.type(BankAccountType.ABA)
.bankAccountNumber(miraklAbaBankAccountInformation.getBankAccountNumber())
.businessName(Optional.ofNullable(source.getProfessionalInformation())
.map(MiraklProfessionalInformation::getCorporateName)
.orElse(null))
.firstName(contactInformation.getFirstname())
.lastName(contactInformation.getLastname())
.country(contactInformation.getCountry())
.city(miraklAbaBankAccountInformation.getBankCity())
.stateProvince(source.getAdditionalFieldValues())
.postalCode(miraklAbaBankAccountInformation.getBankZip())
.addressLine1(contactInformation.getStreet1())
.addressLine2(Optional.ofNullable(contactInformation.getStreet2())
.orElse(StringUtils.EMPTY))
.token(source.getAdditionalFieldValues())
.hyperwalletProgram(source.getAdditionalFieldValues())
.build();
//@formatter:on
}
/**
* {@inheritDoc}
*/
@Override
public boolean isApplicable(final MiraklShop source) {
return Objects.nonNull(source.getPaymentInformation())
&& source.getPaymentInformation() instanceof MiraklAbaBankAccountInformation;
}
}
| 4,943 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/mirakl/MiraklShopToCanadianBankAccountModelConverterStrategy.java | package com.paypal.sellers.bankaccountextraction.services.converters.mirakl;
import com.mirakl.client.mmp.domain.shop.MiraklContactInformation;
import com.mirakl.client.mmp.domain.shop.MiraklProfessionalInformation;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.mirakl.client.mmp.domain.shop.bank.MiraklCanadianBankAccountInformation;
import com.mirakl.client.mmp.domain.shop.bank.MiraklPaymentInformation;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
import com.paypal.sellers.bankaccountextraction.model.CanadianBankAccountModel;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyInfo;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
/**
* Class to convert from {@link MiraklShop} to {@link CanadianBankAccountModel}
*/
@Slf4j
@Service
public class MiraklShopToCanadianBankAccountModelConverterStrategy implements Strategy<MiraklShop, BankAccountModel> {
private final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver;
public MiraklShopToCanadianBankAccountModelConverterStrategy(
final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver) {
this.hyperwalletBankAccountCurrencyResolver = hyperwalletBankAccountCurrencyResolver;
}
/**
* {@inheritDoc}
*/
@Override
public BankAccountModel execute(final MiraklShop source) {
final MiraklPaymentInformation paymentInformation = source.getPaymentInformation();
final MiraklCanadianBankAccountInformation miraklCanadianBankAccountInformation = (MiraklCanadianBankAccountInformation) paymentInformation;
final MiraklContactInformation contactInformation = source.getContactInformation();
final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo = hyperwalletBankAccountCurrencyResolver
.getCurrencyForCountry(BankAccountType.CANADIAN.name(), Locale.CANADA.getCountry(),
source.getCurrencyIsoCode().name());
//@formatter:off
return CanadianBankAccountModel.builder()
.bankId(miraklCanadianBankAccountInformation.getInstitutionNumber())
.branchId(miraklCanadianBankAccountInformation.getTransitNumber())
.transferMethodCountry(Locale.CANADA.getCountry())
.transferMethodCurrency(hyperwalletBankAccountCurrencyInfo.getCurrency())
.transferType(hyperwalletBankAccountCurrencyInfo.getTransferType())
.type(BankAccountType.CANADIAN)
.bankAccountNumber(miraklCanadianBankAccountInformation.getBankAccountNumber())
.businessName(Optional.ofNullable(source.getProfessionalInformation())
.map(MiraklProfessionalInformation::getCorporateName)
.orElse(null))
.firstName(contactInformation.getFirstname())
.lastName(contactInformation.getLastname())
.country(contactInformation.getCountry())
.city(miraklCanadianBankAccountInformation.getBankCity())
.stateProvince(source.getAdditionalFieldValues())
.postalCode(miraklCanadianBankAccountInformation.getBankZip())
.addressLine1(contactInformation.getStreet1())
.addressLine2(Optional.ofNullable(contactInformation.getStreet2())
.orElse(StringUtils.EMPTY))
.token(source.getAdditionalFieldValues())
.hyperwalletProgram(source.getAdditionalFieldValues())
.build();
//@formatter:on
}
/**
* {@inheritDoc}
*/
@Override
public boolean isApplicable(final MiraklShop source) {
return Objects.nonNull(source.getPaymentInformation())
&& source.getPaymentInformation() instanceof MiraklCanadianBankAccountInformation;
}
}
| 4,944 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/bankaccountextraction/services/converters/mirakl/MiraklShopToIBANBankAccountModelConverterStrategy.java | package com.paypal.sellers.bankaccountextraction.services.converters.mirakl;
import com.mirakl.client.mmp.domain.shop.MiraklContactInformation;
import com.mirakl.client.mmp.domain.shop.MiraklProfessionalInformation;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.mirakl.client.mmp.domain.shop.bank.MiraklIbanBankAccountInformation;
import com.mirakl.client.mmp.domain.shop.bank.MiraklPaymentInformation;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.BankAccountType;
import com.paypal.sellers.bankaccountextraction.model.IBANBankAccountModel;
import com.paypal.sellers.bankaccountextraction.model.TransferType;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyInfo;
import com.paypal.sellers.bankaccountextraction.services.converters.currency.HyperwalletBankAccountCurrencyResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Optional;
/**
* Class to convert from {@link MiraklShop} to {@link IBANBankAccountModel}
*/
@Slf4j
@Service
public class MiraklShopToIBANBankAccountModelConverterStrategy implements Strategy<MiraklShop, BankAccountModel> {
private final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver;
public MiraklShopToIBANBankAccountModelConverterStrategy(
final HyperwalletBankAccountCurrencyResolver hyperwalletBankAccountCurrencyResolver) {
this.hyperwalletBankAccountCurrencyResolver = hyperwalletBankAccountCurrencyResolver;
}
/**
* {@inheritDoc}
*/
@Override
public IBANBankAccountModel execute(@NonNull final MiraklShop source) {
final MiraklPaymentInformation paymentInformation = source.getPaymentInformation();
final MiraklIbanBankAccountInformation miraklIbanBankAccountInformation = (MiraklIbanBankAccountInformation) paymentInformation;
final MiraklContactInformation contactInformation = source.getContactInformation();
final String bankCountryIsoCode = extractCountryFromIban(source, miraklIbanBankAccountInformation);
final HyperwalletBankAccountCurrencyInfo hyperwalletBankAccountCurrencyInfo = hyperwalletBankAccountCurrencyResolver
.getCurrencyForCountry(BankAccountType.IBAN.name(), bankCountryIsoCode,
source.getCurrencyIsoCode().name());
//@formatter:off
return IBANBankAccountModel.builder()
.transferMethodCountry(bankCountryIsoCode)
.transferMethodCurrency(source.getCurrencyIsoCode().name())
.transferMethodCurrency(hyperwalletBankAccountCurrencyInfo.getCurrency())
.transferType(TransferType.BANK_ACCOUNT)
.type(BankAccountType.IBAN)
.bankBic(miraklIbanBankAccountInformation.getBic())
.bankAccountNumber(miraklIbanBankAccountInformation.getIban())
.businessName(Optional.ofNullable(source.getProfessionalInformation())
.map(MiraklProfessionalInformation::getCorporateName)
.orElse(null))
.firstName(contactInformation.getFirstname())
.lastName(contactInformation.getLastname())
.country(contactInformation.getCountry())
.addressLine1(contactInformation.getStreet1())
.addressLine2(Optional.ofNullable(contactInformation.getStreet2())
.orElse(StringUtils.EMPTY))
.city(miraklIbanBankAccountInformation.getBankCity())
.stateProvince(source.getAdditionalFieldValues())
.token(source.getAdditionalFieldValues())
.hyperwalletProgram(source.getAdditionalFieldValues())
.build();
//@formatter:on
}
private String extractCountryFromIban(final MiraklShop source, final MiraklIbanBankAccountInformation ibanInfo) {
final String iban = ibanInfo.getIban();
if (StringUtils.isBlank(iban) || iban.length() < 2) {
throw new IllegalStateException("IBAN invalid on shop: %s".formatted(source.getId()));
}
return iban.substring(0, 2);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isApplicable(final MiraklShop source) {
return Objects.nonNull(source.getPaymentInformation())
&& source.getPaymentInformation() instanceof MiraklIbanBankAccountInformation;
}
}
| 4,945 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/BusinessStakeholdersExtractionJobsConfig.java | package com.paypal.sellers.stakeholdersextraction;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobBuilder;
import com.paypal.sellers.professionalsellersextraction.ProfessionalSellersExtractionJobsConfig;
import com.paypal.sellers.stakeholdersextraction.batchjobs.BusinessStakeholdersRetryBatchJob;
import com.paypal.sellers.professionalsellersextraction.jobs.ProfessionalSellersExtractJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration class for scheduling jobs at startup
*/
@Configuration
public class BusinessStakeholdersExtractionJobsConfig {
private static final String TRIGGER_SUFFIX = "Trigger";
private static final String RETRY_JOB_NAME = "BusinessStakeholdersRetryJob";
@Bean
public JobDetail businessStakeholdersRetryJob(
final BusinessStakeholdersRetryBatchJob businessStakeholdersRetryBatchJob) {
//@formatter:off
return QuartzBatchJobBuilder.newJob(businessStakeholdersRetryBatchJob)
.withIdentity(RETRY_JOB_NAME)
.storeDurably()
.build();
//@formatter:on
}
/**
* Schedules the recurring job {@link ProfessionalSellersExtractJob} with the
* {@code jobDetails} set on
* {@link ProfessionalSellersExtractionJobsConfig#professionalSellerExtractJob()}
* @param jobDetails the {@link JobDetail}
* @return the {@link Trigger}
*/
@Bean
public Trigger businessStakeholdersRetryTrigger(
@Qualifier("businessStakeholdersRetryJob") final JobDetail jobDetails,
@Value("${hmc.jobs.scheduling.retry-jobs.businessstakeholders}") final String cronExpression) {
//@formatter:off
return TriggerBuilder.newTrigger()
.forJob(jobDetails)
.withIdentity(TRIGGER_SUFFIX + RETRY_JOB_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
//@formatter:on
}
}
| 4,946 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholderExtractJobItem.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
/**
* Class that holds the needed information for batch processing
* {@link BusinessStakeHolderModel}
*/
public class BusinessStakeholderExtractJobItem extends AbstractBatchJobItem<BusinessStakeHolderModel> {
public static final String ITEM_TYPE = "BusinessStakeholder";
protected BusinessStakeholderExtractJobItem(final BusinessStakeHolderModel item) {
super(item);
}
/**
* Returns the client user id and the stakeholder id.
* @return the client user id and the stakeholder id.
*/
@Override
public String getItemId() {
return getItem().getClientUserId() + "-" + getItem().getStkId();
}
/**
* Returns the business stakeholder item type.
* @return BusinessStakeholder as the business stakeholder item type.
*/
@Override
public String getItemType() {
return ITEM_TYPE;
}
}
| 4,947 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholdersRetryBatchJob.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractRetryBatchJob;
import org.springframework.stereotype.Component;
/**
* Retries items that have failed during the business stakeholders extract job
*/
@Component
public class BusinessStakeholdersRetryBatchJob
extends AbstractRetryBatchJob<BatchJobContext, BusinessStakeholderExtractJobItem> {
private final BusinessStakeholdersExtractBatchJobItemProcessor businessStakeholdersExtractBatchJobItemProcessor;
private final BusinessStakeholdersRetryBatchJobItemsExtractor businessStakeholdersRetryBatchJobItemsExtractor;
public BusinessStakeholdersRetryBatchJob(
final BusinessStakeholdersExtractBatchJobItemProcessor businessStakeholdersExtractBatchJobItemProcessor,
final BusinessStakeholdersRetryBatchJobItemsExtractor businessStakeholdersRetryBatchJobItemsExtractor) {
this.businessStakeholdersExtractBatchJobItemProcessor = businessStakeholdersExtractBatchJobItemProcessor;
this.businessStakeholdersRetryBatchJobItemsExtractor = businessStakeholdersRetryBatchJobItemsExtractor;
}
@Override
protected BatchJobItemProcessor<BatchJobContext, BusinessStakeholderExtractJobItem> getBatchJobItemProcessor() {
return businessStakeholdersExtractBatchJobItemProcessor;
}
@Override
protected BatchJobItemsExtractor<BatchJobContext, BusinessStakeholderExtractJobItem> getBatchJobItemsExtractor() {
return businessStakeholdersRetryBatchJobItemsExtractor;
}
}
| 4,948 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholdersExtractBatchJob.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractExtractBatchJob;
import org.springframework.stereotype.Component;
/**
* Extract business stakeholders job for extracting Mirakl professional sellers data and
* populate it on HyperWallet as users.
*/
@Component
public class BusinessStakeholdersExtractBatchJob
extends AbstractExtractBatchJob<BatchJobContext, BusinessStakeholderExtractJobItem> {
private final BusinessStakeholdersExtractBatchJobItemsExtractor professionalSellersExtractBatchJobItemsExtractor;
private final BusinessStakeholdersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor;
public BusinessStakeholdersExtractBatchJob(
final BusinessStakeholdersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor,
final BusinessStakeholdersExtractBatchJobItemsExtractor professionalSellersExtractBatchJobItemsExtractor) {
this.professionalSellersExtractBatchJobItemProcessor = professionalSellersExtractBatchJobItemProcessor;
this.professionalSellersExtractBatchJobItemsExtractor = professionalSellersExtractBatchJobItemsExtractor;
}
/**
* Retrieves the business stakeholders batch job item processor
* @return the {@link BatchJobItemProcessor} for
* {@link BusinessStakeholderExtractJobItem}
*/
@Override
protected BatchJobItemProcessor<BatchJobContext, BusinessStakeholderExtractJobItem> getBatchJobItemProcessor() {
return this.professionalSellersExtractBatchJobItemProcessor;
}
/**
* Retrieves the business stakeholders batch job items extractor
* @return the {@link BatchJobItemsExtractor} for
* {@link BusinessStakeholderExtractJobItem}
*/
@Override
protected BatchJobItemsExtractor<BatchJobContext, BusinessStakeholderExtractJobItem> getBatchJobItemsExtractor() {
return this.professionalSellersExtractBatchJobItemsExtractor;
}
}
| 4,949 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholdersRetryBatchJobItemsExtractor.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobfailures.services.BatchJobFailedItemService;
import com.paypal.jobsystem.batchjobfailures.services.cache.BatchJobFailedItemCacheService;
import com.paypal.jobsystem.batchjobfailures.support.AbstractCachingFailedItemsBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.stakeholdersextraction.services.BusinessStakeholderExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Extract business stakeholders for retry from the failed items cache.
*/
@Component
public class BusinessStakeholdersRetryBatchJobItemsExtractor
extends AbstractCachingFailedItemsBatchJobItemsExtractor<BatchJobContext, BusinessStakeholderExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
private final BusinessStakeholderExtractService businessStakeholderExtractService;
protected BusinessStakeholdersRetryBatchJobItemsExtractor(final BatchJobFailedItemService batchJobFailedItemService,
final BatchJobFailedItemCacheService batchJobFailedItemCacheService,
final MiraklSellersExtractService miraklSellersExtractService,
final BusinessStakeholderExtractService businessStakeholderExtractService) {
super(BusinessStakeholderExtractJobItem.class, BusinessStakeholderExtractJobItem.ITEM_TYPE,
batchJobFailedItemService, batchJobFailedItemCacheService);
this.miraklSellersExtractService = miraklSellersExtractService;
this.businessStakeholderExtractService = businessStakeholderExtractService;
}
@Override
protected Collection<BusinessStakeholderExtractJobItem> getItems(final List<String> ids) {
final List<SellerModel> miraklProfessionalSellers = miraklSellersExtractService.extractProfessionals(ids);
final List<BusinessStakeHolderModel> businessStakeHolderModels = businessStakeholderExtractService
.extractBusinessStakeHolders(miraklProfessionalSellers);
return businessStakeHolderModels.stream().map(BusinessStakeholderExtractJobItem::new)
.collect(Collectors.toList());
}
}
| 4,950 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholdersExtractBatchJobItemsExtractor.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobaudit.services.BatchJobTrackingService;
import com.paypal.jobsystem.batchjobsupport.support.AbstractDynamicWindowDeltaBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.stakeholdersextraction.services.BusinessStakeholderExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* The extractor class for retrieving all the business stakeholders within a delta time
* from mirakl
*/
@Component
public class BusinessStakeholdersExtractBatchJobItemsExtractor
extends AbstractDynamicWindowDeltaBatchJobItemsExtractor<BatchJobContext, BusinessStakeholderExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
private final BusinessStakeholderExtractService businessStakeholderExtractService;
public BusinessStakeholdersExtractBatchJobItemsExtractor(
final MiraklSellersExtractService miraklSellersExtractService,
final BusinessStakeholderExtractService businessStakeholderExtractService,
final BatchJobTrackingService batchJobTrackingService) {
super(batchJobTrackingService);
this.miraklSellersExtractService = miraklSellersExtractService;
this.businessStakeholderExtractService = businessStakeholderExtractService;
}
/**
* Retrieves all the stakeholders modified since the {@code delta} time and returns
* them as a {@link BusinessStakeholderExtractJobItem}
* @param delta the cut-out {@link Date}
* @return a {@link Collection} of {@link BusinessStakeholderExtractJobItem}
*/
@Override
protected Collection<BusinessStakeholderExtractJobItem> getItems(final BatchJobContext ctx, final Date delta) {
final List<SellerModel> miraklProfessionalSellers = miraklSellersExtractService.extractProfessionals(delta);
final List<BusinessStakeHolderModel> businessStakeHolderModels = businessStakeholderExtractService
.extractBusinessStakeHolders(miraklProfessionalSellers);
return businessStakeHolderModels.stream().map(BusinessStakeholderExtractJobItem::new)
.collect(Collectors.toList());
}
}
| 4,951 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/batchjobs/BusinessStakeholdersExtractBatchJobItemProcessor.java | package com.paypal.sellers.stakeholdersextraction.batchjobs;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.stakeholdersextraction.services.strategies.HyperWalletBusinessStakeHolderStrategyExecutor;
import org.springframework.stereotype.Component;
/**
* Business stakeholders extract batch job item processor for creating the users in HW.
*/
@Component
public class BusinessStakeholdersExtractBatchJobItemProcessor
implements BatchJobItemProcessor<BatchJobContext, BusinessStakeholderExtractJobItem> {
private final HyperWalletBusinessStakeHolderStrategyExecutor hyperWalletBusinessStakeHolderStrategyExecutor;
private final TokenSynchronizationService<BusinessStakeHolderModel> businessStakeholderTokenSynchronizationService;
public BusinessStakeholdersExtractBatchJobItemProcessor(
final HyperWalletBusinessStakeHolderStrategyExecutor hyperWalletBusinessStakeHolderStrategyExecutor,
final TokenSynchronizationService<BusinessStakeHolderModel> businessStakeholderTokenSynchronizationService) {
this.hyperWalletBusinessStakeHolderStrategyExecutor = hyperWalletBusinessStakeHolderStrategyExecutor;
this.businessStakeholderTokenSynchronizationService = businessStakeholderTokenSynchronizationService;
}
/**
* Processes the {@link BusinessStakeholderExtractJobItem} with the
* {@link HyperWalletBusinessStakeHolderStrategyExecutor} and update the executed
* {@link BusinessStakeHolderModel}.
* @param ctx The {@link BatchJobContext}
* @param jobItem The {@link BusinessStakeholderExtractJobItem}
*/
@Override
public void processItem(final BatchJobContext ctx, final BusinessStakeholderExtractJobItem jobItem) {
final BusinessStakeHolderModel synchronizedBusinessStakeHolderModel = businessStakeholderTokenSynchronizationService
.synchronizeToken(jobItem.getItem());
hyperWalletBusinessStakeHolderStrategyExecutor.execute(synchronizedBusinessStakeHolderModel);
}
}
| 4,952 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/model/BusinessStakeHolderConstants.java | package com.paypal.sellers.stakeholdersextraction.model;
/**
* Holds the id of the custom fields created for stakeholders in Mirakl
*/
public final class BusinessStakeHolderConstants {
private BusinessStakeHolderConstants() {
}
public static final String TOKEN = "hw-stakeholder-token";
public static final String BUSINESS = "hw-stakeholder-business-contact";
public static final String DIRECTOR = "hw-stakeholder-director";
public static final String UBO = "hw-stakeholder-ubo";
public static final String SMO = "hw-stakeholder-smo";
public static final String FIRST_NAME = "hw-stakeholder-first-name";
public static final String MIDDLE_NAME = "hw-stakeholder-middle-name";
public static final String LAST_NAME = "hw-stakeholder-last-name";
public static final String DOB = "hw-stakeholder-dob";
public static final String COUNTRY_OF_BIRTH = "hw-stakeholder-country-of-birth";
public static final String NATIONALITY = "hw-stakeholder-nationality";
public static final String GENDER = "hw-stakeholder-gender";
public static final String PHONE_NUMBER = "hw-stakeholder-phone-number";
public static final String MOBILE_NUMBER = "hw-stakeholder-mobile-number";
public static final String EMAIL = "hw-stakeholder-email";
public static final String ADDRESS_LINE_1 = "hw-stakeholder-address-line1";
public static final String ADDRESS_LINE_2 = "hw-stakeholder-address-line2";
public static final String CITY = "hw-stakeholder-city";
public static final String STATE = "hw-stakeholder-state";
public static final String POST_CODE = "hw-stakeholder-post-code";
public static final String COUNTRY = "hw-stakeholder-country";
public static final String GOVERNMENT_ID_TYPE = "hw-stakeholder-government-id-type";
public static final String GOVERNMENT_ID_NUM = "hw-stakeholder-government-id-num";
public static final String GOVERNMENT_ID_COUNT = "hw-stakeholder-government-id-count";
public static final String DRIVERS_LICENSE_NUM = "hw-stakeholder-drivers-license-num";
public static final String DRIVERS_LICENSE_CNT = "hw-stakeholder-drivers-license-cnt";
}
| 4,953 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/model/BusinessStakeHolderModel.java | package com.paypal.sellers.stakeholdersextraction.model;
import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue;
import com.paypal.sellers.sellerextractioncommons.model.SellerGender;
import com.paypal.sellers.sellerextractioncommons.model.SellerGovernmentIdType;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderConstants.*;
import static com.paypal.sellers.sellerextractioncommons.model.SellerModelConstants.HYPERWALLET_PROGRAM;
import static com.paypal.sellers.sellerextractioncommons.model.SellerModelConstants.HYPERWALLET_USER_TOKEN;
/**
* Creates an object of type {@link BusinessStakeHolderModel}
*/
@Slf4j
@Getter
@Builder
public class BusinessStakeHolderModel {
private final String timeZone;
private final int stkId;
private final boolean justCreated;
private final String userToken;
private final String clientUserId;
private final String token;
private final Boolean businessContact;
private final Boolean director;
private final Boolean ubo;
private final Boolean smo;
private final String firstName;
private final String middleName;
private final String lastName;
private final Date dateOfBirth;
private final String countryOfBirth;
private final String countryOfNationality;
private final SellerGender gender;
private final String phoneNumber;
private final String mobileNumber;
private final String email;
private final String governmentId;
private final SellerGovernmentIdType governmentIdType;
private final String driversLicenseId;
private final String addressLine1;
private final String addressLine2;
private final String city;
private final String stateProvince;
private final String country;
private final String postalCode;
private final String hyperwalletProgram;
public BusinessStakeHolderModelBuilder toBuilder() {
//@formatter:off
return BusinessStakeHolderModel.builder()
.stkId(stkId)
.userToken(userToken)
.clientUserId(clientUserId)
.token(token)
.businessContact(businessContact)
.director(director)
.ubo(ubo)
.smo(smo)
.firstName(firstName)
.middleName(middleName)
.lastName(lastName)
.timeZone(timeZone)
.dateOfBirth(dateOfBirth)
.countryOfBirth(countryOfBirth)
.countryOfNationality(countryOfNationality)
.gender(gender)
.phoneNumber(phoneNumber)
.mobileNumber(mobileNumber)
.email(email)
.governmentId(governmentId)
.governmentIdType(governmentIdType)
.driversLicenseId(driversLicenseId)
.addressLine1(addressLine1)
.addressLine2(addressLine2)
.city(city)
.stateProvince(stateProvince)
.country(country)
.postalCode(postalCode)
.hyperwalletProgram(hyperwalletProgram);
//@formatter:on
}
public boolean isEmpty() {
return Objects.isNull(token) && Objects.isNull(businessContact) && Objects.isNull(director)
&& Objects.isNull(ubo) && Objects.isNull(smo) && Objects.isNull(firstName) && Objects.isNull(middleName)
&& Objects.isNull(lastName) && Objects.isNull(dateOfBirth) && Objects.isNull(countryOfBirth)
&& Objects.isNull(countryOfNationality) && Objects.isNull(gender) && Objects.isNull(phoneNumber)
&& Objects.isNull(mobileNumber) && Objects.isNull(email) && Objects.isNull(governmentId)
&& Objects.isNull(governmentIdType) && Objects.isNull(driversLicenseId) && Objects.isNull(addressLine1)
&& Objects.isNull(addressLine2) && Objects.isNull(city) && Objects.isNull(stateProvince)
&& Objects.isNull(country) && Objects.isNull(postalCode);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BusinessStakeHolderModel)) {
return false;
}
//@formatter:off
final BusinessStakeHolderModel that = (BusinessStakeHolderModel) o;
return EqualsBuilder.reflectionEquals(this, that);
//@formatter:on
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public static class BusinessStakeHolderModelBuilder {
private static final String BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE = "Business Stake Holder number {} incorrect. System only allows Business stake holder attributes from 1 to 5";
public BusinessStakeHolderModelBuilder token(final String token) {
this.token = token;
return this;
}
public BusinessStakeHolderModelBuilder token(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
token = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(TOKEN, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder businessContact(final List<MiraklAdditionalFieldValue> fields,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklBooleanCustomFieldValue(fields, getCustomFieldCode(BUSINESS, businessStakeHolderNumber))
.ifPresent(retrievedBusinessContact -> businessContact = Boolean
.valueOf(retrievedBusinessContact));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder userToken(final List<MiraklAdditionalFieldValue> fields) {
getMiraklStringCustomFieldValue(fields, HYPERWALLET_USER_TOKEN)
.ifPresent(retrievedToken -> userToken = retrievedToken);
return this;
}
private BusinessStakeHolderModelBuilder businessContact(final Boolean businessContact) {
this.businessContact = businessContact;
return this;
}
public BusinessStakeHolderModelBuilder director(final List<MiraklAdditionalFieldValue> fields,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklBooleanCustomFieldValue(fields, getCustomFieldCode(DIRECTOR, businessStakeHolderNumber))
.ifPresent(retrievedDirector -> director = Boolean.valueOf(retrievedDirector));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
private BusinessStakeHolderModelBuilder director(final Boolean director) {
this.director = director;
return this;
}
public BusinessStakeHolderModelBuilder ubo(final List<MiraklAdditionalFieldValue> fields,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklBooleanCustomFieldValue(fields, getCustomFieldCode(UBO, businessStakeHolderNumber))
.ifPresent(retrievedUbo -> ubo = Boolean.valueOf(retrievedUbo));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder smo(final List<MiraklAdditionalFieldValue> fields,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklBooleanCustomFieldValue(fields, getCustomFieldCode(SMO, businessStakeHolderNumber))
.ifPresent(retrievedSmo -> smo = Boolean.valueOf(retrievedSmo));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder firstName(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
firstName = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(FIRST_NAME, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder middleName(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
middleName = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(MIDDLE_NAME, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder lastName(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
lastName = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(LAST_NAME, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder dateOfBirth(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
dateOfBirth = getMiraklDateCustomFieldValue(fieldValues,
getCustomFieldCode(DOB, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder countryOfBirth(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
countryOfBirth = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(COUNTRY_OF_BIRTH, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder countryOfNationality(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
countryOfNationality = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(NATIONALITY, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder gender(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklSingleValueListCustomFieldValue(fieldValues,
getCustomFieldCode(GENDER, businessStakeHolderNumber))
.ifPresent(retrievedGovernmentIdType -> gender = EnumUtils.getEnum(SellerGender.class,
retrievedGovernmentIdType));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder phoneNumber(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
phoneNumber = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(PHONE_NUMBER, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder mobileNumber(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
mobileNumber = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(MOBILE_NUMBER, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder email(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
email = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(EMAIL, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder governmentId(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
governmentId = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(GOVERNMENT_ID_NUM, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder governmentIdType(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
getMiraklSingleValueListCustomFieldValue(fieldValues,
getCustomFieldCode(GOVERNMENT_ID_TYPE, businessStakeHolderNumber))
.ifPresent(retrievedGovernmentIdType -> governmentIdType = EnumUtils
.getEnum(SellerGovernmentIdType.class, retrievedGovernmentIdType));
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder driversLicenseId(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
driversLicenseId = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(DRIVERS_LICENSE_NUM, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder addressLine1(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
addressLine1 = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(ADDRESS_LINE_1, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder addressLine2(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
addressLine2 = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(ADDRESS_LINE_2, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder city(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
city = getMiraklStringCustomFieldValue(fieldValues, getCustomFieldCode(CITY, businessStakeHolderNumber))
.orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder country(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
country = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(COUNTRY, businessStakeHolderNumber)).orElse(null);
return this;
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder stateProvince(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
stateProvince = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(STATE, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder postalCode(final List<MiraklAdditionalFieldValue> fieldValues,
final Integer businessStakeHolderNumber) {
if (validateBusinessStakeHolderNumber(businessStakeHolderNumber)) {
postalCode = getMiraklStringCustomFieldValue(fieldValues,
getCustomFieldCode(POST_CODE, businessStakeHolderNumber)).orElse(null);
}
else {
log.warn(BUSINESS_STAKE_HOLDER_OUT_OF_INBOUND_MESSAGE, businessStakeHolderNumber);
}
return this;
}
public BusinessStakeHolderModelBuilder hyperwalletProgram(final List<MiraklAdditionalFieldValue> fieldValues) {
getMiraklSingleValueListCustomFieldValue(fieldValues, HYPERWALLET_PROGRAM)
.ifPresent(hyperwalletProgramValue -> hyperwalletProgram = hyperwalletProgramValue);
return this;
}
private Optional<String> getMiraklSingleValueListCustomFieldValue(final List<MiraklAdditionalFieldValue> fields,
final String customFieldCode) {
//@formatter:off
return fields.stream()
.filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklValueListAdditionalFieldValue.class::cast).findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue);
//@formatter:on
}
private Optional<String> getMiraklStringCustomFieldValue(final List<MiraklAdditionalFieldValue> fields,
final String customFieldCode) {
//@formatter:off
return fields.stream().filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklStringAdditionalFieldValue.class::cast)
.findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue);
//@formatter:on
}
private Optional<String> getMiraklBooleanCustomFieldValue(final List<MiraklAdditionalFieldValue> fields,
final String customFieldCode) {
return fields.stream().filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklBooleanAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklBooleanAdditionalFieldValue.class::cast).findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue);
}
private Optional<Date> getMiraklDateCustomFieldValue(final List<MiraklAdditionalFieldValue> fieldValues,
final String customFieldCode) {
return fieldValues.stream().filter(field -> field.getCode().equals(customFieldCode))
.filter(MiraklAdditionalFieldValue.MiraklDateAdditionalFieldValue.class::isInstance)
.map(MiraklAdditionalFieldValue.MiraklDateAdditionalFieldValue.class::cast).findAny()
.map(MiraklAdditionalFieldValue.MiraklAbstractAdditionalFieldWithSingleValue::getValue)
.map((dateAsStringISO8601 -> {
try {
final ZonedDateTime zonedDateTime = Instant.parse(dateAsStringISO8601)
.atZone(ZoneId.of(timeZone));
final long offsetMillis = TimeUnit.SECONDS
.toMillis(ZoneOffset.from(zonedDateTime).getTotalSeconds());
final long isoMillis = zonedDateTime.toInstant().toEpochMilli();
return new Date(isoMillis + offsetMillis);
}
catch (final DateTimeParseException dtpex) {
log.error("Date value with [{}] is not in the correct ISO8601 format", dateAsStringISO8601);
return null;
}
}));
}
@NotNull
private String getCustomFieldCode(final String customField, final Integer businessStakeHolderNumber) {
return customField.concat("-").concat(String.valueOf(businessStakeHolderNumber));
}
private boolean validateBusinessStakeHolderNumber(final Integer businessStakeHolderNumber) {
return Objects.nonNull(businessStakeHolderNumber) && businessStakeHolderNumber > 0
&& businessStakeHolderNumber < 6;
}
private BusinessStakeHolderModelBuilder postalCode(final String postalCode) {
this.postalCode = postalCode;
return this;
}
private BusinessStakeHolderModelBuilder country(final String country) {
this.country = country;
return this;
}
private BusinessStakeHolderModelBuilder stateProvince(final String stateProvince) {
this.stateProvince = stateProvince;
return this;
}
private BusinessStakeHolderModelBuilder city(final String city) {
this.city = city;
return this;
}
private BusinessStakeHolderModelBuilder addressLine2(final String addressLine2) {
this.addressLine2 = addressLine2;
return this;
}
private BusinessStakeHolderModelBuilder addressLine1(final String addressLine1) {
this.addressLine1 = addressLine1;
return this;
}
private BusinessStakeHolderModelBuilder driversLicenseId(final String driversLicenseId) {
this.driversLicenseId = driversLicenseId;
return this;
}
private BusinessStakeHolderModelBuilder governmentIdType(final SellerGovernmentIdType governmentIdType) {
this.governmentIdType = governmentIdType;
return this;
}
private BusinessStakeHolderModelBuilder governmentId(final String governmentId) {
this.governmentId = governmentId;
return this;
}
private BusinessStakeHolderModelBuilder email(final String email) {
this.email = email;
return this;
}
private BusinessStakeHolderModelBuilder mobileNumber(final String mobileNumber) {
this.mobileNumber = mobileNumber;
return this;
}
private BusinessStakeHolderModelBuilder phoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
private BusinessStakeHolderModelBuilder gender(final SellerGender gender) {
this.gender = gender;
return this;
}
private BusinessStakeHolderModelBuilder countryOfNationality(final String countryOfNationality) {
this.countryOfNationality = countryOfNationality;
return this;
}
private BusinessStakeHolderModelBuilder countryOfBirth(final String countryOfBirth) {
this.countryOfBirth = countryOfBirth;
return this;
}
private BusinessStakeHolderModelBuilder dateOfBirth(final Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
return this;
}
private BusinessStakeHolderModelBuilder lastName(final String lastName) {
this.lastName = lastName;
return this;
}
private BusinessStakeHolderModelBuilder middleName(final String middleName) {
this.middleName = middleName;
return this;
}
private BusinessStakeHolderModelBuilder firstName(final String firstName) {
this.firstName = firstName;
return this;
}
private BusinessStakeHolderModelBuilder smo(final Boolean smo) {
this.smo = smo;
return this;
}
private BusinessStakeHolderModelBuilder ubo(final Boolean ubo) {
this.ubo = ubo;
return this;
}
public BusinessStakeHolderModelBuilder userToken(final String userToken) {
this.userToken = userToken;
return this;
}
public BusinessStakeHolderModelBuilder hyperwalletProgram(final String hyperwalletProgram) {
this.hyperwalletProgram = hyperwalletProgram;
return this;
}
}
}
| 4,954 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/BusinessStakeholderExtractServiceImpl.java | package com.paypal.sellers.stakeholdersextraction.services;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Class that creates the stakeholder in Hyperwallet
*/
@Slf4j
@Service
public class BusinessStakeholderExtractServiceImpl implements BusinessStakeholderExtractService {
protected static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further "
+ "information:\n";
@Override
public List<BusinessStakeHolderModel> extractBusinessStakeHolders(
final List<SellerModel> professionalSellerModels) {
//@formatter:off
return professionalSellerModels
.stream()
.map(SellerModel::getBusinessStakeHolderDetails)
.flatMap(Collection::stream)
.filter(Predicate.not(BusinessStakeHolderModel::isEmpty))
.collect(Collectors.toList());
//@formatter:on
}
}
| 4,955 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/BusinessStakeholderTokenUpdateServiceImpl.java | package com.paypal.sellers.stakeholdersextraction.services;
import com.mirakl.client.core.exception.MiraklApiException;
import com.mirakl.client.mmp.operator.domain.shop.update.MiraklUpdateShop;
import com.mirakl.client.mmp.operator.request.shop.MiraklUpdateShopsRequest;
import com.mirakl.client.mmp.request.additionalfield.MiraklRequestAdditionalFieldValue;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.mirakl.client.MiraklClient;
import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderConstants;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static com.paypal.sellers.stakeholdersextraction.services.BusinessStakeholderExtractServiceImpl.ERROR_MESSAGE_PREFIX;
/**
* Class that updates the token extracted from hyperwallet
*/
@Slf4j
@Service
public class BusinessStakeholderTokenUpdateServiceImpl implements BusinessStakeholderTokenUpdateService {
private static final String EMAIL_SUBJECT_MESSAGE = "Issue detected getting shop information in Mirakl";
private static final String HYPHEN = "-";
private final MiraklClient miraklOperatorClient;
private final MailNotificationUtil sellerMailNotificationUtil;
public BusinessStakeholderTokenUpdateServiceImpl(final MiraklClient miraklOperatorClient,
final MailNotificationUtil sellerMailNotificationUtil) {
this.miraklOperatorClient = miraklOperatorClient;
this.sellerMailNotificationUtil = sellerMailNotificationUtil;
}
@Override
public void updateBusinessStakeholderToken(final String clientUserId,
final List<BusinessStakeHolderModel> businessStakeHolderModels) {
if (CollectionUtils.isEmpty(businessStakeHolderModels)) {
log.info("No data for business stakeholders on store [{}]", clientUserId);
return;
}
final MiraklUpdateShop miraklUpdateShop = createMiraklUpdateFieldRequestForStakeholders(clientUserId,
businessStakeHolderModels);
final MiraklUpdateShopsRequest request = new MiraklUpdateShopsRequest(List.of(miraklUpdateShop));
try {
miraklOperatorClient.updateShops(request);
}
catch (final MiraklApiException ex) {
log.error("Something went wrong getting information of shop [{}]", clientUserId);
sellerMailNotificationUtil.sendPlainTextEmail(EMAIL_SUBJECT_MESSAGE,
(ERROR_MESSAGE_PREFIX + "Something went wrong getting information of shop [%s]%n%s")
.formatted(clientUserId, MiraklLoggingErrorsUtil.stringify(ex)));
}
}
private MiraklUpdateShop createMiraklUpdateFieldRequestForStakeholders(final String clientUserId,
final List<BusinessStakeHolderModel> businessStakeHolderModels) {
final MiraklUpdateShop miraklUpdateShop = new MiraklUpdateShop();
miraklUpdateShop.setShopId(Long.valueOf(clientUserId));
final List<String> stakeholderTokens = new ArrayList<>();
final List<MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue> stakeholdersTokenFields = businessStakeHolderModels
.stream().map(businessStakeHolderModel -> {
stakeholderTokens.add(businessStakeHolderModel.getToken());
return new MiraklRequestAdditionalFieldValue.MiraklSimpleRequestAdditionalFieldValue(
BusinessStakeHolderConstants.TOKEN + HYPHEN + businessStakeHolderModel.getStkId(),
businessStakeHolderModel.getToken());
}).collect(Collectors.toList());
log.info("Storing business stakeholder tokens [{}] for shop [{}]", String.join(",", stakeholderTokens),
clientUserId);
miraklUpdateShop.setAdditionalFieldValues(Collections.unmodifiableList(stakeholdersTokenFields));
return miraklUpdateShop;
}
}
| 4,956 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/BusinessStakeholderTokenUpdateService.java | package com.paypal.sellers.stakeholdersextraction.services;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import java.util.List;
/**
* Manipulates the interaction between the connector and Mirakl
*/
public interface BusinessStakeholderTokenUpdateService {
/**
* Updates the token of every businessStakeholder belonging to an specific shop
* @param clientUserId the client user ID.
* @param businessStakeHolderModels a {@link List} of
* {@link BusinessStakeHolderModel}s.
*/
void updateBusinessStakeholderToken(String clientUserId, List<BusinessStakeHolderModel> businessStakeHolderModels);
}
| 4,957 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/BusinessStakeholderTokenSynchronizationServiceImpl.java | package com.paypal.sellers.stakeholdersextraction.services;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.HyperwalletException;
import com.hyperwallet.clientsdk.model.HyperwalletBusinessStakeholder;
import com.hyperwallet.clientsdk.model.HyperwalletList;
import com.mirakl.client.core.exception.MiraklException;
import com.paypal.infrastructure.support.exceptions.HMCException;
import com.paypal.infrastructure.support.exceptions.HMCHyperwalletAPIException;
import com.paypal.infrastructure.support.exceptions.HMCMiraklAPIException;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Class that implements the {@link TokenSynchronizationService} interface for the
* synchronization of tokens for business stakeholders
*/
@Slf4j
@Service("businessStakeholdersTokenSynchronizationService")
public class BusinessStakeholderTokenSynchronizationServiceImpl
implements TokenSynchronizationService<BusinessStakeHolderModel> {
@Value("${hmc.jobs.settings.stk-mandatory-email}")
private boolean isStkEmailMandatory;
private final UserHyperwalletSDKService userHyperwalletSDKService;
private final BusinessStakeholderTokenUpdateService businessStakeholderTokenUpdateService;
private final MailNotificationUtil mailNotificationUtil;
public BusinessStakeholderTokenSynchronizationServiceImpl(final UserHyperwalletSDKService userHyperwalletSDKService,
final BusinessStakeholderTokenUpdateService businessStakeholderTokenUpdateService,
final MailNotificationUtil mailNotificationUtil) {
this.userHyperwalletSDKService = userHyperwalletSDKService;
this.businessStakeholderTokenUpdateService = businessStakeholderTokenUpdateService;
this.mailNotificationUtil = mailNotificationUtil;
}
/**
* Ensures the Business stakeholder's token between Hyperwallet and Mirakl is
* synchronized.
* @param businessStakeHolderModel to be synchronized.
* @return the businessStakeHolderModel with the token synchronized.
*/
@Override
public BusinessStakeHolderModel synchronizeToken(final BusinessStakeHolderModel businessStakeHolderModel) {
checkBusinessStakeHolderEmail(businessStakeHolderModel);
if (StringUtils.isNotBlank(businessStakeHolderModel.getToken())) {
log.debug(
"Hyperwallet token already exists for business stakeholder [{}] for shop [{}], synchronization not needed",
businessStakeHolderModel.getToken(), businessStakeHolderModel.getClientUserId());
return businessStakeHolderModel;
}
final Optional<HyperwalletBusinessStakeholder> hyperwalletBusinessStakeholder = getHwBusinessStakeHolder(
businessStakeHolderModel);
if (hyperwalletBusinessStakeholder.isPresent()) {
log.debug("Hyperwallet business stakeholder with email [{}] for shop [{}] found",
businessStakeHolderModel.getEmail(), businessStakeHolderModel.getClientUserId());
final BusinessStakeHolderModel synchronizedBusinessStakeHolderModel = updateBusinessStakeHolderWithHyperwalletToken(
businessStakeHolderModel, hyperwalletBusinessStakeholder.get());
updateTokenInMirakl(synchronizedBusinessStakeHolderModel);
return synchronizedBusinessStakeHolderModel;
}
else {
log.debug("Hyperwallet business stakeholder [{}] for shop [{}] not found",
businessStakeHolderModel.getStkId(), businessStakeHolderModel.getClientUserId());
return businessStakeHolderModel;
}
}
private void checkBusinessStakeHolderEmail(final BusinessStakeHolderModel businessStakeHolderModel) {
if (isStkEmailMandatory() && StringUtils.isBlank(businessStakeHolderModel.getEmail())
&& StringUtils.isBlank(businessStakeHolderModel.getToken())) {
mailNotificationUtil.sendPlainTextEmail(
String.format("Validation error occurred when processing a stakeholder for seller {%s}",
businessStakeHolderModel.getClientUserId()),
String.format(
"There was an error processing the {%s} seller and the operation could not be completed. Email address for the stakeholder {%d} must be filled.\n"
+ "Please check the logs for further information.",
businessStakeHolderModel.getClientUserId(), businessStakeHolderModel.getStkId()));
throw new HMCException(
String.format("Business stakeholder without email and Hyperwallet token defined for shop [%s]",
businessStakeHolderModel.getClientUserId()));
}
}
private void updateTokenInMirakl(final BusinessStakeHolderModel synchronizedBusinessStakeHolderModel) {
try {
businessStakeholderTokenUpdateService.updateBusinessStakeholderToken(
synchronizedBusinessStakeHolderModel.getClientUserId(),
List.of(synchronizedBusinessStakeHolderModel));
}
catch (final MiraklException e) {
log.error(String.format("Error while updating Mirakl business stakeholder [%s] for shop [%s]",
synchronizedBusinessStakeHolderModel.getToken(),
synchronizedBusinessStakeHolderModel.getClientUserId()), e);
throw new HMCMiraklAPIException(e);
}
}
@SuppressWarnings("java:S3516") // Sonar false positive
private Optional<HyperwalletBusinessStakeholder> getHwBusinessStakeHolder(
final BusinessStakeHolderModel businessStakeHolderModel) {
if (StringUtils.isBlank(businessStakeHolderModel.getEmail())) {
return Optional.empty();
}
else {
final HyperwalletList<HyperwalletBusinessStakeholder> hwBusinessStakeHolders = getHwBusinessStakeHoldersByUserToken(
businessStakeHolderModel);
//@formatter:off
return Stream.ofNullable(hwBusinessStakeHolders.getData())
.flatMap(Collection::stream)
.filter(hwstk -> businessStakeHolderModel.getEmail().equals(hwstk.getEmail()))
.findFirst();
//@formatter:on
}
}
private HyperwalletList<HyperwalletBusinessStakeholder> getHwBusinessStakeHoldersByUserToken(
final BusinessStakeHolderModel businessStakeHolderModel) {
final Hyperwallet hyperwalletSDK = userHyperwalletSDKService
.getHyperwalletInstanceByHyperwalletProgram(businessStakeHolderModel.getHyperwalletProgram());
try {
return hyperwalletSDK.listBusinessStakeholders(businessStakeHolderModel.getUserToken());
}
catch (final HyperwalletException e) {
log.error(String.format("Error while getting Hyperwallet business stakeholders for shop [%s].%n%s",
businessStakeHolderModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)), e);
throw new HMCHyperwalletAPIException(e);
}
}
private BusinessStakeHolderModel updateBusinessStakeHolderWithHyperwalletToken(
final BusinessStakeHolderModel businessStakeHolderModel,
final HyperwalletBusinessStakeholder hyperwalletBusinessStakeholder) {
return businessStakeHolderModel.toBuilder().token(hyperwalletBusinessStakeholder.getToken()).build();
}
protected boolean isStkEmailMandatory() {
return isStkEmailMandatory;
}
}
| 4,958 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/BusinessStakeholderExtractService.java | package com.paypal.sellers.stakeholdersextraction.services;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import java.util.List;
/**
* Holds the logic to manipulate stakeholders between mirakl and hyperwallet
*/
public interface BusinessStakeholderExtractService {
/**
* Extracts the information held in Mirakl for the {@code professionalSellerModels}
* and the token stored in {@code createdHyperWalletUsers} to create Business
* Stakeholders in Hyperwallet and update the token in Mirakl
* @param professionalSellerModels
* @return
*/
List<BusinessStakeHolderModel> extractBusinessStakeHolders(List<SellerModel> professionalSellerModels);
}
| 4,959 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/strategies/HyperWalletCreateBusinessStakeHolderServiceStrategy.java | package com.paypal.sellers.stakeholdersextraction.services.strategies;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.HyperwalletException;
import com.hyperwallet.clientsdk.model.HyperwalletBusinessStakeholder;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.stakeholdersextraction.services.BusinessStakeholderTokenUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Slf4j
@Service
public class HyperWalletCreateBusinessStakeHolderServiceStrategy
implements Strategy<BusinessStakeHolderModel, BusinessStakeHolderModel> {
private final Converter<BusinessStakeHolderModel, HyperwalletBusinessStakeholder> businessStakeHolderModelHyperwalletBusinessStakeholderConverter;
private final UserHyperwalletSDKService userHyperwalletSDKService;
private final MailNotificationUtil mailNotificationUtil;
private final BusinessStakeholderTokenUpdateService businessStakeholderTokenUpdateService;
private static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further "
+ "information:\n";
public HyperWalletCreateBusinessStakeHolderServiceStrategy(
final Converter<BusinessStakeHolderModel, HyperwalletBusinessStakeholder> businessStakeHolderModelHyperwalletBusinessStakeholderConverter,
final UserHyperwalletSDKService userHyperwalletSDKService, final MailNotificationUtil mailNotificationUtil,
final BusinessStakeholderTokenUpdateService businessStakeholderTokenUpdateService) {
this.businessStakeHolderModelHyperwalletBusinessStakeholderConverter = businessStakeHolderModelHyperwalletBusinessStakeholderConverter;
this.userHyperwalletSDKService = userHyperwalletSDKService;
this.mailNotificationUtil = mailNotificationUtil;
this.businessStakeholderTokenUpdateService = businessStakeholderTokenUpdateService;
}
/**
* Executes the business logic based on the content of
* {@code businessStakeHolderModel} and returns a {@link BusinessStakeHolderModel}
* class based on a set of strategies
* @param businessStakeHolderModel the businessStakeHolderModel object of type
* {@link BusinessStakeHolderModel}
* @return the converted object of type {@link BusinessStakeHolderModel}
*/
@Override
public BusinessStakeHolderModel execute(final BusinessStakeHolderModel businessStakeHolderModel) {
final HyperwalletBusinessStakeholder hyperWalletBusinessStakeHolder = businessStakeHolderModelHyperwalletBusinessStakeholderConverter
.convert(businessStakeHolderModel);
try {
final Hyperwallet hyperwallet = userHyperwalletSDKService
.getHyperwalletInstanceByHyperwalletProgram(businessStakeHolderModel.getHyperwalletProgram());
final HyperwalletBusinessStakeholder hyperWalletBusinessStakeHolderResponse = hyperwallet
.createBusinessStakeholder(businessStakeHolderModel.getUserToken(), hyperWalletBusinessStakeHolder);
final BusinessStakeHolderModel createdBusinessStakeHolderModel = businessStakeHolderModel.toBuilder()
.token(hyperWalletBusinessStakeHolderResponse.getToken()).justCreated(true).build();
businessStakeholderTokenUpdateService.updateBusinessStakeholderToken(
createdBusinessStakeHolderModel.getClientUserId(), List.of(createdBusinessStakeHolderModel));
return createdBusinessStakeHolderModel;
}
catch (final HyperwalletException e) {
log.error(String.format("Stakeholder not created for clientId [%s].%n%s",
businessStakeHolderModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)), e);
mailNotificationUtil.sendPlainTextEmail("Issue detected when creating business stakeholder in Hyperwallet",
String.format(ERROR_MESSAGE_PREFIX + "Business stakeholder not created for clientId [%s]%n%s",
businessStakeHolderModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)));
}
return null;
}
/**
* Checks whether the strategy must be executed based on the {@code source}
* @param source the source object
* @return returns whether the strategy is applicable or not
*/
@Override
public boolean isApplicable(final BusinessStakeHolderModel source) {
return Objects.isNull(source.getToken());
}
}
| 4,960 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/strategies/HyperWalletUpdateBusinessStakeHolderServiceStrategy.java | package com.paypal.sellers.stakeholdersextraction.services.strategies;
import com.hyperwallet.clientsdk.Hyperwallet;
import com.hyperwallet.clientsdk.HyperwalletException;
import com.hyperwallet.clientsdk.model.HyperwalletBusinessStakeholder;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.hyperwallet.services.UserHyperwalletSDKService;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.infrastructure.support.logging.HyperwalletLoggingErrorsUtil;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Slf4j
@Service
public class HyperWalletUpdateBusinessStakeHolderServiceStrategy
implements Strategy<BusinessStakeHolderModel, BusinessStakeHolderModel> {
private final Converter<BusinessStakeHolderModel, HyperwalletBusinessStakeholder> businessStakeHolderModelHyperwalletBusinessStakeholderConverter;
private final UserHyperwalletSDKService userHyperwalletSDKService;
private final MailNotificationUtil mailNotificationUtil;
private static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further "
+ "information:\n";
public HyperWalletUpdateBusinessStakeHolderServiceStrategy(
final Converter<BusinessStakeHolderModel, HyperwalletBusinessStakeholder> businessStakeHolderModelHyperwalletBusinessStakeholderConverter,
final UserHyperwalletSDKService userHyperwalletSDKService,
final MailNotificationUtil mailNotificationUtil) {
this.businessStakeHolderModelHyperwalletBusinessStakeholderConverter = businessStakeHolderModelHyperwalletBusinessStakeholderConverter;
this.userHyperwalletSDKService = userHyperwalletSDKService;
this.mailNotificationUtil = mailNotificationUtil;
}
/**
* Executes the business logic based on the content of
* {@code businessStakeHolderModel} and returns a {@link BusinessStakeHolderModel}
* class based on a set of strategies
* @param businessStakeHolderModel the businessStakeHolderModel object of type
* {@link BusinessStakeHolderModel}
* @return the converted object of type {@link BusinessStakeHolderModel}
*/
@Override
public BusinessStakeHolderModel execute(final BusinessStakeHolderModel businessStakeHolderModel) {
final HyperwalletBusinessStakeholder hyperWalletBusinessStakeHolder = businessStakeHolderModelHyperwalletBusinessStakeholderConverter
.convert(businessStakeHolderModel);
try {
log.info("Updating stakeholder [{}] for user [{}]", hyperWalletBusinessStakeHolder.getToken(),
businessStakeHolderModel.getUserToken());
final Hyperwallet hyperwallet = userHyperwalletSDKService
.getHyperwalletInstanceByHyperwalletProgram(businessStakeHolderModel.getHyperwalletProgram());
hyperwallet.updateBusinessStakeholder(businessStakeHolderModel.getUserToken(),
hyperWalletBusinessStakeHolder);
return businessStakeHolderModel;
}
catch (final HyperwalletException e) {
log.error(String.format("Stakeholder not updated for clientId [%s].%n%s",
businessStakeHolderModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)), e);
mailNotificationUtil.sendPlainTextEmail("Issue detected when updating business stakeholder in Hyperwallet",
String.format(ERROR_MESSAGE_PREFIX + "Business stakeholder not updated for clientId [%s]%n%s",
businessStakeHolderModel.getClientUserId(), HyperwalletLoggingErrorsUtil.stringify(e)));
}
return null;
}
/**
* Checks whether the strategy must be executed based on the {@code source}
* @param source the source object
* @return returns whether the strategy is applicable or not
*/
@Override
public boolean isApplicable(final BusinessStakeHolderModel source) {
return Objects.nonNull(source.getToken());
}
}
| 4,961 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/strategies/HyperWalletBusinessStakeHolderStrategyExecutor.java | package com.paypal.sellers.stakeholdersextraction.services.strategies;
import com.paypal.infrastructure.support.strategy.SingleAbstractStrategyExecutor;
import com.paypal.infrastructure.support.strategy.Strategy;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* Executor class that controls strategies to insert or update business stake holders
* information for a certain seller into Hyperwallet
*/
@Service
public class HyperWalletBusinessStakeHolderStrategyExecutor
extends SingleAbstractStrategyExecutor<BusinessStakeHolderModel, BusinessStakeHolderModel> {
private final Set<Strategy<BusinessStakeHolderModel, BusinessStakeHolderModel>> strategies;
public HyperWalletBusinessStakeHolderStrategyExecutor(
final Set<Strategy<BusinessStakeHolderModel, BusinessStakeHolderModel>> strategies) {
this.strategies = strategies;
}
@Override
protected Set<Strategy<BusinessStakeHolderModel, BusinessStakeHolderModel>> getStrategies() {
return strategies;
}
}
| 4,962 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/converters/ListAdditionalFieldValuesToBusinessStakeHolderModelConverter.java | package com.paypal.sellers.stakeholdersextraction.services.converters;
import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.sellers.sellerextractioncommons.configuration.SellersMiraklApiConfig;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Converts from a pair of a list of {@link MiraklAdditionalFieldValue} and
* {@link Integer} into {@link BusinessStakeHolderModel}
*/
@Service
public class ListAdditionalFieldValuesToBusinessStakeHolderModelConverter
implements Converter<Triple<List<MiraklAdditionalFieldValue>, Integer, String>, BusinessStakeHolderModel> {
@Resource
private SellersMiraklApiConfig sellersMiraklApiConfig;
/**
* Method that retrieves a {@link Pair<List<MiraklAdditionalFieldValue>, Integer>} and
* returns a {@link BusinessStakeHolderModel}
* @param source the source object {@link Pair<List<MiraklAdditionalFieldValue>,
* Integer>}
* @return the returned object {@link BusinessStakeHolderModel}
*/
@Override
public BusinessStakeHolderModel convert(final Triple<List<MiraklAdditionalFieldValue>, Integer, String> source) {
final List<MiraklAdditionalFieldValue> additionalFieldValues = source.getLeft();
final Integer businessStakeHolderNumber = source.getMiddle();
final String clientId = source.getRight();
//@formatter:off
return getBuilder()
.stkId(businessStakeHolderNumber)
.token(additionalFieldValues, businessStakeHolderNumber)
.userToken(additionalFieldValues)
.clientUserId(clientId)
.businessContact(additionalFieldValues, businessStakeHolderNumber)
.director(additionalFieldValues, businessStakeHolderNumber)
.ubo(additionalFieldValues, businessStakeHolderNumber)
.smo(additionalFieldValues, businessStakeHolderNumber)
.firstName(additionalFieldValues, businessStakeHolderNumber)
.middleName(additionalFieldValues, businessStakeHolderNumber)
.lastName(additionalFieldValues, businessStakeHolderNumber)
.timeZone(sellersMiraklApiConfig.getTimeZone())
.dateOfBirth(additionalFieldValues, businessStakeHolderNumber)
.countryOfBirth(additionalFieldValues, businessStakeHolderNumber)
.countryOfNationality(additionalFieldValues, businessStakeHolderNumber)
.gender(additionalFieldValues, businessStakeHolderNumber)
.phoneNumber(additionalFieldValues, businessStakeHolderNumber)
.mobileNumber(additionalFieldValues, businessStakeHolderNumber)
.email(additionalFieldValues, businessStakeHolderNumber)
.governmentId(additionalFieldValues, businessStakeHolderNumber)
.governmentIdType(additionalFieldValues, businessStakeHolderNumber)
.driversLicenseId(additionalFieldValues, businessStakeHolderNumber)
.addressLine1(additionalFieldValues, businessStakeHolderNumber)
.addressLine2(additionalFieldValues, businessStakeHolderNumber)
.city(additionalFieldValues, businessStakeHolderNumber)
.stateProvince(additionalFieldValues, businessStakeHolderNumber)
.country(additionalFieldValues, businessStakeHolderNumber)
.postalCode(additionalFieldValues, businessStakeHolderNumber)
.hyperwalletProgram(additionalFieldValues)
.build();
//@formatter:on
}
protected BusinessStakeHolderModel.BusinessStakeHolderModelBuilder getBuilder() {
return BusinessStakeHolderModel.builder();
}
}
| 4,963 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/stakeholdersextraction/services/converters/BusinessStakeHolderModelToHyperWalletBusinessStakeHolderConverter.java | package com.paypal.sellers.stakeholdersextraction.services.converters;
import com.hyperwallet.clientsdk.model.HyperwalletBusinessStakeholder;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* Converts from internal {@link BusinessStakeHolderModel} to
* {@link HyperwalletBusinessStakeholder}
*/
@Service
public class BusinessStakeHolderModelToHyperWalletBusinessStakeHolderConverter
implements Converter<BusinessStakeHolderModel, HyperwalletBusinessStakeholder> {
/**
* Method that retrieves a {@link BusinessStakeHolderModel} and returns a
* {@link HyperwalletBusinessStakeholder}
* @param source the source object {@link BusinessStakeHolderModel}
* @return the returned object {@link HyperwalletBusinessStakeholder}
*/
@Override
public HyperwalletBusinessStakeholder convert(final BusinessStakeHolderModel source) {
final HyperwalletBusinessStakeholder hyperwalletBusinessStakeholder = new HyperwalletBusinessStakeholder();
hyperwalletBusinessStakeholder.token(source.getToken());
hyperwalletBusinessStakeholder.setIsBusinessContact(source.getBusinessContact());
hyperwalletBusinessStakeholder.isDirector(source.getDirector());
hyperwalletBusinessStakeholder.isUltimateBeneficialOwner(source.getUbo());
hyperwalletBusinessStakeholder.isSeniorManagingOfficial(source.getSmo());
hyperwalletBusinessStakeholder.profileType(HyperwalletBusinessStakeholder.ProfileType.INDIVIDUAL);
hyperwalletBusinessStakeholder.setFirstName(source.getFirstName());
hyperwalletBusinessStakeholder.setMiddleName(source.getMiddleName());
hyperwalletBusinessStakeholder.setLastName(source.getLastName());
Optional.ofNullable(source.getDateOfBirth()).ifPresent(hyperwalletBusinessStakeholder::setDateOfBirth);
hyperwalletBusinessStakeholder.countryOfBirth(source.getCountryOfBirth());
hyperwalletBusinessStakeholder.setCountryOfNationality(source.getCountryOfNationality());
Optional.ofNullable(source.getGender()).ifPresent(gender -> hyperwalletBusinessStakeholder
.setGender(EnumUtils.getEnum(HyperwalletBusinessStakeholder.Gender.class, gender.name())));
hyperwalletBusinessStakeholder.setPhoneNumber(source.getPhoneNumber());
hyperwalletBusinessStakeholder.setMobileNumber(source.getMobileNumber());
hyperwalletBusinessStakeholder.setEmail(source.getEmail());
hyperwalletBusinessStakeholder.setGovernmentId(source.getGovernmentId());
Optional.ofNullable(source.getGovernmentIdType()).ifPresent(
sellerGovernmentIdType -> hyperwalletBusinessStakeholder.setGovernmentIdType(EnumUtils.getEnum(
HyperwalletBusinessStakeholder.GovernmentIdType.class, sellerGovernmentIdType.name())));
hyperwalletBusinessStakeholder.setDriversLicenseId(source.getDriversLicenseId());
hyperwalletBusinessStakeholder.setAddressLine1(source.getAddressLine1());
hyperwalletBusinessStakeholder.setAddressLine2(source.getAddressLine2());
hyperwalletBusinessStakeholder.setCity(source.getCity());
hyperwalletBusinessStakeholder.setStateProvince(source.getStateProvince());
hyperwalletBusinessStakeholder.setCountry(source.getCountry());
hyperwalletBusinessStakeholder.setPostalCode(source.getPostalCode());
return hyperwalletBusinessStakeholder;
}
}
| 4,964 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/IndividualSellersExtractionJobsConfig.java | package com.paypal.sellers.individualsellersextraction;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobBuilder;
import com.paypal.sellers.individualsellersextraction.batchjobs.IndividualSellersExtractBatchJob;
import com.paypal.sellers.individualsellersextraction.batchjobs.IndividualSellersRetryBatchJob;
import com.paypal.sellers.individualsellersextraction.jobs.IndividualSellersExtractJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration class for scheduling jobs at startup
*/
@Configuration
public class IndividualSellersExtractionJobsConfig {
private static final String TRIGGER_SUFFIX = "Trigger";
private static final String JOB_NAME = "IndividualSellersExtractJob";
private static final String RETRY_JOB_NAME = "IndividualSellersExtractRetryJob";
/**
* Creates a recurring job {@link IndividualSellersExtractBatchJob}
* @return the {@link JobDetail}
*/
@Bean
public JobDetail sellerExtractJob() {
//@formatter:off
return JobBuilder.newJob(IndividualSellersExtractJob.class)
.withIdentity(JOB_NAME)
.storeDurably()
.build();
//@formatter:on
}
/**
* Schedules the recurring job {@link IndividualSellersExtractJob} with the
* {@code jobDetails} set on
* {@link IndividualSellersExtractionJobsConfig#sellerExtractJob()}
* @param jobDetails the {@link JobDetail}
* @return the {@link Trigger}
*/
@Bean
public Trigger sellerExtractTrigger(@Qualifier("sellerExtractJob") final JobDetail jobDetails,
@Value("${hmc.jobs.scheduling.extract-jobs.sellers}") final String cronExpression) {
//@formatter:off
return TriggerBuilder.newTrigger()
.forJob(jobDetails)
.withIdentity(TRIGGER_SUFFIX + JOB_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
//@formatter:on
}
/**
* Creates a recurring job {@link IndividualSellersRetryBatchJob}
* @return the {@link JobDetail}
*/
@Bean
public JobDetail sellerExtractRetryJob(final IndividualSellersRetryBatchJob individualSellersRetryBatchJob) {
//@formatter:off
return QuartzBatchJobBuilder.newJob(individualSellersRetryBatchJob)
.withIdentity(RETRY_JOB_NAME)
.storeDurably()
.build();
//@formatter:on
}
/**
* Schedules the recurring job {@link IndividualSellersRetryBatchJob} with the
* {@code jobDetails} set on
* {@link IndividualSellersExtractionJobsConfig#sellerExtractRetryJob(IndividualSellersRetryBatchJob)}
* ()}
* @param jobDetails the {@link JobDetail}
* @return the {@link Trigger}
*/
@Bean
public Trigger sellerExtractRetryTrigger(@Qualifier("sellerExtractRetryJob") final JobDetail jobDetails,
@Value("${hmc.jobs.scheduling.retry-jobs.sellers}") final String cronExpression) {
//@formatter:off
return TriggerBuilder.newTrigger()
.forJob(jobDetails)
.withIdentity(TRIGGER_SUFFIX + RETRY_JOB_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
//@formatter:on
}
}
| 4,965 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersExtractBatchJobItemProcessor.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.strategies.HyperWalletUserServiceStrategyExecutor;
import org.springframework.stereotype.Component;
/**
* Individual sellers extract batch job item processor for creating the users in HW
*/
@Component
public class IndividualSellersExtractBatchJobItemProcessor
implements BatchJobItemProcessor<BatchJobContext, IndividualSellersExtractJobItem> {
private final HyperWalletUserServiceStrategyExecutor hyperWalletUserServiceStrategyExecutor;
private final TokenSynchronizationService<SellerModel> sellersTokenSynchronizationService;
public IndividualSellersExtractBatchJobItemProcessor(
final HyperWalletUserServiceStrategyExecutor hyperWalletUserServiceStrategyExecutor,
final TokenSynchronizationService<SellerModel> sellersTokenSynchronizationService) {
this.hyperWalletUserServiceStrategyExecutor = hyperWalletUserServiceStrategyExecutor;
this.sellersTokenSynchronizationService = sellersTokenSynchronizationService;
}
/**
* Processes the {@link IndividualSellersExtractJobItem} with the
* {@link HyperWalletUserServiceStrategyExecutor}
* @param ctx The {@link BatchJobContext}
* @param jobItem The {@link IndividualSellersExtractJobItem}
*/
@Override
public void processItem(final BatchJobContext ctx, final IndividualSellersExtractJobItem jobItem) {
final SellerModel sellerModel = sellersTokenSynchronizationService.synchronizeToken(jobItem.getItem());
hyperWalletUserServiceStrategyExecutor.execute(sellerModel);
}
}
| 4,966 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersRetryBatchJob.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractRetryBatchJob;
import org.springframework.stereotype.Component;
/**
* Retries items that have failed during the individual sellers extract job
*/
@Component
public class IndividualSellersRetryBatchJob
extends AbstractRetryBatchJob<BatchJobContext, IndividualSellersExtractJobItem> {
private final IndividualSellersRetryBatchJobItemExtractor individualSellersRetryBatchJobItemExtractor;
private final IndividualSellersExtractBatchJobItemProcessor individualSellersExtractBatchJobItemProcessor;
public IndividualSellersRetryBatchJob(
final IndividualSellersRetryBatchJobItemExtractor individualSellersRetryBatchJobItemExtractor,
final IndividualSellersExtractBatchJobItemProcessor individualSellersExtractBatchJobItemProcessor) {
this.individualSellersRetryBatchJobItemExtractor = individualSellersRetryBatchJobItemExtractor;
this.individualSellersExtractBatchJobItemProcessor = individualSellersExtractBatchJobItemProcessor;
}
/**
* Retrieves the individual seller batch job item processor
* @return the {@link BatchJobItemProcessor} for
* {@link IndividualSellersExtractJobItem}
*/
@Override
protected BatchJobItemProcessor<BatchJobContext, IndividualSellersExtractJobItem> getBatchJobItemProcessor() {
return individualSellersExtractBatchJobItemProcessor;
}
/**
* Retrieves the individual seller batch job items extractor
* @return the {@link BatchJobItemsExtractor} for
* {@link IndividualSellersExtractJobItem}
*/
@Override
protected BatchJobItemsExtractor<BatchJobContext, IndividualSellersExtractJobItem> getBatchJobItemsExtractor() {
return individualSellersRetryBatchJobItemExtractor;
}
}
| 4,967 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersExtractBatchJob.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractExtractBatchJob;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
/**
* Extract individual sellers job for extracting Mirakl sellers data and populate it on
* HyperWallet as users
*/
@Component
public class IndividualSellersExtractBatchJob
extends AbstractExtractBatchJob<BatchJobContext, IndividualSellersExtractJobItem> {
@Resource
private IndividualSellersExtractBatchJobItemProcessor individualSellersExtractBatchJobItemProcessor;
@Resource
private IndividualSellersExtractBatchJobItemsExtractor individualSellersExtractBatchJobItemsExtractor;
/**
* Retrieves the individual seller batch job item processor
* @return the {@link BatchJobItemProcessor} for
* {@link IndividualSellersExtractJobItem}
*/
@Override
protected BatchJobItemProcessor<BatchJobContext, IndividualSellersExtractJobItem> getBatchJobItemProcessor() {
return this.individualSellersExtractBatchJobItemProcessor;
}
/**
* Retrieves the individual seller batch job items extractor
* @return the {@link BatchJobItemsExtractor} for
* {@link IndividualSellersExtractJobItem}
*/
@Override
protected BatchJobItemsExtractor<BatchJobContext, IndividualSellersExtractJobItem> getBatchJobItemsExtractor() {
return this.individualSellersExtractBatchJobItemsExtractor;
}
}
| 4,968 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersExtractJobItem.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobItem;
import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
/**
* Class that holds the needed information for batch processing {@link SellerModel}
*/
public class IndividualSellersExtractJobItem extends AbstractBatchJobItem<SellerModel> {
public static final String ITEM_TYPE = "IndividualSeller";
public IndividualSellersExtractJobItem(final SellerModel item) {
super(item);
}
/**
* Returns the {@code clientUserId} of a {@link SellerModel}
* @return the {@link String} clientUserId
*/
@Override
public String getItemId() {
return getItem().getClientUserId();
}
/**
* Returns the type as {@link String} of the {@link BatchJobItem}
* @return {@code IndividualSeller}
*/
@Override
public String getItemType() {
return ITEM_TYPE;
}
}
| 4,969 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersRetryBatchJobItemExtractor.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobfailures.services.BatchJobFailedItemService;
import com.paypal.jobsystem.batchjobfailures.services.cache.BatchJobFailedItemCacheService;
import com.paypal.jobsystem.batchjobfailures.support.AbstractCachingFailedItemsBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class IndividualSellersRetryBatchJobItemExtractor
extends AbstractCachingFailedItemsBatchJobItemsExtractor<BatchJobContext, IndividualSellersExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
public IndividualSellersRetryBatchJobItemExtractor(final MiraklSellersExtractService miraklSellersExtractService,
final BatchJobFailedItemService batchJobFailedItemService,
final BatchJobFailedItemCacheService batchJobFailedItemCacheService) {
super(IndividualSellersExtractJobItem.class, IndividualSellersExtractJobItem.ITEM_TYPE,
batchJobFailedItemService, batchJobFailedItemCacheService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
@Override
protected Collection<IndividualSellersExtractJobItem> getItems(final List<String> ids) {
return miraklSellersExtractService.extractSellers(ids).stream().map(IndividualSellersExtractJobItem::new)
.collect(Collectors.toList());
}
}
| 4,970 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/batchjobs/IndividualSellersExtractBatchJobItemsExtractor.java | package com.paypal.sellers.individualsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjobsupport.support.AbstractDynamicWindowDeltaBatchJobItemsExtractor;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobaudit.services.BatchJobTrackingService;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* The extractor class for retrieving all the sellers within a delta time from mirakl
*/
@Component
public class IndividualSellersExtractBatchJobItemsExtractor
extends AbstractDynamicWindowDeltaBatchJobItemsExtractor<BatchJobContext, IndividualSellersExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
public IndividualSellersExtractBatchJobItemsExtractor(final MiraklSellersExtractService miraklSellersExtractService,
final BatchJobTrackingService batchJobTrackingService) {
super(batchJobTrackingService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
/**
* Retrieves all the sellers modified since the {@code delta} time and returns them as
* a {@link IndividualSellersExtractJobItem}
* @param delta the cut-out {@link Date}
* @return a {@link Collection} of {@link IndividualSellersExtractJobItem}
*/
@Override
protected Collection<IndividualSellersExtractJobItem> getItems(final BatchJobContext ctx, final Date delta) {
final List<SellerModel> miraklIndividualSellers = miraklSellersExtractService.extractIndividuals(delta);
return miraklIndividualSellers.stream().map(IndividualSellersExtractJobItem::new).collect(Collectors.toList());
}
}
| 4,971 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/jobs/IndividualSellersExtractJob.java | package com.paypal.sellers.individualsellersextraction.jobs;
import com.paypal.jobsystem.quartzadapter.support.AbstractBatchJobSupportQuartzJob;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobAdapterFactory;
import com.paypal.sellers.individualsellersextraction.batchjobs.IndividualSellersExtractBatchJob;
import org.quartz.*;
/**
* Quartz Job for executing the {@link IndividualSellersExtractBatchJob}.
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class IndividualSellersExtractJob extends AbstractBatchJobSupportQuartzJob implements Job {
private final IndividualSellersExtractBatchJob individualSellersExtractBatchJob;
public IndividualSellersExtractJob(final QuartzBatchJobAdapterFactory quartzBatchJobAdapterFactory,
final IndividualSellersExtractBatchJob individualSellersExtractBatchJob) {
super(quartzBatchJobAdapterFactory);
this.individualSellersExtractBatchJob = individualSellersExtractBatchJob;
}
/**
* {@inheritDoc}
*/
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
executeBatchJob(individualSellersExtractBatchJob, context);
}
}
| 4,972 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/controllers/IndividualSellersExtractJobController.java | package com.paypal.sellers.individualsellersextraction.controllers;
import com.paypal.jobsystem.quartzintegration.controllers.AbstractJobController;
import com.paypal.sellers.individualsellersextraction.batchjobs.IndividualSellersExtractBatchJob;
import com.paypal.sellers.individualsellersextraction.jobs.IndividualSellersExtractJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* Specific controller to fire Extract Seller process
*/
@Slf4j
@RestController
@RequestMapping("/job")
public class IndividualSellersExtractJobController extends AbstractJobController {
private static final String DEFAULT_SELLERS_EXTRACT_JOB_NAME = "SellersExtractJobSingleExecution";
/**
* Triggers the {@link IndividualSellersExtractBatchJob} with the {@code delta} time
* to retrieve shops created or updated since that {@code delta} and schedules the job
* with the {@code name} provided
* @param delta the {@link Date} in {@link DateTimeFormat.ISO}
* @param name the job name in {@link String}
* @return a {@link ResponseEntity<String>} with the name of the job scheduled
* @throws SchedulerException if quartz {@link org.quartz.Scheduler} fails
*/
@PostMapping("/sellers-extract")
public ResponseEntity<String> runJob(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final Date delta,
@RequestParam(required = false, defaultValue = DEFAULT_SELLERS_EXTRACT_JOB_NAME) final String name)
throws SchedulerException {
runSingleJob(name, IndividualSellersExtractJob.class, delta);
return ResponseEntity.accepted().body(name);
}
}
| 4,973 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/individualsellersextraction/services/converters/MiraklShopToIndividualSellerModelConverter.java | package com.paypal.sellers.individualsellersextraction.services.converters;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.paypal.infrastructure.support.strategy.StrategyExecutor;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.sellerextractioncommons.configuration.SellersMiraklApiConfig;
import com.paypal.sellers.sellerextractioncommons.services.converters.AbstractMiraklShopToSellerModelConverter;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerProfileType;
import org.springframework.stereotype.Service;
@Service
public class MiraklShopToIndividualSellerModelConverter extends AbstractMiraklShopToSellerModelConverter {
protected MiraklShopToIndividualSellerModelConverter(
final StrategyExecutor<MiraklShop, BankAccountModel> miraklShopBankAccountModelStrategyExecutor,
final SellersMiraklApiConfig sellersMiraklApiConfig) {
super(miraklShopBankAccountModelStrategyExecutor, sellersMiraklApiConfig);
}
/**
* Method that retrieves a {@link MiraklShop} and returns a {@link SellerModel}
* @param source the source object {@link MiraklShop}
* @return the returned object {@link SellerModel}
*/
@Override
public SellerModel execute(final MiraklShop source) {
final var sellerModelBuilder = getCommonFieldsBuilder(source);
sellerModelBuilder.profileType(SellerProfileType.INDIVIDUAL);
return sellerModelBuilder.build();
}
@Override
public boolean isApplicable(final MiraklShop source) {
return !source.isProfessional();
}
}
| 4,974 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/ProfessionalSellersExtractionJobsConfig.java | package com.paypal.sellers.professionalsellersextraction;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobBuilder;
import com.paypal.sellers.professionalsellersextraction.batchjobs.ProfessionalSellersRetryBatchJob;
import com.paypal.sellers.professionalsellersextraction.jobs.ProfessionalSellersExtractJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuration class for scheduling jobs at startup
*/
@Configuration
public class ProfessionalSellersExtractionJobsConfig {
private static final String TRIGGER_SUFFIX = "Trigger";
private static final String JOB_NAME = "ProfessionalSellersExtractJob";
private static final String RETRY_JOB_NAME = "ProfessionalSellersRetryJob";
/**
* Creates a recurring job {@link ProfessionalSellersExtractJob}
* @return the {@link JobDetail}
*/
@Bean
public JobDetail professionalSellerExtractJob() {
//@formatter:off
return JobBuilder.newJob(ProfessionalSellersExtractJob.class)
.withIdentity(JOB_NAME)
.storeDurably()
.build();
//@formatter:on
}
/**
* Schedules the recurring job {@link ProfessionalSellersExtractJob} with the
* {@code jobDetails} set on
* {@link ProfessionalSellersExtractionJobsConfig#professionalSellerExtractJob()}
* @param jobDetails the {@link JobDetail}
* @return the {@link Trigger}
*/
@Bean
public Trigger professionalSellerExtractTrigger(
@Qualifier("professionalSellerExtractJob") final JobDetail jobDetails,
@Value("${hmc.jobs.scheduling.extract-jobs.professionalsellers}") final String cronExpression) {
//@formatter:off
return TriggerBuilder.newTrigger()
.forJob(jobDetails)
.withIdentity(TRIGGER_SUFFIX + JOB_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
//@formatter:on
}
@Bean
public JobDetail professionalSellerRetryJob(
final ProfessionalSellersRetryBatchJob professionalSellersRetryBatchJob) {
//@formatter:off
return QuartzBatchJobBuilder.newJob(professionalSellersRetryBatchJob)
.withIdentity(RETRY_JOB_NAME)
.storeDurably()
.build();
//@formatter:on
}
@Bean
public Trigger professionalSellerRetryTrigger(@Qualifier("professionalSellerRetryJob") final JobDetail jobDetails,
@Value("${hmc.jobs.scheduling.retry-jobs.professionalsellers}") final String cronExpression) {
//@formatter:off
return TriggerBuilder.newTrigger()
.forJob(jobDetails)
.withIdentity(TRIGGER_SUFFIX + RETRY_JOB_NAME)
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
//@formatter:on
}
}
| 4,975 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellersRetryBatchJobItemsExtractor.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobfailures.services.BatchJobFailedItemService;
import com.paypal.jobsystem.batchjobfailures.services.cache.BatchJobFailedItemCacheService;
import com.paypal.jobsystem.batchjobfailures.support.AbstractCachingFailedItemsBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Extract professional sellers for retry from the failed items cache.
*/
@Component
public class ProfessionalSellersRetryBatchJobItemsExtractor
extends AbstractCachingFailedItemsBatchJobItemsExtractor<BatchJobContext, ProfessionalSellerExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
protected ProfessionalSellersRetryBatchJobItemsExtractor(final BatchJobFailedItemService batchJobFailedItemService,
final BatchJobFailedItemCacheService batchJobFailedItemCacheService,
final MiraklSellersExtractService miraklSellersExtractService) {
super(ProfessionalSellerExtractJobItem.class, ProfessionalSellerExtractJobItem.ITEM_TYPE,
batchJobFailedItemService, batchJobFailedItemCacheService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
@Override
protected Collection<ProfessionalSellerExtractJobItem> getItems(final List<String> ids) {
return miraklSellersExtractService.extractProfessionals(ids).stream().map(ProfessionalSellerExtractJobItem::new)
.collect(Collectors.toList());
}
}
| 4,976 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellersRetryBatchJob.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractRetryBatchJob;
import org.springframework.stereotype.Component;
/**
* Retries items that have failed during the professional sellers extract job
*/
@Component
public class ProfessionalSellersRetryBatchJob
extends AbstractRetryBatchJob<BatchJobContext, ProfessionalSellerExtractJobItem> {
private final ProfessionalSellersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor;
private final ProfessionalSellersRetryBatchJobItemsExtractor professionalSellersRetryBatchJobItemsExtractor;
public ProfessionalSellersRetryBatchJob(
final ProfessionalSellersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor,
final ProfessionalSellersRetryBatchJobItemsExtractor professionalSellersRetryBatchJobItemsExtractor) {
this.professionalSellersExtractBatchJobItemProcessor = professionalSellersExtractBatchJobItemProcessor;
this.professionalSellersRetryBatchJobItemsExtractor = professionalSellersRetryBatchJobItemsExtractor;
}
@Override
protected BatchJobItemProcessor<BatchJobContext, ProfessionalSellerExtractJobItem> getBatchJobItemProcessor() {
return professionalSellersExtractBatchJobItemProcessor;
}
@Override
protected BatchJobItemsExtractor<BatchJobContext, ProfessionalSellerExtractJobItem> getBatchJobItemsExtractor() {
return professionalSellersRetryBatchJobItemsExtractor;
}
}
| 4,977 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellersExtractBatchJobItemsExtractor.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobaudit.services.BatchJobTrackingService;
import com.paypal.jobsystem.batchjobsupport.support.AbstractDynamicWindowDeltaBatchJobItemsExtractor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.MiraklSellersExtractService;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* The extractor class for retrieving all the sellers within a delta time from mirakl
*/
@Component
public class ProfessionalSellersExtractBatchJobItemsExtractor
extends AbstractDynamicWindowDeltaBatchJobItemsExtractor<BatchJobContext, ProfessionalSellerExtractJobItem> {
private final MiraklSellersExtractService miraklSellersExtractService;
public ProfessionalSellersExtractBatchJobItemsExtractor(
final MiraklSellersExtractService miraklSellersExtractService,
final BatchJobTrackingService batchJobTrackingService) {
super(batchJobTrackingService);
this.miraklSellersExtractService = miraklSellersExtractService;
}
/**
* Retrieves all the sellers modified since the {@code delta} time and returns them as
* a {@link ProfessionalSellerExtractJobItem}
* @param delta the cut-out {@link Date}
* @return a {@link Collection} of {@link ProfessionalSellerExtractJobItem}
*/
@Override
protected Collection<ProfessionalSellerExtractJobItem> getItems(final BatchJobContext ctx, final Date delta) {
final List<SellerModel> miraklProfessionalSellers = this.miraklSellersExtractService
.extractProfessionals(delta);
return miraklProfessionalSellers.stream().map(ProfessionalSellerExtractJobItem::new)
.collect(Collectors.toList());
}
}
| 4,978 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellerExtractJobItem.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjobsupport.support.AbstractBatchJobItem;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
/**
* Class that holds the needed information for batch processing {@link SellerModel}
*/
public class ProfessionalSellerExtractJobItem extends AbstractBatchJobItem<SellerModel> {
public static final String ITEM_TYPE = "ProfessionalSeller";
protected ProfessionalSellerExtractJobItem(final SellerModel item) {
super(item);
}
/**
* Returns the client user id.
* @return the client user id.
*/
@Override
public String getItemId() {
return getItem().getClientUserId();
}
/**
* Returns the seller item type.
* @return ProfessionalSeller as the seller item type.
*/
@Override
public String getItemType() {
return ITEM_TYPE;
}
}
| 4,979 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellersExtractBatchJob.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemsExtractor;
import com.paypal.jobsystem.batchjobsupport.support.AbstractExtractBatchJob;
import org.springframework.stereotype.Component;
/**
* Extract professional sellers job for extracting Mirakl professional sellers data and
* populate it on HyperWallet as users.
*/
@Component
public class ProfessionalSellersExtractBatchJob
extends AbstractExtractBatchJob<BatchJobContext, ProfessionalSellerExtractJobItem> {
private final ProfessionalSellersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor;
private final ProfessionalSellersExtractBatchJobItemsExtractor professionalSellersExtractBatchJobItemsExtractor;
public ProfessionalSellersExtractBatchJob(
final ProfessionalSellersExtractBatchJobItemProcessor professionalSellersExtractBatchJobItemProcessor,
final ProfessionalSellersExtractBatchJobItemsExtractor professionalSellersExtractBatchJobItemsExtractor) {
this.professionalSellersExtractBatchJobItemProcessor = professionalSellersExtractBatchJobItemProcessor;
this.professionalSellersExtractBatchJobItemsExtractor = professionalSellersExtractBatchJobItemsExtractor;
}
/**
* Retrieves the seller batch job item processor
* @return the {@link BatchJobItemProcessor} for
* {@link ProfessionalSellerExtractJobItem}
*/
@Override
protected BatchJobItemProcessor<BatchJobContext, ProfessionalSellerExtractJobItem> getBatchJobItemProcessor() {
return this.professionalSellersExtractBatchJobItemProcessor;
}
/**
* Retrieves the seller batch job items extractor
* @return the {@link BatchJobItemsExtractor} for
* {@link ProfessionalSellerExtractJobItem}
*/
@Override
protected BatchJobItemsExtractor<BatchJobContext, ProfessionalSellerExtractJobItem> getBatchJobItemsExtractor() {
return this.professionalSellersExtractBatchJobItemsExtractor;
}
}
| 4,980 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/batchjobs/ProfessionalSellersExtractBatchJobItemProcessor.java | package com.paypal.sellers.professionalsellersextraction.batchjobs;
import com.paypal.infrastructure.support.services.TokenSynchronizationService;
import com.paypal.jobsystem.batchjob.model.BatchJobContext;
import com.paypal.jobsystem.batchjobsupport.model.BatchJobItemProcessor;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.services.strategies.HyperWalletUserServiceStrategyExecutor;
import org.springframework.stereotype.Component;
/**
* Sellers extract batch job item processor for creating the users in HW.
*/
@Component
public class ProfessionalSellersExtractBatchJobItemProcessor
implements BatchJobItemProcessor<BatchJobContext, ProfessionalSellerExtractJobItem> {
private final HyperWalletUserServiceStrategyExecutor hyperWalletUserServiceStrategyExecutor;
private final TokenSynchronizationService<SellerModel> sellersTokenSynchronizationService;
public ProfessionalSellersExtractBatchJobItemProcessor(
final HyperWalletUserServiceStrategyExecutor hyperWalletUserServiceStrategyExecutor,
final TokenSynchronizationService<SellerModel> sellersTokenSynchronizationService) {
this.hyperWalletUserServiceStrategyExecutor = hyperWalletUserServiceStrategyExecutor;
this.sellersTokenSynchronizationService = sellersTokenSynchronizationService;
}
/**
* Processes the {@link ProfessionalSellerExtractJobItem} with the
* {@link HyperWalletUserServiceStrategyExecutor}.
* @param ctx The {@link BatchJobContext}
* @param jobItem The {@link ProfessionalSellerExtractJobItem}
*/
@Override
public void processItem(final BatchJobContext ctx, final ProfessionalSellerExtractJobItem jobItem) {
final SellerModel sellerModel = sellersTokenSynchronizationService.synchronizeToken(jobItem.getItem());
hyperWalletUserServiceStrategyExecutor.execute(sellerModel);
}
}
| 4,981 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/jobs/ProfessionalSellersExtractJob.java | package com.paypal.sellers.professionalsellersextraction.jobs;
import com.paypal.jobsystem.quartzadapter.support.AbstractBatchJobSupportQuartzJob;
import com.paypal.jobsystem.quartzadapter.job.QuartzBatchJobAdapterFactory;
import com.paypal.sellers.stakeholdersextraction.batchjobs.BusinessStakeholdersExtractBatchJob;
import com.paypal.sellers.professionalsellersextraction.batchjobs.ProfessionalSellersExtractBatchJob;
import org.quartz.*;
/**
* Quartz Job for executing the {@link ProfessionalSellersExtractBatchJob}.
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ProfessionalSellersExtractJob extends AbstractBatchJobSupportQuartzJob implements Job {
private final ProfessionalSellersExtractBatchJob professionalSellersExtractBatchJob;
private final BusinessStakeholdersExtractBatchJob businessStakeholdersExtractBatchJob;
public ProfessionalSellersExtractJob(final QuartzBatchJobAdapterFactory quartzBatchJobAdapterFactory,
final ProfessionalSellersExtractBatchJob professionalSellersExtractBatchJob,
final BusinessStakeholdersExtractBatchJob businessStakeholdersExtractBatchJob) {
super(quartzBatchJobAdapterFactory);
this.professionalSellersExtractBatchJob = professionalSellersExtractBatchJob;
this.businessStakeholdersExtractBatchJob = businessStakeholdersExtractBatchJob;
}
/**
* {@inheritDoc}
*/
@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {
executeBatchJob(professionalSellersExtractBatchJob, context);
executeBatchJob(businessStakeholdersExtractBatchJob, context);
}
}
| 4,982 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/controllers/ProfessionalSellersExtractJobController.java | package com.paypal.sellers.professionalsellersextraction.controllers;
import com.paypal.jobsystem.quartzintegration.controllers.AbstractJobController;
import com.paypal.sellers.professionalsellersextraction.jobs.ProfessionalSellersExtractJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* Specific controller to fire Extract Seller process
*/
@Slf4j
@RestController
@RequestMapping("/job")
public class ProfessionalSellersExtractJobController extends AbstractJobController {
private static final String DEFAULT_PROFESSIONAL_SELLERS_EXTRACT_JOB_NAME = "ProfessionalSellersExtractJobSingleExecution";
/**
* Triggers the {@link ProfessionalSellersExtractJob} with the {@code delta} time to
* retrieve shops created or updated since that {@code delta} and schedules the job
* with the {@code name} provided
* @param delta the {@link Date} in {@link DateTimeFormat.ISO}
* @param name the job name in {@link String}
* @return a {@link ResponseEntity<String>} with the name of the job scheduled
* @throws SchedulerException if quartz {@link org.quartz.Scheduler} fails
*/
@PostMapping("/professional-sellers-extract")
public ResponseEntity<String> runJob(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final Date delta,
@RequestParam(required = false,
defaultValue = DEFAULT_PROFESSIONAL_SELLERS_EXTRACT_JOB_NAME) final String name)
throws SchedulerException {
runSingleJob(name, ProfessionalSellersExtractJob.class, delta);
return ResponseEntity.accepted().body(name);
}
}
| 4,983 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/services | Create_ds/mirakl-hyperwallet-connector/hmc-sellers/src/main/java/com/paypal/sellers/professionalsellersextraction/services/converters/MiraklShopToProfessionalSellerModelConverter.java | package com.paypal.sellers.professionalsellersextraction.services.converters;
import com.mirakl.client.mmp.domain.common.MiraklAdditionalFieldValue;
import com.mirakl.client.mmp.domain.shop.MiraklShop;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.support.strategy.StrategyExecutor;
import com.paypal.sellers.bankaccountextraction.model.BankAccountModel;
import com.paypal.sellers.sellerextractioncommons.configuration.SellersMiraklApiConfig;
import com.paypal.sellers.sellerextractioncommons.services.converters.AbstractMiraklShopToSellerModelConverter;
import com.paypal.sellers.stakeholdersextraction.model.BusinessStakeHolderModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerModel;
import com.paypal.sellers.sellerextractioncommons.model.SellerProfileType;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/***
* Strategy to ensure the converts only happens when the user is a Professional type
*/
@Service
public class MiraklShopToProfessionalSellerModelConverter extends AbstractMiraklShopToSellerModelConverter {
private final Converter<Triple<List<MiraklAdditionalFieldValue>, Integer, String>, BusinessStakeHolderModel> pairBusinessStakeHolderModelConverter;
protected MiraklShopToProfessionalSellerModelConverter(
final StrategyExecutor<MiraklShop, BankAccountModel> miraklShopBankAccountModelStrategyExecutor,
final Converter<Triple<List<MiraklAdditionalFieldValue>, Integer, String>, BusinessStakeHolderModel> pairBusinessStakeHolderModelConverter,
final SellersMiraklApiConfig sellersMiraklApiConfig) {
super(miraklShopBankAccountModelStrategyExecutor, sellersMiraklApiConfig);
this.pairBusinessStakeHolderModelConverter = pairBusinessStakeHolderModelConverter;
}
/**
* Method that retrieves a {@link MiraklShop} and returns a {@link SellerModel}
* @param source the source object {@link MiraklShop}
* @return the returned object {@link SellerModel}
*/
@Override
public SellerModel execute(final MiraklShop source) {
final var sellerModelBuilder = getCommonFieldsBuilder(source);
//@formatter:off
final List<BusinessStakeHolderModel> businessStakeHolderList = IntStream.range(1, 6).mapToObj(
i -> pairBusinessStakeHolderModelConverter.convert(Triple.of(source.getAdditionalFieldValues(), i, source.getId())))
.filter(Objects::nonNull)
.filter(Predicate.not(BusinessStakeHolderModel::isEmpty))
.collect(Collectors.toCollection(ArrayList::new));
final List<MiraklAdditionalFieldValue> additionalFieldValues = source.getAdditionalFieldValues();
return sellerModelBuilder.profileType(SellerProfileType.BUSINESS)
.companyRegistrationCountry(additionalFieldValues)
.businessRegistrationStateProvince(additionalFieldValues)
.companyName(source.getProfessionalInformation().getCorporateName())
.companyRegistrationNumber(source.getProfessionalInformation().getIdentificationNumber())
.vatNumber(source.getProfessionalInformation().getTaxIdentificationNumber())
.businessStakeHolderDetails(businessStakeHolderList)
.build();
//@formatter:on
}
@Override
public boolean isApplicable(final MiraklShop source) {
return source.isProfessional();
}
}
| 4,984 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/ReportsArchTest.java | package com.paypal.reports;
import com.paypal.testsupport.archrules.SliceLayeredModulePackageStructureRules;
import com.paypal.testsupport.archrules.SliceLayeredModuleWeakenedLayerProtectionRules;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.junit.ArchTests;
@AnalyzeClasses(packages = "com.paypal.reports", importOptions = ImportOption.DoNotIncludeTests.class)
public class ReportsArchTest {
@ArchTest
public static final ArchTests packageRules = ArchTests.in(SliceLayeredModulePackageStructureRules.class);
@ArchTest
public static final ArchTests layerRules = ArchTests.in(SliceLayeredModuleWeakenedLayerProtectionRules.class);
}
| 4,985 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/model/HmcBraintreeTransactionLineTest.java | package com.paypal.reports.model;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.model.HmcBraintreeTransactionLine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class HmcBraintreeTransactionLineTest {
private static final String BRAIN_TREE_ORDER_ID = "braintreeOrderId";
private static final String PAYMENT_TRANSACTION_ID = "paymentTransactionId";
@Test
void builder_shouldCreateBraintreeTransactionLineObject() {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime now = TimeMachine.now();
//@formatter:off
final HmcBraintreeTransactionLine result = HmcBraintreeTransactionLine.builder()
.orderId(BRAIN_TREE_ORDER_ID)
.amount(BigDecimal.ONE)
.paymentTransactionTime(now)
.paymentTransactionId(PAYMENT_TRANSACTION_ID)
.build();
//@formatter:on
assertThat(result.getAmount()).isEqualTo(BigDecimal.ONE);
assertThat(result.getOrderId()).isEqualTo(BRAIN_TREE_ORDER_ID);
assertThat(result.getPaymentTransactionTime()).isEqualTo(now);
assertThat(result.getPaymentTransactionId()).isEqualTo(PAYMENT_TRANSACTION_ID);
}
}
| 4,986 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/model/HmcFinancialReportLineTest.java | package com.paypal.reports.model;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.model.HmcFinancialReportLine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class HmcFinancialReportLineTest {
private static final String BRAIN_TREE_ORDER_ID = "braintreeOrderId";
private static final String ORDER_ID = "orderId";
private static final String SELLER_ID = "sellerId";
private static final String MIRAKL_TRANSACTION_LINE_ID = "miraklTransactionLineId";
private static final String MIRAKL_TRANSACTION_TYPE = "miraklTransactionType";
private static final String PAYMENT_TRANSACTION_ID = "paymentTransactionId";
@Test
void builder_shouldCreateFinancialReportTransactionLineObject() {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime now = TimeMachine.now();
//@formatter:off
final HmcFinancialReportLine result = HmcFinancialReportLine.builder()
.braintreeCommerceOrderId(BRAIN_TREE_ORDER_ID)
.miraklOrderId(ORDER_ID)
.miraklSellerId(SELLER_ID)
.miraklTransactionLineId(MIRAKL_TRANSACTION_LINE_ID)
.miraklTransactionTime(now)
.miraklTransactionType(MIRAKL_TRANSACTION_TYPE)
.braintreeAmount(BigDecimal.ONE)
.currencyIsoCode("EUR")
.braintreeTransactionId(PAYMENT_TRANSACTION_ID)
.braintreeTransactionTime(now)
.build();
//@formatter:on
assertThat(result.getBraintreeCommerceOrderId()).isEqualTo(BRAIN_TREE_ORDER_ID);
assertThat(result.getMiraklOrderId()).isEqualTo(ORDER_ID);
assertThat(result.getMiraklSellerId()).isEqualTo(SELLER_ID);
assertThat(result.getMiraklTransactionLineId()).isEqualTo(MIRAKL_TRANSACTION_LINE_ID);
assertThat(result.getMiraklTransactionTime()).isEqualTo(now);
assertThat(result.getMiraklTransactionType()).isEqualTo(MIRAKL_TRANSACTION_TYPE);
assertThat(result.getBraintreeAmount()).isEqualTo(BigDecimal.ONE);
assertThat(result.getBraintreeTransactionId()).isEqualTo(PAYMENT_TRANSACTION_ID);
assertThat(result.getBraintreeTransactionTime()).isEqualTo(now);
assertThat(result.getCurrencyIsoCode()).isEqualTo("EUR");
}
}
| 4,987 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/model/HmcMiraklTransactionLineTest.java | package com.paypal.reports.model;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.model.HmcMiraklTransactionLine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class HmcMiraklTransactionLineTest {
private static final String ORDER_ID = "orderId";
private static final String SELLER_ID = "sellerId";
private static final String MIRAKL_TRANSACTION_LINE_ID = "miraklTransactionLineId";
private static final String MIRAKL_TRANSACTION_TYPE = "miraklTransactionType";
private static final String PAYMENT_TRANSACTION_ID = "paymentTransactionId";
@Test
void builder_shouldCreateMiraklTransactionLineObject() {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime now = TimeMachine.now();
//@formatter:off
final HmcMiraklTransactionLine result = HmcMiraklTransactionLine.builder()
.creditAmount(BigDecimal.ONE)
.debitAmount(BigDecimal.TEN)
.orderId(ORDER_ID)
.sellerId(SELLER_ID)
.transactionLineId(MIRAKL_TRANSACTION_LINE_ID)
.transactionTime(now)
.transactionType(MIRAKL_TRANSACTION_TYPE)
.transactionNumber(PAYMENT_TRANSACTION_ID)
.build();
//@formatter:on
assertThat(result.getCreditAmount()).isEqualTo(BigDecimal.ONE);
assertThat(result.getDebitAmount()).isEqualTo(BigDecimal.TEN);
assertThat(result.getOrderId()).isEqualTo(ORDER_ID);
assertThat(result.getSellerId()).isEqualTo(SELLER_ID);
assertThat(result.getTransactionLineId()).isEqualTo(MIRAKL_TRANSACTION_LINE_ID);
assertThat(result.getTransactionTime()).isEqualTo(now);
assertThat(result.getTransactionType()).isEqualTo(MIRAKL_TRANSACTION_TYPE);
assertThat(result.getTransactionNumber()).isEqualTo(PAYMENT_TRANSACTION_ID);
}
}
| 4,988 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/jobs/ReportsExtractJobTest.java | package com.paypal.reports.jobs;
import com.paypal.reports.services.ReportsExtractService;
import org.assertj.core.api.AssertionsForInterfaceTypes;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import java.util.Date;
import java.util.Map;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ReportsExtractJobTest {
private static final String FILE_NAME = "fileName";
@InjectMocks
@Spy
private ReportsExtractJob testObj;
@Mock
private Date startDateMock, endDateMock;
@Mock
private ReportsExtractService reportsExtractServiceMock;
@Mock
private JobExecutionContext contextMock;
@Mock
private JobDetail jobDetailMock;
@Test
void execute() {
doReturn(startDateMock).when(testObj).getStartDate(contextMock);
doReturn(endDateMock).when(testObj).getEndDate(contextMock);
doReturn(FILE_NAME).when(testObj).getFileName(contextMock);
testObj.execute(contextMock);
verify(reportsExtractServiceMock).extractFinancialReport(startDateMock, endDateMock, FILE_NAME);
}
@Test
void creteJobDataMap_shouldAddStartDateEndDateAndFileNamePassedAsArgument() {
final Date startDate = new Date();
final Date endDate = new Date();
final String fileName = "fileName";
final JobDataMap result = ReportsExtractJob.createJobDataMap(startDate, endDate, fileName);
AssertionsForInterfaceTypes.assertThat(result).contains(Map.entry("startDate", startDate),
Map.entry("endDate", endDate), Map.entry("fileName", fileName));
}
@Test
void getStartDate_shouldReturnStartDateWhenJobExecutionContextWithStartDateIsPassedAsArgument() {
final Date now = new Date();
when(contextMock.getJobDetail()).thenReturn(jobDetailMock);
final JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("startDate", now);
when(jobDetailMock.getJobDataMap()).thenReturn(jobDataMap);
final Date result = testObj.getStartDate(contextMock);
assertThat(result).isEqualTo(now);
}
@Test
void getEndDate_shouldReturnEndDateTimeWhenJobExecutionContextWithEndDateIsPassedAsArgument() {
final Date now = new Date();
when(contextMock.getJobDetail()).thenReturn(jobDetailMock);
final JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("endDate", now);
when(jobDetailMock.getJobDataMap()).thenReturn(jobDataMap);
final Date result = testObj.getEndDate(contextMock);
assertThat(result).isEqualTo(now);
}
@Test
void getFileName_shouldReturnFileNameWhenJobExecutionContextWithFileNameIsPassedAsArgument() {
final String fileName = "fileName.csv";
when(contextMock.getJobDetail()).thenReturn(jobDetailMock);
final JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("fileName", fileName);
when(jobDetailMock.getJobDataMap()).thenReturn(jobDataMap);
final String result = testObj.getFileName(contextMock);
assertThat(result).isEqualTo(fileName);
}
}
| 4,989 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/controllers/ReportsExtractControllerTest.java | package com.paypal.reports.controllers;
import com.paypal.jobsystem.quartzintegration.services.JobService;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.jobs.ReportsExtractJob;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.quartz.SchedulerException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class ReportsExtractControllerTest {
private static final String JOB_NAME = "jobName";
private static final String FILE_NAME = "fileName";
@InjectMocks
private ReportsExtractController testObj;
@Mock
private JobService jobServiceMock;
@Test
void runJob_shouldCallCreateAndRunSingleExecutionJobAndTestingReportsSessionDataWithTheTransformedValues()
throws SchedulerException {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime startLocalDate = TimeMachine.now();
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 12, 10, 20, 45));
final LocalDateTime endLocalDate = TimeMachine.now();
final Date startDate = DateUtil.convertToDate(startLocalDate, ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(endLocalDate, ZoneId.systemDefault());
testObj.runJob(startDate, endDate, "jobName", "fileName");
verify(jobServiceMock).createAndRunSingleExecutionJob(JOB_NAME, ReportsExtractJob.class,
ReportsExtractJob.createJobDataMap(startDate, endDate, FILE_NAME), null);
}
}
| 4,990 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/controllers/DownloadReportControllerTest.java | package com.paypal.reports.controllers;
import com.paypal.reports.configuration.ReportsConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DownloadReportControllerTest {
private static final String REPO_PATH = "REPO_PATH/";
private static final String ABSOLUTE_PATH = "/absolute/path";
@Spy
@InjectMocks
private DownloadReportController testObj;
@Mock
private Path pathMock, absolutePathMock;
@Mock
private ReportsConfig reportsConfigMock;
private static final String FILE_NAME = "filename.txt";
private static final byte[] FILE_BYTES = hexStringToByteArray();
private static MockedStatic<Paths> PATHS_MOCK;
private static MockedStatic<Files> FILES_MOCK;
@BeforeEach
void setUp() {
when(reportsConfigMock.getRepoPath()).thenReturn(REPO_PATH);
PATHS_MOCK = mockStatic(Paths.class);
FILES_MOCK = mockStatic(Files.class);
}
@AfterEach
void deRegisterStaticMocks() {
PATHS_MOCK.close();
FILES_MOCK.close();
}
@Test
void getFinancialReport_shouldReturnHttpStatusOK_whenFileIsCorrectlyAllocated() {
PATHS_MOCK.when(() -> Paths.get(REPO_PATH + FILE_NAME)).thenReturn(pathMock);
FILES_MOCK.when(() -> Files.readAllBytes(pathMock)).thenReturn(FILE_BYTES);
final ResponseEntity<Resource> result = this.testObj.getFinancialReport(FILE_NAME);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void getFinancialReport_shouldReturnHttpStatusNOT_FOUND_whenFileDoesNotExist() {
PATHS_MOCK.when(() -> Paths.get(REPO_PATH + FILE_NAME)).thenReturn(pathMock);
final NoSuchFileException noSuchFileException = new NoSuchFileException("Something bad happened");
FILES_MOCK.when(() -> Files.readAllBytes(pathMock)).thenThrow(noSuchFileException);
when(pathMock.toAbsolutePath()).thenReturn(absolutePathMock);
when(absolutePathMock.toString()).thenReturn(ABSOLUTE_PATH);
final ResponseEntity<Resource> result = this.testObj.getFinancialReport(FILE_NAME);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
@Test
void getFinancialReport_shouldReturnHttpStatusBAD_REQUEST_whenFileCannotBeRead() {
PATHS_MOCK.when(() -> Paths.get(REPO_PATH + FILE_NAME)).thenReturn(pathMock);
final IOException ioException = new IOException("Something bad happened");
FILES_MOCK.when(() -> Files.readAllBytes(pathMock)).thenThrow(ioException);
final ResponseEntity<Resource> result = this.testObj.getFinancialReport(FILE_NAME);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
private static byte[] hexStringToByteArray() {
final String filename_bytes = "filename_bytes";
final int len = filename_bytes.length();
final byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(filename_bytes.charAt(i), 16) << 4)
+ Character.digit(filename_bytes.charAt(i + 1), 16));
}
return data;
}
}
| 4,991 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/HMCFileServiceImplTest.java | package com.paypal.reports.services.impl;
import com.paypal.infrastructure.support.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.MockedStatic;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class HMCFileServiceImplTest {
private static final String PREFIX_FILE = "prefixFile";
private static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
private static final String DATE = "2020-11-10_20-45";
private static final String FILE_NAME = "prefixFile_2020-11-10_20-45.csv";
private static final List<String> CONTENT_LINES = List.of("column11,column12,column13",
"column21,column22,column23");
private static final String HEADERS = "headerColumn1,headerColumn2,headerColumn3";
@Spy
@InjectMocks
private HMCFileServiceImpl testObj;
private static MockedStatic<DateUtil> DATEUTIL_MOCK;
private static MockedStatic<LocalDateTime> LOCALDATETIME_MOCK;
private static LocalDateTime NOW;
@BeforeEach
void setUp() {
NOW = LocalDateTime.of(2020, 11, 10, 20, 45);
DATEUTIL_MOCK = mockStatic(DateUtil.class);
LOCALDATETIME_MOCK = mockStatic(LocalDateTime.class);
}
@AfterEach
void deRegisterStaticMocks() {
DATEUTIL_MOCK.close();
LOCALDATETIME_MOCK.close();
}
@Test
void saveCSVFile_shouldSaveCSVFile_whenPathAndContentAreNotNull() throws IOException {
final String path = getClass().getResource("").getPath();
doReturn(FILE_NAME).when(testObj).printCSVFile(Paths.get(path + FILE_NAME), HEADERS, FILE_NAME, CONTENT_LINES);
LOCALDATETIME_MOCK.when(LocalDateTime::now).thenReturn(NOW);
DATEUTIL_MOCK.when(() -> DateUtil.convertToString(NOW, DATE_FORMAT)).thenReturn(DATE);
final String resultFileName = testObj.saveCSVFile(path, PREFIX_FILE, CONTENT_LINES, HEADERS);
verify(testObj).printCSVFile(Paths.get(path + FILE_NAME), HEADERS, FILE_NAME, CONTENT_LINES);
assertThat(resultFileName).isEqualTo(FILE_NAME);
}
@Test
void saveCSVFile_shouldEmptyString_whenContentIsNull() {
final String path = getClass().getResource("").getPath();
final String resultFileName = testObj.saveCSVFile(path, PREFIX_FILE, null, HEADERS);
assertThat(resultFileName).isEqualTo(StringUtils.EMPTY);
}
}
| 4,992 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/ReportsBraintreeRefundsExtractServiceImplTest.java | package com.paypal.reports.services.impl;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.util.GraphQLClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.reports.model.HmcBraintreeRefundLine;
import com.paypal.reports.model.HmcBraintreeTransactionLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ReportsBraintreeRefundsExtractServiceImplTest {
private MyReportsBraintreeTransactionsRefunds testObj;
// ISO-8601 format
private final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_INSTANT;
private String refundSearchQuery;
@Mock
private BraintreeGateway braintreeGatewayMock;
@Mock
private Converter<Map<String, Object>, HmcBraintreeRefundLine> mapToBraintreeRefundLineConverterMock;
@Mock
private GraphQLClient graphQLClientMock;
@BeforeEach
void setUp() {
testObj = Mockito.spy(
new MyReportsBraintreeTransactionsRefunds(braintreeGatewayMock, mapToBraintreeRefundLineConverterMock));
refundSearchQuery = Paths.get("src", "test", "resources", "graphQLRefundsSearchQuery.graphql").toFile()
.toString();
}
@Test
void getAllRefundsByTypeAndDateInterval_shouldReturnTwoRefundsWhenGraphQLQueryReturnsTwoNodesOnOnePage()
throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> graphQLQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageRefundQueryResponse.json").toFile(), Map.class);
final Map<String, Object> graphQLFirstEdge = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageRefundFirstEdge.json").toFile(), Map.class);
final Map<String, Object> graphQLSecondEdge = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageRefundSecondEdge.json").toFile(), Map.class);
when(graphQLClientMock.query(refundSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(graphQLQueryResponseMap);
final HmcBraintreeRefundLine firstRefund = HmcBraintreeRefundLine.builder().paymentTransactionId("firstRefund")
.build();
when(mapToBraintreeRefundLineConverterMock.convert(graphQLFirstEdge)).thenReturn(firstRefund);
final HmcBraintreeRefundLine secondRefund = HmcBraintreeRefundLine.builder()
.paymentTransactionId("secondRefund").build();
when(mapToBraintreeRefundLineConverterMock.convert(graphQLSecondEdge)).thenReturn(secondRefund);
final List<HmcBraintreeRefundLine> result = testObj.getAllRefundsByTypeAndDateInterval("SETTLED", startDate,
endDate);
assertThat(result.stream().map(HmcBraintreeRefundLine::getPaymentTransactionId))
.containsExactlyInAnyOrder("firstRefund", "secondRefund");
verify(mapToBraintreeRefundLineConverterMock, times(2)).convert(any());
}
@Test
void getAllRefundsByTypeAndDateInterval_shouldReturnTwoRefundsWhenGraphQLQueryReturnsOneNodePerPagePage()
throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> graphQLFirstPageQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLTwoPagesRefundQueryResponseOne.json").toFile(),
Map.class);
final Map<String, Object> graphQLSecondPageQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLTwoPagesRefundQueryResponseTwo.json").toFile(),
Map.class);
final Map<String, Object> graphQLFirstEdge = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageRefundFirstEdge.json").toFile(), Map.class);
final Map<String, Object> graphQLSecondEdge = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageRefundSecondEdge.json").toFile(), Map.class);
when(graphQLClientMock.query(refundSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(graphQLFirstPageQueryResponseMap);
when(graphQLClientMock.query(refundSearchQuery,
createInputVars("SETTLED", startDate, endDate,
"ZEhKaGJuTmhZM1JwYjI1ZmJYWjVZWFp4YW1vOzIwMjEtMDUtMTNUMDY6NTY6MDNa")))
.thenReturn(graphQLSecondPageQueryResponseMap);
final HmcBraintreeRefundLine firstRefund = HmcBraintreeRefundLine.builder().paymentTransactionId("firstRefund")
.build();
when(mapToBraintreeRefundLineConverterMock.convert(graphQLFirstEdge)).thenReturn(firstRefund);
final HmcBraintreeRefundLine secondRefund = HmcBraintreeRefundLine.builder()
.paymentTransactionId("secondRefund").build();
when(mapToBraintreeRefundLineConverterMock.convert(graphQLSecondEdge)).thenReturn(secondRefund);
final List<HmcBraintreeRefundLine> result = testObj.getAllRefundsByTypeAndDateInterval("SETTLED", startDate,
endDate);
assertThat(result.stream().map(HmcBraintreeTransactionLine::getPaymentTransactionId))
.containsExactlyInAnyOrder("firstRefund", "secondRefund");
verify(mapToBraintreeRefundLineConverterMock, times(2)).convert(any());
}
@Test
void getAllRefundsByTypeAndDateInterval_shouldReturnAnEmptyListOfRefunds() throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> emptyResponse = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLEmptyRefundResponse.json").toFile(), Map.class);
when(graphQLClientMock.query(refundSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(emptyResponse);
final List<HmcBraintreeRefundLine> result = testObj.getAllRefundsByTypeAndDateInterval("SETTLED", startDate,
endDate);
assertThat(result).isEmpty();
}
Map<String, Object> createInputVars(final String transactionType, final Date startDate, final Date endDate,
final String cursor) {
final HashMap<String, Object> isTransactionType = new HashMap<>(
Map.of("status", (Map.of("is", transactionType))));
final HashMap<String, Object> vars = new HashMap<>(Map.of("input", isTransactionType));
if (cursor != null) {
vars.put("after", cursor);
}
final HashMap<String, Object> intervalDates = new HashMap<>();
if (startDate != null) {
intervalDates.put("greaterThanOrEqualTo", convertToISO8601(DateUtil.convertToLocalDateTime(startDate)));
}
if (endDate != null) {
intervalDates.put("lessThanOrEqualTo", convertToISO8601(DateUtil.convertToLocalDateTime(endDate)));
}
if (!intervalDates.isEmpty()) {
final Map<String, Object> input = (Map<String, Object>) vars.get("input");
input.put("createdAt", intervalDates);
}
return vars;
}
private String convertToISO8601(final LocalDateTime date) {
final TemporalAccessor temp = date.atZone(ZoneId.systemDefault());
return DATE_FORMATTER.format(temp);
}
private class MyReportsBraintreeTransactionsRefunds extends ReportsBraintreeRefundsExtractServiceImpl {
public MyReportsBraintreeTransactionsRefunds(final BraintreeGateway braintreeGateway,
final Converter<Map<String, Object>, HmcBraintreeRefundLine> mapToBraintreeRefundLineConverter) {
super(braintreeGateway, mapToBraintreeRefundLineConverter);
}
@Override
protected GraphQLClient getGraphQLClient() {
return graphQLClientMock;
}
@Override
protected String getSearchQuery() {
return refundSearchQuery;
}
}
}
| 4,993 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/ReportsBraintreeTransactionExtractServiceImplTest.java | package com.paypal.reports.services.impl;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.util.GraphQLClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.reports.model.HmcBraintreeTransactionLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ReportsBraintreeTransactionExtractServiceImplTest {
// ISO-8601 format
private final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_INSTANT;
private String transactionSearchQuery;
private MyReportsBraintreeTransactionsExtractServiceImpl testObj;
@Mock
private BraintreeGateway braintreeGatewayMock;
@Mock
private Converter<Map<String, Object>, HmcBraintreeTransactionLine> mapToBraintreeTransactionLineConverterMock;
@Mock
private GraphQLClient graphQLClientMock;
@BeforeEach
void setUp() {
testObj = Mockito.spy(new MyReportsBraintreeTransactionsExtractServiceImpl(braintreeGatewayMock,
mapToBraintreeTransactionLineConverterMock));
transactionSearchQuery = Paths.get("src", "test", "resources", "graphQLTransactionSearchQuery.graphql").toFile()
.toString();
}
@Test
void getAllTransactionsByTypeAndDateInterval_shouldReturnTwoTransactionsWhenGraphQLQueryReturnsTwoNodesOnOnePage()
throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> graphQLQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLOnePageQueryResponse.json").toFile(), Map.class);
final Map<String, Object> graphQLFirstEdge = new ObjectMapper()
.readValue(Paths.get("src", "test", "resources", "graphQLOnePageFirstEdge.json").toFile(), Map.class);
final Map<String, Object> graphQLSecondEdge = new ObjectMapper()
.readValue(Paths.get("src", "test", "resources", "graphQLOnePageSecondEdge.json").toFile(), Map.class);
when(graphQLClientMock.query(transactionSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(graphQLQueryResponseMap);
final HmcBraintreeTransactionLine firstTransaction = HmcBraintreeTransactionLine.builder()
.paymentTransactionId("firstTransaction").build();
when(mapToBraintreeTransactionLineConverterMock.convert(graphQLFirstEdge)).thenReturn(firstTransaction);
final HmcBraintreeTransactionLine secondTransaction = HmcBraintreeTransactionLine.builder()
.paymentTransactionId("secondTransaction").build();
when(mapToBraintreeTransactionLineConverterMock.convert(graphQLSecondEdge)).thenReturn(secondTransaction);
final List<HmcBraintreeTransactionLine> result = testObj.getAllTransactionsByTypeAndDateInterval("SETTLED",
startDate, endDate);
assertThat(result.stream().map(HmcBraintreeTransactionLine::getPaymentTransactionId))
.containsExactlyInAnyOrder("firstTransaction", "secondTransaction");
verify(mapToBraintreeTransactionLineConverterMock, times(2)).convert(any());
}
@Test
void getAllTransactionsByTypeAndDateInterval_shouldReturnTwoTransactionsWhenGraphQLQueryReturnsOneNodePerPagePage()
throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> graphQLFirstPageQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLTwoPagesQueryResponseOne.json").toFile(), Map.class);
final Map<String, Object> graphQLSecondPageQueryResponseMap = new ObjectMapper().readValue(
Paths.get("src", "test", "resources", "graphQLTwoPagesQueryResponseTwo.json").toFile(), Map.class);
final Map<String, Object> graphQLFirstEdge = new ObjectMapper()
.readValue(Paths.get("src", "test", "resources", "graphQLOnePageFirstEdge.json").toFile(), Map.class);
final Map<String, Object> graphQLSecondEdge = new ObjectMapper()
.readValue(Paths.get("src", "test", "resources", "graphQLOnePageSecondEdge.json").toFile(), Map.class);
when(graphQLClientMock.query(transactionSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(graphQLFirstPageQueryResponseMap);
when(graphQLClientMock.query(transactionSearchQuery,
createInputVars("SETTLED", startDate, endDate,
"ZEhKaGJuTmhZM1JwYjI1ZmJYWjVZWFp4YW1vOzIwMjEtMDUtMTNUMDY6NTY6MDNa")))
.thenReturn(graphQLSecondPageQueryResponseMap);
final HmcBraintreeTransactionLine firstTransaction = HmcBraintreeTransactionLine.builder()
.paymentTransactionId("firstTransaction").build();
when(mapToBraintreeTransactionLineConverterMock.convert(graphQLFirstEdge)).thenReturn(firstTransaction);
final HmcBraintreeTransactionLine secondTransaction = HmcBraintreeTransactionLine.builder()
.paymentTransactionId("secondTransaction").build();
when(mapToBraintreeTransactionLineConverterMock.convert(graphQLSecondEdge)).thenReturn(secondTransaction);
final List<HmcBraintreeTransactionLine> result = testObj.getAllTransactionsByTypeAndDateInterval("SETTLED",
startDate, endDate);
assertThat(result.stream().map(HmcBraintreeTransactionLine::getPaymentTransactionId))
.containsExactlyInAnyOrder("firstTransaction", "secondTransaction");
verify(mapToBraintreeTransactionLineConverterMock, times(2)).convert(any());
}
@Test
void getAllTransactionsByTypeAndDateInterval_shouldReturnAnEmptyListOfTransactions() throws IOException {
final Date startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22),
ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
doReturn(graphQLClientMock).when(testObj).getGraphQLClient();
final Map<String, Object> emptyResponse = new ObjectMapper()
.readValue(Paths.get("src", "test", "resources", "graphQLEmptyResponse.json").toFile(), Map.class);
when(graphQLClientMock.query(transactionSearchQuery, createInputVars("SETTLED", startDate, endDate, null)))
.thenReturn(emptyResponse);
final List<HmcBraintreeTransactionLine> result = testObj.getAllTransactionsByTypeAndDateInterval("SETTLED",
startDate, endDate);
assertThat(result).isEmpty();
}
Map<String, Object> createInputVars(final String transactionType, final Date startDate, final Date endDate,
final String cursor) {
final HashMap<String, Object> isTransactionType = new HashMap<>(
Map.of("status", (Map.of("is", transactionType))));
final HashMap<String, Object> vars = new HashMap<>(Map.of("input", isTransactionType));
if (cursor != null) {
vars.put("after", cursor);
}
final HashMap<String, Object> intervalDates = new HashMap<>();
if (startDate != null) {
intervalDates.put("greaterThanOrEqualTo", convertToISO8601(DateUtil.convertToLocalDateTime(startDate)));
}
if (endDate != null) {
intervalDates.put("lessThanOrEqualTo", convertToISO8601(DateUtil.convertToLocalDateTime(endDate)));
}
if (!intervalDates.isEmpty()) {
final Map<String, Object> input = (Map<String, Object>) vars.get("input");
input.put("createdAt", intervalDates);
}
return vars;
}
private String convertToISO8601(final LocalDateTime date) {
final TemporalAccessor temp = date.atZone(ZoneId.systemDefault());
return DATE_FORMATTER.format(temp);
}
private class MyReportsBraintreeTransactionsExtractServiceImpl
extends ReportsBraintreeTransactionsExtractServiceImpl {
public MyReportsBraintreeTransactionsExtractServiceImpl(final BraintreeGateway braintreeGateway,
final Converter<Map<String, Object>, HmcBraintreeTransactionLine> mapToBraintreeTransactionLineConverter) {
super(braintreeGateway, mapToBraintreeTransactionLineConverter);
}
@Override
protected GraphQLClient getGraphQLClient() {
return graphQLClientMock;
}
@Override
protected String getSearchQuery() {
return transactionSearchQuery;
}
}
}
| 4,994 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/ReportsExtractServiceImplTest.java | package com.paypal.reports.services.impl;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.configuration.ReportsConfig;
import com.paypal.reports.services.FinancialReportService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ReportsExtractServiceImplTest {
@InjectMocks
private ReportsExtractServiceImpl testObj;
@Mock
private FinancialReportService financialReportServiceMock;
@Mock
private ReportsConfig reportsConfigMock;
@Mock
private MailNotificationUtil mailNotificationUtilMock;
private static final String FILE_NAME = "fileName";
private static final String SERVER_URI = "http://localhost:8080";
@Test
void extractFinancialReport_shouldCallToFinancialReportServiceInOrderToGenerateTheFinancialReport() {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime startLocalDate = TimeMachine.now();
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 12, 10, 20, 45));
final LocalDateTime endLocalDate = TimeMachine.now();
final Date startDate = DateUtil.convertToDate(startLocalDate, ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(endLocalDate, ZoneId.systemDefault());
when(reportsConfigMock.getHmcServerUri()).thenReturn(SERVER_URI);
when(financialReportServiceMock.generateFinancialReport(startDate, endDate, FILE_NAME)).thenReturn(FILE_NAME);
testObj.extractFinancialReport(startDate, endDate, FILE_NAME);
verify(financialReportServiceMock).generateFinancialReport(startDate, endDate, FILE_NAME);
verify(mailNotificationUtilMock).sendPlainTextEmail(
"Your Marketplace Financial Report from " + startDate + " to " + endDate,
"Below there is a link to your Marketplace Financial Report for the period from " + startDate + " to "
+ endDate + ". Please click on it to download the report:\n\n" + SERVER_URI
+ "/downloads/financial-report/" + FILE_NAME);
}
}
| 4,995 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/FinancialReportConverterServiceImplTest.java | package com.paypal.reports.services.impl;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.reports.model.HmcBraintreeTransactionLine;
import com.paypal.reports.model.HmcFinancialReportLine;
import com.paypal.reports.model.HmcMiraklTransactionLine;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class FinancialReportConverterServiceImplTest {
private FinancialReportConverterServiceImpl testObj;
@Mock
private Converter<HmcBraintreeTransactionLine, HmcFinancialReportLine> hmcBraintreeTransactionLineHmcFinancialReportLineConverterMock;
@Mock
private Converter<HmcMiraklTransactionLine, HmcFinancialReportLine> hmcMiraklTransactionLineHmcFinancialReportLineConverterMock;
@Mock
private Converter<Pair<HmcBraintreeTransactionLine, HmcMiraklTransactionLine>, HmcFinancialReportLine> hmcFinancialReportLineConverterMock;
@Mock
private HmcBraintreeTransactionLine hmcBraintreeTransactionLineMock;
@Mock
private HmcMiraklTransactionLine hmcMiraklTransactionLineMock;
@BeforeEach
void setUp() {
testObj = new FinancialReportConverterServiceImpl(
hmcBraintreeTransactionLineHmcFinancialReportLineConverterMock,
hmcMiraklTransactionLineHmcFinancialReportLineConverterMock, hmcFinancialReportLineConverterMock);
}
@Test
void convertBraintreeTransactionLineIntoFinancialReportLine_shouldCallToBraintreeTransactionLineToFinancialReportLineConverter() {
testObj.convertBraintreeTransactionLineIntoFinancialReportLine(hmcBraintreeTransactionLineMock);
verify(hmcBraintreeTransactionLineHmcFinancialReportLineConverterMock).convert(hmcBraintreeTransactionLineMock);
}
@Test
void convertMiraklTransactionLineIntoFinancialReportLine_shouldCallToMiraklTransactionLineToFinancialReportLineConverter() {
testObj.convertMiraklTransactionLineIntoFinancialReportLine(hmcMiraklTransactionLineMock);
verify(hmcMiraklTransactionLineHmcFinancialReportLineConverterMock).convert(hmcMiraklTransactionLineMock);
}
@Test
void convertBrainTreeAndMiraklTransactionLineIntoFinancialReportLine_shouldCallToBraintreeAndMiraklTransactionLineToFinancialReportLineConverter() {
testObj.convertBrainTreeAndMiraklTransactionLineIntoFinancialReportLine(hmcBraintreeTransactionLineMock,
hmcMiraklTransactionLineMock);
verify(hmcFinancialReportLineConverterMock)
.convert(Pair.of(hmcBraintreeTransactionLineMock, hmcMiraklTransactionLineMock));
}
}
| 4,996 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/FinancialReportServiceImplTest.java | package com.paypal.reports.services.impl;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.infrastructure.support.date.TimeMachine;
import com.paypal.reports.configuration.ReportsConfig;
import com.paypal.reports.model.HmcBraintreeTransactionLine;
import com.paypal.reports.model.HmcFinancialReportLine;
import com.paypal.reports.model.HmcMiraklTransactionLine;
import com.paypal.reports.model.graphql.braintree.paymentransaction.BraintreeTransactionStatusEnum;
import com.paypal.reports.services.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class FinancialReportServiceImplTest {
private FinancialReportServiceImpl testObj;
@Mock
private FinancialReportConverterService financialReportConverterServiceMock;
@Mock
private ReportsConfig reportsConfigMock;
@Mock
private HMCFileService hmcFileServiceMock;
@Mock
private ReportsBraintreeTransactionsExtractService reportsBraintreeTransactionsExtractServiceMock;
@Mock
private ReportsBraintreeRefundsExtractService reportsBraintreeRefundsExtractServiceMock;
@Mock
private ReportsMiraklExtractService reportsMiraklExtractServiceMock;
private static final String PREFIX_FILE_NAME = "prefixFileName";
private static final String FILE_NAME = "fileName";
private static final String REPO_PATH = "/repo/path";
private static final String HEADER = "braintreeCommerceOrderId,miraklOrderId,miraklSellerId,miraklTransactionLineId,miraklTransactionTime,TransactionType,braintreeAmount,miraklDebitAmount,miraklCreditAmount,currencyIsoCode,braintreeTransactionId,braintreeTransactionTime";
private static final List<String> FINANCIAL_REPORT_LINES = List.of(
"20001,,,,,,120,,,EUR,6jkals83,2020-11-10 20:45:00",
",000000009-B,2003,abcd-12345-2145-bb,2020-11-10 20:45:00,ORDER_CANCELATION,0,99.0,,GBP,7jkals83,",
"20000,000000009-A,2002,abcd-12345-2145-aa,2020-11-10 20:45:00,ORDER_AMOUNT,100,93.0,,USD,5jkals83,2020-11-10 20:45:00");
@BeforeEach
void setUp() {
testObj = new FinancialReportServiceImpl(financialReportConverterServiceMock, reportsConfigMock,
hmcFileServiceMock, reportsBraintreeTransactionsExtractServiceMock,
reportsBraintreeRefundsExtractServiceMock, reportsMiraklExtractServiceMock);
}
@Test
void generateFinancialReport_shouldCallBrainTreeAndMiraklAndGenerateProperFinancialReportLines() {
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 11, 10, 20, 45));
final LocalDateTime startLocalDate = TimeMachine.now();
TimeMachine.useFixedClockAt(LocalDateTime.of(2020, 12, 10, 20, 45));
final LocalDateTime endLocalDate = TimeMachine.now();
final Date startDate = DateUtil.convertToDate(startLocalDate, ZoneId.systemDefault());
final Date endDate = DateUtil.convertToDate(endLocalDate, ZoneId.systemDefault());
final HmcBraintreeTransactionLine braintreeCommonTransactionLine = getBraintreeCommonTransactionLine(
startLocalDate);
final HmcBraintreeTransactionLine unjoinableBraintreeTransactionLine = getUnjoinableBraintreeTransactionLine(
startLocalDate);
final HmcMiraklTransactionLine unjoinableMiraklTransactionLine = getUnjoinableMiraklTransactionLine(
startLocalDate);
final HmcMiraklTransactionLine miraklCommonTransactionLine = getMiraklCommonTransactionLine(startLocalDate);
final HmcFinancialReportLine unjoinableBraintreeFinancialLine = getUnjoinableBraintreeFinancialLine(
startLocalDate);
final HmcFinancialReportLine unjoinableMiraklFinancialLine = getUnjoinableMiraklFinancialLine(startLocalDate);
final HmcFinancialReportLine commonBraintreeAndMiraklFinancialLine = getCommonBraintreeAndMiraklFinancialLine(
startLocalDate);
when(reportsConfigMock.getRepoPath()).thenReturn(REPO_PATH);
when(reportsConfigMock.getFinancialReportHeader()).thenReturn(HEADER);
when(reportsBraintreeTransactionsExtractServiceMock.getAllTransactionsByTypeAndDateInterval(
BraintreeTransactionStatusEnum.SETTLED.toString(), startDate, endDate))
.thenReturn(List.of(braintreeCommonTransactionLine, unjoinableBraintreeTransactionLine));
when(reportsMiraklExtractServiceMock.getAllTransactionLinesByDate(startDate, endDate))
.thenReturn(List.of(unjoinableMiraklTransactionLine, miraklCommonTransactionLine));
when(financialReportConverterServiceMock
.convertBraintreeTransactionLineIntoFinancialReportLine(unjoinableBraintreeTransactionLine))
.thenReturn(unjoinableBraintreeFinancialLine);
when(financialReportConverterServiceMock
.convertMiraklTransactionLineIntoFinancialReportLine(unjoinableMiraklTransactionLine))
.thenReturn(unjoinableMiraklFinancialLine);
when(financialReportConverterServiceMock.convertBrainTreeAndMiraklTransactionLineIntoFinancialReportLine(
braintreeCommonTransactionLine, miraklCommonTransactionLine))
.thenReturn(commonBraintreeAndMiraklFinancialLine);
when(hmcFileServiceMock.saveCSVFile(REPO_PATH, PREFIX_FILE_NAME, FINANCIAL_REPORT_LINES, HEADER))
.thenReturn(FILE_NAME);
testObj.generateFinancialReport(startDate, endDate, PREFIX_FILE_NAME);
verify(hmcFileServiceMock).saveCSVFile(REPO_PATH, PREFIX_FILE_NAME, FINANCIAL_REPORT_LINES, HEADER);
}
private HmcBraintreeTransactionLine getUnjoinableBraintreeTransactionLine(final LocalDateTime date) {
//@formatter:off
return HmcBraintreeTransactionLine.builder()
.orderId("20001")
.amount(BigDecimal.valueOf(120))
.currencyIsoCode("EUR")
.paymentTransactionTime(date)
.paymentTransactionId("6jkals83")
.build();
//@formatter:on
}
private HmcFinancialReportLine getUnjoinableBraintreeFinancialLine(final LocalDateTime date) {
//@formatter:off
return HmcFinancialReportLine.builder()
.braintreeCommerceOrderId("20001")
.braintreeAmount(BigDecimal.valueOf(120))
.currencyIsoCode("EUR")
.braintreeTransactionTime(date)
.braintreeTransactionId("6jkals83")
.build();
//@formatter:on
}
private HmcBraintreeTransactionLine getBraintreeCommonTransactionLine(final LocalDateTime date) {
//@formatter:off
return HmcBraintreeTransactionLine.builder()
.orderId("20000")
.amount(BigDecimal.valueOf(100))
.currencyIsoCode("USD")
.paymentTransactionTime(date)
.paymentTransactionId("5jkals83")
.build();
//@formatter:on
}
private HmcMiraklTransactionLine getUnjoinableMiraklTransactionLine(final LocalDateTime date) {
//@formatter:off
return HmcMiraklTransactionLine.builder()
.orderId("000000009-B")
.sellerId("2003")
.transactionLineId("abcd-12345-2145-bb")
.transactionType("ORDER_CANCELATION")
.transactionTime(date)
.debitAmount(BigDecimal.valueOf(99.0))
.currencyIsoCode("GBP")
.build();
//@formatter:on
}
private HmcFinancialReportLine getUnjoinableMiraklFinancialLine(final LocalDateTime date) {
//@formatter:off
return HmcFinancialReportLine.builder()
.miraklOrderId("000000009-B")
.miraklSellerId("2003")
.miraklTransactionLineId("abcd-12345-2145-bb")
.miraklTransactionType("ORDER_CANCELATION")
.miraklTransactionTime(date)
.miraklDebitAmount(BigDecimal.valueOf(99.0))
.currencyIsoCode("GBP")
.braintreeTransactionId("7jkals83")
.build();
//@formatter:on
}
private HmcFinancialReportLine getCommonBraintreeAndMiraklFinancialLine(final LocalDateTime date) {
//@formatter:off
return HmcFinancialReportLine.builder()
.braintreeCommerceOrderId("20000")
.miraklOrderId("000000009-A")
.miraklSellerId("2002")
.miraklTransactionLineId("abcd-12345-2145-aa")
.miraklTransactionType("ORDER_AMOUNT")
.miraklTransactionTime(date)
.braintreeAmount(BigDecimal.valueOf(100))
.miraklDebitAmount(BigDecimal.valueOf(93.0))
.currencyIsoCode("USD")
.braintreeTransactionId("5jkals83")
.braintreeTransactionTime(date)
.build();
//@formatter:on
}
private HmcMiraklTransactionLine getMiraklCommonTransactionLine(final LocalDateTime date) {
//@formatter:off
return HmcMiraklTransactionLine.builder()
.orderId("000000009-A")
.sellerId("2002")
.transactionLineId("abcd-12345-2145-aa")
.transactionType("ORDER_AMOUNT")
.transactionTime(date)
.debitAmount(BigDecimal.valueOf(93.0))
.currencyIsoCode("USD")
.transactionNumber("5jkals83")
.build();
//@formatter:on
}
}
| 4,997 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/ReportsMiraklExtractServiceImplTest.java | package com.paypal.reports.services.impl;
import com.mirakl.client.core.exception.MiraklException;
import com.mirakl.client.mmp.domain.payment.MiraklTransactionLog;
import com.mirakl.client.mmp.domain.payment.MiraklTransactionLogs;
import com.mirakl.client.mmp.request.payment.MiraklGetTransactionLogsRequest;
import com.paypal.infrastructure.mail.services.MailNotificationUtil;
import com.paypal.infrastructure.mirakl.client.MiraklClient;
import com.paypal.infrastructure.support.converter.Converter;
import com.paypal.infrastructure.support.date.DateUtil;
import com.paypal.infrastructure.support.logging.MiraklLoggingErrorsUtil;
import com.paypal.reports.model.HmcMiraklTransactionLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import static com.paypal.infrastructure.support.date.DateUtil.convertToLocalDateTime;
import static com.paypal.infrastructure.support.date.DateUtil.convertToString;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ReportsMiraklExtractServiceImplTest {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String ERROR_MESSAGE_PREFIX = "There was an error, please check the logs for further information:\n";
Date startDate, endDate;
@InjectMocks
private ReportsMiraklExtractServiceImpl testObj;
@Mock
private MiraklClient reportsMiraklApiClientMock;
@Mock
private Converter<MiraklTransactionLog, HmcMiraklTransactionLine> miraklTransactionLogHMCMiraklTransactionLineConverterMock;
@Mock
private MiraklTransactionLogs transactionLogsMock;
@Mock
private MiraklTransactionLog transactionLogOneMock, transactionLogTwoMock;
@Mock
private HmcMiraklTransactionLine hmcMiraklTransactionLineOneMock, hmcMiraklTransactionLineTwoMock;
@Mock
private MailNotificationUtil mailNotificationMock;
@Captor
private ArgumentCaptor<MiraklGetTransactionLogsRequest> miraklGetTransactionLogsRequest;
@BeforeEach
void setUp() {
startDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 19, 12, 30, 22), ZoneId.systemDefault());
endDate = DateUtil.convertToDate(LocalDateTime.of(2021, 5, 20, 12, 0, 22), ZoneId.systemDefault());
}
@Test
void getAllTransactions_shouldReturnHMCMiraklTransactionLinesCorrespondingWithTransactionLineLog() {
when(reportsMiraklApiClientMock.getTransactionLogs(miraklGetTransactionLogsRequest.capture()))
.thenReturn(transactionLogsMock);
when(transactionLogsMock.getTotalCount()).thenReturn(Long.valueOf(2));
when(transactionLogsMock.getLines()).thenReturn(List.of(transactionLogOneMock, transactionLogTwoMock));
when(miraklTransactionLogHMCMiraklTransactionLineConverterMock.convert(transactionLogOneMock))
.thenReturn(hmcMiraklTransactionLineOneMock);
when(miraklTransactionLogHMCMiraklTransactionLineConverterMock.convert(transactionLogTwoMock))
.thenReturn(hmcMiraklTransactionLineTwoMock);
final List<HmcMiraklTransactionLine> result = testObj.getAllTransactionLinesByDate(startDate, endDate);
assertThat(result).containsExactlyInAnyOrder(hmcMiraklTransactionLineOneMock, hmcMiraklTransactionLineTwoMock);
}
@Test
void getAllTransactions_shouldReturnAnEmptyListWhenSDKResponseIsEmpty() {
when(reportsMiraklApiClientMock.getTransactionLogs(miraklGetTransactionLogsRequest.capture()))
.thenReturn(transactionLogsMock);
when(transactionLogsMock.getTotalCount()).thenReturn(Long.valueOf(0));
when(transactionLogsMock.getLines()).thenReturn(null);
final List<HmcMiraklTransactionLine> result = testObj.getAllTransactionLinesByDate(startDate, endDate);
assertThat(result).isEmpty();
}
@Test
void getAllTransactions_shouldSendAnEmailWhenMiraklSDKThrowsAnException() {
final MiraklException thrownException = new MiraklException("Something went wrong contacting Mirakl");
when(reportsMiraklApiClientMock.getTransactionLogs(any())).thenThrow(thrownException);
final List<HmcMiraklTransactionLine> result = testObj.getAllTransactionLinesByDate(startDate, endDate);
assertThat(result).isEmpty();
verify(mailNotificationMock).sendPlainTextEmail("Issue detected retrieving log lines from Mirakl",
(ERROR_MESSAGE_PREFIX + "Something went wrong getting transaction log information from %s to %s\n%s")
.formatted(convertToString(convertToLocalDateTime(startDate), DATE_FORMAT),
convertToString(convertToLocalDateTime(endDate), DATE_FORMAT),
MiraklLoggingErrorsUtil.stringify(thrownException)));
}
}
| 4,998 |
0 | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services | Create_ds/mirakl-hyperwallet-connector/hmc-reports/src/test/java/com/paypal/reports/services/impl/AbstractHmcFileServiceTest.java | package com.paypal.reports.services.impl;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
@ExtendWith(MockitoExtension.class)
class AbstractHmcFileServiceTest {
@Spy
@InjectMocks
private MyAbstractHmcFileService testObj;
@Mock
private CSVPrinter csvPrinterMock;
private static final String FILE_NAME = "prefixFile_2020-11-10_20-45.csv";
private static final List<String> CONTENT_LINES = List.of("column11,column12,column13",
"column21,column22,column23");
private static final String HEADERS = "headerColumn1,headerColumn2,headerColumn3";
@Test
void printCSVFile_shouldCallToApacheCSVToSaveCSVFile() throws IOException {
final String path = getClass().getResource("").getPath();
doReturn(csvPrinterMock).when(testObj).getCSVPrinter(Paths.get(path), HEADERS, FILE_NAME);
doNothing().when(csvPrinterMock).printRecords(CONTENT_LINES);
doNothing().when(csvPrinterMock).flush();
final String resultFileName = testObj.printCSVFile(Paths.get(path), HEADERS, FILE_NAME, CONTENT_LINES);
assertThat(resultFileName).isEqualTo(FILE_NAME);
}
@Test
void printCSVFile_shouldReturnEmptyStringWhenCSVPrinterCouldNotBeCreated() throws IOException {
final String path = getClass().getResource("").getPath();
doReturn(null).when(testObj).getCSVPrinter(Paths.get(path), HEADERS, FILE_NAME);
final String resultFileName = testObj.printCSVFile(Paths.get(path), HEADERS, FILE_NAME, CONTENT_LINES);
assertThat(resultFileName).isEqualTo(StringUtils.EMPTY);
}
private static class MyAbstractHmcFileService extends AbstractHmcFileService {
}
}
| 4,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.