'Dashboard',
'products' => 'Products',
'excel' => 'Excel export',
'review' => 'Review',
'orders' => 'Orders',
'mapping' => 'Mapping',
'pricing' => 'Pricing',
'logs' => 'Logs',
'health' => 'Health',
'settings' => 'Settings',
);
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'menu' ), 60 );
add_filter( 'submenu_file', array( __CLASS__, 'current_submenu' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'assets' ) );
add_action( 'admin_post_okelsync_action', array( __CLASS__, 'handle' ) );
add_action( 'add_meta_boxes', array( __CLASS__, 'boxes' ) );
add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'save_product_box' ) );
add_action( 'woocommerce_process_shop_order_meta', array( __CLASS__, 'save_order_box' ), 40 );
add_filter( 'plugin_action_links_' . plugin_basename( OKELSYNC_FILE ), function ( $links ) {
array_unshift( $links, '' . esc_html__( 'Dashboard', 'okel-sync' ) . ' ' );
return $links;
} );
}
/** Its own top-level menu (right under WooCommerce) with one sub-page per screen. */
public static function menu() {
// same loop as the app logo (assets/logo.svg), cropped for the 20px menu slot; strokes keep their colours
$icon = 'data:image/svg+xml;base64,' . base64_encode( ' ' );
add_menu_page( 'Okel', 'Okel', 'manage_woocommerce', 'okelsync', array( __CLASS__, 'page' ), $icon, '55.6' );
foreach ( self::TABS as $tab => $label ) {
$slug = 'dashboard' === $tab ? 'okelsync' : 'admin.php?page=okelsync&tab=' . $tab;
add_submenu_page( 'okelsync', 'Okel · ' . $label, $label, 'manage_woocommerce', $slug, 'dashboard' === $tab ? array( __CLASS__, 'page' ) : '' );
}
}
/** Highlights the right sub-menu item for the current tab. */
public static function current_submenu( $submenu_file ) {
if ( isset( $_GET['page'] ) && 'okelsync' === $_GET['page'] && ! empty( $_GET['tab'] ) && 'dashboard' !== $_GET['tab'] ) { // phpcs:ignore WordPress.Security.NonceVerification
return 'admin.php?page=okelsync&tab=' . sanitize_key( $_GET['tab'] ); // phpcs:ignore WordPress.Security.NonceVerification
}
return $submenu_file;
}
public static function assets( $hook ) {
$screen = get_current_screen();
$ours = false !== strpos( (string) $hook, 'okelsync' ) || ( $screen && in_array( $screen->id, array( 'product', 'shop_order', 'woocommerce_page_wc-orders' ), true ) );
if ( $ours ) {
wp_enqueue_style( 'okelsync-admin', plugins_url( 'assets/admin.css', OKELSYNC_FILE ), array(), OKELSYNC_VERSION );
}
}
private static function url( $tab = 'dashboard', $args = array() ) {
return add_query_arg( array_merge( array( 'page' => 'okelsync', 'tab' => $tab ), $args ), admin_url( 'admin.php' ) );
}
private static function action_form( $do, $label, $fields = array(), $class = 'ls-btn', $confirm = '' ) {
echo '
';
}
private static function chip( $status ) {
$labels = array( 'synced' => 'Synced', 'pending' => 'Not listed', 'awaiting_approval' => 'Needs review', 'failed' => 'Needs fix', 'unmapped' => 'Map category', 'excluded' => 'Excluded', 'success' => 'OK', 'error' => 'Error', 'info' => 'Info', 'skipped' => 'Skipped', 'connected' => 'Connected', 'reauth_required' => 'Reconnect' );
$s = $status ? $status : 'pending';
return '' . esc_html( isset( $labels[ $s ] ) ? $labels[ $s ] : $s ) . ' ';
}
// ======================= page shell =======================
public static function page() {
$tab = isset( $_GET['tab'] ) && isset( self::TABS[ $_GET['tab'] ] ) ? sanitize_key( $_GET['tab'] ) : 'dashboard'; // phpcs:ignore WordPress.Security.NonceVerification
$shop = Okelsync_Store::shop();
echo 'Okel Woo ⇄ TikTok Shop
';
foreach ( self::TABS as $k => $label ) {
echo '' . esc_html( $label ) . ' ';
}
echo ' Connection ' . esc_html( ! empty( $shop['name'] ) ? $shop['name'] : 'Not connected' ) . ' ' . esc_html( 'cloud' === Okelsync_Store::get( 'mode' ) ? 'Cloud mode (Okel app)' : ( ! empty( $shop['expires_at'] ) ? sprintf( 'Token renews automatically · %dd left', max( 0, round( ( $shop['expires_at'] - time() ) / DAY_IN_SECONDS ) ) ) : 'Standalone mode' ) ) . '
';
if ( ! empty( $_GET['okelsync_error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
echo 'Something went wrong ' . esc_html( sanitize_text_field( wp_unslash( $_GET['okelsync_error'] ) ) ) . '
'; // phpcs:ignore WordPress.Security.NonceVerification
}
if ( ! empty( $_GET['okelsync_ok'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
echo 'Done.
';
}
call_user_func( array( __CLASS__, 'tab_' . $tab ) );
echo ' ';
}
private static function h1( $title, $sub = '' ) {
echo '' . esc_html( $title ) . ' ' . ( $sub ? '' . esc_html( $sub ) . '
' : '' ) . ' ';
}
private static function counts() {
global $wpdb;
$rows = $wpdb->get_results( "SELECT meta_value s, COUNT(*) n FROM {$wpdb->postmeta} WHERE meta_key = '_okelsync_status' GROUP BY meta_value", ARRAY_A );
$out = array();
foreach ( $rows as $r ) {
$out[ $r['s'] ] = (int) $r['n'];
}
return $out;
}
// ======================= tabs =======================
public static function tab_dashboard() {
global $wpdb;
$s = Okelsync_Store::get();
$shop = Okelsync_Store::shop();
$counts = self::counts();
$pending = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}okelsync_approvals WHERE status = 'pending'" );
$failed = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}okelsync_jobs WHERE status = 'failed'" );
$orders = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}okelsync_logs WHERE entity = 'order' AND status = 'success' AND message LIKE %s AND created_at > %s", 'Created order%', gmdate( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ) ) );
$maps = count( array_filter( (array) $s['category_map'], function ( $m ) {
return $m['tiktok_id'] && ( 'suggested' !== $m['source'] || $m['confidence'] >= 80 );
} ) );
$steps = array(
array( 'App keys entered', (bool) $s['app_key'] || 'cloud' === $s['mode'], 'settings' ),
array( 'Connect TikTok Shop', ! empty( $shop['access_token'] ) || 'cloud' === $s['mode'], 'settings' ),
array( 'Warehouse & carrier', (bool) $s['warehouse_id'], 'settings' ),
array( 'Map categories', $maps > 0, 'mapping' ),
array( 'First product synced', ! empty( $counts['synced'] ), 'products' ),
);
self::h1( 'Dashboard', 'woo_to_tiktok' === $s['direction'] ? 'WooCommerce is the catalogue master. Orders come in from TikTok automatically.' : 'TikTok is the catalogue master. Listings are imported into WooCommerce.' );
echo '';
foreach ( array( 'woo_to_tiktok' => 'Woo → TikTok', 'tiktok_to_woo' => 'TikTok → Woo' ) as $dir => $label ) {
self::action_form( 'set_direction', $label, array( 'direction' => $dir ), $s['direction'] === $dir ? 'ls-seg on' : 'ls-seg' );
}
echo '
';
self::action_form( 'sweep', 'Run Sweep', array(), 'ls-btn ls-pink' );
echo '
';
foreach ( array( array( 'Products live on TikTok', isset( $counts['synced'] ) ? $counts['synced'] : 0 ), array( 'TikTok orders · 30 days', $orders ), array( 'Changes to review', $pending ), array( 'Tasks needing attention', $failed ) ) as $k ) {
echo '
' . esc_html( $k[0] ) . ' ' . esc_html( $k[1] ) . '
';
}
echo '
';
if ( ! empty( $counts['failed'] ) || ! empty( $counts['unmapped'] ) ) {
echo '' . esc_html( ( isset( $counts['failed'] ) ? $counts['failed'] : 0 ) + ( isset( $counts['unmapped'] ) ? $counts['unmapped'] : 0 ) ) . ' product(s) need a fix Open Products . Each one says how to fix it.
';
}
self::logs_table( 8 );
}
public static function tab_products() {
$tiktok_first = 'tiktok_to_woo' === Okelsync_Store::get( 'direction' );
$view = isset( $_GET['view'] ) ? sanitize_key( $_GET['view'] ) : ( $tiktok_first ? 'tiktok' : 'woo' ); // phpcs:ignore WordPress.Security.NonceVerification
$views = $tiktok_first ? array( 'tiktok' => 'TikTok products', 'woo' => 'WooCommerce · import list' ) : array( 'woo' => 'WooCommerce products', 'tiktok' => 'TikTok listings · import' );
echo '' . esc_html( $tiktok_first ? 'Mode: TikTok → WooCommerce' : 'Mode: WooCommerce → TikTok' ) . ' · change it on the Dashboard ';
if ( 'tiktok' === $view ) {
self::products_tiktok( $tiktok_first );
} else {
self::products_woo();
}
}
private static function products_tiktok( $master ) {
self::h1( $master ? 'TikTok products' : 'TikTok listings', $master ? 'Your TikTok Shop is the catalogue master. Edit price or stock here (linked WooCommerce products update to match), and import listings into WooCommerce.' : 'Pick TikTok Shop listings to import into WooCommerce. Matching SKUs are linked instead of duplicated.' );
if ( ! okelsync_standalone() ) {
echo 'Connect TikTok in Settings (standalone mode) to see your TikTok listings here. In cloud mode, use the Okel app’s Products page. ';
return;
}
try {
$edit = isset( $_GET['edit'] ) ? sanitize_text_field( wp_unslash( $_GET['edit'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
if ( $edit ) {
self::listing_editor( $edit );
}
$page = Okelsync_Sync::tiktok_listings( isset( $_GET['pt'] ) ? sanitize_text_field( wp_unslash( $_GET['pt'] ) ) : null ); // phpcs:ignore WordPress.Security.NonceVerification
} catch ( Exception $e ) {
echo '' . esc_html( $e->getMessage() ) . ' ' . esc_html( isset( $e->hint ) ? $e->hint : '' ) . '
';
return;
}
$ids = array();
foreach ( $page['products'] as $tp ) {
if ( ! Okelsync_Sync::linked_parent( $tp['id'] ) ) {
$ids[] = $tp['id'];
}
}
echo ' ';
if ( $ids ) {
self::action_form( 'import_listings', 'Import all (' . count( $ids ) . ')', array( 'ids' => implode( ',', $ids ) ), 'ls-btn ls-pink' );
}
echo '
TikTok listing SKU Price Stock Action ';
foreach ( $page['products'] as $tp ) {
$sku = isset( $tp['skus'][0] ) ? $tp['skus'][0] : array();
$img = isset( $tp['main_images'][0]['urls'][0] ) ? $tp['main_images'][0]['urls'][0] : '';
$stock = 0;
foreach ( $tp['skus'] as $x ) {
$stock += isset( $x['inventory'][0]['quantity'] ) ? (int) $x['inventory'][0]['quantity'] : 0;
}
$parent = Okelsync_Sync::linked_parent( $tp['id'] );
echo '' . ( $img ? '
' : '
' ) . '
' . esc_html( $tp['title'] ) . ' ' . esc_html( $tp['id'] ) . '
';
echo '' . esc_html( isset( $sku['seller_sku'] ) ? $sku['seller_sku'] : '—' ) . '' . ( count( $tp['skus'] ) > 1 ? ' +' . (int) ( count( $tp['skus'] ) - 1 ) . ' ' : '' ) . ' ';
echo '' . esc_html( isset( $sku['price']['sale_price'] ) ? $sku['price']['sale_price'] : '—' ) . ' ' . (int) $stock . ' ';
echo 'Edit ';
if ( $parent ) {
echo '✓ In WooCommerce ';
} else {
self::action_form( 'import_listings', 'Import', array( 'ids' => $tp['id'] ), 'ls-btn ls-pink' );
}
echo ' ';
}
if ( ! $page['products'] ) {
echo 'No TikTok listings found. ';
}
echo '
';
if ( $page['next'] ) {
echo '';
}
}
private static function listing_editor( $id ) {
$tp = Okelsync_Sync::tiktok_listing( $id );
$parent = Okelsync_Sync::linked_parent( $id );
echo 'Edit: ' . esc_html( $tp['title'] ) . ' Close ';
echo '' . ( $parent ? 'Linked to WooCommerce: saving updates both TikTok and WooCommerce.' : 'Not in WooCommerce yet: saving changes TikTok only.' ) . '
';
echo ' ';
}
private static function products_woo() {
$status = isset( $_GET['status'] ) ? sanitize_key( $_GET['status'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
$paged = max( 1, isset( $_GET['paged'] ) ? (int) $_GET['paged'] : 1 ); // phpcs:ignore WordPress.Security.NonceVerification
$args = array( 'post_type' => 'product', 'post_status' => array( 'publish', 'private', 'draft' ), 'posts_per_page' => 25, 'paged' => $paged );
if ( $status ) {
$args['meta_query'] = array( array( 'key' => '_okelsync_status', 'value' => $status ) ); // phpcs:ignore WordPress.DB.SlowDBQuery
}
$q = new WP_Query( $args );
self::h1( 'Products', 'Every WooCommerce product with its TikTok status. Failures show the exact fix.' );
echo '';
self::action_form( 'link_tiktok', 'Link TikTok listings' );
self::action_form( 'push_all', 'Push all', array(), 'ls-btn ls-pink' );
echo '
';
}
// ======================= Excel export =======================
public static function tab_excel() {
self::h1( 'Excel export', 'Fill TikTok’s own bulk-upload file with your products. No TikTok app keys needed. Nothing is sent to TikTok: you check the file and upload it yourself.' );
$saved = Okelsync_Excel::saved();
echo '1. TikTok’s template In Seller Center open Products › Manage products › Bulk actions › Upload in bulk. Pick your category, download the template, then choose that file here.
';
echo '';
if ( $saved ) {
echo 'Using: ' . esc_html( $saved['name'] ) . '
';
}
echo ' ';
if ( ! $saved ) {
return;
}
try {
$tpl = Okelsync_Excel::inspect( $saved['path'] );
} catch ( Exception $e ) {
echo 'Something went wrong ' . esc_html( $e->getMessage() ) . '
';
return;
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only filters.
$tcat = isset( $_GET['tcat'] ) ? (int) $_GET['tcat'] : 0;
$wcat = isset( $_GET['wcat'] ) ? (int) $_GET['wcat'] : 0;
$paged = max( 1, isset( $_GET['paged'] ) ? (int) $_GET['paged'] : 1 );
// phpcs:enable
$tcat = isset( $tpl['categories'][ $tcat ] ) ? $tcat : 0;
if ( ! $tpl['categories'] ) {
echo 'This template has no category in it. Download it again with a category ticked.
';
return;
}
echo '';
$args = array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => 25, 'paged' => $paged );
if ( $wcat ) {
$args['tax_query'] = array( array( 'taxonomy' => 'product_cat', 'terms' => $wcat ) ); // phpcs:ignore WordPress.DB.SlowDBQuery
}
$q = new WP_Query( $args );
echo '';
}
/** Sends the filled template to the browser. Nonce and rights are checked in handle(). */
private static function excel_download() {
$saved = Okelsync_Excel::saved();
if ( ! $saved ) {
throw new Exception( 'Choose TikTok’s template again.' );
}
$tpl = Okelsync_Excel::inspect( $saved['path'] );
$i = (int) self::field( 'tcat' );
$ids = isset( $_POST['ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['ids'] ) ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Missing
$rows = array();
if ( ! isset( $tpl['categories'][ $i ] ) ) {
throw new Exception( 'Choose the TikTok category again.' );
}
foreach ( array_filter( $ids ) as $id ) {
$p = wc_get_product( $id );
if ( ! $p || 'publish' !== $p->get_status() ) {
continue;
}
list( $r, $stop ) = Okelsync_Excel::build( $p, $tpl, $tpl['categories'][ $i ], true );
if ( ! $stop ) {
$rows = array_merge( $rows, $r );
}
}
if ( ! $rows ) {
throw new Exception( 'Tick at least one product that has no red message.' );
}
$file = Okelsync_Excel::write( $saved['path'], $tpl, $rows );
nocache_headers();
header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' );
header( 'Content-Disposition: attachment; filename="tiktok-upload-' . gmdate( 'Y-m-d' ) . '.xlsx"' );
header( 'Content-Length: ' . filesize( $file ) );
readfile( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
wp_delete_file( $file );
exit;
}
public static function tab_review() {
global $wpdb;
$rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}okelsync_approvals WHERE status = 'pending' ORDER BY id DESC LIMIT 200", ARRAY_A );
self::h1( 'Review queue', 'New listings, images and variant changes wait here. Nothing reaches TikTok until you approve it.' );
if ( $rows ) {
echo '';
self::action_form( 'approve_all', 'Approve all', array(), 'ls-btn ls-dark' );
self::action_form( 'reject_all', 'Reject all' );
echo '
';
}
$labels = array( 'create' => 'List new product', 'title' => 'Title', 'description' => 'Description', 'images' => 'Images', 'price' => 'Price', 'stock' => 'Stock', 'variants' => 'Variants / category' );
foreach ( $rows as $r ) {
$p = wc_get_product( $r['product_id'] );
echo '' . esc_html( $p ? $p->get_name() : '#' . $r['product_id'] ) . ' ' . esc_html( isset( $labels[ $r['field'] ] ) ? $labels[ $r['field'] ] : $r['field'] ) . ' ';
self::action_form( 'approve', 'Approve', array( 'id' => $r['id'] ), 'ls-btn ls-dark' );
self::action_form( 'reject', 'Reject', array( 'id' => $r['id'] ) );
echo '
TikTok now ' . self::render_value( json_decode( $r['old_value'], true ), $r['field'] ) . '
After approval ' . self::render_value( json_decode( $r['new_value'], true ), $r['field'] ) . '
'; // phpcs:ignore WordPress.Security.EscapeOutput
}
if ( ! $rows ) {
echo 'All clear. Changes that need your OK appear here. ';
}
}
private static function render_value( $v, $field ) {
if ( null === $v ) {
return 'Not on TikTok yet
';
}
if ( 'images' === $field && is_array( $v ) ) {
$o = '';
foreach ( $v as $src ) {
$o .= ' ';
}
return $o;
}
if ( 'description' === $field ) {
return '' . wp_kses_post( $v ) . '
';
}
if ( is_array( $v ) ) {
return '' . esc_html( wp_json_encode( $v, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ) . ' ';
}
return '' . esc_html( $v ) . '
';
}
public static function tab_orders() {
$orders = wc_get_orders( array( 'limit' => 50, 'meta_key' => '_okelsync_order_id', 'meta_compare' => 'EXISTS', 'orderby' => 'date', 'order' => 'DESC' ) ); // phpcs:ignore WordPress.DB.SlowDBQuery
self::h1( 'Orders', 'TikTok orders become WooCommerce orders automatically. Add tracking in the order\'s Okel box and it goes back to TikTok.' );
echo '';
self::action_form( 'poll', 'Check for orders' );
echo '
TikTok order WooCommerce Status Total Tracking ';
foreach ( $orders as $o ) {
$t = Okelsync_Sync::tracking_of( $o );
echo '' . esc_html( $o->get_meta( '_okelsync_order_id' ) ) . ' ' . esc_html( $o->get_date_created() ? $o->get_date_created()->date_i18n( 'j M Y H:i' ) : '' ) . ' #' . (int) $o->get_id() . ' ' . esc_html( wc_get_order_status_name( $o->get_status() ) ) . ' ' . wp_kses_post( $o->get_formatted_order_total() ) . ' ' . ( $t ? esc_html( $t[0] ) . ( $o->get_meta( '_okelsync_tracking_pushed' ) ? ' ' . self::chip( 'synced' ) : '' ) : ( 'TIKTOK' === $o->get_meta( '_okelsync_shipping_type' ) ? 'TikTok shipping' : 'Add tracking ' ) ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput
}
if ( ! $orders ) {
echo 'No TikTok orders yet. ';
}
echo '
';
}
public static function tab_mapping() {
$map = Okelsync_Store::get( 'category_map' );
$terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => true ) );
$paths = array();
$error = '';
try {
if ( okelsync_standalone() ) {
$paths = Okelsync_Sync::leaf_paths();
}
} catch ( Exception $e ) {
$error = $e->getMessage() . ' — ' . ( isset( $e->hint ) ? $e->hint : '' );
}
self::h1( 'Category mapping', 'Matches of 80% or more are used automatically. Accept or pick the rest.' );
if ( $error ) {
echo 'Could not load TikTok categories ' . esc_html( $error ) . '
';
}
echo '';
self::action_form( 'suggest', 'Re-suggest' );
self::action_form( 'accept_all', 'Accept all suggestions', array(), 'ls-btn ls-dark' );
echo '
';
foreach ( $paths as $c ) {
echo '';
}
echo ' WooCommerce category TikTok category Match Change ';
foreach ( (array) $terms as $t ) {
$m = isset( $map[ (string) $t->term_id ] ) ? $map[ (string) $t->term_id ] : null;
echo '' . esc_html( $t->name ) . ' ' . (int) $t->count . ' products ' . ( $m && $m['tiktok_id'] ? esc_html( $m['name'] ) : 'Not mapped ' ) . ' ' . ( $m ? esc_html( 'manual' === $m['source'] ? 'Chosen by you' : ( 'accepted' === $m['source'] ? 'Accepted' : $m['confidence'] . '%' ) ) : '' ) . ' ';
if ( $m && $m['tiktok_id'] ) {
echo 'Attributes ';
}
echo ' ';
}
echo '
';
$attrs_for = isset( $_GET['attrs'] ) ? sanitize_text_field( wp_unslash( $_GET['attrs'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
if ( $attrs_for && okelsync_standalone() ) {
$defaults = Okelsync_Store::get( 'attr_defaults' );
echo 'Attributes for category ' . esc_html( $attrs_for ) . ' The WooCommerce attribute with the same name is used first, then this default.
';
}
}
public static function tab_pricing() {
$rules = (array) Okelsync_Store::get( 'pricing_rules' );
self::h1( 'Pricing rules', 'Most specific wins: product › tag › category › all products. A push is blocked, never silently changed, if it breaks your minimum margin.' );
echo 'Applies to Rule Rounding Min margin ';
foreach ( $rules as $i => $r ) {
echo '' . esc_html( $r['scope'] . ( $r['scope_value'] ? ' = ' . $r['scope_value'] : '' ) ) . ' ' . esc_html( $r['type'] . ' ' . $r['value'] . ( 'fx' === $r['type'] ? ' × ' . $r['fx_rate'] : '' ) ) . ' ' . esc_html( $r['rounding'] ) . ' ' . esc_html( '' === (string) $r['min_margin'] ? '—' : $r['min_margin'] . '%' ) . ' ';
self::action_form( 'rule_delete', 'Delete', array( 'i' => $i ) );
echo ' ';
}
if ( ! $rules ) {
echo 'No rules: TikTok uses your WooCommerce prices. ';
}
echo '
';
}
private static function logs_table( $limit = 100 ) {
global $wpdb;
$logs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}okelsync_logs ORDER BY id DESC LIMIT %d", $limit ), ARRAY_A );
echo 'When Direction Result What happened Code ';
foreach ( $logs as $l ) {
$dir = array( 'woo_to_tiktok' => 'Woo → TikTok', 'tiktok_to_woo' => 'TikTok → Woo', 'system' => 'System' );
echo '' . esc_html( human_time_diff( strtotime( $l['created_at'] . ' UTC' ) ) ) . ' ago ' . esc_html( isset( $dir[ $l['direction'] ] ) ? $dir[ $l['direction'] ] : $l['direction'] ) . ' ' . self::chip( $l['status'] ) . ' ' . esc_html( $l['message'] ) . ( $l['hint'] && 'error' === $l['status'] ? 'Fix: ' . esc_html( $l['hint'] ) . ' ' : '' ) . ' ' . esc_html( (string) $l['code'] ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput
}
if ( ! $logs ) {
echo 'No activity yet. ';
}
echo '
';
}
public static function tab_logs() {
global $wpdb;
$failed = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}okelsync_jobs WHERE status = 'failed' ORDER BY id DESC LIMIT 100", ARRAY_A );
self::h1( 'Logs', 'Every sync in plain English. Failed tasks keep the reason and the fix.' );
if ( $failed ) {
echo '
Needs attention (' . count( $failed ) . ') ';
self::action_form( 'retry_all', 'Retry all', array(), 'ls-btn ls-dark' );
echo '';
foreach ( $failed as $j ) {
echo '' . esc_html( $j['type'] ) . ' ' . (int) $j['attempts'] . ' attempt(s) ';
self::action_form( 'retry', 'Retry', array( 'id' => $j['id'] ) );
echo '
' . esc_html( $j['last_error'] ) . '
How to fix: ' . esc_html( $j['hint'] ) . '
';
}
echo ' ';
}
self::logs_table();
}
public static function tab_health() {
$s = Okelsync_Store::get();
$shop = Okelsync_Store::shop();
$checks = array(
array( 'WooCommerce', true, 'WooCommerce ' . WC()->version . ' · ' . get_woocommerce_currency(), '' ),
array( 'HTTPS', is_ssl() || 0 === strpos( home_url(), 'https' ), home_url(), 'TikTok webhooks need HTTPS on your site.' ),
array( 'Action Scheduler', function_exists( 'as_schedule_single_action' ), 'Background tasks', 'Update WooCommerce: it ships Action Scheduler.' ),
array( 'WP-Cron', ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ), defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ? 'Disabled: make sure a real cron calls wp-cron.php every minute' : 'Running', 'Set up a server cron for wp-cron.php.' ),
array( 'Mode', true, 'cloud' === $s['mode'] ? 'Cloud (the Okel app does the syncing)' : 'Standalone (this plugin does the syncing)', '' ),
);
if ( 'standalone' === $s['mode'] ) {
$checks[] = array( 'TikTok app keys', (bool) $s['app_key'], $s['app_key'] ? 'Entered' : 'Missing', 'Enter App Key/Secret in Settings.' );
$checks[] = array( 'TikTok Shop', ! empty( $shop['access_token'] ) && 'connected' === ( isset( $shop['status'] ) ? $shop['status'] : '' ), ! empty( $shop['name'] ) ? $shop['name'] . ' · ' . ( isset( $shop['status'] ) ? $shop['status'] : '' ) : 'Not connected', 'Click "Connect TikTok Shop" in Settings.' );
$checks[] = array( 'Webhook URL', true, rest_url( 'okelsync/v1/webhook' ), '' );
} else {
$checks[] = array( 'Cloud link', $s['cloud_endpoint'] && $s['cloud_token'], $s['cloud_endpoint'] ? $s['cloud_endpoint'] : 'Not set', 'Paste the endpoint and token from the Okel app › Settings › WordPress plugin.' );
}
$others = array();
foreach ( (array) get_option( 'active_plugins', array() ) as $pl ) {
if ( preg_match( '/tiktok/i', $pl ) && false === strpos( $pl, 'okel-sync' ) ) {
$others[] = $pl;
}
}
$checks[] = array( 'Other TikTok plugins', ! $others, $others ? implode( ', ', $others ) : 'None', 'Two TikTok connectors syncing the same shop will overwrite each other. Disable sync in the other one.' );
self::h1( 'Health check' );
echo '';
foreach ( $checks as $c ) {
echo '' . esc_html( $c[0] ) . ' ' . esc_html( $c[2] ) . ' ' . ( ! $c[1] && $c[3] ? 'Fix: ' . esc_html( $c[3] ) . ' ' : '' ) . ' ';
}
echo ' ';
}
public static function tab_settings() {
$s = Okelsync_Store::get();
$shop = Okelsync_Store::shop();
self::h1( 'Settings' );
echo '';
if ( 'standalone' === $s['mode'] && $s['app_key'] ) {
echo '';
self::action_form( 'connect', ! empty( $shop['access_token'] ) ? 'Reconnect TikTok' : 'Connect TikTok Shop', array(), 'ls-btn ls-pink' );
if ( ! empty( $shop['access_token'] ) ) {
self::action_form( 'disconnect', 'Disconnect', array(), 'ls-btn', 'Disconnect TikTok? Listings on TikTok stay as they are.' );
}
echo '
';
}
}
/** A sanitised text field from the submitted form ('' when absent). Nonce is checked in handle(). */
private static function field( $key ) {
return isset( $_POST[ $key ] ) ? sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
}
// ======================= actions =======================
public static function handle() {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_die( 'forbidden' );
}
check_admin_referer( 'okelsync_action' );
global $wpdb;
$do = isset( $_POST['do'] ) ? sanitize_key( $_POST['do'] ) : '';
$back = wp_get_referer() ? wp_get_referer() : self::url();
$back = remove_query_arg( array( 'okelsync_ok', 'okelsync_error' ), $back );
$at = $wpdb->prefix . 'okelsync_approvals';
try {
switch ( $do ) {
case 'sweep':
Okelsync_Store::enqueue( 'sweep.run', array(), 'sweep.run' );
break;
case 'set_direction':
$dir = isset( $_POST['direction'] ) && 'tiktok_to_woo' === $_POST['direction'] ? 'tiktok_to_woo' : 'woo_to_tiktok';
Okelsync_Store::update( array( 'direction' => $dir ) );
break;
case 'import_listings':
foreach ( array_filter( array_map( 'sanitize_text_field', explode( ',', self::field( 'ids' ) ) ) ) as $lid ) {
Okelsync_Store::enqueue( 'listing.import', array( 'id' => $lid ), 'listing.import:' . $lid );
}
break;
case 'listing_save':
$lid = sanitize_text_field( wp_unslash( isset( $_POST['id'] ) ? $_POST['id'] : '' ) );
$raw = isset( $_POST['skus'] ) ? (array) wp_unslash( $_POST['skus'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$skus = array();
foreach ( $raw as $sku_id => $v ) {
$skus[ sanitize_text_field( $sku_id ) ] = array( 'price' => isset( $v['price'] ) ? sanitize_text_field( $v['price'] ) : '', 'stock' => isset( $v['stock'] ) ? sanitize_text_field( $v['stock'] ) : '' );
}
Okelsync_Sync::save_listing( $lid, $skus );
$back = remove_query_arg( 'edit', $back );
break;
case 'push_all':
foreach ( get_posts( array( 'post_type' => 'product', 'numberposts' => -1, 'fields' => 'ids', 'post_status' => array( 'publish', 'private' ) ) ) as $id ) {
Okelsync_Store::enqueue( 'product.push', array( 'id' => $id, 'approved' => array( 'all' ) ), 'product.push:' . $id );
}
break;
case 'push_selected':
foreach ( array_map( 'intval', isset( $_POST['ids'] ) ? (array) $_POST['ids'] : array() ) as $id ) {
Okelsync_Store::enqueue( 'product.push', array( 'id' => $id, 'approved' => array( 'all' ) ), 'product.push:' . $id );
}
break;
case 'link_tiktok':
Okelsync_Store::enqueue( 'reverse.import', array(), 'reverse.import' );
break;
case 'poll':
Okelsync_Store::enqueue( 'orders.poll', array(), 'orders.poll' );
break;
case 'approve':
case 'reject':
case 'approve_all':
case 'reject_all':
$ids = in_array( $do, array( 'approve', 'reject' ), true ) ? array( (int) $_POST['id'] ) : array_map( 'intval', $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE status = %s', $at, 'pending' ) ) );
$rows = array();
foreach ( $ids as $approval_id ) {
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d AND status = %s', $at, $approval_id, 'pending' ), ARRAY_A );
if ( $row ) {
$rows[] = $row;
}
}
if ( 0 === strpos( $do, 'reject' ) ) {
foreach ( $rows as $r ) {
$wpdb->update( $at, array( 'status' => 'rejected' ), array( 'id' => $r['id'] ) );
if ( 'create' === $r['field'] ) {
update_post_meta( $r['product_id'], '_okelsync_status', 'excluded' );
}
}
} else {
$by = array();
foreach ( $rows as $r ) {
$by[ $r['product_id'] ][] = 'create' === $r['field'] ? 'all' : $r['field'];
}
foreach ( $by as $pid => $fields ) {
Okelsync_Store::enqueue( 'product.push', array( 'id' => $pid, 'approved' => $fields ), 'product.push:' . $pid );
}
}
break;
case 'suggest':
Okelsync_Store::enqueue( 'mapping.suggest', array(), 'mapping.suggest' );
break;
case 'accept_all':
$map = Okelsync_Store::get( 'category_map' );
foreach ( $map as &$m ) {
if ( 'suggested' === $m['source'] && $m['tiktok_id'] ) {
$m['source'] = 'accepted';
}
}
unset( $m );
Okelsync_Store::update( array( 'category_map' => $map ) );
break;
case 'map':
$raw = isset( $_POST['tiktok'] ) ? sanitize_text_field( wp_unslash( $_POST['tiktok'] ) ) : '';
list( $id, $path ) = array_map( 'trim', array_pad( explode( '|', $raw, 2 ), 2, '' ) );
if ( ! ctype_digit( $id ) ) {
throw new Okelsync_Fix_Required( 'Pick a category from the list', 'Start typing, then choose a suggestion.' );
}
$map = Okelsync_Store::get( 'category_map' );
$map[ (string) (int) self::field( 'woo' ) ] = array( 'tiktok_id' => $id, 'name' => $path, 'confidence' => 100, 'source' => 'manual', 'woo_name' => sanitize_text_field( wp_unslash( isset( $_POST['woo_name'] ) ? $_POST['woo_name'] : '' ) ) );
Okelsync_Store::update( array( 'category_map' => $map ) );
break;
case 'attr_defaults':
$all = Okelsync_Store::get( 'attr_defaults' );
$cat = self::field( 'cat' );
$all[ $cat ] = array_filter( array_map( 'sanitize_text_field', wp_unslash( isset( $_POST['d'] ) ? (array) $_POST['d'] : array() ) ) );
Okelsync_Store::update( array( 'attr_defaults' => $all ) );
break;
case 'rule_add':
$rules = (array) Okelsync_Store::get( 'pricing_rules' );
$rules[] = array(
'scope' => sanitize_key( self::field( 'scope' ) ),
'scope_value' => self::field( 'scope_value' ),
'type' => sanitize_key( self::field( 'type' ) ),
'value' => (float) self::field( 'value' ),
'fx_rate' => (float) self::field( 'fx_rate' ),
'rounding' => sanitize_key( self::field( 'rounding' ) ),
'min_margin' => '' === self::field( 'min_margin' ) ? '' : (float) self::field( 'min_margin' ),
'priority' => (int) self::field( 'priority' ),
'enabled' => 1,
);
Okelsync_Store::update( array( 'pricing_rules' => $rules ) );
break;
case 'rule_delete':
$rules = (array) Okelsync_Store::get( 'pricing_rules' );
unset( $rules[ (int) $_POST['i'] ] );
Okelsync_Store::update( array( 'pricing_rules' => array_values( $rules ) ) );
break;
case 'retry':
Okelsync_Store::retry( (int) $_POST['id'] );
break;
case 'retry_all':
foreach ( $wpdb->get_col( "SELECT id FROM {$wpdb->prefix}okelsync_jobs WHERE status = 'failed'" ) as $id ) {
Okelsync_Store::retry( $id );
}
break;
case 'save_settings':
$patch = array();
foreach ( array( 'mode', 'app_key', 'service_id', 'cloud_endpoint', 'direction', 'inventory_source', 'shipped_status', 'warehouse_id', 'default_carrier' ) as $k ) {
$patch[ $k ] = isset( $_POST[ $k ] ) ? sanitize_text_field( wp_unslash( $_POST[ $k ] ) ) : '';
}
$patch['stock_buffer'] = max( 0, (int) self::field( 'stock_buffer' ) );
$patch['own_brand'] = isset( $_POST['own_brand'] ) ? sanitize_text_field( wp_unslash( $_POST['own_brand'] ) ) : '';
$patch['brand_words'] = isset( $_POST['brand_words'] ) ? sanitize_textarea_field( wp_unslash( $_POST['brand_words'] ) ) : '';
foreach ( array( 'sync_products', 'sync_inventory', 'sync_prices', 'sync_orders', 'sync_fulfillment', 'zero_stock_inactive', 'auto_new', 'auto_title', 'auto_description', 'auto_price', 'auto_stock', 'auto_images', 'auto_variants', 'square_images', 'fill_descriptions' ) as $k ) {
$patch[ $k ] = empty( $_POST[ $k ] ) ? 0 : 1;
}
if ( ! empty( $_POST['app_secret'] ) ) {
$patch['app_secret'] = Okelsync_Store::encrypt( sanitize_text_field( wp_unslash( $_POST['app_secret'] ) ) );
}
if ( ! empty( $_POST['cloud_token'] ) ) {
$patch['cloud_token'] = Okelsync_Store::encrypt( sanitize_text_field( wp_unslash( $_POST['cloud_token'] ) ) );
}
Okelsync_Store::update( $patch );
break;
case 'excel_template':
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- checked by is_uploaded_file() and Okelsync_Excel::remember().
$tmp = isset( $_FILES['template']['tmp_name'] ) ? $_FILES['template']['tmp_name'] : '';
if ( ! is_string( $tmp ) || ! is_uploaded_file( $tmp ) ) {
throw new Exception( 'Choose the template file first.' );
}
Okelsync_Excel::remember( $tmp, sanitize_file_name( wp_unslash( $_FILES['template']['name'] ) ) );
// phpcs:enable
$back = self::url( 'excel' );
break;
case 'excel_download':
self::excel_download();
break;
case 'connect':
$state = wp_generate_password( 24, false );
set_transient( 'okelsync_state_' . get_current_user_id(), $state, HOUR_IN_SECONDS );
wp_redirect( Okelsync_Store::client()->authorize_url( Okelsync_Store::get( 'service_id' ), $state ) ); // phpcs:ignore WordPress.Security.SafeRedirect
exit;
case 'disconnect':
delete_option( 'okelsync_shop' );
break;
}
wp_safe_redirect( add_query_arg( 'okelsync_ok', 1, $back ) );
} catch ( Exception $e ) {
wp_safe_redirect( add_query_arg( 'okelsync_error', rawurlencode( $e->getMessage() . ( isset( $e->hint ) ? ' — ' . $e->hint : '' ) ), $back ) );
}
exit;
}
// ======================= meta boxes =======================
public static function boxes() {
add_meta_box( 'okelsync-product', 'Okel · TikTok', array( __CLASS__, 'product_box' ), 'product', 'side', 'default' );
$screen = function_exists( 'wc_get_page_screen_id' ) ? wc_get_page_screen_id( 'shop-order' ) : 'shop_order';
add_meta_box( 'okelsync-order', 'Okel · TikTok tracking', array( __CLASS__, 'order_box' ), $screen, 'side', 'high' );
}
public static function product_box( $post ) {
$id = $post->ID;
wp_nonce_field( 'okelsync_product', 'okelsync_product_nonce' );
echo '' . self::chip( get_post_meta( $id, '_okelsync_status', true ) ) . ( get_post_meta( $id, '_okelsync_tiktok_id', true ) ? ' TikTok ID ' . esc_html( get_post_meta( $id, '_okelsync_tiktok_id', true ) ) . ' ' : '' ) . '
'; // phpcs:ignore WordPress.Security.EscapeOutput
$hint = get_post_meta( $id, '_okelsync_hint', true );
if ( $hint ) {
echo '
How to fix: ' . esc_html( $hint ) . '
';
}
$shop = Okelsync_Store::shop();
$product = wc_get_product( $id );
if ( $product && ! empty( $shop['access_token'] ) && 'yes' !== get_post_meta( $id, '_okelsync_exclude', true ) ) {
try {
$desired = Okelsync_Sync::build_desired( $product );
$tips = isset( $desired[3] ) ? $desired[3] : array();
// blocking problems first, then advisory tips
foreach ( array_reverse( $desired[1] ) as $issue ) {
array_unshift( $tips, $issue[1] . '. ' . $issue[2] );
}
if ( $tips ) {
echo '
Approval tips ' . implode( ' ', array_map( 'esc_html', $tips ) ) . ' '; // phpcs:ignore WordPress.Security.EscapeOutput
}
} catch ( Exception $e ) {
unset( $e ); // tips are advisory
}
}
echo '
Don\'t sell on TikTok
';
echo '
TikTok title
';
echo '
TikTok price
';
echo '
Cost price (for margin checks)
';
echo '
TikTok category ID (optional)
';
}
public static function save_product_box( $id ) {
if ( ! isset( $_POST['okelsync_product_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['okelsync_product_nonce'] ) ), 'okelsync_product' ) || ! current_user_can( 'edit_product', $id ) ) {
return;
}
update_post_meta( $id, '_okelsync_exclude', empty( $_POST['_okelsync_exclude'] ) ? 'no' : 'yes' );
foreach ( array( '_okelsync_title', '_okelsync_price', '_okelsync_cost', '_okelsync_category' ) as $k ) {
update_post_meta( $id, $k, isset( $_POST[ $k ] ) ? sanitize_text_field( wp_unslash( $_POST[ $k ] ) ) : '' );
}
}
public static function order_box( $post_or_order ) {
$order = $post_or_order instanceof WC_Order ? $post_or_order : wc_get_order( $post_or_order->ID );
if ( ! $order ) {
return;
}
$tid = $order->get_meta( '_okelsync_order_id' );
if ( ! $tid ) {
echo 'Not a TikTok Shop order.
';
return;
}
wp_nonce_field( 'okelsync_order', 'okelsync_order_nonce' );
echo 'TikTok order ' . esc_html( $tid ) . '
';
if ( 'TIKTOK' === $order->get_meta( '_okelsync_shipping_type' ) ) {
echo '
TikTok ships this order. Print the label in Seller Center; completing this order marks the package shipped.
';
return;
}
$providers = array();
if ( okelsync_standalone() ) {
try {
$opt = $order->get_meta( '_okelsync_delivery_option' );
$providers = Okelsync_Sync::providers( $opt ? $opt : 'default' );
} catch ( Exception $e ) {
$providers = array();
}
}
echo 'Tracking number
Carrier ';
if ( $providers ) {
echo 'Default carrier ';
foreach ( $providers as $p ) {
echo 'get_meta( '_okelsync_provider_id' ), $p['id'], false ) . '>' . esc_html( $p['name'] ) . ' ';
}
echo ' ';
} else {
echo ' ';
}
echo '
Supplier tracking (dropshipping)
';
$pushed = $order->get_meta( '_okelsync_tracking_pushed' );
echo '' . ( $pushed ? 'Sent to TikTok: ' . esc_html( $pushed ) : 'Saved tracking is sent to TikTok automatically.' ) . '
';
}
public static function save_order_box( $order_id ) {
if ( ! isset( $_POST['okelsync_order_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['okelsync_order_nonce'] ) ), 'okelsync_order' ) || ! current_user_can( 'edit_shop_orders' ) ) {
return;
}
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
foreach ( array( '_okelsync_tracking_number', '_okelsync_carrier', '_okelsync_provider_id', '_okelsync_supplier_tracking' ) as $k ) {
if ( isset( $_POST[ $k ] ) ) {
$order->update_meta_data( $k, sanitize_text_field( wp_unslash( $_POST[ $k ] ) ) );
}
}
if ( ! empty( $_POST['_okelsync_provider_id'] ) && okelsync_standalone() ) {
foreach ( Okelsync_Sync::providers( $order->get_meta( '_okelsync_delivery_option' ) ? $order->get_meta( '_okelsync_delivery_option' ) : 'default' ) as $p ) {
if ( $p['id'] === $_POST['_okelsync_provider_id'] ) {
$order->update_meta_data( '_okelsync_carrier', $p['name'] );
}
}
}
$order->save();
}
}