| 1 |
<?php |
| 2 |
|
| 3 |
namespace SuperFrete_API; |
| 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/SuperFreteBase.php'; |
| 25 |
require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFretePAC.php'; |
| 26 |
require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteSEDEX.php'; |
| 27 |
require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteMiniEnvio.php'; |
| 28 |
require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteJadlog.php'; |
| 29 |
require_once plugin_dir_path(__FILE__) . 'Shipping/SuperFreteLoggi.php'; |
| 30 |
} |
| 31 |
}); |
| 32 |
|
| 33 |
add_filter('woocommerce_shipping_methods', function ($methods) { |
| 34 |
// Register all individual shipping methods |
| 35 |
$methods['superfrete_pac'] = '\SuperFrete_API\Shipping\SuperFretePAC'; |
| 36 |
$methods['superfrete_sedex'] = '\SuperFrete_API\Shipping\SuperFreteSEDEX'; |
| 37 |
$methods['superfrete_mini_envio'] = '\SuperFrete_API\Shipping\SuperFreteMiniEnvios'; |
| 38 |
$methods['superfrete_jadlog'] = '\SuperFrete_API\Shipping\SuperFreteJadlog'; |
| 39 |
$methods['superfrete_loggi'] = '\SuperFrete_API\Shipping\SuperFreteLoggi'; |
| 40 |
|
| 41 |
// Remove the consolidated method if it exists |
| 42 |
unset($methods['superfrete_shipping']); |
| 43 |
|
| 44 |
return $methods; |
| 45 |
}); |
| 46 |
|
| 47 |
|
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Inclui os arquivos necessários do plugin |
| 52 |
*/ |
| 53 |
private function includes() |
| 54 |
{ |
| 55 |
require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_Settings.php'; |
| 56 |
require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/Admin_Menu.php'; |
| 57 |
require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/WebhookAdmin.php'; |
| 58 |
require_once plugin_dir_path(__FILE__) . '../api/Http/Request.php'; |
| 59 |
require_once plugin_dir_path(__FILE__) . '../api/Http/WebhookVerifier.php'; |
| 60 |
require_once plugin_dir_path(__FILE__) . '../api/Helpers/Logger.php'; |
| 61 |
require_once plugin_dir_path(__FILE__) . 'Controllers/ProductShipping.php'; |
| 62 |
require_once plugin_dir_path(__FILE__) . 'Controllers/SuperFrete_Order.php'; |
| 63 |
require_once plugin_dir_path(__FILE__) . 'Controllers/Admin/SuperFrete_OrderActions.php'; |
| 64 |
require_once plugin_dir_path(__FILE__) . 'Controllers/WebhookController.php'; |
| 65 |
require_once plugin_dir_path(__FILE__) . 'Controllers/WebhookRetryManager.php'; |
| 66 |
require_once plugin_dir_path(__FILE__) . 'Controllers/OAuthController.php'; |
| 67 |
require_once plugin_dir_path(__FILE__) . 'Controllers/DocumentFields.php'; |
| 68 |
require_once plugin_dir_path(__FILE__) . 'Controllers/CheckoutFields.php'; |
| 69 |
require_once plugin_dir_path(__FILE__) . 'Helpers/AddressHelper.php'; |
| 70 |
require_once plugin_dir_path(__FILE__) . 'Helpers/ShippingMigration.php'; |
| 71 |
require_once plugin_dir_path(__FILE__) . 'Helpers/SuperFrete_Notice.php'; |
| 72 |
|
| 73 |
// Include database migrations if file exists |
| 74 |
$migrations_file = plugin_dir_path(__FILE__) . '../database/webhook_migrations.php'; |
| 75 |
if (file_exists($migrations_file)) { |
| 76 |
require_once $migrations_file; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Check if WooFunnels Aero Checkout is active |
| 82 |
*/ |
| 83 |
private function is_woofunnels_checkout_active() |
| 84 |
{ |
| 85 |
return class_exists('WFACP_Common') || class_exists('WFACP_Template_Common'); |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* Inicializa o plugin e adiciona suas funcionalidades |
| 90 |
*/ |
| 91 |
public function init_plugin() |
| 92 |
{ |
| 93 |
|
| 94 |
new \SuperFrete_API\Admin\SuperFrete_OrderActions(); |
| 95 |
new \SuperFrete_API\Admin\SuperFrete_Settings(); |
| 96 |
new \SuperFrete_API\Admin\WebhookAdmin(); |
| 97 |
new \SuperFrete_API\Controllers\ProductShipping(); |
| 98 |
if (class_exists('\SuperFrete_API\Admin\Admin_Menu')) { |
| 99 |
new \SuperFrete_API\Admin\Admin_Menu(); |
| 100 |
} |
| 101 |
new \SuperFrete_API\Controllers\SuperFrete_Order(); |
| 102 |
new \SuperFrete_API\Controllers\WebhookController(); |
| 103 |
new \SuperFrete_API\Controllers\WebhookRetryManager(); |
| 104 |
new \SuperFrete_API\Controllers\OAuthController(); |
| 105 |
\SuperFrete_API\Helpers\Logger::init(); |
| 106 |
|
| 107 |
// Initialize webhook database tables (if class exists) |
| 108 |
if (class_exists('\SuperFrete_API\Database\WebhookMigrations')) { |
| 109 |
\SuperFrete_API\Database\WebhookMigrations::run_migrations(); |
| 110 |
} |
| 111 |
|
| 112 |
add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']); |
| 113 |
add_action('wp', function () { |
| 114 |
if (!wp_next_scheduled('superfrete_clear_log_event')) { |
| 115 |
wp_schedule_event(time(), 'every_five_days', 'superfrete_clear_log_event'); |
| 116 |
} |
| 117 |
}); |
| 118 |
add_filter('woocommerce_package_rates', [$this, 'ordenar_metodos_frete_por_preco'], 100, 2); |
| 119 |
|
| 120 |
// Also try hooking at an even later stage to ensure our sorting is final |
| 121 |
add_filter('woocommerce_shipping_package_rates', [$this, 'ordenar_metodos_frete_por_preco'], 999, 2); |
| 122 |
|
| 123 |
// Adiciona os campos 'Número' e 'Bairro' nas configurações da loja |
| 124 |
add_filter('woocommerce_general_settings', [$this, 'add_custom_store_address_fields']); |
| 125 |
|
| 126 |
add_filter('cron_schedules', function ($schedules) { |
| 127 |
$schedules['every_five_days'] = [ |
| 128 |
'interval' => 5 * DAY_IN_SECONDS, |
| 129 |
'display' => __('A cada 5 dias') |
| 130 |
]; |
| 131 |
return $schedules; |
| 132 |
}); |
| 133 |
|
| 134 |
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'))))) { |
| 135 |
new \SuperFrete_API\Controllers\ProductShipping(); |
| 136 |
} else { |
| 137 |
add_action('admin_notices', [$this, 'superfrete_configs_setup_notice']); |
| 138 |
} |
| 139 |
add_action('superfrete_clear_log_event', function () { |
| 140 |
\SuperFrete_API\Helpers\Logger::clear_log(); |
| 141 |
// Also cleanup old webhook logs (if class exists) |
| 142 |
if (class_exists('\SuperFrete_API\Database\WebhookMigrations')) { |
| 143 |
\SuperFrete_API\Database\WebhookMigrations::cleanup_old_logs(); |
| 144 |
} |
| 145 |
// Clear old shipping cache entries |
| 146 |
if (class_exists('\SuperFrete_API\Shipping\SuperFreteBase')) { |
| 147 |
\SuperFrete_API\Shipping\SuperFreteBase::clear_cache(); |
| 148 |
} |
| 149 |
}); |
| 150 |
|
| 151 |
// Register custom order statuses |
| 152 |
add_action('init', [$this, 'register_custom_order_statuses']); |
| 153 |
|
| 154 |
// Run migration and create shipping zone after shipping methods are registered |
| 155 |
add_action('wp_loaded', function () { |
| 156 |
// Make sure WooCommerce is loaded |
| 157 |
if (!class_exists('WooCommerce') || !class_exists('WC_Shipping_Zones')) { |
| 158 |
return; |
| 159 |
} |
| 160 |
// Check if we need to force migration due to plugin update |
| 161 |
$current_version = get_option('superfrete_plugin_version', '0.0.0'); |
| 162 |
$plugin_file = plugin_dir_path(__FILE__) . '../superfrete.php'; |
| 163 |
|
| 164 |
if (file_exists($plugin_file)) { |
| 165 |
if (!function_exists('get_plugin_data')) { |
| 166 |
require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 167 |
} |
| 168 |
$plugin_data = get_plugin_data($plugin_file); |
| 169 |
$new_version = $plugin_data['Version'] ?? '1.0.0'; |
| 170 |
|
| 171 |
// If version changed, reset migration to force re-run |
| 172 |
if (version_compare($current_version, $new_version, '<')) { |
| 173 |
delete_option('superfrete_shipping_migrated'); |
| 174 |
delete_option('superfrete_individual_methods_migrated'); // New migration flag |
| 175 |
update_option('superfrete_plugin_version', $new_version); |
| 176 |
Logger::log('SuperFrete', "Plugin updated from $current_version to $new_version - forcing migration"); |
| 177 |
} |
| 178 |
|
| 179 |
// Force migration for individual methods (version 3.2.0+) |
| 180 |
if (version_compare($current_version, '3.2.0', '<') && version_compare($new_version, '3.2.0', '>=')) { |
| 181 |
delete_option('superfrete_shipping_migrated'); |
| 182 |
delete_option('superfrete_individual_methods_migrated'); |
| 183 |
Logger::log('SuperFrete', "Forcing migration to individual shipping methods (v3.2.0)"); |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
// Delay migration to ensure shipping methods are registered |
| 188 |
// Only run migration once per request to avoid loops |
| 189 |
if (!get_transient('superfrete_migration_running')) { |
| 190 |
set_transient('superfrete_migration_running', true, 30); // 30 second lock |
| 191 |
\SuperFrete_API\Helpers\ShippingMigration::migrate_shipping_methods(); |
| 192 |
delete_transient('superfrete_migration_running'); |
| 193 |
} |
| 194 |
if (!class_exists('\WC_Shipping_Zones')) return; |
| 195 |
|
| 196 |
$zone_name = 'Brasil - SuperFrete'; |
| 197 |
$existing_zones = \WC_Shipping_Zones::get_zones(); |
| 198 |
|
| 199 |
foreach ($existing_zones as $zone) { |
| 200 |
if ($zone['zone_name'] === $zone_name) return; |
| 201 |
} |
| 202 |
|
| 203 |
$zone = new \WC_Shipping_Zone(); |
| 204 |
$zone->set_zone_name($zone_name); |
| 205 |
$zone->save(); |
| 206 |
|
| 207 |
$zone_id = $zone->get_id(); |
| 208 |
$locations = [ |
| 209 |
['code' => 'BR', 'type' => 'country'], |
| 210 |
]; |
| 211 |
|
| 212 |
global $wpdb; |
| 213 |
foreach ($locations as $location) { |
| 214 |
$wpdb->insert("{$wpdb->prefix}woocommerce_zone_locations", [ |
| 215 |
'zone_id' => $zone_id, |
| 216 |
'location_code' => $location['code'], |
| 217 |
'location_type' => $location['type'], |
| 218 |
]); |
| 219 |
} |
| 220 |
// Add all individual SuperFrete methods |
| 221 |
$method_ids = ['superfrete_pac', 'superfrete_sedex', 'superfrete_jadlog', 'superfrete_mini_envio', 'superfrete_loggi']; |
| 222 |
|
| 223 |
// Check if the shipping methods are registered |
| 224 |
$wc_shipping = \WC_Shipping::instance(); |
| 225 |
$available_methods = $wc_shipping->get_shipping_methods(); |
| 226 |
|
| 227 |
foreach ($method_ids as $method_id) { |
| 228 |
if (isset($available_methods[$method_id])) { |
| 229 |
$instance_id = $zone->add_shipping_method($method_id); |
| 230 |
|
| 231 |
// Get the method instance and enable it |
| 232 |
$methods = $zone->get_shipping_methods(); |
| 233 |
foreach ($methods as $method) { |
| 234 |
if ($method->id === $method_id && $method->get_instance_id() == $instance_id) { |
| 235 |
$method->enabled = 'yes'; |
| 236 |
$method->update_option('enabled', 'yes'); |
| 237 |
$method->update_option('title', $method->method_title); |
| 238 |
$method->save(); |
| 239 |
Logger::debug("Shipping method $method_id enabled in zone (Instance ID: $instance_id)", 'App'); |
| 240 |
break; |
| 241 |
} |
| 242 |
} |
| 243 |
} else { |
| 244 |
Logger::debug("Shipping method $method_id not registered yet", 'App'); |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
Logger::debug('Zona de entrega "Brasil - SuperFrete" criada com o método ativado.', 'App'); |
| 249 |
}); |
| 250 |
} |
| 251 |
|
| 252 |
public function ordenar_metodos_frete_por_preco($rates, $package) |
| 253 |
{ |
| 254 |
if (empty($rates)) |
| 255 |
return $rates; |
| 256 |
|
| 257 |
// Log original order for debugging |
| 258 |
$original_order = []; |
| 259 |
foreach ($rates as $rate_id => $rate) { |
| 260 |
$original_order[] = $rate->label . ' - R$ ' . number_format(floatval($rate->cost), 2, ',', '.'); |
| 261 |
} |
| 262 |
Logger::debug('Original shipping order: ' . implode(' | ', $original_order), 'Shipping'); |
| 263 |
|
| 264 |
// Reordena os métodos de frete pelo valor (crescente - do menor para o maior) |
| 265 |
uasort($rates, function ($a, $b) { |
| 266 |
$cost_a = floatval($a->cost); |
| 267 |
$cost_b = floatval($b->cost); |
| 268 |
|
| 269 |
// Free shipping (cost = 0) should come first |
| 270 |
if ($cost_a == 0 && $cost_b > 0) return -1; |
| 271 |
if ($cost_b == 0 && $cost_a > 0) return 1; |
| 272 |
|
| 273 |
// Both free or both paid - sort by cost ascending |
| 274 |
if ($cost_a == $cost_b) { |
| 275 |
// If costs are equal, sort by delivery time (faster first) |
| 276 |
$time_a = isset($a->meta_data['delivery_time']) ? intval($a->meta_data['delivery_time']) : 999; |
| 277 |
$time_b = isset($b->meta_data['delivery_time']) ? intval($b->meta_data['delivery_time']) : 999; |
| 278 |
return $time_a <=> $time_b; |
| 279 |
} |
| 280 |
|
| 281 |
return $cost_a <=> $cost_b; |
| 282 |
}); |
| 283 |
|
| 284 |
// Log sorted order for debugging |
| 285 |
$sorted_order = []; |
| 286 |
foreach ($rates as $rate_id => $rate) { |
| 287 |
$sorted_order[] = $rate->label . ' - R$ ' . number_format(floatval($rate->cost), 2, ',', '.'); |
| 288 |
} |
| 289 |
Logger::debug('Sorted shipping order: ' . implode(' | ', $sorted_order), 'Shipping'); |
| 290 |
|
| 291 |
return $rates; |
| 292 |
} |
| 293 |
|
| 294 |
|
| 295 |
function add_custom_store_address_fields($settings) |
| 296 |
{ |
| 297 |
$new_settings = []; |
| 298 |
|
| 299 |
foreach ($settings as $setting) { |
| 300 |
$new_settings[] = $setting; |
| 301 |
|
| 302 |
// Após o campo de endereço 1 |
| 303 |
if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_address') { |
| 304 |
$new_settings[] = [ |
| 305 |
'title' => 'Número', |
| 306 |
'desc_tip' => 'Número do endereço da loja', |
| 307 |
'id' => 'woocommerce_store_number', |
| 308 |
'type' => 'text', |
| 309 |
'css' => 'min-width:300px;', |
| 310 |
'default' => '', |
| 311 |
'autoload' => false, |
| 312 |
]; |
| 313 |
} |
| 314 |
|
| 315 |
// Após o campo de cidade |
| 316 |
if (isset($setting['id']) && $setting['id'] === 'woocommerce_store_city') { |
| 317 |
$new_settings[] = [ |
| 318 |
'title' => 'Bairro', |
| 319 |
'desc_tip' => 'Bairro da loja', |
| 320 |
'id' => 'woocommerce_store_neighborhood', |
| 321 |
'type' => 'text', |
| 322 |
'css' => 'min-width:300px;', |
| 323 |
'default' => '', |
| 324 |
'autoload' => false, |
| 325 |
]; |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
return $new_settings; |
| 330 |
} |
| 331 |
|
| 332 |
/** |
| 333 |
* Register custom order statuses for better tracking |
| 334 |
*/ |
| 335 |
public function register_custom_order_statuses() |
| 336 |
{ |
| 337 |
// Register custom 'shipped' status |
| 338 |
register_post_status('wc-shipped', [ |
| 339 |
'label' => 'Enviado', |
| 340 |
'public' => true, |
| 341 |
'exclude_from_search' => false, |
| 342 |
'show_in_admin_all_list' => true, |
| 343 |
'show_in_admin_status_list' => true, |
| 344 |
'label_count' => _n_noop('Enviado <span class="count">(%s)</span>', 'Enviado <span class="count">(%s)</span>') |
| 345 |
]); |
| 346 |
|
| 347 |
// Add custom statuses to WooCommerce order statuses |
| 348 |
add_filter('wc_order_statuses', function($order_statuses) { |
| 349 |
$order_statuses['wc-shipped'] = 'Enviado'; |
| 350 |
return $order_statuses; |
| 351 |
}); |
| 352 |
} |
| 353 |
|
| 354 |
public function superfrete_configs_setup_notice() |
| 355 |
{ |
| 356 |
?> |
| 357 |
<div class="error notice"> |
| 358 |
<p><b>SuperFrete</b></p> |
| 359 |
<p> |
| 360 |
Para utilizar o plugin você deve |
| 361 |
<a |
| 362 |
href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=shipping§ion=options#superfrete_settings_section-description')); ?>"> |
| 363 |
configurar seu acesso a SuperFrete |
| 364 |
</a> |
| 365 |
e configurar um |
| 366 |
<a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings')); ?>"> |
| 367 |
endereço |
| 368 |
</a>. |
| 369 |
</p> |
| 370 |
</div> |
| 371 |
<?php |
| 372 |
} |
| 373 |
|
| 374 |
/** |
| 375 |
* Adiciona um link para as configurações na página de plugins. |
| 376 |
*/ |
| 377 |
public static function superfrete_add_settings_link($links) |
| 378 |
{ |
| 379 |
$settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=shipping§ion=options#superfrete_settings_section-description') . '">Configurações</a>'; |
| 380 |
array_unshift($links, $settings_link); |
| 381 |
return $links; |
| 382 |
} |
| 383 |
|
| 384 |
// Criar a função que limpa os logs |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
static function singleShippingCountry() |
| 389 |
{ |
| 390 |
if (!function_exists('WC') || !is_object(WC()->countries)) |
| 391 |
return false; |
| 392 |
|
| 393 |
$countries = WC()->countries->get_shipping_countries(); |
| 394 |
|
| 395 |
if (count($countries) == 1) { |
| 396 |
foreach (WC()->countries->get_shipping_countries() as $key => $value) { |
| 397 |
return $key; |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
return false; |
| 402 |
} |
| 403 |
|
| 404 |
public function enqueue_assets() |
| 405 |
{ |
| 406 |
|
| 407 |
wp_localize_script( |
| 408 |
'jquery', |
| 409 |
'superfrete_setting', |
| 410 |
array( |
| 411 |
'wc_ajax_url' => \WC_AJAX::get_endpoint('%%endpoint%%'), |
| 412 |
'ajaxUrl' => admin_url('admin-ajax.php'), |
| 413 |
'loading' => 'Loading..', |
| 414 |
'auto_select_country' => apply_filters('pisol_ppscw_auto_select_country', self::singleShippingCountry()), |
| 415 |
'load_location_by_ajax' => 1 |
| 416 |
) |
| 417 |
); |
| 418 |
|
| 419 |
wp_enqueue_style('superfrete-popup-css', plugin_dir_url(__FILE__) . '../assets/styles/superfrete.css', [], '1.0'); |
| 420 |
|
| 421 |
// Add shipping sorting script on checkout |
| 422 |
if (is_checkout()) { |
| 423 |
add_action('wp_footer', [$this, 'add_shipping_sorting_script']); |
| 424 |
|
| 425 |
// Enqueue document field script for checkout |
| 426 |
// Skip if WooFunnels Aero Checkout is active (they have their own masking) |
| 427 |
if (!$this->is_woofunnels_checkout_active()) { |
| 428 |
wp_enqueue_script( |
| 429 |
'superfrete-document-field', |
| 430 |
plugin_dir_url(__FILE__) . '../assets/js/document-field.js', |
| 431 |
['jquery'], |
| 432 |
'1.0.0', |
| 433 |
true |
| 434 |
); |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
// Add theme customization support |
| 439 |
add_action('wp_head', [$this, 'add_theme_customization_styles'], 100); |
| 440 |
wp_enqueue_script( |
| 441 |
'superfrete-popup', |
| 442 |
plugin_dir_url(__FILE__) . '../assets/scripts/superfrete-popup.js', |
| 443 |
['jquery'], |
| 444 |
'1.0.0', // Versão do script |
| 445 |
true |
| 446 |
); |
| 447 |
wp_localize_script('superfrete-popup', 'superfrete_ajax', [ |
| 448 |
'ajax_url' => admin_url('admin-ajax.php'), |
| 449 |
]); |
| 450 |
} |
| 451 |
|
| 452 |
public function register_ajax_actions() |
| 453 |
{ |
| 454 |
add_action('wp_ajax_superfrete_update_address', [$this, 'handle_superfrete_update_address']); |
| 455 |
add_action('wp_ajax_nopriv_superfrete_update_address', [$this, 'handle_superfrete_update_address']); |
| 456 |
} |
| 457 |
|
| 458 |
// Criar a função que limpa os logs |
| 459 |
|
| 460 |
|
| 461 |
public function handle_superfrete_update_address() |
| 462 |
{ |
| 463 |
// Verifica o nonce |
| 464 |
if (!isset($_POST['_ajax_nonce']) || !wp_verify_nonce($_POST['_ajax_nonce'], 'superfrete_update_address_nonce')) { |
| 465 |
wp_send_json_error(['message' => 'Requisição inválida.'], 403); |
| 466 |
} |
| 467 |
|
| 468 |
if (!session_id()) { |
| 469 |
session_start(); |
| 470 |
} |
| 471 |
|
| 472 |
if (!isset($_POST['order_id'])) { |
| 473 |
wp_send_json_error(['message' => 'ID do pedido ausente.'], 400); |
| 474 |
} |
| 475 |
|
| 476 |
$order_id = intval($_POST['order_id']); |
| 477 |
$order = wc_get_order($order_id); |
| 478 |
|
| 479 |
if (!$order) { |
| 480 |
wp_send_json_error(['message' => 'Pedido não encontrado.'], 404); |
| 481 |
} |
| 482 |
|
| 483 |
$current_shipping = $order->get_address('shipping'); |
| 484 |
|
| 485 |
$updated_data = [ |
| 486 |
'first_name' => sanitize_text_field($_POST['name']), |
| 487 |
'address_1' => sanitize_text_field($_POST['address']), |
| 488 |
'address_2' => sanitize_text_field($_POST['complement']), |
| 489 |
'number' => sanitize_text_field($_POST['number']), |
| 490 |
'neighborhood' => sanitize_text_field($_POST['district']), |
| 491 |
'city' => sanitize_text_field($_POST['city']), |
| 492 |
'state' => sanitize_text_field($_POST['state_abbr']), |
| 493 |
'postcode' => sanitize_text_field($_POST['postal_code']) |
| 494 |
]; |
| 495 |
if (!empty($updated_data['number'])) { |
| 496 |
$order->update_meta_data('_shipping_number', $updated_data['number']); |
| 497 |
} |
| 498 |
if (!empty($updated_data['neighborhood'])) { |
| 499 |
$order->update_meta_data('_shipping_neighborhood', $updated_data['neighborhood']); |
| 500 |
} |
| 501 |
|
| 502 |
foreach ($updated_data as $key => $value) { |
| 503 |
if (empty($current_shipping[$key]) && !empty($value)) { |
| 504 |
$current_shipping[$key] = $value; |
| 505 |
} |
| 506 |
} |
| 507 |
$order->set_address($current_shipping, 'shipping'); |
| 508 |
$order->save(); |
| 509 |
$_SESSION['superfrete_correction'][$order_id] = $current_shipping; |
| 510 |
|
| 511 |
wp_send_json_success(['message' => 'Campos vazios preenchidos e endereço atualizado!', 'order_id' => $order_id]); |
| 512 |
} |
| 513 |
|
| 514 |
/** |
| 515 |
* Add theme customization styles with CSS variables |
| 516 |
*/ |
| 517 |
public function add_theme_customization_styles() { |
| 518 |
// Complete CSS variables with SuperFrete brand defaults |
| 519 |
$default_variables = array( |
| 520 |
// Primary brand colors |
| 521 |
'--superfrete-primary-color' => '#0fae79', |
| 522 |
'--superfrete-primary-hover' => '#0d9969', |
| 523 |
'--superfrete-secondary-color' => '#c3ff01', |
| 524 |
'--superfrete-secondary-hover' => '#b3e600', |
| 525 |
'--superfrete-success-color' => '#4CAF50', |
| 526 |
'--superfrete-error-color' => '#e74c3c', |
| 527 |
'--superfrete-info-color' => '#2196F3', |
| 528 |
'--superfrete-warning-color' => '#ff9800', |
| 529 |
|
| 530 |
// Background colors |
| 531 |
'--superfrete-bg-color' => '#ffffff', |
| 532 |
'--superfrete-bg-white' => '#ffffff', |
| 533 |
'--superfrete-bg-light' => '#f8f9fa', |
| 534 |
'--superfrete-bg-dark' => '#1a1a1a', |
| 535 |
|
| 536 |
// Text colors |
| 537 |
'--superfrete-text-color' => '#1a1a1a', |
| 538 |
'--superfrete-text-light' => '#777777', |
| 539 |
'--superfrete-text-white' => '#ffffff', |
| 540 |
'--superfrete-heading-color' => '#1a1a1a', |
| 541 |
|
| 542 |
// Border colors |
| 543 |
'--superfrete-border-color' => '#e0e0e0', |
| 544 |
'--superfrete-border-light' => '#f0f0f0', |
| 545 |
'--superfrete-border-dark' => '#cccccc', |
| 546 |
|
| 547 |
// Typography |
| 548 |
'--superfrete-font-family' => 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', |
| 549 |
'--superfrete-font-size-small' => '12px', |
| 550 |
'--superfrete-font-size-base' => '14px', |
| 551 |
'--superfrete-font-size-large' => '16px', |
| 552 |
'--superfrete-font-size-xl' => '18px', |
| 553 |
'--superfrete-font-weight-normal' => '400', |
| 554 |
'--superfrete-font-weight-medium' => '500', |
| 555 |
'--superfrete-font-weight-bold' => '600', |
| 556 |
'--superfrete-line-height' => '1.5', |
| 557 |
|
| 558 |
// Spacing |
| 559 |
'--superfrete-spacing-xs' => '4px', |
| 560 |
'--superfrete-spacing-sm' => '8px', |
| 561 |
'--superfrete-spacing-md' => '12px', |
| 562 |
'--superfrete-spacing-lg' => '16px', |
| 563 |
'--superfrete-spacing-xl' => '24px', |
| 564 |
'--superfrete-spacing-xxl' => '32px', |
| 565 |
|
| 566 |
// Border radius |
| 567 |
'--superfrete-radius-sm' => '4px', |
| 568 |
'--superfrete-radius-md' => '6px', |
| 569 |
'--superfrete-radius-lg' => '8px', |
| 570 |
'--superfrete-radius-xl' => '12px', |
| 571 |
'--superfrete-radius-full' => '50px', |
| 572 |
|
| 573 |
// Shadows |
| 574 |
'--superfrete-shadow-sm' => '0 1px 3px rgba(0, 0, 0, 0.1)', |
| 575 |
'--superfrete-shadow-md' => '0 2px 6px rgba(0, 0, 0, 0.1)', |
| 576 |
'--superfrete-shadow-lg' => '0 4px 12px rgba(0, 0, 0, 0.15)', |
| 577 |
|
| 578 |
// Z-index |
| 579 |
'--superfrete-z-base' => '1', |
| 580 |
'--superfrete-z-overlay' => '100', |
| 581 |
'--superfrete-z-loading' => '101', |
| 582 |
'--superfrete-z-modal' => '200', |
| 583 |
|
| 584 |
// Animation |
| 585 |
'--superfrete-transition-fast' => '0.15s ease', |
| 586 |
'--superfrete-transition-normal' => '0.3s ease', |
| 587 |
'--superfrete-transition-slow' => '0.5s ease', |
| 588 |
); |
| 589 |
|
| 590 |
// Get custom CSS variables from database |
| 591 |
$custom_variables = get_option('superfrete_custom_css_vars', array()); |
| 592 |
|
| 593 |
// Merge defaults with custom variables |
| 594 |
$merged_variables = array_merge($default_variables, $custom_variables); |
| 595 |
|
| 596 |
// Allow themes to modify CSS variables |
| 597 |
$css_variables = apply_filters('superfrete_css_variables', $merged_variables); |
| 598 |
|
| 599 |
// Build CSS string |
| 600 |
$custom_css = ':root {'; |
| 601 |
foreach ($css_variables as $variable => $value) { |
| 602 |
$custom_css .= sprintf('%s: %s;', esc_attr($variable), esc_attr($value)); |
| 603 |
} |
| 604 |
$custom_css .= '}'; |
| 605 |
|
| 606 |
// Allow themes to add custom CSS |
| 607 |
$additional_css = apply_filters('superfrete_custom_css', ''); |
| 608 |
|
| 609 |
// Output the styles |
| 610 |
if (!empty($custom_css) || !empty($additional_css)) { |
| 611 |
echo '<style id="superfrete-theme-customization">'; |
| 612 |
echo $custom_css; |
| 613 |
echo $additional_css; |
| 614 |
echo '</style>'; |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
/** |
| 619 |
* Add JavaScript to sort shipping options by price on the frontend |
| 620 |
*/ |
| 621 |
public function add_shipping_sorting_script() { |
| 622 |
?> |
| 623 |
<script type="text/javascript"> |
| 624 |
jQuery(document).ready(function($) { |
| 625 |
function sortShippingOptions() { |
| 626 |
console.log('SuperFrete: Attempting to sort shipping options...'); |
| 627 |
|
| 628 |
// Try multiple selectors to find shipping options |
| 629 |
var $containers = [ |
| 630 |
$('#shipping_method'), |
| 631 |
$('.woocommerce-shipping-methods'), |
| 632 |
$('ul.woocommerce-shipping-methods'), |
| 633 |
$('.shipping-methods'), |
| 634 |
$('[id*="shipping_method"]'), |
| 635 |
$('ul li input[name^="shipping_method"]').closest('ul') |
| 636 |
]; |
| 637 |
|
| 638 |
var foundContainer = false; |
| 639 |
|
| 640 |
$.each($containers, function(index, $container) { |
| 641 |
if ($container.length > 0) { |
| 642 |
console.log('SuperFrete: Found container #' + index + ':', $container); |
| 643 |
|
| 644 |
var $options = $container.find('li'); |
| 645 |
if ($options.length <= 1) { |
| 646 |
console.log('SuperFrete: Not enough options to sort (' + $options.length + ')'); |
| 647 |
return true; // Continue to next container |
| 648 |
} |
| 649 |
|
| 650 |
foundContainer = true; |
| 651 |
console.log('SuperFrete: Found ' + $options.length + ' shipping options to sort'); |
| 652 |
|
| 653 |
// Log original order |
| 654 |
$options.each(function(i) { |
| 655 |
var text = $(this).text(); |
| 656 |
var price = extractPrice(text); |
| 657 |
console.log('SuperFrete: Option ' + i + ': ' + text.substring(0, 50) + '... (Price: ' + price + ')'); |
| 658 |
}); |
| 659 |
|
| 660 |
// Convert to array and sort |
| 661 |
var sortedOptions = $options.get().sort(function(a, b) { |
| 662 |
var priceA = extractPrice($(a).text()); |
| 663 |
var priceB = extractPrice($(b).text()); |
| 664 |
|
| 665 |
// Free shipping (0) comes first |
| 666 |
if (priceA === 0 && priceB > 0) return -1; |
| 667 |
if (priceB === 0 && priceA > 0) return 1; |
| 668 |
|
| 669 |
// Sort by price ascending |
| 670 |
return priceA - priceB; |
| 671 |
}); |
| 672 |
|
| 673 |
// Reorder the DOM elements |
| 674 |
$.each(sortedOptions, function(index, element) { |
| 675 |
$container.append(element); |
| 676 |
}); |
| 677 |
|
| 678 |
console.log('SuperFrete: Shipping options sorted successfully!'); |
| 679 |
|
| 680 |
// Log sorted order |
| 681 |
$container.find('li').each(function(i) { |
| 682 |
var text = $(this).text(); |
| 683 |
var price = extractPrice(text); |
| 684 |
console.log('SuperFrete: Sorted option ' + i + ': ' + text.substring(0, 50) + '... (Price: ' + price + ')'); |
| 685 |
}); |
| 686 |
|
| 687 |
return false; // Break out of loop |
| 688 |
} |
| 689 |
}); |
| 690 |
|
| 691 |
if (!foundContainer) { |
| 692 |
console.log('SuperFrete: No shipping container found. Available elements:'); |
| 693 |
console.log('- #shipping_method:', $('#shipping_method').length); |
| 694 |
console.log('- .woocommerce-shipping-methods:', $('.woocommerce-shipping-methods').length); |
| 695 |
console.log('- ul.woocommerce-shipping-methods:', $('ul.woocommerce-shipping-methods').length); |
| 696 |
console.log('- All shipping method inputs:', $('input[name^="shipping_method"]').length); |
| 697 |
} |
| 698 |
} |
| 699 |
|
| 700 |
function extractPrice(text) { |
| 701 |
// Extract price from text like "R$ 23,72", "R$ 15,49", "Grátis" |
| 702 |
if (text.toLowerCase().includes('grátis') || text.toLowerCase().includes('gratuito') || text.toLowerCase().includes('free')) { |
| 703 |
return 0; |
| 704 |
} |
| 705 |
|
| 706 |
// Match pattern like "R$ 23,72" or "23,72" |
| 707 |
var match = text.match(/R\$?\s*(\d+)[,.](\d{2})/); |
| 708 |
if (match) { |
| 709 |
return parseFloat(match[1] + '.' + match[2]); |
| 710 |
} |
| 711 |
|
| 712 |
// Match pattern like "R$ 23" or "23" |
| 713 |
match = text.match(/R\$?\s*(\d+)/); |
| 714 |
if (match) { |
| 715 |
return parseFloat(match[1]); |
| 716 |
} |
| 717 |
|
| 718 |
console.log('SuperFrete: Could not extract price from: ' + text); |
| 719 |
return 999999; // Unknown prices go to the end |
| 720 |
} |
| 721 |
|
| 722 |
// Sort on initial load with multiple attempts |
| 723 |
console.log('SuperFrete: Initializing shipping sort...'); |
| 724 |
setTimeout(sortShippingOptions, 500); |
| 725 |
setTimeout(sortShippingOptions, 1000); |
| 726 |
setTimeout(sortShippingOptions, 2000); |
| 727 |
setTimeout(sortShippingOptions, 3000); |
| 728 |
|
| 729 |
// Sort when shipping is recalculated |
| 730 |
$(document.body).on('updated_checkout updated_shipping_method wc_checkout_place_order', function(e) { |
| 731 |
console.log('SuperFrete: Checkout updated, re-sorting shipping...', e.type); |
| 732 |
setTimeout(sortShippingOptions, 200); |
| 733 |
setTimeout(sortShippingOptions, 500); |
| 734 |
}); |
| 735 |
|
| 736 |
// Also try when any shipping method is changed |
| 737 |
$(document).on('change', 'input[name^="shipping_method"]', function() { |
| 738 |
console.log('SuperFrete: Shipping method changed, re-sorting...'); |
| 739 |
setTimeout(sortShippingOptions, 100); |
| 740 |
}); |
| 741 |
}); |
| 742 |
</script> |
| 743 |
<?php |
| 744 |
} |
| 745 |
} |
| 746 |
|