PluginProbe
SuperFrete / 2.1.5
SuperFrete v2.1.5
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.5, at app/App.php

294 lines 10.9 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 }
99
100 public function ordenar_metodos_frete_por_preco($rates, $package)
101 {
102 if (empty($rates))
103 return $rates;
104
105 // Reordena os métodos de frete pelo valor (crescente)
106 uasort($rates, function ($a, $b) {
107 return $a->cost <=> $b->cost;
108 });
109
110 return $rates;
111 }
112
113
114 function add_custom_store_address_fields($settings)
115 {
116 $new_settings = [];
117
118 foreach ($settings as $setting) {
119 $new_settings[] = $setting;
120
121 // Após o campo de endereço 1
122 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_address') {
123 $new_settings[] = [
124 'title' => 'Número',
125 'desc_tip' => 'Número do endereço da loja',
126 'id' => 'woocommerce_store_number',
127 'type' => 'text',
128 'css' => 'min-width:300px;',
129 'default' => '',
130 'autoload' => false,
131 ];
132 }
133
134 // Após o campo de cidade
135 if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_city') {
136 $new_settings[] = [
137 'title' => 'Bairro',
138 'desc_tip' => 'Bairro da loja',
139 'id' => 'woocommerce_store_neighborhood',
140 'type' => 'text',
141 'css' => 'min-width:300px;',
142 'default' => '',
143 'autoload' => false,
144 ];
145 }
146 }
147
148 return $new_settings;
149 }
150
151
152 public function superfrete_configs_setup_notice()
153 {
154 ?>
155 <div class="error notice">
156 <p><b>SuperFrete</b></p>
157 <p>
158 Para utilizar o plugin você deve
159 <a
160 href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description')); ?>">
161 configurar seu acesso a SuperFrete
162 </a>
163 e configurar um
164 <a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings')); ?>">
165 endereço
166 </a>.
167 </p>
168 </div>
169 <?php
170 }
171
172 /**
173 * Adiciona um link para as configurações na página de plugins.
174 */
175 public static function superfrete_add_settings_link($links)
176 {
177 $settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=shipping&section=options#superfrete_settings_section-description') . '">Configurações</a>';
178 array_unshift($links, $settings_link);
179 return $links;
180 }
181
182 // Criar a função que limpa os logs
183
184
185
186 static function singleShippingCountry()
187 {
188 if (!function_exists('WC') || !is_object(WC()->countries))
189 return false;
190
191 $countries = WC()->countries->get_shipping_countries();
192
193 if (count($countries) == 1) {
194 foreach (WC()->countries->get_shipping_countries() as $key => $value) {
195 return $key;
196 }
197 }
198
199 return false;
200 }
201
202 public function enqueue_assets()
203 {
204
205 wp_localize_script(
206 'jquery',
207 'superfrete_setting',
208 array(
209 'wc_ajax_url' => \WC_AJAX::get_endpoint('%%endpoint%%'),
210 'ajaxUrl' => admin_url('admin-ajax.php'),
211 'loading' => 'Loading..',
212 'auto_select_country' => apply_filters('pisol_ppscw_auto_select_country', self::singleShippingCountry()),
213 'load_location_by_ajax' => 1
214 )
215 );
216
217 wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0');
218
219 wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0');
220 wp_enqueue_script(
221 'superfrete-popup',
222 plugin_dir_url(__FILE__) . '../assets/scripts/superfrete-popup.js',
223 ['jquery'],
224 '1.0.0', // Versão do script
225 true
226 );
227 wp_localize_script('superfrete-popup', 'superfrete_ajax', [
228 'ajax_url' => admin_url('admin-ajax.php'),
229 ]);
230 }
231
232 public function register_ajax_actions()
233 {
234 add_action('wp_ajax_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
235 add_action('wp_ajax_nopriv_superfrete_update_address', [$this, 'handle_superfrete_update_address']);
236 }
237
238 // Criar a função que limpa os logs
239
240
241 public function handle_superfrete_update_address()
242 {
243 // Verifica o nonce
244 if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'superfrete_update_address_nonce')) {
245 wp_send_json_error(['message' => 'Requisição inválida.'], 403);
246 }
247
248 if (!session_id()) {
249 session_start();
250 }
251
252 if (!isset($_POST['order_id'])) {
253 wp_send_json_error(['message' => 'ID do pedido ausente.'], 400);
254 }
255
256 $order_id = intval($_POST['order_id']);
257 $order = wc_get_order($order_id);
258
259 if (!$order) {
260 wp_send_json_error(['message' => 'Pedido não encontrado.'], 404);
261 }
262
263 $current_shipping = $order->get_address('shipping');
264
265 $updated_data = [
266 'first_name' => sanitize_text_field($_POST['name']),
267 'address_1' => sanitize_text_field($_POST['address']),
268 'address_2' => sanitize_text_field($_POST['complement']),
269 'number' => sanitize_text_field($_POST['number']),
270 'neighborhood' => sanitize_text_field($_POST['district']),
271 'city' => sanitize_text_field($_POST['city']),
272 'state' => sanitize_text_field($_POST['state_abbr']),
273 'postcode' => sanitize_text_field($_POST['postal_code'])
274 ];
275 if (!empty($updated_data['number'])) {
276 $order->update_meta_data('_shipping_number', $updated_data['number']);
277 }
278 if (!empty($updated_data['neighborhood'])) {
279 $order->update_meta_data('_shipping_neighborhood', $updated_data['neighborhood']);
280 }
281
282 foreach ($updated_data as $key => $value) {
283 if (empty($current_shipping[$key]) && !empty($value)) {
284 $current_shipping[$key] = $value;
285 }
286 }
287 $order->set_address($current_shipping, 'shipping');
288 $order->save();
289 $_SESSION['superfrete_correction'][$order_id] = $current_shipping;
290
291 wp_send_json_success(['message' => 'Campos vazios preenchidos e endereço atualizado!', 'order_id' => $order_id]);
292 }
293 }
294