496 lines
22 KiB
PHP
Raw Normal View History

<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
if( !class_exists('APIMIRAVIA') ) {
class APIMIRAVIA {
function __construct() {
$actionsPrivate = array(
'miravia_upload_product',
'miravia_update_product',
'miravia_authorize',
'miravia_create_profile',
'miravia_download_order',
'send_products_miravia',
'miravia_check_job',
'miravia_cancel_job',
'miravia_notify',
'miravia_request_notify',
'miravia_packed_order',
'miravia_print_label',
'miravia_get_brands',
'miravia_connect_product',
'disconnect_product_miravia'
);
foreach( $actionsPrivate as $action ){
add_action( 'wp_ajax_'.$action, array( $this, $action ) );
add_action( 'wp_ajax_nopriv_'.$action, array( $this, $action ) );
}
}
function miravia_connect_product(){
global $wpdb;
if ( !current_user_can( 'manage_woocommerce' ) ) { exit; }
$res = array('ok' => false);
$sku = sanitize_text_field($_POST['sku']);
$profile_id = MiraviaCore::get_profile_by_product($sku);
LOG::add("Profile encontrado {$profile_id} -> {$sku}");
if($profile_id) {
$id_remote = sanitize_text_field($_POST['id_remote']);
$id_local = wc_get_product_id_by_sku($sku);
$existe = MiraviaCore::get_product_miravia($id_local);
if(!$existe) {
$_product = wc_get_product($id_local);
//Save product data
$wpdb->insert($wpdb->prefix.'miravia_products', array(
'id_woocommerce' => $id_local,
'sku' => $_product->get_sku() ?: $id_local,
'id_miravia' => $id_remote,
'profile_id' => $profile_id,
'stock' => $_product->get_regular_price(),
'price' => $_product->get_regular_price(),
'sale_price' => $_product->get_sale_price(),
));
LOG::add("Conectando producto ({$id_local}) remoto {$sku} con {$id_remote} con el profile {$profile_id}");
update_post_meta($id_local, '_miravia_product_id', $id_remote);
update_post_meta($id_local, '_miravia_sync_date', time());
$res['ok'] = true;
}else{
$res['alert'] = "This product exist";
}
}
wp_send_json($res);
}
function miravia_print_label() {
$id = sanitize_text_field($_POST['id']);
$package_id = sanitize_text_field($_POST['package_id']);
$account_id = get_post_meta($id, '_miravia_account_id', true);
$labelResult = false;
$account = MiraviaCore::get_accounts($account_id);
$link = new MiraviaLink($account['token']);
if($account_id) {
$labelResult = $link->getShippingLabel($package_id);
}
wp_send_json($labelResult);
}
function miravia_get_brands() {
$token = MiraviaCore::get_miravia_account_default();
if($token) {
$token = $token['token'];
$link = new MiraviaCategory($token);
$brands = $link->getBrands();
}else{
$brands = [];
}
wp_send_json($brands);
}
function miravia_packed_order(){
$id = sanitize_text_field($_POST['id']);
$account_id = get_post_meta($id, '_miravia_account_id', true);
$order_miravia_id = get_post_meta($id, '_miravia_order_id', true);
if($account_id) {
$account = MiraviaCore::get_accounts($account_id);
$link = new MiraviaLink($account['token']);
$resultPack = false;
list($order, $items) = MiraviaCore::get_order_woocommerce($id);
$resultPack = $link->orderPack($order_miravia_id, array('products' => $items));
update_post_meta($id, '_miravia_packed_result', $resultPack);
}else{
LOG::add("{$id} no ha sido importado, no tiene ID de Cuenta", false, 'pack_order');
LOG::add([$_POST, $account_id], false, 'pack_order');
}
wp_send_json($resultPack);
}
function miravia_check_job() {
$id = sanitize_text_field($_POST['id']);
if($id) {
$apiKey = sanitize_text_field($_POST['token']);
$link = new MiraviaLink($apiKey);
$result = $link->getFeedInfo($id);
// LOG::add($result, false, 'check_job');
if($result and $result['result']['processing_status'] == 'DONE') {
foreach($result['response'] as $sku => $value) {
if($value['status'] == 'FAIL') {
if($value['detail']['message']['errorDetail'] and count($value['detail']['message']['errorDetail']) > 0) {
LOG::add('SET JOB Detail' . $id . ' -> ' . $value['detail']['message']['errorDetail'][0]['message'] . ' -- ' . $sku, false, 'check_job');
MiraviaCore::set_error_product_job($sku, $id, $value['detail']['message']['errorDetail'][0]['message']);
}else{
LOG::add('SET JOB MSG' . $id . ' -> ' . $value['detail']['message']['errorMsg'] . ' -- ' . $sku, false, 'check_job');
MiraviaCore::set_error_product_job($sku, $id, $value['detail']['message']['errorMsg']);
}
}else{
//Controlar los updates
if(!isset($value['id'])) {
$value['id'] = false;
}
MiraviaCore::set_id_miravia_product_job($sku, $id, $value['id']);
}
}
}
if($result) {
// MiraviaCore::set_status_job($id, $result['result']['processing_status']);
wp_send_json(array('status' => $result['result']['processing_status']));
}else{
wp_send_json(array('status' => false));
}
}
}function miravia_cancel_job() {
$id = sanitize_text_field($_POST['id']);
if($id) {
$apiKey = sanitize_text_field($_POST['token']);
$link = new MiraviaLink($apiKey);
$result = $link->cancelFeed($id);
LOG::add($result, false, 'result_cancel_job');
if($result and $result['success']) {
MiraviaCore::clear_job($id);
wp_send_json(array('success' => true));
}else{
MiraviaCore::clear_job($id);
wp_send_json(array('error' => true, 'message' => 'You can cancel this job, products unlock locally'));
}
}
}
function miravia_request_notify() {
MiraviaCore::request_notify(sanitize_text_field($_POST['token']), sanitize_text_field($_POST['message']));
}
function miravia_download_order($id = false, $token = false) {
$id = $id ?: sanitize_text_field($_POST['id']);
$apiKey = $token ?: sanitize_text_field($_POST['token']);
$existe = MiraviaCore::order_exist($id);
if(count($existe) > 0) {
LOG::add("Order {$id} exists");
return;
}
$link = new MiraviaLink($apiKey);
$order_from_miravia = $link->getOrder($id);
$order_from_miravia['data']['account_id'] = sanitize_text_field($_POST['account_id']);
$miravia_order = new MVOrder();
$miravia_order->create($order_from_miravia['data']);
}
function miravia_notify(){
LOG::add('Datos recibidos de notificación', false, 'notify');
// LOG::add($_REQUEST, false, 'notify');
if(isset($_GET['seller'])) {
$idPedido = false;
$action = sanitize_text_field($_GET['message']);
if(sanitize_text_field($_GET['miravia_action']) == 'notify') {
if(str_contains($action, 'neworder-')) {
$idPedido = substr($action, 9);
$action = 'neworder';
}
switch($action) {
case 'update_stock':
$profiles = MiraviaCore::get_profiles_by_seller(sanitize_text_field($_GET['seller']));
foreach($profiles as $k => $p) {
$this->send_stock_price_miravia($p['id'], false);
}
//update_option('miravia_notify_' . $action . '_in', time());
break;
case 'neworder':
if($idPedido) {
if(isset($_GET['status']) and sanitize_text_field($_GET['status']) == 'pending') {
$account = MiraviaCore::get_miravia_account_default(sanitize_text_field($_GET['seller']), 'userid');
$this->miravia_download_order($idPedido, $account['token']);
}else{
LOG::add("Order status is ".sanitize_text_field($_GET['status'])." => {$idPedido}");
}
}
break;
default:
LOG::add("Action notify no recognized");
break;
}
}elseif(sanitize_text_field($_GET['miravia_action']) == 'feed') {
MiraviaCore::procesarFeed();
}elseif(sanitize_text_field($_GET['miravia_action']) == 'stock_sresync') {
$accounts = MiraviaCore::resync_stock();
if($accounts) {
foreach($accounts as $a) {
MiraviaCore::request_notify($a['token'], 'update_stock');
}
}
}
wp_send_json(array('success' => true), 200);
die();
}
wp_send_json(array('success' => false), 400);
die();
}
function send_products_miravia() {
$profile = sanitize_text_field($_POST['profile']);
LOG::add("Enviando productos del perfil {$profile}");
if ( !current_user_can( 'manage_woocommerce' ) ) { exit; }
$result = array(
'id' => 0,
'error' => false,
'message' => ''
);
$accounts = MiraviaCore::accounts_by_profile($profile);
$product = MiraviaCore::get_products_by_profile($profile);
if($product) {
foreach($accounts as $a) {
//Enviar los productos con cada una de las cuentas de usuario registrados en el profile.
//Comprobar el producto si no se ha enviado
// LOG::add("Comprobando producto en job");
// LOG::add($product);
$productsToSend = array(
'update' => array(),
'create' => array()
);
if($product){
foreach($product as $k => $p) {
if(MiraviaCore::check_product_onjob($p->id)) {
unset($product[$k]);
}else{
if($product and $product[$k]->id_miravia != 0 and $product[$k]->id_miravia != '' and $product[$k]->id_miravia != '0') {
$product[$k]->created = 1;
array_push($productsToSend['update'], $product[$k]);
}else{
array_push($productsToSend['create'], $product[$k]);
}
}
}
}
//Check after check on job
// LOG::add("PRODUCTOS DESPUES");
// LOG::add($product);
if(count($product) == 0) {
wp_send_json(array('error' => true, 'message' => 'All products is on job, please wait to complete this before send again.'));
wp_die();
}
if(count($productsToSend['create']) > 0) {
$link = new MiraviaLink($a['token']);
$feed = new MiraviaFeed();
$feed->setProducts($productsToSend['create']);
//Apply Rules
$feed = MiraviaCore::applyFilter($feed, $a['id'], $profile);
$productJson = $feed->getJsonCreate();
if(MIRAVIA_DEBUG == '0') {
$result = $link->sendFeed($productJson);
if(isset($result['feed_result']) and $result['feed_result']['success']) {
MiraviaCore::set_job_product(array_column($productsToSend['create'], 'id'), $profile, $result['feed_result']['result']);
}
}
}
if(count($productsToSend['update']) > 0) {
$link = new MiraviaLink($a['token']);
$feed = new MiraviaFeed();
$feed->setProducts($productsToSend['update']);
//Apply Rules
$feed = MiraviaCore::applyFilter($feed, $a['id'], $profile);
$productJsonUpdate = $feed->getJsonUpdate();
if(MIRAVIA_DEBUG == '0') {
$result = $link->sendFeed($productJsonUpdate, 'update');
if(isset($result['feed_result']) and $result['feed_result']['success']) {
MiraviaCore::set_job_product(array_column($productsToSend['update'], 'id'), $profile, $result['feed_result']['result']);
}
}
}
if(MIRAVIA_DEBUG == '1') {
wp_send_json(array('error' => true, 'message' => 'Debug Active', 'update' => $productJsonUpdate, 'create' => $productJson, 'initData' => $productsToSend));
die();
}
LOG::add("Enviando " . count($product) . " productos con token {$a['token']}");
LOG::add($result);
}
}
wp_send_json($product);
wp_die();
}
function send_stock_price_miravia($profile = false, $returnValue = true) {
if(!$profile) {
$profile = sanitize_text_field($_POST['profile']);
}
LOG::add("Enviando productos del perfil {$profile}");
if ($returnValue and !current_user_can( 'manage_woocommerce' ) ) { exit; }
$result = array(
'id' => 0,
'error' => false,
'message' => ''
);
$accounts = MiraviaCore::accounts_by_profile($profile);
$product = MiraviaCore::get_products_by_profile($profile, true);
$isOnlyStock = get_option('miravia_only_stock', '0') == '1';
if($product) {
foreach($accounts as $a) {
//Enviar los productos con cada una de las cuentas de usuario registrados en el profile.
//Comprobar el producto si no se ha enviado
foreach($product as $k => $p) {
if(MiraviaCore::check_product_onjob($p->id)) {
unset($product[$k]);
}
}
//Check after check on job
if(count($product) == 0) {
wp_send_json(array('error' => true, 'message' => 'All products is on job, please wait to complete this before send again.'));
wp_die();
}
$link = new MiraviaLink($a['token']);
$feed = new MiraviaFeed();
$feed->setProducts($product);
//Apply Rules
$feed = MiraviaCore::applyFilter($feed, $a['id'], $profile);
$stockJson = $feed->getJsonUpdateStock($isOnlyStock);
if(MIRAVIA_DEBUG == '1') {
wp_send_json($stockJson);
die();
}
$result = $link->updateStock($stockJson);
if(isset($result['feed_result']) and $result['feed_result']['success']) {
MiraviaCore::set_job_product(array_column($product, 'id'), $profile, $result['feed_result']['result']);
}
}
}
if($returnValue) {
wp_send_json($product);
wp_die();
}
}
function miravia_create_profile() {
$apiKey = sanitize_text_field($_REQUEST['api_key']);
$link = new MiraviaLink($apiKey);
$sellerInfo = $link->getSellerInfo(admin_url('admin-ajax.php?action=miravia_notify'));
if($sellerInfo) {
if(!MiraviaCore::get_accounts($sellerInfo['seller_id'], 'userid')) {
$profile = MiraviaCore::add_account(array(
'name' => $sellerInfo['seller_name'],
'token' => $apiKey,
'userid' => $sellerInfo['seller_id'],
'lang' => $sellerInfo['country'],
'email' => $sellerInfo['email'],
'config' => '{short_code: "'.$sellerInfo['short_code'].'"}',
));
}
}
wp_redirect( admin_url('admin.php?page=miravia_settings&subpage=accounts') );
wp_send_json(array('ok' => true));
}
function disconnect_product_miravia(){
if ( !current_user_can( 'manage_woocommerce' ) ) { exit; }
$id = $_POST['id'];
LOG::add("Desconectando producto {$id} de miravia");
update_post_meta($id, '_miravia_product_id', 0);
update_post_meta($id, '_miravia_sync_date', 0);
wp_send_json(array('ok' => true));
}
function miravia_authorize() {
LOG::add("Solicitando autorización a Miravia");
$link = new MiraviaLink();
$register_link = $link->getRegisterUrl(admin_url('admin-ajax.php?action=miravia_create_profile'));
LOG::add("Register link is " . $register_link);
wp_redirect( $register_link );
wp_send_json(array('ok' => true));
}
function miravia_upload_product() {
if ( !current_user_can( 'manage_woocommerce' ) ) { exit; }
$result = array(
'id' => 0,
'error' => false,
'message' => ''
);
$id = sanitize_text_field($_POST['id']);
$product = new MVProduct($id, 2);
wp_send_json($product);
wp_die();
$response = $product->send();
if(isset($response['item_id'])) {
//Producto subido
update_post_meta($id, '_miravia_product_id',$response['item_id']);
update_post_meta($id, '_miravia_sync_date',time());
$result['id'] = $response['item_id'];
}else{
$result['error'] = true;
$result['message'] = $response['errors'][0]['message'];
}
wp_send_json($result);
wp_die();
}
function miravia_update_product() {
if ( !current_user_can( 'manage_woocommerce' ) ) { exit; }
$result = array(
'id' => 0,
'error' => false,
'message' => ''
);
$id = sanitize_text_field($_POST['id']);
$product = new MVProduct($id);
$response = $product;
if(is_array($response) and count($response) == 0) {
//Producto subido
update_post_meta($id, '_miravia_sync_date',time());
$result['id'] = $id;
}else{
$result['error'] = true;
$result['message'] = $response['errors'][0]['message'];
}
wp_send_json($result);
wp_die();
}
}
$APIMIRAVIA = new APIMIRAVIA();
}