Módulos de transportistas - funciones, creación y configuración

Este artículo fue escrito por Fabien Serny y publicado el 28 de septiembre de 2011 en el blog PrestaShop.

Prefacio

Tenga en cuenta que este artículo está dirigido a desarrolladores avanzados (el conocimiento de los hook, el objeto Transportista ...) y se aplica a PrestaShop 1.4 y versiones posteriores.
Para saber lo que es un hook, le recomiendo leer el artículo de Julien Breux aquí: Comprensión y uso de hooks

En un nivel básico PrestaShop le permite crear transportistas y configurar la manera como los gastos de envío son calculados basados en rangos de peso y precio que puede especificar en el back office.

Los límites de este sistema se alcanzan cuando desea recuperar precios a través de servicios web (UPS, USPS, Fedex) o si desea crear su propio sistema para el cálculo de gastos de envío (por número de artículos en la cesta, restringiendose de un transportista o de uno o más países, etc.).

Aquí es cuando los módulos de transportista entran en juego.

¿Por dónde empiezo?

Hay un módulo básico que se puede descargar aquí. El artículo comenzará a partir de este módulo básico, pero por supuesto usted puede modificarlo y adaptarlo a sus necesidades

En nuestro ejemplo, usted puede manejar dos transportistas y establecer un costo adicional para ellos, además del precio por rango configurado en el back office.

Algunas partes del código se duplican deliberadamente para ayudarle a entender el mecanismo. Depende de usted manejar su lista específica de transportistas (utilizando un cuadro de datos, por ejemplo).

Explicación del ejemplo

En primer lugar, tenga en cuenta el hecho de que el módulo pertenece a la clase CarrierModule y no la clase Module. Por ahora, vamos a hacer una breve lista de los métodos contenidos en este módulo y la forma en que funciona en general.

1) Los métodos __construct, install y uninstall

Construct:

// The carrier id is automatically filled in with the right id for the carrier.
// We will look at the purpose of this a little later.
public  $id_carrier;

private $_html = '';
private $_postErrors = array();
private $_moduleName = 'mycarrier';
/*
** Construct Method
**
*/
public function __construct()
{
       // Variables common to all modules (no need to present them)
    $this->name = 'mycarrier';
    $this->tab = 'shipping_logistics';
    $this->version = '1.0';
    $this->author = 'YourName';
    $this->limited_countries = array('fr', 'us');
    parent::__construct ();
    $this->displayName = $this->l('My Carrier');
    $this->description = $this->l('Delivery methods that you want');
        // If the module is installed, we run a few checks
    if (self::isInstalled($this->name))
    {
        // We retrieve the list of carrier ids
        global $cookie;
        $carriers = Carrier::getCarriers($cookie->id_lang, true, false, false,
                NULL, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
        $id_carrier_list = array();
        foreach($carriers as $carrier)
            $id_carrier_list[] .= $carrier['id_carrier'];




        // We look to see if the carriers have been created for the module
        // And if any additional fees have been configured
        // These warnings will appear on the page where the modules are listed
        $warning = array();
        if (!in_array((int)(Configuration::get('MYCARRIER1_CARRIER_ID')),
                   $id_carrier_list)) $warning[] .= $this->l('"Carrier 1"').' ';
        if (!in_array((int)(Configuration::get('MYCARRIER2_CARRIER_ID')),
               $id_carrier_list)) $warning[] .= $this->l('"Carrier 2 Overcost"').' ';
        if (!Configuration::get('MYCARRIER1_OVERCOST'))
            $warning[] .= $this->l('"Carrier 1 Overcost"').' ';
        if (!Configuration::get('MYCARRIER2_OVERCOST'))
            $warning[] .= $this->l('"Carrier 2 Overcost"').' ';
        if (count($warning))
    $this->warning .= implode(' , ',$warning).$this->l('must be <br />configured');
    }
}

Install:

/*
** Install / Uninstall Methods
**
*/
public function install()
{
    // We create a table containing information on the two carriers
   // that we want to create

    $carrierConfig = array(
    0 => array('name' => 'Carrier1',
      'id_tax_rules_group' => 0, // We do not apply thecarriers tax
      'active' => true, 'deleted' => 0,
      'shipping_handling' => false,
      'range_behavior' => 0,
      'delay' => array(
        'fr' => 'Description 1',
        'en' => 'Description 1',
        Language::getIsoById(Configuration::get
                ('PS_LANG_DEFAULT')) => 'Description 1'),
      'id_zone' => 1, // Area where the carrier operates
      'is_module' => true, // We specify that it is a module
      'shipping_external' => true,
      'external_module_name' => 'mycarrier', // We specify the name of the module
      'need_range' => true // We specify that we want the calculations for the ranges
    // that are configured in the back office
      ),
     1 => array('name' => 'Carrier2',
      'id_tax_rules_group' => 0,
      'active' => true,
      'deleted' => 0,
      'shipping_handling' => false,
      'range_behavior' => 0,
      'delay' => array(
        'fr' => 'Description 1',
        'en' => 'Description 1',
        Language::getIsoById(Configuration::get<br />
               ('PS_LANG_DEFAULT')) => 'Description 1'),
      'id_zone' => 1,
      'is_module' => true,
      'shipping_external' => true,
      'external_module_name' => 'mycarrier',
      'need_range' => true
    ),
);
    // We create the two carriers and retrieve the carrier ids
    // And save the ids in a database
    // Feel free to take a look at the code to see how installExternalCarrier works
    // However you should not normally need to modify this function

    $id_carrier1 = $this->installExternalCarrier($carrierConfig[0]);
    $id_carrier2 = $this->installExternalCarrier($carrierConfig[1]);
    Configuration::updateValue('MYCARRIER1_CARRIER_ID', (int)$id_carrier1);
    Configuration::updateValue('MYCARRIER2_CARRIER_ID', (int)$id_carrier2);
    // Then proceed with a standard module install
    // Later we will take a look at the purpose of theupdatecarrier hook

    if (!parent::install() ||
        !Configuration::updateValue('MYCARRIER1_OVERCOST', '') ||
        !Configuration::updateValue('MYCARRIER2_OVERCOST', '') ||
        !$this->registerHook('updateCarrier'))
        return false;

    return true;
}

Uninstall:

public function uninstall()
{
    // We first carry out a classic uninstall of a module
    if (!parent::uninstall() ||
        !Configuration::deleteByName('MYCARRIER1_OVERCOST') ||
        !Configuration::deleteByName('MYCARRIER2_OVERCOST') ||
        !$this->unregisterHook('updateCarrier'))
        return false;
    // We delete the carriers we created earlier
    $Carrier1 = new Carrier((int)(Configuration::get('MYCARRIER1_CARRIER_ID')));
    $Carrier2 = new Carrier((int)(Configuration::get('MYCARRIER2_CARRIER_ID')));
// If one of the two modules was the default carrier,
//we choose another
    if (Configuration::get('PS_CARRIER_DEFAULT') == (int)($Carrier1->id) ||
        Configuration::get('PS_CARRIER_DEFAULT') == (int)($Carrier2->id))
    {
        global $cookie;
        $carriersD = Carrier::getCarriers($cookie->id_lang, true, false, false, <br />
                NULL, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
        foreach($carriersD as $carrierD)
            if ($carrierD['active'] AND !$carrierD['deleted']
                AND ($carrierD['name'] != $this->_config['name']))
                Configuration::updateValue('PS_CARRIER_DEFAULT',<br />
                                $carrierD['id_carrier']);
    }
    // Then we delete the carriers using variable delete
    // in order to keep the carrier history for orders placed with them

    $Carrier1->deleted = 1;
    $Carrier2->deleted = 1;
    if (!$Carrier1->update() || !$Carrier2->update())
        return false;

    return true;
}

2) Métodos del Back Office

No voy a concentrarme en la mayoría de los métodos de back office (getContent, _displayForm, _postValidation and _postProcess), ya que son relativamente simples y se encuentran ahí para que pueda establecer los costos del transportista. Le dejaré descubrirlos en el módulo de ejemplo.

Sin embargo, me gustaría concentrarme en el método hookupdateCarrier. En PrestaShop, cada vez que edita un transportista, el transportista se archiva automáticamente y uno nuevo es creado.

Técnicamente, PrestaShop cambia la bandera de eliminado del transportista a 1 y crear uno nuevo.

Por eso, cuando edita un transportista a través de la pestaña "Transportista" en su back office, su id cambia.

Por lo tanto, debe conectar con un hook el módulo con el fin de actualizar el Id del transportista cuando este cambia.

/*
** Hook update carrier
**
*/
public function hookupdateCarrier($params)
{
    // Update the id for carrier 1
    if ((int)($params['id_carrier']) == (int)(Configuration::get<br />('MYCARRIER1_CARRIER_ID')))
        Configuration::updateValue('MYCARRIER1_CARRIER_ID', (int)<br />
                ($params['carrier']->id));
    // Update the id for carrier 2
    if ((int)($params['id_carrier']) == (int)(Configuration::get<br />('MYCARRIER2_CARRIER_ID')))
        Configuration::updateValue('MYCARRIER2_CARRIER_ID', (int)<br />
               ($params['carrier']->id));
}

3) Métodos de front office

/*
** Front Methods
**
** If you set the variable need_range to true when you created your carrier
** in the install() method, the method called up by the Cart class
** will be getOrderShippingCost()
** Otherwise the method called up will be getOrderShippingCostExternal
**
** The $params variable contains the basket, the customer and their addresses
** The $shipping_cost variable contains the cost calculated
** according to the price ranges set
** for the carrier in the backoffice
**
*/

public function getOrderShippingCost($params, $shipping_cost)
{
    // This example returns the shipping fee with the additional cost
    // but you can call up a webservice or perform the calculation you want
    // before returning the final shipping fee

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER1_CARRIER_ID')) &&
        Configuration::get('MYCARRIER1_OVERCOST') > 1)
        return (float)(Configuration::get('MYCARRIER1_OVERCOST'));

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER2_CARRIER_ID')) &&
        Configuration::get('MYCARRIER2_OVERCOST') > 1)
        return (float)(Configuration::get('MYCARRIER2_OVERCOST'));
    // If the carrier is not recognised, just return false
    // and the carrier will not appear in the carrier list

    return false;
}
public function getOrderShippingCostExternal($params)
{
    // This example returns the additional cost
    // but you can call up a webservice or perform the calculation you want
    // before returning the final shipping fee

    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER1_CARRIER_ID')) &&
        Configuration::get('MYCARRIER1_OVERCOST') > 1)
                return (float)(Configuration::get('MYCARRIER1_OVERCOST'));
    if ($this->id_carrier == (int)(Configuration::get('MYCARRIER2_CARRIER_ID')) &&
            Configuration::get('MYCARRIER2_OVERCOST') > 1)
                return (float)(Configuration::get('MYCARRIER2_OVERCOST'));
    / If the carrier is not recognised, just return false
    // and the carrier will not appear in the carrier list

    return false;
}

Medidas adicionales

El ejemplo es muy sencillo, pero puede crear módulos más complejos mediante la asociación con servicios web, por ejemplo (como es el caso de los módulos UPS) o realizar un cálculo basado en el número de productos en su carrito.

En resumen, ahora ya domina el cálculo de gastos de envío