Search in sources :

Example 11 with IntegrationConfiguration

use of com.salesmanager.core.model.system.IntegrationConfiguration in project shopizer by shopizer-ecommerce.

the class PaymentServiceImpl method initTransaction.

@Override
public Transaction initTransaction(Order order, Customer customer, Payment payment, MerchantStore store) throws ServiceException {
    Validate.notNull(store);
    Validate.notNull(payment);
    Validate.notNull(order);
    Validate.notNull(order.getTotal());
    payment.setCurrency(store.getCurrency());
    BigDecimal amount = order.getTotal();
    // must have a shipping module configured
    Map<String, IntegrationConfiguration> modules = this.getPaymentModulesConfigured(store);
    if (modules == null) {
        throw new ServiceException("No payment module configured");
    }
    IntegrationConfiguration configuration = modules.get(payment.getModuleName());
    if (configuration == null) {
        throw new ServiceException("Payment module " + payment.getModuleName() + " is not configured");
    }
    if (!configuration.isActive()) {
        throw new ServiceException("Payment module " + payment.getModuleName() + " is not active");
    }
    PaymentModule module = this.paymentModules.get(order.getPaymentModuleCode());
    if (module == null) {
        throw new ServiceException("Payment module " + order.getPaymentModuleCode() + " does not exist");
    }
    IntegrationModule integrationModule = getPaymentMethodByCode(store, payment.getModuleName());
    return module.initTransaction(store, customer, amount, payment, configuration, integrationModule);
}
Also used : PaymentModule(com.salesmanager.core.modules.integration.payment.model.PaymentModule) ServiceException(com.salesmanager.core.business.exception.ServiceException) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) BigDecimal(java.math.BigDecimal) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule)

Example 12 with IntegrationConfiguration

use of com.salesmanager.core.model.system.IntegrationConfiguration in project shopizer by shopizer-ecommerce.

the class PaymentServiceImpl method processRefund.

@Override
public Transaction processRefund(Order order, Customer customer, MerchantStore store, BigDecimal amount) throws ServiceException {
    Validate.notNull(customer);
    Validate.notNull(store);
    Validate.notNull(amount);
    Validate.notNull(order);
    Validate.notNull(order.getOrderTotal());
    BigDecimal orderTotal = order.getTotal();
    if (amount.doubleValue() > orderTotal.doubleValue()) {
        throw new ServiceException("Invalid amount, the refunded amount is greater than the total allowed");
    }
    String module = order.getPaymentModuleCode();
    Map<String, IntegrationConfiguration> modules = this.getPaymentModulesConfigured(store);
    if (modules == null) {
        throw new ServiceException("No payment module configured");
    }
    IntegrationConfiguration configuration = modules.get(module);
    if (configuration == null) {
        throw new ServiceException("Payment module " + module + " is not configured");
    }
    PaymentModule paymentModule = this.paymentModules.get(module);
    if (paymentModule == null) {
        throw new ServiceException("Payment module " + paymentModule + " does not exist");
    }
    boolean partial = false;
    if (amount.doubleValue() != order.getTotal().doubleValue()) {
        partial = true;
    }
    IntegrationModule integrationModule = getPaymentMethodByCode(store, module);
    // get the associated transaction
    Transaction refundable = transactionService.getRefundableTransaction(order);
    if (refundable == null) {
        throw new ServiceException("No refundable transaction for this order");
    }
    Transaction transaction = paymentModule.refund(partial, store, refundable, order, amount, configuration, integrationModule);
    transaction.setOrder(order);
    transactionService.create(transaction);
    OrderTotal refund = new OrderTotal();
    refund.setModule(Constants.OT_REFUND_MODULE_CODE);
    refund.setText(Constants.OT_REFUND_MODULE_CODE);
    refund.setTitle(Constants.OT_REFUND_MODULE_CODE);
    refund.setOrderTotalCode(Constants.OT_REFUND_MODULE_CODE);
    refund.setOrderTotalType(OrderTotalType.REFUND);
    refund.setValue(amount);
    refund.setSortOrder(100);
    refund.setOrder(order);
    order.getOrderTotal().add(refund);
    // update order total
    orderTotal = orderTotal.subtract(amount);
    // update ordertotal refund
    Set<OrderTotal> totals = order.getOrderTotal();
    for (OrderTotal total : totals) {
        if (total.getModule().equals(Constants.OT_TOTAL_MODULE_CODE)) {
            total.setValue(orderTotal);
        }
    }
    order.setTotal(orderTotal);
    order.setStatus(OrderStatus.REFUNDED);
    OrderStatusHistory orderHistory = new OrderStatusHistory();
    orderHistory.setOrder(order);
    orderHistory.setStatus(OrderStatus.REFUNDED);
    orderHistory.setDateAdded(new Date());
    order.getOrderHistory().add(orderHistory);
    orderService.saveOrUpdate(order);
    return transaction;
}
Also used : IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) BigDecimal(java.math.BigDecimal) Date(java.util.Date) PaymentModule(com.salesmanager.core.modules.integration.payment.model.PaymentModule) ServiceException(com.salesmanager.core.business.exception.ServiceException) Transaction(com.salesmanager.core.model.payments.Transaction) OrderTotal(com.salesmanager.core.model.order.OrderTotal) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule)

Example 13 with IntegrationConfiguration

use of com.salesmanager.core.model.system.IntegrationConfiguration in project shopizer by shopizer-ecommerce.

the class PaymentApi method configure.

@PostMapping(value = "/private/modules/payment")
public void configure(@RequestBody IntegrationModuleConfiguration configuration, @ApiIgnore MerchantStore merchantStore) {
    try {
        List<IntegrationModule> modules = paymentService.getPaymentMethods(merchantStore);
        Map<String, IntegrationModule> map = modules.stream().collect(Collectors.toMap(IntegrationModule::getCode, module -> module));
        IntegrationModule config = map.get(configuration.getCode());
        if (config == null) {
            throw new ResourceNotFoundException("Payment module [" + configuration.getCode() + "] not found");
        }
        Map<String, IntegrationConfiguration> configuredModules = paymentService.getPaymentModulesConfigured(merchantStore);
        IntegrationConfiguration integrationConfiguration = configuredModules.get(configuration.getCode());
        if (integrationConfiguration == null) {
            integrationConfiguration = new IntegrationConfiguration();
            integrationConfiguration.setModuleCode(configuration.getCode());
        }
        integrationConfiguration.setActive(configuration.isActive());
        integrationConfiguration.setDefaultSelected(configuration.isDefaultSelected());
        integrationConfiguration.setIntegrationKeys(configuration.getIntegrationKeys());
        integrationConfiguration.setIntegrationOptions(configuration.getIntegrationOptions());
        paymentService.savePaymentModuleConfiguration(integrationConfiguration, merchantStore);
    } catch (ServiceException e) {
        LOGGER.error("Error getting payment modules", e);
        throw new ServiceRuntimeException("Error saving payment module", e);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) IntegrationModuleConfiguration(com.salesmanager.shop.model.system.IntegrationModuleConfiguration) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ServiceException(com.salesmanager.core.business.exception.ServiceException) RequestBody(org.springframework.web.bind.annotation.RequestBody) Language(com.salesmanager.core.model.reference.language.Language) ApiOperation(io.swagger.annotations.ApiOperation) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) Api(io.swagger.annotations.Api) Tag(io.swagger.annotations.Tag) PostMapping(org.springframework.web.bind.annotation.PostMapping) Logger(org.slf4j.Logger) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) PaymentService(com.salesmanager.core.business.services.payments.PaymentService) IntegrationModuleSummaryEntity(com.salesmanager.shop.model.system.IntegrationModuleSummaryEntity) ApiIgnore(springfox.documentation.annotations.ApiIgnore) List(java.util.List) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) SwaggerDefinition(io.swagger.annotations.SwaggerDefinition) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ServiceException(com.salesmanager.core.business.exception.ServiceException) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 14 with IntegrationConfiguration

use of com.salesmanager.core.model.system.IntegrationConfiguration in project shopizer by shopizer-ecommerce.

the class ShippingConfigurationApi method shippingModule.

/**
 * Get merchant shipping module details
 *
 * @param code
 * @param merchantStore
 * @param language
 * @return
 */
@GetMapping("/private/modules/shipping/{code}")
@ApiOperation(httpMethod = "GET", value = "Shipping module by code", produces = "application/json", response = List.class)
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT") })
public IntegrationConfiguration shippingModule(@PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) {
    try {
        // configured modules
        List<IntegrationModule> modules = shippingService.getShippingMethods(merchantStore);
        // check if exist
        Optional<IntegrationModule> checkIfExist = modules.stream().filter(m -> m.getCode().equals(code)).findAny();
        if (!checkIfExist.isPresent()) {
            throw new ResourceNotFoundException("Shipping module [" + code + "] not found");
        }
        IntegrationConfiguration config = shippingService.getShippingConfiguration(code, merchantStore);
        if (config == null) {
            config = new IntegrationConfiguration();
        }
        /**
         * Build return object for now this is a read copy
         */
        config.setActive(config.isActive());
        config.setDefaultSelected(config.isDefaultSelected());
        config.setIntegrationKeys(config.getIntegrationKeys());
        config.setIntegrationOptions(config.getIntegrationOptions());
        return config;
    } catch (ServiceException e) {
        LOGGER.error("Error getting shipping module [" + code + "]", e);
        throw new ServiceRuntimeException("Error getting shipping module [" + code + "]", e);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) IntegrationModuleConfiguration(com.salesmanager.shop.model.system.IntegrationModuleConfiguration) ShippingFacade(com.salesmanager.shop.store.controller.shipping.facade.ShippingFacade) Constants(com.salesmanager.shop.constants.Constants) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ServiceException(com.salesmanager.core.business.exception.ServiceException) RequestBody(org.springframework.web.bind.annotation.RequestBody) Language(com.salesmanager.core.model.reference.language.Language) ApiOperation(io.swagger.annotations.ApiOperation) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) AuthorizationUtils(com.salesmanager.shop.utils.AuthorizationUtils) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) Api(io.swagger.annotations.Api) Tag(io.swagger.annotations.Tag) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ShippingService(com.salesmanager.core.business.services.shipping.ShippingService) PostMapping(org.springframework.web.bind.annotation.PostMapping) Logger(org.slf4j.Logger) ApiImplicitParam(io.swagger.annotations.ApiImplicitParam) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) IntegrationModuleSummaryEntity(com.salesmanager.shop.model.system.IntegrationModuleSummaryEntity) ApiIgnore(springfox.documentation.annotations.ApiIgnore) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Stream(java.util.stream.Stream) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) SwaggerDefinition(io.swagger.annotations.SwaggerDefinition) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) Optional(java.util.Optional) PersistableAddress(com.salesmanager.shop.model.references.PersistableAddress) ReadableAddress(com.salesmanager.shop.model.references.ReadableAddress) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ServiceException(com.salesmanager.core.business.exception.ServiceException) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) GetMapping(org.springframework.web.bind.annotation.GetMapping) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ApiOperation(io.swagger.annotations.ApiOperation)

Example 15 with IntegrationConfiguration

use of com.salesmanager.core.model.system.IntegrationConfiguration in project shopizer by shopizer-ecommerce.

the class UPSParsedElements method getShippingQuotes.

@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages, BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store, IntegrationConfiguration configuration, IntegrationModule module, ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {
    Validate.notNull(configuration, "IntegrationConfiguration must not be null for USPS shipping module");
    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }
    BigDecimal total = orderTotal;
    if (packages == null) {
        return null;
    }
    List<ShippingOption> options = null;
    // only applies to Canada and US
    Country country = delivery.getCountry();
    if (!(country.getIsoCode().equals("US") || country.getIsoCode().equals("CA"))) {
        return null;
    // throw new IntegrationException("UPS Not configured for shipping in country " + country.getIsoCode());
    }
    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
        language = Locale.ENGLISH.getLanguage();
    }
    String pack = configuration.getIntegrationOptions().get("packages").get(0);
    Map<String, String> keys = configuration.getIntegrationKeys();
    String accessKey = keys.get("accessKey");
    String userId = keys.get("userId");
    String password = keys.get("password");
    String host = null;
    String protocol = null;
    String port = null;
    String url = null;
    StringBuilder xmlbuffer = new StringBuilder();
    HttpPost httppost = null;
    BufferedReader reader = null;
    try {
        String env = configuration.getEnvironment();
        Set<String> regions = module.getRegionsSet();
        if (!regions.contains(store.getCountry().getIsoCode())) {
            throw new IntegrationException("Can't use the service for store country code ");
        }
        Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
        for (String key : moduleConfigsMap.keySet()) {
            ModuleConfig moduleConfig = moduleConfigsMap.get(key);
            if (moduleConfig.getEnv().equals(env)) {
                host = moduleConfig.getHost();
                protocol = moduleConfig.getScheme();
                port = moduleConfig.getPort();
                url = moduleConfig.getUri();
            }
        }
        StringBuilder xmlreqbuffer = new StringBuilder();
        xmlreqbuffer.append("<?xml version=\"1.0\"?>");
        xmlreqbuffer.append("<AccessRequest>");
        xmlreqbuffer.append("<AccessLicenseNumber>");
        xmlreqbuffer.append(accessKey);
        xmlreqbuffer.append("</AccessLicenseNumber>");
        xmlreqbuffer.append("<UserId>");
        xmlreqbuffer.append(userId);
        xmlreqbuffer.append("</UserId>");
        xmlreqbuffer.append("<Password>");
        xmlreqbuffer.append(password);
        xmlreqbuffer.append("</Password>");
        xmlreqbuffer.append("</AccessRequest>");
        String xmlhead = xmlreqbuffer.toString();
        String weightCode = store.getWeightunitcode();
        String measureCode = store.getSeizeunitcode();
        if (weightCode.equals("KG")) {
            weightCode = "KGS";
        } else {
            weightCode = "LBS";
        }
        String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>Shopizer</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>";
        StringBuilder xmldatabuffer = new StringBuilder();
        /**
         * <Shipment>
         *
         * <Shipper> <Address> <City></City>
         * <StateProvinceCode>QC</StateProvinceCode>
         * <CountryCode>CA</CountryCode> <PostalCode></PostalCode>
         * </Address> </Shipper>
         *
         * <ShipTo> <Address> <City>Redwood Shores</City>
         * <StateProvinceCode>CA</StateProvinceCode>
         * <CountryCode>US</CountryCode> <PostalCode></PostalCode>
         * <ResidentialAddressIndicator/> </Address> </ShipTo>
         *
         * <Package> <PackagingType> <Code>21</Code> </PackagingType>
         * <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code>
         * </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight>
         * <PackageServiceOptions> <InsuredValue>
         * <CurrencyCode>CAD</CurrencyCode>
         * <MonetaryValue>100</MonetaryValue> </InsuredValue>
         * </PackageServiceOptions> </Package>
         *
         * </Shipment>
         *
         * <CustomerClassification> <Code>03</Code>
         * </CustomerClassification> </RatingServiceSelectionRequest>
         * *
         */
        /**
         *Map countriesMap = (Map) RefCache.getAllcountriesmap(LanguageUtil
         *					.getLanguageNumberCode(locale.getLanguage()));
         *			Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil
         *					.getLanguageNumberCode(locale.getLanguage()));
         *
         *			Country storeCountry = (Country) countriesMap.get(store
         *					.getCountry());
         *
         *			Country customerCountry = (Country) countriesMap.get(customer
         *					.getCustomerCountryId());
         *
         *			int sZone = -1;
         *			try {
         *				sZone = Integer.parseInt(store.getZone());
         *			} catch (Exception e) {
         *				// TODO: handle exception
         *			}
         *
         *			Zone storeZone = (Zone) zonesMap.get(sZone);
         *			Zone customerZone = (Zone) zonesMap.get(customer
         *					.getCustomerZoneId());*
         */
        xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>");
        // xmldatabuffer.append("<Description>Daily Pickup</Description>");
        xmldatabuffer.append("<Shipment><Shipper>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(store.getStorecity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(store.getStorestateprovince())) {
        if (store.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            // zone code
            xmldatabuffer.append(store.getZone().getCode());
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(store.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
        xmldatabuffer.append("</PostalCode></Address></Shipper>");
        // ship to
        xmldatabuffer.append("<ShipTo>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(delivery.getCity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(customer.getCustomerState())) {
        if (delivery.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            // zone code
            xmldatabuffer.append(delivery.getZone().getCode());
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(delivery.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
        xmldatabuffer.append("</PostalCode></Address></ShipTo>");
        for (PackageDetails packageDetail : packages) {
            xmldatabuffer.append("<Package>");
            xmldatabuffer.append("<PackagingType>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</PackagingType>");
            // weight
            xmldatabuffer.append("<PackageWeight>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(weightCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Weight>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Weight>");
            xmldatabuffer.append("</PackageWeight>");
            // dimension
            xmldatabuffer.append("<Dimensions>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(measureCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Length>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Length>");
            xmldatabuffer.append("<Width>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Width>");
            xmldatabuffer.append("<Height>");
            xmldatabuffer.append(new BigDecimal(packageDetail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Height>");
            xmldatabuffer.append("</Dimensions>");
            xmldatabuffer.append("</Package>");
        }
        xmldatabuffer.append("</Shipment>");
        xmldatabuffer.append("</RatingServiceSelectionRequest>");
        xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString());
        LOGGER.debug("UPS QUOTE REQUEST " + xmlbuffer.toString());
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            // HttpClient client = new HttpClient();
            httppost = new HttpPost(protocol + "://" + host + ":" + port + url);
            StringEntity entity = new StringEntity(xmlbuffer.toString(), ContentType.APPLICATION_ATOM_XML);
            // RequestEntity entity = new StringRequestEntity(
            // xmlbuffer.toString(), "text/plain", "UTF-8");
            httppost.setEntity(entity);
            // Create a custom response handler
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity1 = response.getEntity();
                    return entity1 != null ? EntityUtils.toString(entity1) : null;
                } else {
                    LOGGER.error("Communication Error with ups quote " + status);
                    throw new ClientProtocolException("UPS quote communication error " + status);
                }
            };
            String data = httpclient.execute(httppost, responseHandler);
            // int result = response.getStatusLine().getStatusCode();
            // int result = client.executeMethod(httppost);
            /*			if (result != 200) {
				LOGGER.error("Communication Error with ups quote " + result + " "
						+ protocol + "://" + host + ":" + port + url);
				throw new Exception("UPS quote communication error " + result);
			}*/
            LOGGER.debug("ups quote response " + data);
            UPSParsedElements parsed = new UPSParsedElements();
            Digester digester = new Digester();
            digester.push(parsed);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription", "setStatusMessage", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0);
            digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", ShippingOption.class);
            // digester.addSetProperties(
            // "RatingServiceSelectionResponse/RatedShipment", "sequence",
            // "optionId" );
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue", "setOptionPriceText", 0);
            // digester
            // .addCallMethod(
            // "RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode",
            // "setCurrency", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0);
            digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery", "setEstimatedNumberOfDays", 0);
            digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "addOption");
            // <?xml
            // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
            // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
            // XML document is well formed but the document is not
            // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>
            Reader xmlreader = new StringReader(data);
            digester.parse(xmlreader);
            if (!StringUtils.isBlank(parsed.getErrorCode())) {
                LOGGER.error("Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
                throw new IntegrationException(parsed.getError());
            }
            if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {
                throw new IntegrationException(parsed.getError());
            }
            if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {
                throw new IntegrationException("No shipping options available for the configuration");
            }
            /*String carrier = getShippingMethodDescription(locale);
			// cost is in CAD, need to do conversion

			boolean requiresCurrencyConversion = false; String storeCurrency
			 = store.getCurrency();
			if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
			 requiresCurrencyConversion = true; }

			LabelUtil labelUtil = LabelUtil.getInstance();
			Map serviceMap = com.salesmanager.core.util.ShippingUtil
					.buildServiceMap("upsxml", locale);

			*/
            /**
             * Details on whit RT quote information to display *
             */
            /*
			MerchantConfiguration rtdetails = config
					.getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
			int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
			if (rtdetails != null) {

				if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
																				// or
																				// not
																				// quotes
					try {
						displayQuoteDeliveryTime = Integer.parseInt(rtdetails
								.getConfigurationValue1());

					} catch (Exception e) {
						log.error("Display quote is not an integer value ["
								+ rtdetails.getConfigurationValue1() + "]");
					}
				}
			}*/
            List<ShippingOption> shippingOptions = parsed.getOptions();
            if (shippingOptions != null) {
                Map<String, String> details = module.getDetails();
                for (ShippingOption option : shippingOptions) {
                    String name = details.get(option.getOptionCode());
                    option.setOptionName(name);
                    if (option.getOptionPrice() == null) {
                        String priceText = option.getOptionPriceText();
                        if (StringUtils.isBlank(priceText)) {
                            throw new IntegrationException("Price text is null for option " + name);
                        }
                        try {
                            BigDecimal price = new BigDecimal(priceText);
                            option.setOptionPrice(price);
                        } catch (Exception e) {
                            throw new IntegrationException("Can't convert to numeric price " + priceText);
                        }
                    }
                }
            }
            return shippingOptions;
        }
    } catch (Exception e1) {
        LOGGER.error("UPS quote error", e1);
        throw new IntegrationException(e1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignore) {
            }
        }
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }
}
Also used : ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpPost(org.apache.http.client.methods.HttpPost) ShippingOrigin(com.salesmanager.core.model.shipping.ShippingOrigin) DataUtils(com.salesmanager.core.business.utils.DataUtils) LoggerFactory(org.slf4j.LoggerFactory) Delivery(com.salesmanager.core.model.common.Delivery) StringUtils(org.apache.commons.lang3.StringUtils) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) ArrayList(java.util.ArrayList) EntityUtils(org.apache.http.util.EntityUtils) BigDecimal(java.math.BigDecimal) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Locale(java.util.Locale) CustomIntegrationConfiguration(com.salesmanager.core.model.system.CustomIntegrationConfiguration) Map(java.util.Map) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) Logger(org.slf4j.Logger) Country(com.salesmanager.core.model.reference.country.Country) Digester(org.apache.commons.digester.Digester) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Set(java.util.Set) StringEntity(org.apache.http.entity.StringEntity) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) Reader(java.io.Reader) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) List(java.util.List) Validate(org.apache.commons.lang3.Validate) StringReader(java.io.StringReader) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) BufferedReader(java.io.BufferedReader) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) ResponseHandler(org.apache.http.client.ResponseHandler) ShippingQuoteModule(com.salesmanager.core.modules.integration.shipping.model.ShippingQuoteModule) HttpClients(org.apache.http.impl.client.HttpClients) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) Reader(java.io.Reader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) Digester(org.apache.commons.digester.Digester) StringReader(java.io.StringReader) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) BigDecimal(java.math.BigDecimal) ClientProtocolException(org.apache.http.client.ClientProtocolException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) BufferedReader(java.io.BufferedReader) Country(com.salesmanager.core.model.reference.country.Country) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails)

Aggregations

IntegrationConfiguration (com.salesmanager.core.model.system.IntegrationConfiguration)27 ServiceException (com.salesmanager.core.business.exception.ServiceException)20 IntegrationModule (com.salesmanager.core.model.system.IntegrationModule)16 IntegrationException (com.salesmanager.core.modules.integration.IntegrationException)10 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)9 List (java.util.List)9 Language (com.salesmanager.core.model.reference.language.Language)8 BigDecimal (java.math.BigDecimal)8 Map (java.util.Map)8 CustomIntegrationConfiguration (com.salesmanager.core.model.system.CustomIntegrationConfiguration)7 PaymentModule (com.salesmanager.core.modules.integration.payment.model.PaymentModule)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)6 MerchantConfiguration (com.salesmanager.core.model.system.MerchantConfiguration)6 IntegrationModuleConfiguration (com.salesmanager.shop.model.system.IntegrationModuleConfiguration)6 IntegrationModuleSummaryEntity (com.salesmanager.shop.model.system.IntegrationModuleSummaryEntity)6 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)6 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)6 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)6