PluginProbe
SuperFrete / 2.1.6
SuperFrete v2.1.6
trunk 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 3.2.1 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4
superfrete / app / App.php

App.php in SuperFrete 2.1.6, at app/App.php

344 lines 12.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace SuperFrete;
4
5 use SuperFrete_API\Helpers\Logger;
6
7 if (!defined('ABSPATH')) {
8 exit; // Segurança para evitar acesso direto
9 }
10
11 class App
12 {
13
14 /**
15 * Construtor que inicializa o plugin
16 */
17 public function __construct()
18 {
19 $this->includes();
20 add_action('plugins_loaded', [$this, 'init_plugin']);
21 $this->register_ajax_actions();
22 add_action('woocommerce_shipping_init', function () {
23 if (class_exists('WC_Shipping_Method')) {
24 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFretePAC.php';
25 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteSEDEX.php';
26 require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteMiniEnvio.php';
27 }
28 });
29
30 add_filter('woocommerce_shipping_methods', function ($methods) {
31 if (class_exists('\SuperFrete_API\Shipping\SuperFretePAC') && class_exists('\SuperFrete_API\Shipping\SuperFreteSEDEX') && class_exists('\SuperFrete_API\Shipping\SuperFreteMiniEnvios')) {
32 $methods['superfrete_pac'] = '\SuperFrete_API\Shipping\SuperFretePAC';
33 $methods['superfrete_sedex'] = '\SuperFrete_API\Shipping\SuperFreteSEDEX';
34 $methods['superfrete_mini_envio'] = '\SuperFrete_API\Shipping\SuperFreteMiniEnvios';
35 }
36 return $methods;
37 });
38
39
40 }
41
42 /**
43 * Inclui os arquivos necessários do plugin
44 */
45 private function includes()
46 {
47 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_Settings.php';
48 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/Admin_Menu.php';
49 require_once plugin_dir_path(__FILE__) . '../api/Http/Request.php';
50 require_once plugin_dir_path(__FILE__) . '../api/Helpers/Logger.php';
51 require_once plugin_dir_path(__FILE__) . 'Controllers/ProductShipping.php';
52 require_once plugin_dir_path(__FILE__) . 'Controllers/SuperFrete_Order.php';
53 require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_OrderActions.php';
54 require_once plugin_dir_path(__FILE__) . '../app/Helpers/SuperFrete_Notice.php';
55 }
56
57 /**
58 * Inicializa o plugin e adiciona suas funcionalidades
59 */
60 public function init_plugin()
61 {
62
63 new \SuperFrete_API\Admin\SuperFrete_OrderActions();
64 new \SuperFrete_API\Admin\SuperFrete_Settings();
65 new \SuperFrete_API\Controllers\ProductShipping();
66 if (class_exists('\SuperFrete_API\Admin\Admin_Menu')) {
67 new \SuperFrete_API\Admin\Admin_Menu();
68 }
69 new \SuperFrete_API\Controllers\SuperFrete_Order();
70 \SuperFrete_API\Helpers\Logger::init();
71 add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
72 add_action('wp', function () {
73 if (!wp_next_scheduled('superfrete_clear_log_event')) {
74 wp_schedule_event(time(), 'every_five_days', 'superfrete_clear_log_event');
75 }
76 });
77 add_filter('woocommerce_package_rates', [$this, 'ordenar_metodos_frete_por_preco'], 10, 2);
78
79 // Adiciona os campos 'Número' e 'Bairro' nas configurações da loja
80 add_filter('woocommerce_general_settings', [$this, 'add_custom_store_address_fields']);
81
82 add_filter('cron_schedules', function ($schedules) {
83 $schedules['every_five_days'] = [
84 'interval' => 5 * DAY_IN_SECONDS,
85 'display' => __('A cada 5 dias')
86 ];
87 return $schedules;
88 });
89
90 if (!empty(get_option('woocommerce_store_postcode')) && (!empty(get_option('superfrete_api_token')) || (get_option('superfrete_sandbox_mode') === 'yes' && !empty(get_option('superfrete_api_token_sandbox'))))) {
91 new \SuperFrete_API\Controllers\ProductShipping();
92 } else {
93 add_action('admin_notices', [$this, 'superfrete_configs_setup_notice']);
94 }
95 add_action('superfrete_clear_log_event', function () {
96 \SuperFrete_API\Helpers\Logger::clear_log();
97 });
98 add_action('init', function () {
99 if (!class_exists('\WC_Shipping_Zones')) return;
100
101 $zone_name = 'Brasil - SuperFrete';
102 $existing_zones = \WC_Shipping_Zones::get_zones();
103
104 foreach ($existing_zones as $zone) {
105 if ($zone['zone_name'] === $zone_name) return;
106 }
107
108 $zone = new \WC_Shipping_Zone();
109 $zone->set_zone_name($zone_name);
110 $zone->save();
111
112 $zone_id = $zone->get_id();
113 $locations = [
114 ['code' => 'BR', 'type' => 'country'],
115 ];
116
117 global $wpdb;
118 foreach ($locations as $location) {
119 $wpdb->insert("{$wpdb->prefix}woocommerce_zone_locations", [
120 'zone_id' => $zone_id,
121 'location_code' => $location['code'],
122 'location_type' => $location['type'],
123 ]);
124 }
125 // Adiciona os métodos: Mini Envios, PAC e SEDEX
126 $methods_to_add = [
127 'superfrete_mini_envio',
128 'superfrete_pac',
129 'superfrete_sedex',
130 ];
131
132 foreach ($methods_to_add as $method_id) {
133 $zone->add_shipping_method($method_id);
134 }
135
136 // Ativa os métodos
137 $methods = $zone->get_shipping_methods(true);
138 foreach ($methods as $method) {
139 if (in_array($method->id, $methods_to_add)) {
140 $method->enabled = 'yes';
141 $method->save();
142 }
143 }
144
145 error_log('�
146 Zona de entrega "Brasil - SuperFrete" criada com o método ativado.');
147 });
148 }
149
150 public function ordenar_metodos_frete_por_preco($rates, $package)
151 {
152 if (empty($rates))
153 return $rates;
154
155 // Reordena os métodos de frete pelo valor (crescente)
156 uasort($rates, function ($a, $b) {
157 return $a->cost <=> $b->cost;
158 });
159
160 return $rates;
161 }
162
163
164 function add_custom_store_address_fields($settings)
165 {
166 $new_settings = [];
167
168 foreach ($settings as $setting) {
169 $new_settings[] = $setting;
170
171 // Após o campo de endereço 1
172 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_address') {
173 $new_settings[] = [
174 'title' => 'Número',
175 'desc_tip' => 'Número do endereço da loja',
176 'id' => 'woocommerce_store_number',
177 'type' => 'text',
178 'css' => 'min-width:300px;',
179 'default' => '',
180 'autoload' => false,
181 ];
182 }
183
184 // Após o campo de cidade
185 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_city') {
186 $new_settings[] = [
187 'title' => 'Bairro',
188 'desc_tip' => 'Bairro da loja',
189 'id' => 'woocommerce_store_neighborhood',
190 'type' => 'text',
191 'css' => 'min-width:300px;',
192 'default' => '',
193 'autoload' => false,
194 ];
195 }
196 }
197
198 return $new_settings;
199 }
200
201
202 public function superfrete_configs_setup_notice()
203 {
204 ?>
205 <div class="error notice">
206 <p><b>SuperFrete</b></p>
207 <p>
208 Para utilizar o plugin você deve
209 <a
210 href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description')); ?>">
211 configurar seu acesso a SuperFrete
212 </a>
213 e configurar um
214 <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings')); ?>">
215 endereço
216 </a>.
217 </p>
218 </div>
219 <?php
220 }
221
222 /**
223 * Adiciona um link para as configurações na página de plugins.
224 */
225 public static function superfrete_add_settings_link($links)
226 {
227 $settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description') . '">Configurações</a>';
228 array_unshift($links, $settings_link);
229 return $links;
230 }
231
232 // Criar a função que limpa os logs
233
234
235
236 static function singleShippingCountry()
237 {
238 if (!function_exists('WC') || !is_object(WC()->countries))
239 return false;
240
241 $countries = WC()->countries->get_shipping_countries();
242
243 if (count($countries) == 1) {
244 foreach (WC()->countries->get_shipping_countries() as $key => $value) {
245 return $key;
246 }
247 }
248
249 return false;
250 }
251
252 public function enqueue_assets()
253 {
254
255 wp_localize_script(
256 'jquery',
257 'superfrete_setting',
258 array(
259 'wc_ajax_url' => \WC_AJAX::get_endpoint('%%endpoint%%'),
260 'ajaxUrl' => admin_url('admin-ajax.php'),
261 'loading' => 'Loading..',
262 'auto_select_country' => apply_filters('pisol_ppscw_auto_select_country', self::singleShippingCountry()),
263 'load_location_by_ajax' => 1
264 )
265 );
266
267 wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0');
268
269 wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0');
270 wp_enqueue_script(
271 'superfrete-popup',
272 plugin_dir_url(__FILE__) . '../assets/scripts/superfrete-popup.js',
273 ['jquery'],
274 '1.0.0', // Versão do script
275 true
276 );
277 wp_localize_script('superfrete-popup', 'superfrete_ajax', [
278 'ajax_url' => admin_url('admin-ajax.php'),
279 ]);
280 }
281
282 public function register_ajax_actions()
283 {
284 add_action('wp_ajax_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
285 add_action('wp_ajax_nopriv_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
286 }
287
288 // Criar a função que limpa os logs
289
290
291 public function handle_superfrete_update_address()
292 {
293 // Verifica o nonce
294 if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'superfrete_update_address_nonce')) {
295 wp_send_json_error(['message' => 'Requisição inválida.'], 403);
296 }
297
298 if (!session_id()) {
299 session_start();
300 }
301
302 if (!isset($_POST['order_id'])) {
303 wp_send_json_error(['message' => 'ID do pedido ausente.'], 400);
304 }
305
306 $order_id = intval($_POST['order_id']);
307 $order = wc_get_order($order_id);
308
309 if (!$order) {
310 wp_send_json_error(['message' => 'Pedido não encontrado.'], 404);
311 }
312
313 $current_shipping = $order->get_address('shipping');
314
315 $updated_data = [
316 'first_name' => sanitize_text_field($_POST['name']),
317 'address_1' => sanitize_text_field($_POST['address']),
318 'address_2' => sanitize_text_field($_POST['complement']),
319 'number' => sanitize_text_field($_POST['number']),
320 'neighborhood' => sanitize_text_field($_POST['district']),
321 'city' => sanitize_text_field($_POST['city']),
322 'state' => sanitize_text_field($_POST['state_abbr']),
323 'postcode' => sanitize_text_field($_POST['postal_code'])
324 ];
325 if (!empty($updated_data['number'])) {
326 $order->update_meta_data('_shipping_number', $updated_data['number']);
327 }
328 if (!empty($updated_data['neighborhood'])) {
329 $order->update_meta_data('_shipping_neighborhood', $updated_data['neighborhood']);
330 }
331
332 foreach ($updated_data as $key => $value) {
333 if (empty($current_shipping[$key]) && !empty($value)) {
334 $current_shipping[$key] = $value;
335 }
336 }
337 $order->set_address($current_shipping, 'shipping');
338 $order->save();
339 $_SESSION['superfrete_correction'][$order_id] = $current_shipping;
340
341 wp_send_json_success(['message' => 'Campos vazios preenchidos e endereço atualizado!', 'order_id' => $order_id]);
342 }
343 }
344