Developer forum

Forum » Development » Custom fee shipping by postal code

Custom fee shipping by postal code

Jose Caudevilla
Reply

Hi:

I have a problem with the creation of a custom shipping fee provider.

I need to implement a custom shipping fee that depends of the postal code entered by the user in the shipping cart.

Here is a snaptshot of the cart:

 

Reading the api i found that the Dynamicweb.Ecommerce.Orders.FeeProvider do this work.

https://doc.dynamicweb.com/api/html/eeeaa875-de83-a97d-af2b-30da4902dc57.htm

The main idea is that the "calcular" button reload the cart calling the  CartV2.GotoStep0 function and then the FeeProvider should be called to get the 

shipping fee based in the postal code (this information is saved into DW database as a custom item).

I implementing it but the FeeProvider is called sometimes, not always.

 

I dont know what is wrong.

Is there another way to implement a custom Fee Shipping?

 

Regards.

 

 


Replies

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply
This post has been marked as an answer

There are no other ways - you have to ensure that the shipping method that uses the provider is applied to the order when the button is pressed.

But try to show us the code and the template - i am not sure I understand the cartv2.step0 function is. The cart is form, and if you change anything in the form, post it to the page you are on, and things should trigger.

BR Nicolai

Votes for this answer: 1
 
Jose Caudevilla
Reply

Hi Nicolai:

 

Of course, here is the template form code fragment where the user puts the postal code:

 

   
                        <form name="ordersubmit" id="OrderSubmit" method="post" action="/Default.aspx?ID=2439" autocomplete="off">
                            <div class="cart-summary__info u-pull--right u-border-top dw-mod">
                                <div id="codigo_postal" style="margin-top: 15px;">
                                      @if (string.IsNullOrEmpty(GetString("CodigoPostalEnvio.Clean")))
                                      {
                                        <div class="cart-summary__info dw-mod">
                                            <p style="font-size:14px;color:#f33;">
                                                <strong>
                                                    Indica tu código postal para calcular tus gastos de envío y poder continuar con el proceso de compra:
                                                </strong>
                                            </p>
                                        </div>
                                      }
                                    <div class="cart-summary__info dw-mod">
                                        <i class="fas fa-map-pin"></i>
                                        Código postal
                                    </div>
                                    <div class="cart-summary__info u-pull--right dw-mod">
                                        <input type="text" name="CodigoPostalEnvio" maxlength="5" value='@GetString("CodigoPostalEnvio.Clean")' 
pattern='((0[1-9]|5[0-2])|[1-4][0-9])[0-9]{3}'>
                                        <!-- @GetString("CodigoPostalEnvio") -->
                                        <button type="submit" class="btn btn--primary dw-mod" name="CartV2.GotoStep0" id="CartV2.GotoStep0">Calcular</button>
                                    </div>
                                </div>
                               
                            </div>
                        </form>

 

The id of the form is the same id that dynamic use to go to the next step of the order process. Maybe this is the error.

 

Jose,

Regards.

 

 

 

 

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply
This post has been marked as an answer

Well - this will definitely not work.

You need to have the right country and shipping method in here to work correctly. And you have forgotten to show your code in the feeprovider...

Votes for this answer: 1
 
Jose Caudevilla
Reply

Thanks Nicolai and sorry , i forgot to send the feeprovider

 

Here is the code of the provider:

 

 [AddInActive(true)]
    [AddInLabel("Gastos de envio por codigo postal")]
    [AddInName("Netaservice.FeeProviderCodigoPostal")]
    public class FeeProviderCodigoPostal : Dynamicweb.Ecommerce.Orders.FeeProvider
    {
        public override Dynamicweb.Ecommerce.Prices.PriceRaw FindFee(Dynamicweb.Ecommerce.Orders.Order order)
        {
         
            Dynamicweb.Ecommerce.Prices.PriceRaw returnFee = null;
            double gastosEnvio = 0.0;
            Discount discount = new Discount();
            //comprobar si los gastos de envio son gratis
            foreach (var ol in order.OrderLines)
            {

                if (!string.IsNullOrEmpty(ol.DiscountId))
                {
                    using (var myDr = Database.CreateDataReader("SELECT * FROM EcomDiscount WHERE DiscountId="+ ol.DiscountId + ";"))
                    {
                        while (myDr.Read())
                        {
                            //si los gastos de envio son gratis poner los gastos de envio a 0
                            if(Convert.ToBoolean(myDr["DiscountAddFreeShipping"]) && Convert.ToBoolean(myDr["DiscountActive"]))
                                return new Dynamicweb.Ecommerce.Prices.PriceRaw(0.0, Dynamicweb.Ecommerce.Common.Application.DefaultCurrency);
                        }
                    }
                }
            }
            //comprobar si se ha introducido un codigo postal
            string codigoPostal = order.OrderFieldValues.GetOrderFieldValue("CodigoPostalEnvio").Value as string;
            if(!string.IsNullOrEmpty(codigoPostal))
            {
                //buscar el codigo postal en la tabla
                //añadir la linea de subida a domicilio

                bool existeCodigoPostal = false;
                bool isBaleares = false;

                //comprobar si el codigo postal existe en la tabla
                using (var myDr = Database.CreateDataReader("SELECT * FROM ItemType_Codigos_postales WHERE Codigo_postal='" + codigoPostal + "';"))
                {
                    //leer valor
                    while (myDr.Read())
                    {
                        existeCodigoPostal = true;
                        //comprobar si es baleares
                        if (!string.IsNullOrEmpty(Convert.ToString(myDr["Provincia"]))
                            && Convert.ToString(myDr["Provincia"]).Equals("Baleares"))
                            isBaleares = true;
                        break;
                    }
                }


                //si existe el codigo postal buscamos los gastos de envio de los articulos
                foreach(var orderLine in order.OrderLines)
                {
                  
                    foreach (var g in orderLine.Product.Groups)
                    {
                            bool hasGasto = false;
                            using (var myDir = Database.CreateDataReader("SELECT TOP(1) * FROM ItemType_GastosEnvioGrupo WHERE GroupId='" + g.Id + "';"))
                            {
                                while (myDir.Read())
                                {

                                    if(isBaleares)
                                    {
                                        gastosEnvio += (Convert.ToDouble(myDir["Gasto_baleares"]) * orderLine.Quantity);
                                    }
                                    else if (existeCodigoPostal)
                                    {
                                        gastosEnvio += (Convert.ToDouble(myDir["Gasto_con_cp"]) * orderLine.Quantity);
                                    }
                                    else
                                    {
                                        gastosEnvio += (Convert.ToDouble(myDir["Gasto_sin_cp"]) * orderLine.Quantity);
                                    }
                                    hasGasto = true;
                                    break;
                                }
                            }
                            //si ya se han insertado los gastos de envio se comprueba el siguiente articulo
                            if (hasGasto)
                                break;
                    }
                }
            }       
            OrderService orderService = new OrderService();
            orderService.RemoveOrderCache(order.Id);
            //aplicar gastos de envio
            returnFee = new Dynamicweb.Ecommerce.Prices.PriceRaw(gastosEnvio, Dynamicweb.Ecommerce.Common.Application.DefaultCurrency);
            return returnFee;
        }
    }

 

 

Also i modify the form to put a default country code and payment and still without work. Here is the modified form template

 <form name="ordersubmit" id="OrderSubmit" method="post" action="/Default.aspx?ID=2439" autocomplete="off">
                        <div class="cart-summary__info u-pull--right u-border-top dw-mod">
                            <div id="codigo_postal" style="margin-top: 15px;">
                                @if (string.IsNullOrEmpty(GetString("CodigoPostalEnvio.Clean")))
                                {
                                <div class="cart-summary__info dw-mod">
                                    <p style="font-size:14px;color:#f33;">
                                        <strong>
                                            Indica tu código postal para calcular tus gastos de envío y poder continuar con el proceso de compra:
                                        </strong>
                                    </p>
                                </div>
                                }
                                <div class="cart-summary__info dw-mod">
                                    <i class="fas fa-map-pin"></i>
                                    Código postal
                                </div>
                                <div class="cart-summary__info u-pull--right dw-mod">
                                    <input type="text" name="CodigoPostalEnvio" maxlength="5" value='@GetString("CodigoPostalEnvio.Clean")' pattern='((0[1-9]|5[0-2])|[1-4][0-9])[0-9]{3}'>
                                    <!-- @GetString("CodigoPostalEnvio") -->
                                    <button type="submit" class="btn btn--primary dw-mod" name="CartV2.GotoStep0" id="CartV2.GotoStep0">Calcular</button>
                                </div>
                                <!-- Campos auxiliares -->
                                <div style="display: none;">
                                    <select class="u-full-width" name="EcomOrderCustomerCountry" id="EcomOrderCustomerCountry" onchange="Cart.SubmitCart()">
                                        <option value="ES" selected="">Spain</option>
                                    </select>
                                </div>
                                <div style="display: none;">
                                    <input id="EcomCartPaymethodId_PAY11" name="EcomCartPaymethodId" type="radio" checked="true" value="PAY11" data-expand="savedCards_Contrareembolso" class="form__control  dw-mod">
                                </div>
                            </div>

                        </div>
                    </form>

 

Debuging i found that the feed is only called when on click on the minicart button... not in the purchase process

 

Jose,

Regards.

 
Jose Caudevilla
Reply

Problem solved!

 

The problem was in my DynamicWeb configuration. I had no default shipping selected in my country configuration.

Now i have select one and it works well!

Thanks for your help Nicolai.

 

Jose,

Regards.

 
Nicolai Pedersen Dynamicweb Employee
Nicolai Pedersen
Reply

Hi Jose.

Good find! And thank you for the update.

BR Nicolai

 
Jose Caudevilla
Reply

I have a issue with the country configuration.

I have a default shipping method.

Sometimes the default shipping method is select to none, im not sure if this happen when someone empty the cart in the front or my code has a bug.

When this happen my custom FeeProvider doesnt work.

 

 

Jose,

Regards.

 

You must be logged in to post in the forum