Search in sources :

Example 1 with MerchantLog

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

the class PackingBox method getBoxPackagesDetails.

@Override
public List<PackageDetails> getBoxPackagesDetails(List<ShippingProduct> products, MerchantStore store) throws ServiceException {
    if (products == null) {
        throw new ServiceException("Product list cannot be null !!");
    }
    double width = 0;
    double length = 0;
    double height = 0;
    double weight = 0;
    double maxweight = 0;
    // int treshold = 0;
    ShippingConfiguration shippingConfiguration = shippingService.getShippingConfiguration(store);
    if (shippingConfiguration == null) {
        throw new ServiceException("ShippingConfiguration not found for merchant " + store.getCode());
    }
    width = (double) shippingConfiguration.getBoxWidth();
    length = (double) shippingConfiguration.getBoxLength();
    height = (double) shippingConfiguration.getBoxHeight();
    weight = shippingConfiguration.getBoxWeight();
    maxweight = shippingConfiguration.getMaxWeight();
    List<PackageDetails> boxes = new ArrayList<PackageDetails>();
    // maximum number of boxes
    int maxBox = 100;
    int iterCount = 0;
    List<Product> individualProducts = new ArrayList<Product>();
    // need to put items individually
    for (ShippingProduct shippingProduct : products) {
        Product product = shippingProduct.getProduct();
        if (product.isProductVirtual()) {
            continue;
        }
        int qty = shippingProduct.getQuantity();
        Set<ProductAttribute> attrs = shippingProduct.getProduct().getAttributes();
        // set attributes values
        BigDecimal w = product.getProductWeight();
        BigDecimal h = product.getProductHeight();
        BigDecimal l = product.getProductLength();
        BigDecimal wd = product.getProductWidth();
        if (w == null) {
            w = new BigDecimal(defaultWeight);
        }
        if (h == null) {
            h = new BigDecimal(defaultHeight);
        }
        if (l == null) {
            l = new BigDecimal(defaultLength);
        }
        if (wd == null) {
            wd = new BigDecimal(defaultWidth);
        }
        if (attrs != null && attrs.size() > 0) {
            for (ProductAttribute attribute : attrs) {
                if (attribute.getProductAttributeWeight() != null) {
                    w = w.add(attribute.getProductAttributeWeight());
                }
            }
        }
        if (qty > 1) {
            for (int i = 1; i <= qty; i++) {
                Product temp = new Product();
                temp.setProductHeight(h);
                temp.setProductLength(l);
                temp.setProductWidth(wd);
                temp.setProductWeight(w);
                temp.setAttributes(product.getAttributes());
                temp.setDescriptions(product.getDescriptions());
                individualProducts.add(temp);
            }
        } else {
            Product temp = new Product();
            temp.setProductHeight(h);
            temp.setProductLength(l);
            temp.setProductWidth(wd);
            temp.setProductWeight(w);
            temp.setAttributes(product.getAttributes());
            temp.setDescriptions(product.getDescriptions());
            individualProducts.add(temp);
        }
        iterCount++;
    }
    if (iterCount == 0) {
        return null;
    }
    int productCount = individualProducts.size();
    List<PackingBox> boxesList = new ArrayList<PackingBox>();
    // start the creation of boxes
    PackingBox box = new PackingBox();
    // set box max volume
    double maxVolume = width * length * height;
    if (maxVolume == 0 || maxweight == 0) {
        merchantLogService.save(new MerchantLog(store, "shipping", "Check shipping box configuration, it has a volume of " + maxVolume + " and a maximum weight of " + maxweight + ". Those values must be greater than 0."));
        throw new ServiceException("Product configuration exceeds box configuraton");
    }
    box.setVolumeLeft(maxVolume);
    box.setWeightLeft(maxweight);
    // assign first box
    boxesList.add(box);
    // int boxCount = 1;
    List<Product> assignedProducts = new ArrayList<Product>();
    // calculate the volume for the next object
    if (assignedProducts.size() > 0) {
        individualProducts.removeAll(assignedProducts);
        assignedProducts = new ArrayList<Product>();
    }
    boolean productAssigned = false;
    for (Product p : individualProducts) {
        // Set<ProductAttribute> attributes = p.getAttributes();
        productAssigned = false;
        double productWeight = p.getProductWeight().doubleValue();
        // validate if product fits in the box
        if (p.getProductWidth().doubleValue() > width || p.getProductHeight().doubleValue() > height || p.getProductLength().doubleValue() > length) {
            // log message to customer
            merchantLogService.save(new MerchantLog(store, "shipping", "Product " + p.getSku() + " has a demension larger than the box size specified. Will use per item calculation."));
            throw new ServiceException("Product configuration exceeds box configuraton");
        }
        if (productWeight > maxweight) {
            merchantLogService.save(new MerchantLog(store, "shipping", "Product " + p.getSku() + " has a weight larger than the box maximum weight specified. Will use per item calculation."));
            throw new ServiceException("Product configuration exceeds box configuraton");
        }
        double productVolume = (p.getProductWidth().doubleValue() * p.getProductHeight().doubleValue() * p.getProductLength().doubleValue());
        if (productVolume == 0) {
            merchantLogService.save(new MerchantLog(store, "shipping", "Product " + p.getSku() + " has one of the dimension set to 0 and therefore cannot calculate the volume"));
            throw new ServiceException("Product configuration exceeds box configuraton");
        }
        if (productVolume > maxVolume) {
            throw new ServiceException("Product configuration exceeds box configuraton");
        }
        // Iterator boxIter = boxesList.iterator();
        for (PackingBox pbox : boxesList) {
            double volumeLeft = pbox.getVolumeLeft();
            double weightLeft = pbox.getWeightLeft();
            if ((volumeLeft * .75) >= productVolume && pbox.getWeightLeft() >= productWeight) {
                // fit the item
                // in this
                // box
                // fit in the current box
                volumeLeft = volumeLeft - productVolume;
                pbox.setVolumeLeft(volumeLeft);
                weightLeft = weightLeft - productWeight;
                pbox.setWeightLeft(weightLeft);
                assignedProducts.add(p);
                productCount--;
                double w = pbox.getWeight();
                w = w + productWeight;
                pbox.setWeight(w);
                productAssigned = true;
                maxBox--;
                break;
            }
        }
        if (!productAssigned) {
            // create a new box
            box = new PackingBox();
            // set box max volume
            box.setVolumeLeft(maxVolume);
            box.setWeightLeft(maxweight);
            boxesList.add(box);
            double volumeLeft = box.getVolumeLeft() - productVolume;
            box.setVolumeLeft(volumeLeft);
            double weightLeft = box.getWeightLeft() - productWeight;
            box.setWeightLeft(weightLeft);
            assignedProducts.add(p);
            productCount--;
            double w = box.getWeight();
            w = w + productWeight;
            box.setWeight(w);
            maxBox--;
        }
    }
    // now prepare the shipping info
    // number of boxes
    // Iterator ubIt = usedBoxesList.iterator();
    System.out.println("###################################");
    System.out.println("Number of boxes " + boxesList.size());
    System.out.println("###################################");
    for (PackingBox pb : boxesList) {
        PackageDetails details = new PackageDetails();
        details.setShippingHeight(height);
        details.setShippingLength(length);
        details.setShippingWeight(weight + box.getWeight());
        details.setShippingWidth(width);
        details.setItemName(store.getCode());
        boxes.add(details);
    }
    return boxes;
}
Also used : ArrayList(java.util.ArrayList) Product(com.salesmanager.core.model.catalog.product.Product) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) BigDecimal(java.math.BigDecimal) ShippingConfiguration(com.salesmanager.core.model.shipping.ShippingConfiguration) ServiceException(com.salesmanager.core.business.exception.ServiceException) PackageDetails(com.salesmanager.core.model.shipping.PackageDetails) MerchantLog(com.salesmanager.core.model.system.MerchantLog)

Example 2 with MerchantLog

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

the class BeanStreamPayment method sendTransaction.

private Transaction sendTransaction(String orderNumber, MerchantStore store, String transaction, String beanstreamType, TransactionType transactionType, PaymentType paymentType, BigDecimal amount, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
    String agent = "Mozilla/4.0";
    String respText = "";
    Map<String, String> nvp = null;
    DataOutputStream output = null;
    DataInputStream in = null;
    BufferedReader is = null;
    HttpURLConnection conn = null;
    try {
        // transaction = "requestType=BACKEND&merchant_id=300200260&trnType=P&username=carlito&password=shopizer001&orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0&trnCardOwner=Carl Samson&trnCardNumber=5100000020002000&trnExpMonth=10&trnExpYear=14&trnCardCvd=123&trnAmount=77.01&ordName=Carl S&ordAddress1=358 Du Languedoc&ordCity=Victoria&ordProvince=BC&ordPostalCode=V8T2E7&ordCountry=CA&ordPhoneNumber=(444) 555-6666&ordEmailAddress=csamson777@yahoo.com";
        /**
         *			requestType=BACKEND&merchant_id=300200260
         *			&trnType=P
         *			&username=carlito&password=shopizer001
         *			&orderNumber=caa71106-7e3f-4975-a657-a35904dc32a0
         *			&trnCardOwner=Carl Samson
         *			&trnCardNumber=5100000020002000
         *			&trnExpMonth=10
         *			&trnExpYear=14
         *			&trnCardCvd=123
         *			&trnAmount=77.01
         *			&ordName=Carl S
         *			&ordAddress1=378 Du Languedoc
         *			&ordCity=Boucherville
         *			&ordProvince=QC
         *			&ordPostalCode=J3B8J1
         *			&ordCountry=CA
         *			&ordPhoneNumber=(444) 555-6666
         *			&ordEmailAddress=test@yahoo.com
         */
        /**
         *			merchant_id=123456789&requestType=BACKEND
         *			&trnType=P&trnOrderNumber=1234TEST&trnAmount=5.00&trnCardOwner=Joe+Test
         *					&trnCardNumber=4030000010001234
         *					&trnExpMonth=10
         *					&trnExpYear=16
         *					&ordName=Joe+Test
         *					&ordAddress1=123+Test+Street
         *					&ordCity=Victoria
         *					&ordProvince=BC
         *					&ordCountry=CA
         *					&ordPostalCode=V8T2E7
         *					&ordPhoneNumber=5555555555
         *					&ordEmailAddress=joe%40testemail.com
         */
        boolean bSandbox = false;
        if (configuration.getEnvironment().equals("TEST")) {
            // sandbox
            bSandbox = true;
        }
        String server = "";
        ModuleConfig configs = module.getModuleConfigs().get("PROD");
        if (bSandbox) {
            configs = module.getModuleConfigs().get("TEST");
        }
        if (configs == null) {
            throw new IntegrationException("Module not configured for TEST or PROD");
        }
        server = new StringBuffer().append(configs.getScheme()).append("://").append(configs.getHost()).append(":").append(configs.getPort()).append(configs.getUri()).toString();
        URL postURL = new URL(server);
        conn = (HttpURLConnection) postURL.openConnection();
        // Set connection parameters. We need to perform input and output,
        // so set both as true.
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // Set the content type we are POSTing. We impersonate it as
        // encoded form data
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("User-Agent", agent);
        conn.setRequestProperty("Content-Length", String.valueOf(transaction.length()));
        conn.setRequestMethod("POST");
        // get the output stream to POST to.
        output = new DataOutputStream(conn.getOutputStream());
        output.writeBytes(transaction);
        output.flush();
        // Read input from the input stream.
        in = new DataInputStream(conn.getInputStream());
        int rc = conn.getResponseCode();
        if (rc != -1) {
            is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String _line = null;
            while (((_line = is.readLine()) != null)) {
                respText = respText + _line;
            }
            LOGGER.debug("BeanStream response -> " + respText.trim());
            nvp = formatUrlResponse(respText.trim());
        } else {
            throw new IntegrationException("Invalid response from BeanStream, return code is " + rc);
        }
        // check
        // trnApproved=1&trnId=10003067&messageId=1&messageText=Approved&trnOrderNumber=E40089&authCode=TEST&errorType=N&errorFields=
        String transactionApproved = nvp.get("TRNAPPROVED");
        String transactionId = nvp.get("TRNID");
        String messageId = nvp.get("MESSAGEID");
        String messageText = (String) nvp.get("MESSAGETEXT");
        String orderId = (String) nvp.get("TRNORDERNUMBER");
        String authCode = (String) nvp.get("AUTHCODE");
        String errorType = (String) nvp.get("ERRORTYPE");
        String errorFields = (String) nvp.get("ERRORFIELDS");
        if (!StringUtils.isBlank(orderNumber)) {
            nvp.put("INTERNALORDERID", orderNumber);
        }
        if (StringUtils.isBlank(transactionApproved)) {
            throw new IntegrationException("Required field transactionApproved missing from BeanStream response");
        }
        // errors
        if (transactionApproved.equals("0")) {
            merchantLogService.save(new MerchantLog(store, "Can't process BeanStream message " + messageText + " return code id " + messageId));
            IntegrationException te = new IntegrationException("Can't process BeanStream message " + messageText);
            te.setExceptionType(IntegrationException.EXCEPTION_PAYMENT_DECLINED);
            te.setMessageCode("message.payment.beanstream." + messageId);
            te.setErrorCode(IntegrationException.TRANSACTION_EXCEPTION);
            throw te;
        }
        // return parseResponse(type,transaction,respText,nvp,order);
        return this.parseResponse(transactionType, paymentType, nvp, amount);
    } catch (Exception e) {
        if (e instanceof IntegrationException) {
            throw (IntegrationException) e;
        }
        throw new IntegrationException("Error while processing BeanStream transaction", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (output != null) {
            try {
                output.close();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception ignore) {
            // TODO: handle exception
            }
        }
    }
}
Also used : IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) ModuleConfig(com.salesmanager.core.model.system.ModuleConfig) DataInputStream(java.io.DataInputStream) URL(java.net.URL) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader) MerchantLog(com.salesmanager.core.model.system.MerchantLog)

Aggregations

MerchantLog (com.salesmanager.core.model.system.MerchantLog)2 ServiceException (com.salesmanager.core.business.exception.ServiceException)1 Product (com.salesmanager.core.model.catalog.product.Product)1 ProductAttribute (com.salesmanager.core.model.catalog.product.attribute.ProductAttribute)1 PackageDetails (com.salesmanager.core.model.shipping.PackageDetails)1 ShippingConfiguration (com.salesmanager.core.model.shipping.ShippingConfiguration)1 ShippingProduct (com.salesmanager.core.model.shipping.ShippingProduct)1 ModuleConfig (com.salesmanager.core.model.system.ModuleConfig)1 IntegrationException (com.salesmanager.core.modules.integration.IntegrationException)1 BufferedReader (java.io.BufferedReader)1 DataInputStream (java.io.DataInputStream)1 DataOutputStream (java.io.DataOutputStream)1 InputStreamReader (java.io.InputStreamReader)1 BigDecimal (java.math.BigDecimal)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1