Code

< 40 %
40-60 %
> 60 %
1
2
<?php
3
4
/** MODULO ADAPTADO POR ODLANIER
5
 * @author Odlanier de Souza Mendes
6
 * @copyright Dlani
7
 * @email [email protected]
8
 * @version 3.0
9
 * */
10
if (!defined('_PS_VERSION_'))
11
    exit;
12
13
class correios extends CarrierModule {
14
15
    public $id_carrier;
16
    private $_urlWebservice = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?wsdl";
17
    private $_html = '';
18
    private $_postErrors = array();
19
    private $_factorys = array(
20
        "soapclient" => "SOAP Client",
21
        "nusoap" => "NuSoap"
22
    );
23
    private $_factory = "soapclient";
24
    public $servicos_todos = array(
25
        '04510' => 'PAC',# era '41106' => 'PAC',
26
        '04014' => 'SEDEX', # era '40010' => 'SEDEX',
27
        '40215' => 'SEDEX 10',
28
        '40290' => 'SEDEX HOJE',
29
            //'81019' => 'E-SEDEX', 
30
            //'44105' => 'MALOTE',
31
            //'41017' => 'NORMAL', 
32
            //'40045' => 'SEDEX A COBRAR', 
33
    );
34
    private $_moduleName = 'correios';
35
36 6
    function __construct() {
37 6
        $this->name = 'correios';
38 6
        $this->tab = 'shipping_logistics';
39 6
        $this->version = '3.0';
40 6
        $this->author = 'Dlani Mendes';
41 6
        $this->limited_countries = array('br');
42
43 6
        parent::__construct();
44
45
        /* The parent construct is required for translations */
46 6
        $this->page = basename(__file__, '.php');
47 6
        $this->displayName = $this->l('Frete Correios');
48 6
        $this->description = 'Painel de Controle dos Frete Correios.';
49 6
    }
50
51
    function install() {
52
        if (parent::install() == false or
53
                $this->registerHook('updateCarrier') == false or
54
                $this->registerHook('extraCarrier') == false or
55
                $this->registerHook('beforeCarrier') == false)
56
            return false;
57
58
        $this->installCarriers();
59
60
        return true;
61
    }
62
63
    /**
64
     * 
65
     */
66
    private function installCarriers() {
67
        $configBase = array(
68
            'id_tax_rules_group' => 0,
69
            'active' => true,
70
            'deleted' => 0,
71
            'shipping_handling' => false,
72
            'range_behavior' => 0,
73
            'delay' => array("br" => "Entrega pelos Correios."),
74
            'id_zone' => 1,
75
            'is_module' => true,
76
            'shipping_external' => true,
77
            'external_module_name' => $this->_moduleName,
78
            'need_range' => true,
79
            'url' => Tools::getHttpHost(true) . "/modules/correios/rastreio.php?objeto=@",
80
        );
81
82
        $arrayConfigs = array();
83
        foreach ($this->servicos_todos as $codServico => $servico)
84
            $arrayConfigs[] = array(
85
                "name" => "Correios - $servico",
86
                "cod_servico" => $codServico
87
            );
88
89
        foreach ($arrayConfigs as $config) {
90
            $config = array_merge($configBase, $config);
91
            $this->installExternalCarrier($config);
92
        }
93
    }
94
95
    /**
96
     * 
97
     * @param type $config
98
     * @return boolean
99
     */
100
    public function installExternalCarrier($config) {
101
        $check = Db::getInstance()->executeS("SELECT id_carrier FROM " . _DB_PREFIX_ . "carrier WHERE name = '" . $config['name'] . "' ");
102
        if (is_array($check) && !empty($check))
103
            return Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier', array('deleted' => 0), 'UPDATE', ' name = "' . $config['name'] . '" ');
104
105
        $carrier = new Carrier();
106
        $carrier->name = $config['name'];
107
        $carrier->url = $config['url'];
108
        $carrier->id_tax_rules_group = $config['id_tax_rules_group'];
109
        $carrier->id_zone = $config['id_zone'];
110
        $carrier->active = $config['active'];
111
        $carrier->deleted = $config['deleted'];
112
        $carrier->delay = $config['delay'];
113
        $carrier->shipping_handling = $config['shipping_handling'];
114
        $carrier->range_behavior = $config['range_behavior'];
115
        $carrier->is_module = $config['is_module'];
116
        $carrier->shipping_external = $config['shipping_external'];
117
        $carrier->external_module_name = $config['external_module_name'];
118
        $carrier->need_range = $config['need_range'];
119
120
        $languages = Language::getLanguages(true);
121
        foreach ($languages as $language) {
122
            $carrier->delay[(int) $language['id_lang']] = $config['delay']['br'];
123
        }
124
125
        if ($carrier->add()) {
126
            $groups = Group::getGroups(true);
127
            foreach ($groups as $group)
128
                Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_group', array('id_carrier' => (int) ($carrier->id), 'id_group' => (int) ($group['id_group'])), 'INSERT');
129
130
            $rangePrice = new RangePrice();
131
            $rangePrice->id_carrier = $carrier->id;
132
            $rangePrice->delimiter1 = '0';
133
            $rangePrice->delimiter2 = '0';
134
            $rangePrice->add();
135
136
            $rangeWeight = new RangeWeight();
137
            $rangeWeight->id_carrier = $carrier->id;
138
            $rangeWeight->delimiter1 = '0';
139
            $rangeWeight->delimiter2 = '30';
140
            $rangeWeight->add();
141
142
            $zones = Zone::getZones(true);
143
            foreach ($zones as $zone) {
144
                Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier_zone', array('id_carrier' => (int) ($carrier->id), 'id_zone' => (int) ($zone['id_zone'])), 'INSERT');
145
                Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery', array('id_carrier' => (int) ($carrier->id), 'id_range_price' => (int) ($rangePrice->id), 'id_range_weight' => NULL, 'id_zone' => (int) ($zone['id_zone']), 'price' => '0'), 'INSERT');
146
                Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_ . 'delivery', array('id_carrier' => (int) ($carrier->id), 'id_range_price' => NULL, 'id_range_weight' => (int) ($rangeWeight->id), 'id_zone' => (int) ($zone['id_zone']), 'price' => '0'), 'INSERT');
147
            }
148
149
            Configuration::updateValue("PS_CORREIOS_CARRIER_{$carrier->id}", $config['cod_servico']);
150
151
            // Copy Logo
152
            if (!copy(dirname(__FILE__) . '/logos/' . $config['cod_servico'] . '.png', _PS_SHIP_IMG_DIR_ . '/' . (int) $carrier->id . '.jpg'))
153
                return false;
154
155
            // Return ID Carrier
156
            return (int) ($carrier->id);
157
        }
158
        return false;
159
    }
160
161
    /**
162
     * 
163
     * @return boolean
164
     */
165
    public function uninstall() {
166
        // Uninstall Carriers
167
        $result = Db::getInstance()->autoExecute(_DB_PREFIX_ . 'carrier', array('deleted' => 1), 'UPDATE', ' name LIKE "Correios%" ');
168
169
        if (!Configuration::deleteByName('PS_CORREIOS_CEP_ORIG'))
170
            return false;
171
172
        if (!parent::uninstall() OR !$this->unregisterHook('updateCarrier'))
173
            return false;
174
175
        return true;
176
    }
177
178
    /**
179
     * 
180
     * @return type
181
     */
182 1
    public function getContent() {
183 1
        $output = '<h2>' . $this->displayName . '</h2>';
184 1
        if (Tools::isSubmit('submitcarrinho_correios')) {
185
            Configuration::updateValue('PS_CORREIOS_CEP_ORIG', intval($_POST['cep']));
186
187
            $output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="' . $this->
188
                            l('Confirmation') . '" />' . $this->l('Settings updated') . '</div>';
189
        }
190 1
        if (Tools::isSubmit('factory')) {
191
            Configuration::updateValue('PS_CORREIOS_FACTORY', $_POST['factory']);
192
193
            $output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="' . $this->
194
                            l('Confirmation') . '" />' . $this->l('Settings updated') . '</div>';
195
        }
196
197 1
        return $output . $this->displayForm();
198
    }
199
200
    /**
201
     * 
202
     * @return type
203
     */
204 1
    public function displayForm() {
205 1
        $conf = Configuration::getMultiple(array('PS_CORREIOS_CEP_ORIG'));
206 1
        $cep_orig = array_key_exists('cep', $_POST) ? $_POST['cep'] : (array_key_exists('PS_CORREIOS_CEP_ORIG', $conf) ? $conf['PS_CORREIOS_CEP_ORIG'] : '');
207 1
        include (dirname(__file__) . "/form_config.php");
208 1
        return $form_config;
209
    }
210
211
    /**
212
     * 
213
     * @param type $params
214
     * @param type $shipping_cost
215
     * @return boolean
216
     */
217 4
    public function getOrderShippingCost($params, $shipping_cost) {
218 4
        $carrier = new Carrier();
219 4
        $chave = Configuration::get("PS_CORREIOS_CARRIER_{$this->id_carrier}");
220 4
        $address = new Address($params->id_address_delivery);
221
222 4
        $sCepDestino = preg_replace("/([^0-9])/", "", $address->postcode);
223
224
        $paramsCorreios = array(
225 4
            "sCepDestino" => $sCepDestino,
226 4
            "nVlPeso" => (string) $params->getTotalWeight(),
227 4
            "nCdServico" => $chave,
228
        );
229
230 4
        $this->getPriceWebService($paramsCorreios);
231 4
        $custoFrete = $this->getPriceWebService($paramsCorreios);
232
233 4
        if ($custoFrete === false || $custoFrete === 0.0)
234
            return false;
235
236 4
        return $custoFrete + $shipping_cost;
237
    }
238
239
    /**
240
     * 
241
     * @param type $params
242
     * @return type
243
     */
244
    public function getOrderShippingCostExternal($params) {
245
        return $this->getOrderShippingCost($params, 0);
246
    }
247
248
    /**
249
     * 
250
     * @param type $params
251
     */
252
    public function hookupdateCarrier($params) {
253
        
254
    }
255
256
    /**
257
     * 
258
     * @global type $smarty
259
     * @param type $params
260
     * @return type
261
     */
262
    public function hookbeforeCarrier($params) {
263
        global $smarty;
264
        $address = new Address($params['cart']->id_address_delivery);
265
        $smarty->assign(array(
266
            "sCepDestino" => $address->postcode
267
        ));
268
        return $this->display(__file__, 'extra_carrier.tpl');
269
    }
270
271
    /**
272
     * 
273
     * @param type $params
274
     */
275
    public function hookextraCarrier($params) {
276
        
277
    }
278
279
    /**
280
     * 
281
     * @param type $params
282
     * @return type
283
     */
284 4
    private function getPriceWebService($params) {
285
        $paramsBase = array(
286 4
            "nCdEmpresa" => "",
287 4
            "sDsSenha" => "",
288 4
            "sCepOrigem" => str_pad(Configuration::get('PS_CORREIOS_CEP_ORIG'), 8, "0", STR_PAD_LEFT),
289 4
            "nCdFormato" => "1",
290 4
            "nVlComprimento" => "30",
291 4
            "nVlAltura" => "8",
292 4
            "nVlLargura" => "30",
293 4
            "nVlDiametro" => "0",
294 4
            "sCdMaoPropria" => "N",
295 4
            "nVlValorDeclarado" => "0",
296 4
            "sCdAvisoRecebimento" => "N"
297
        );
298 4
        $params = array_merge($paramsBase, $params);
299 4
        $hash = ( implode("|", $params) );
300 4
        $getInCache = $this->getCache($hash);
301
302 4
        if ($getInCache) {
303
            $return = $getInCache;
304
        } else {
305 4
            $this->_factory = Configuration::get("PS_CORREIOS_FACTORY");
306 4
            $method = "getPreco" . ucfirst(strtolower($this->_factory));
307
            
308 4
            $return = $this->$method($params, $hash);
309 4
            $this->setCache($hash, $return);
310
        }
311 4
        return $return;
312
    }
313
314
    /**
315
     * 
316
     * @global type $smarty
317
     * @param type $idCarrier
318
     * @param type $sCepDestino
319
     * @return type
320
     */
321
    public function getPrazoDeEntrega($idCarrier, $sCepDestino) {
322
        global $smarty;
323
        $Carrier = new Carrier($idCarrier);
324
325
        $params = array(
326
            "sCepOrigem" => str_pad(Configuration::get('PS_CORREIOS_CEP_ORIG'), 8, "0", STR_PAD_LEFT),
327
            "nCdServico" => Configuration::get("PS_CORREIOS_CARRIER_{$idCarrier}"),
328
            "sCepDestino" => $sCepDestino,
329
        );
330
331
        $this->_factory = Configuration::get("PS_CORREIOS_FACTORY");
332
        $method = "getPrazo" . ucfirst(strtolower($this->_factory));
333
        $dias = $this->$method($params);
334
335
        $smarty->assign(array(
336
            "nomeServico" => $Carrier->name,
337
            "dias" => $dias
338
        ));
339
340
        return $this->display(__file__, 'prazo_de_entrega.tpl');
341
    }
342
343
    private function getPrazoSoapclient($params) {
344
        try {
345
            $client = new SoapClient($this->_urlWebservice);
346
            $result = $client->CalcPrazo($params);
347
            if (intval($result->CalcPrazoResult->Servicos->cServico->Erro) !== 0)
348
                return false;
349
            else
350
                return (integer) $result->CalcPrazoResult->Servicos->cServico->PrazoEntrega;
351
        } catch (Exception $e) {
352
            return false;
353
        }
354
    }
355
356
    private function getPrazoNusoap($params) {
357
        require_once('vendor/lib/nusoap.php');
358
        $nusoap = new nusoap_client($this->_urlWebservice, 'wsdl');
359
        $nusoap->setUseCURL(true);
360
        $result = $nusoap->call("CalcPrazo", $params);
361
        if (intval($result['CalcPrazoResult']['Servicos']['cServico']['Erro']) !== 0) {
362
            return false;
363
        } else {
364
            return (integer) str_replace(",", ".", $result['CalcPrazoResult']['Servicos']['cServico']['PrazoEntrega']);
365
        }
366
    }
367
368
    /**
369
     * 
370
     * @param type $name
371
     * @param type $value
372
     */
373 4
    private function setCache($name, $value) {
374 4
        if (_PS_CACHE_ENABLED_)
375
            Cache::getInstance()->setQuery($name, $value);
376 4
    }
377
378
    /**
379
     * 
380
     * @param type $name
381
     * @return boolean
382
     */
383 4
    private function getCache($name) {
384 4
        if (_PS_CACHE_ENABLED_)
385
            return Cache::getInstance()->get(md5($name));
386 4
        return false;
387
    }
388
389
    /**
390
     * 
391
     * @param type $params
392
     * @param type $hash
393
     * @return boolean
394
     */
395 4
    private function getPrecoSoapclient($params, $hash) {
396
        try {
397 4
            $client = new SoapClient($this->_urlWebservice);
398
        } catch (Exception $e) {
399
            return false;
400
        }
401 4
        $result = $client->CalcPreco($params);
402
        # var_dump ($result);
403 4
        if (intval($result->CalcPrecoResult->Servicos->cServico->Erro) !== 0) {
404
            $this->setCache($hash, false);
405
            return false;
406
        } else {
407 4
            return (float) str_replace(",", ".", $result->CalcPrecoResult->Servicos->cServico->Valor);
408
        }
409
    }
410
411
    /**
412
     * 
413
     * @param type $params
414
     * @param type $hash
415
     * @return boolean
416
     */
417
    private function getPrecoNusoap($params, $hash) {
418
        require_once('vendor/lib/nusoap.php');
419
        $nusoap = new nusoap_client($this->_urlWebservice, 'wsdl');
420
        $nusoap->setUseCURL(true);
421
        $result = $nusoap->call("CalcPreco", $params);
422
        if (intval($result['CalcPrecoResult']['Servicos']['cServico']['Erro']) !== 0) {
423
            $this->setCache($hash, false);
424
            return false;
425
        } else {
426
            return (float) str_replace(",", ".", $result['CalcPrecoResult']['Servicos']['cServico']['Valor']);
427
        }
428
    }
429
430
}
431
432
?>