false,
'remote_publication' => false,
'remote_catalog_management' => false,
'order_sync' => false,
'cart_recovery' => false,
'recovery_delay_minutes' => 60,
'last_catalog_sync' => '',
'last_catalog_count' => 0,
'last_shoppungpung_sync' => '',
'last_shoppungpung_error' => '',
'last_order_sync' => '',
'last_cart_sync' => '',
'last_error' => '',
];
}
public static function settings() {
$stored = get_option(self::OPTION, []);
return wp_parse_args(is_array($stored) ? $stored : [], self::defaults());
}
private static function dependencies_ready() {
return class_exists('WooCommerce')
&& function_exists('aismart_content_chat_get_connection')
&& !empty(aismart_content_chat_get_connection()['connected']);
}
public static function dependency_notice() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only: picks the admin screen that shows this notice.
if (!current_user_can('activate_plugins') || !isset($_GET['page']) || strpos(sanitize_key(wp_unslash($_GET['page'])), 'aismart-content-commerce') !== 0) {
return;
}
if (!class_exists('WooCommerce')) {
echo '
AISmart Content Commerce requires WooCommerce.
';
} elseif (!function_exists('aismart_content_chat_get_connection')) {
echo 'AISmart Content Commerce requires the AISmart Content Chat plugin.
';
} elseif (empty(aismart_content_chat_get_connection()['connected'])) {
echo 'Connect AISmart Content Chat before synchronizing commerce data.
';
}
}
public static function admin_menu() {
if (!class_exists('WooCommerce')) {
return;
}
$parent = 'woocommerce';
add_submenu_page($parent, 'AISmart Content Commerce', 'AISmart Content Commerce', 'manage_woocommerce', 'aismart-content-commerce', [__CLASS__, 'commerce_page']);
add_submenu_page($parent, 'Catalog Sync', 'Catalog Sync', 'manage_woocommerce', 'aismart-content-commerce-catalog', [__CLASS__, 'catalog_page']);
add_submenu_page($parent, 'Orders & Conversations', 'Orders & Conversations', 'manage_woocommerce', 'aismart-content-commerce-orders', [__CLASS__, 'orders_page']);
add_submenu_page($parent, 'Cart Recovery', 'Cart Recovery', 'manage_woocommerce', 'aismart-content-commerce-recovery', [__CLASS__, 'recovery_page']);
}
public static function admin_assets($hook) {
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
if (strpos((string) $hook, 'aismart-content-commerce') === false && ($screen->id ?? '') !== 'edit-product') {
return;
}
wp_enqueue_style('aismart-content-commerce-admin', plugins_url('assets/admin.css', __FILE__), [], self::VERSION);
}
public static function plugin_action_links($links) {
array_unshift($links, 'Settings');
return $links;
}
public static function studio_plugin_manifest($plugins) {
$plugins = is_array($plugins) ? $plugins : [];
$plugins['aismart-content-commerce'] = [
'name' => 'AISmart Content Commerce',
'version' => self::VERSION,
'connected' => self::dependencies_ready(),
'settings_url' => admin_url('admin.php?page=aismart-content-commerce'),
];
return $plugins;
}
private static function assert_manager($action) {
if (!current_user_can('manage_woocommerce')) {
wp_die(esc_html__('You are not allowed to manage AISmart Content Commerce.', 'aismart-content-commerce'));
}
check_admin_referer($action);
}
private static function redirect_notice($page, $notice, $message = '') {
if ($message !== '') {
set_transient('aismart_content_commerce_notice_' . get_current_user_id(), sanitize_text_field($message), 60);
}
wp_safe_redirect(add_query_arg([
'page' => sanitize_key($page),
'aismart_content_commerce_notice' => sanitize_key($notice),
], admin_url('admin.php')));
exit;
}
public static function save_settings() {
if (!current_user_can('manage_woocommerce')) {
wp_die(esc_html__('You are not allowed to manage AISmart Content Commerce.', 'aismart-content-commerce'));
}
check_admin_referer('aismart_content_commerce_save');
$settings = self::settings();
$settings['catalog_sync'] = isset($_POST['catalog_sync']);
$settings['remote_publication'] = isset($_POST['remote_publication']);
$settings['remote_catalog_management'] = isset($_POST['remote_catalog_management']);
$settings['order_sync'] = isset($_POST['order_sync']);
$settings['cart_recovery'] = isset($_POST['cart_recovery']);
$settings['recovery_delay_minutes'] = max(5, min(10080, absint($_POST['recovery_delay_minutes'] ?? 60)));
update_option(self::OPTION, $settings, false);
self::redirect_notice('aismart-content-commerce', 'saved');
}
public static function publication_routes() {
register_rest_route('telewhats-woocommerce/v1', '/capabilities', [
'methods' => 'GET', 'permission_callback' => '__return_true',
'callback' => static function () {
return ['version' => self::VERSION, 'currency' => get_woocommerce_currency(),
'catalogManagement' => self::dependencies_ready() && !empty(self::settings()['remote_catalog_management']),
'publication' => self::dependencies_ready()
&& !empty(self::settings()['remote_publication'])];
},
]);
register_rest_route('telewhats-woocommerce/v1', '/publication', [
'methods' => 'POST', 'permission_callback' => [__CLASS__, 'verify_publication_command'],
'callback' => [__CLASS__, 'apply_publication_command'],
]);
}
public static function verify_publication_command($request) {
if (!self::dependencies_ready() || empty(self::settings()['remote_publication'])) {
return new WP_Error('telewhats_publication_disabled', 'Remote publication is not enabled.', ['status' => 403]);
}
$token = (string) $request->get_param('command');
if ($token === '' || strlen($token) > 6000) {
return new WP_Error('telewhats_publication_invalid', 'Publication command is invalid.', ['status' => 403]);
}
$verified = aismart_content_chat_api_request('POST', 'api/integrations/webchat/wordpress/commerce/publication/verify', ['command' => $token]);
if (is_wp_error($verified) || !is_array($verified) || empty($verified['productId'])
|| !isset($verified['published']) || !is_bool($verified['published'])
|| !preg_match('/^[a-f0-9-]{36}$/', (string) ($verified['operationId'] ?? ''))) {
return new WP_Error('telewhats_publication_invalid', 'Publication command could not be verified.', ['status' => 403]);
}
self::$publication_commands[$token] = $verified;
return true;
}
public static function apply_publication_command($request) {
$token = (string) $request->get_param('command');
$command = self::$publication_commands[$token] ?? null;
if (!$command) return new WP_Error('telewhats_publication_invalid', 'Publication command was not verified.', ['status' => 403]);
$product = wc_get_product((int) $command['productId']);
if (!$product || $product->is_type('variation') || $product->get_status() === 'trash') {
return new WP_Error('telewhats_product_unavailable', 'Source product is unavailable.', ['status' => 409]);
}
$key = 'aismart_content_commerce_pub_' . $command['operationId'];
if (!add_option($key, time(), '', false)) {
return new WP_Error('telewhats_publication_replayed', 'Publication command has already been used.', ['status' => 409]);
}
wp_schedule_single_event(time() + 120, 'aismart_content_commerce_clear_publication_command', [$key]);
$product->set_status($command['published'] ? 'publish' : 'draft');
$product->save();
$saved = wc_get_product((int) $command['productId']);
return ['productId' => (int) $command['productId'], 'published' => $saved->get_status() === 'publish', 'status' => $saved->get_status()];
}
public static function clear_publication_command($key) {
if (preg_match('/^aismart_content_commerce_pub_[a-f0-9-]{36}$/', (string) $key)) delete_option($key);
}
private static function remote_request($type, $payload) {
if (!self::dependencies_ready()) {
return new WP_Error('telewhats_wc_not_connected', 'Connect AISmart Content Chat before synchronizing WooCommerce.');
}
return aismart_content_chat_api_request(
'POST',
'api/integrations/webchat/wordpress/commerce/' . sanitize_key($type),
$payload
);
}
private static function product_line($product) {
return [
'id' => (string) $product->get_id(),
'sku' => (string) $product->get_sku(),
'name' => (string) $product->get_name(),
'quantity' => 1,
'price' => (float) $product->get_price(),
'stockQuantity' => $product->get_stock_quantity() === null ? null : (int) $product->get_stock_quantity(),
'stockStatus' => (string) $product->get_stock_status(),
'url' => (string) get_permalink($product->get_id()),
];
}
public static function storefront_context() {
$cart = WC()->cart;
$items = [];
foreach (array_slice($cart->get_cart(), 0, 50) as $line) {
$product = $line['data'] ?? null;
if (!$product instanceof WC_Product) continue;
$items[] = array_merge(self::product_line($product), [
'quantity' => absint($line['quantity'] ?? 0),
'imageUrl' => (string) (wp_get_attachment_image_url($product->get_image_id(), 'woocommerce_thumbnail') ?: ''),
]);
}
$orders_available = get_current_user_id() > 0 && !empty(self::settings()['order_sync']);
$orders = [];
if ($orders_available) {
foreach (wc_get_orders(['customer_id' => get_current_user_id(), 'limit' => 5, 'orderby' => 'date', 'order' => 'DESC']) as $order) {
if ((int) $order->get_customer_id() !== get_current_user_id()) continue;
$updated = $order->get_date_modified();
$orders[] = [
'id' => (string) $order->get_id(),
'number' => (string) $order->get_order_number(),
'status' => (string) $order->get_status(),
'total' => (float) $order->get_total(),
'currency' => (string) $order->get_currency(),
'url' => (string) $order->get_view_order_url(),
'updatedAt' => $updated ? $updated->date(DATE_ATOM) : '',
];
}
}
return [
'cart' => ['currency' => get_woocommerce_currency(), 'total' => (float) $cart->get_total('edit'),
'checkoutUrl' => (string) wc_get_checkout_url(), 'items' => $items],
'ordersAvailable' => $orders_available,
'orders' => $orders,
];
}
public static function storefront_add_item($product_id, $variation_id, $quantity) {
$product = wc_get_product($product_id);
if (!$product || $product->get_status() !== 'publish' || !in_array($product->get_type(), ['simple', 'variable'], true)
|| $quantity < 1 || $quantity > 10) {
return new WP_Error('telewhats_product_unavailable', 'This product is not available.');
}
$attributes = [];
if ($product->is_type('variable')) {
$variation = $variation_id ? wc_get_product($variation_id) : false;
if (!$variation || !$variation->is_type('variation') || $variation->get_parent_id() !== $product_id
|| $variation->get_status() !== 'publish' || !$variation->is_purchasable() || !$variation->is_in_stock()) {
return new WP_Error('telewhats_variation_unavailable', 'Choose an available product option.');
}
$attributes = $variation->get_variation_attributes();
if (in_array('', $attributes, true)) {
return new WP_Error('telewhats_variation_options', 'Open the product page to choose all options.');
}
} elseif ($variation_id || !$product->is_purchasable() || !$product->is_in_stock()) {
return new WP_Error('telewhats_product_unavailable', 'This product is not available.');
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own add-to-cart validation filter.
if (!apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $attributes)) {
return new WP_Error('telewhats_cart_validation', 'This item could not be added. Check the product page.');
}
try {
$added = WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $attributes);
} catch (Exception $error) {
return new WP_Error('telewhats_cart_unavailable', 'This item could not be added. Check availability on the product page.');
}
return $added ? true : new WP_Error('telewhats_cart_unavailable', 'This item could not be added to your cart.');
}
public static function storefront_request() {
nocache_headers();
$method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : '';
if ($method !== 'POST' ||!check_ajax_referer('telewhats_wc_storefront', 'nonce', false)) {
wp_send_json_error(['message' => 'Reload the page before updating your cart.'], 403);
}
if (!self::dependencies_ready()) wp_send_json_error(['message' => 'The store connection is unavailable.'], 503);
if (!WC()->cart && function_exists('wc_load_cart')) wc_load_cart();
if (!WC()->cart) wp_send_json_error(['message' => 'The cart is unavailable.'], 503);
$operation = sanitize_key(wp_unslash($_POST['operation'] ?? 'context'));
if (!in_array($operation, ['context', 'add'], true)) wp_send_json_error(['message' => 'Invalid cart action.'], 422);
if ($operation === 'add') {
$added = self::storefront_add_item(absint($_POST['productId'] ?? 0), absint($_POST['variantId'] ?? 0), absint($_POST['quantity'] ?? 1));
if (is_wp_error($added)) wp_send_json_error(['message' => $added->get_error_message()], 422);
}
WC()->cart->calculate_totals();
$context = self::storefront_context();
$session_token = sanitize_text_field(wp_unslash($_POST['sessionToken'] ?? ''));
$recorded = false;
if ($session_token !== '' && strlen($session_token) <= 2048) {
$result = self::remote_request('shopper-context', ['sessionToken' => $session_token, 'context' => $context]);
$recorded = !is_wp_error($result) && !empty($result['recorded']);
}
wp_send_json_success(['cart' => $context['cart'], 'recorded' => $recorded]);
}
public static function catalog_product($product, $include_variants = true) {
$terms = static function ($taxonomy) use ($product) {
if (!taxonomy_exists($taxonomy)) return [];
$names = wp_get_post_terms($product->get_parent_id() ?: $product->get_id(), $taxonomy, ['fields' => 'names']);
return is_wp_error($names) ? [] : array_values($names);
};
$created = $product->get_date_created();
$updated = $product->get_date_modified();
$image_ids = array_values(array_unique(array_filter(array_merge(
[$product->get_image_id()], $product->get_gallery_image_ids()
))));
$image_urls = array_values(array_filter(array_map(static function ($image_id) {
return (string) (wp_get_attachment_image_url($image_id, 'full') ?: '');
}, $image_ids)));
$line = array_merge(self::product_line($product), [
'parentId' => (string) $product->get_parent_id(),
'imageUrl' => $image_urls[0] ?? '',
'imageUrls' => $image_urls,
'type' => (string) $product->get_type(),
'status' => (string) $product->get_status(),
'sourcePublished' => $product->get_status() === 'publish',
'regularPrice' => (float) ($product->get_regular_price() !== '' ? $product->get_regular_price() : $product->get_price()),
'salePrice' => $product->get_sale_price() === '' ? null : (float) $product->get_sale_price(),
'priceMax' => $product->is_type('variable') ? (float) $product->get_variation_price('max', false) : (float) $product->get_price(),
'manageStock' => (bool) $product->managing_stock(),
'featured' => (bool) $product->get_featured(),
'categories' => $terms('product_cat'),
'tags' => $terms('product_tag'),
'brands' => array_values(array_unique(array_merge($terms('product_brand'), $terms('pwb-brand')))),
'publishedAt' => $created ? $created->date(DATE_ATOM) : '',
'updatedAt' => $updated ? $updated->date(DATE_ATOM) : '',
]);
$export_key = (string) $product->get_meta('_telewhats_export_key', true);
if (preg_match('/^tw-[1-9]\d*-[1-9]\d*$/', $export_key)) $line['managedExportKey'] = $export_key;
if ($include_variants) {
$line['variants'] = [];
if ($product->is_type('variable')) {
$children = $product->get_children();
if (count($children) > 2048) throw new RuntimeException('A product supports at most 2048 variants per catalog sync.');
foreach ($children as $child_id) {
$variation = wc_get_product($child_id);
if (!$variation || $variation->get_status() !== 'publish') continue;
$line['variants'][] = self::catalog_product($variation, false);
}
}
}
return $line;
}
public static function queue_catalog_sync($product_id = 0) {
if (empty(self::settings()['catalog_sync'])) return;
if ($product_id instanceof WC_Product) $product_id = $product_id->get_id();
if ($product_id && !in_array(get_post_type($product_id), ['product', 'product_variation'], true)) return;
if (function_exists('as_has_scheduled_action') && as_has_scheduled_action(self::CATALOG_SYNC_HOOK, [], 'aismart-content-commerce')) return;
if (wp_next_scheduled(self::CATALOG_SYNC_HOOK)) return;
self::queue_async(self::CATALOG_SYNC_HOOK, []);
}
public static function sync_catalog() {
$settings = self::settings();
if (empty($settings['catalog_sync']) || !function_exists('wc_get_products')) {
return new WP_Error('telewhats_wc_catalog_disabled', 'Catalog synchronization is disabled.');
}
$args = [
'status' => ['publish', 'private', 'draft', 'pending', 'future'],
'limit' => 50,
'paginate' => true,
'orderby' => 'ID',
'order' => 'ASC',
];
$snapshot_id = wp_generate_uuid4();
$synced_at = gmdate('c');
$pages = 1;
$count = 0;
$result = null;
try {
for ($page = 1; $page <= $pages; $page++) {
$query = wc_get_products(array_merge($args, ['page' => $page]));
$products = is_object($query) && isset($query->products) ? $query->products : [];
$total = is_object($query) && isset($query->total) ? (int) $query->total : count($products);
$pages = max(1, (int) ($query->max_num_pages ?? 1));
if ($pages > 500) throw new RuntimeException('The catalog exceeds the supported 500-page sync limit.');
$result = self::remote_request('catalog', [
'siteUrl' => untrailingslashit(home_url('/')), 'currency' => get_woocommerce_currency(),
'totalProducts' => $total, 'syncedAt' => $synced_at,
'snapshotId' => $snapshot_id, 'page' => $page, 'totalPages' => $pages,
'items' => array_map([__CLASS__, 'catalog_product'], $products),
]);
if (is_wp_error($result)) break;
$count += count($products);
}
} catch (Throwable $error) {
$result = new WP_Error('telewhats_wc_catalog_failed', $error->getMessage());
}
$settings = self::settings();
if (is_wp_error($result)) {
$settings['last_error'] = $result->get_error_message();
} else {
$settings['last_catalog_sync'] = gmdate('c');
$settings['last_catalog_count'] = $count;
$settings['last_error'] = '';
$response = isset($result['data']) ? $result['data'] : $result;
$bridge = $response['shoppungpung'] ?? [];
if (!empty($bridge['synced'])) {
$settings['last_shoppungpung_sync'] = gmdate('c');
$settings['last_shoppungpung_error'] = '';
foreach (($bridge['links'] ?? []) as $link) {
update_post_meta(absint($link['externalId']), '_telewhats_shoppungpung_product_id', absint($link['productId']));
}
} elseif (!empty($bridge['reason'])) {
$settings['last_shoppungpung_error'] = sanitize_text_field($bridge['reason']);
}
}
update_option(self::OPTION, $settings, false);
delete_transient('aismart_content_commerce_linked_catalog');
return $result;
}
private static function linked_catalog() {
if (self::$catalog_state !== null) return self::$catalog_state;
if (!self::dependencies_ready()) return self::$catalog_state = ['items' => [], 'shopifyConnected' => false];
$cached = get_transient('aismart_content_commerce_linked_catalog');
if (is_array($cached)) return self::$catalog_state = $cached;
$response = aismart_content_chat_api_request('GET', 'api/integrations/webchat/wordpress/commerce/products');
if (is_wp_error($response)) return self::$catalog_state = ['items' => [], 'shopifyConnected' => false, 'error' => $response->get_error_message()];
$data = isset($response['data']) ? $response['data'] : $response;
$data = is_array($data) ? $data : ['items' => []];
set_transient('aismart_content_commerce_linked_catalog', $data, 30);
return self::$catalog_state = $data;
}
public static function product_columns($columns) {
$columns['aismart_content_commerce_sync'] = 'Platform sync';
return $columns;
}
private static function sync_label($name, $ready, $detail = '') {
echo '' . esc_html($name) . '';
}
public static function product_column($column, $product_id) {
if ($column !== 'aismart_content_commerce_sync') return;
$catalog = self::linked_catalog();
$product = null;
foreach (($catalog['items'] ?? []) as $item) {
if ((string) ($item['id'] ?? '') === (string) $product_id) { $product = $item; break; }
}
self::sync_label('WooCommerce', true, 'Source product');
self::sync_label('AISmart Content', !empty($product['syncedAt']), !empty($product['syncedAt']) ? 'Catalog received' : 'Not synchronized');
self::sync_label('ShoppungPung', ($product['syncState'] ?? '') === 'synced', !empty($product['shoppungpungProductId']) ? 'Product ' . $product['shoppungpungProductId'] : 'Not synchronized');
self::sync_label(!empty($catalog['shopifyConnected']) ? 'Shopify connected' : 'Shopify not connected', false, 'Store connection only; this product is not copied to Shopify automatically.');
echo '' . esc_html(!empty($product['cfEnabled']) ? 'CF Live enabled' : 'CF Live not enabled') . '';
}
public static function product_sync_toolbar($post_type) {
if ($post_type !== 'product' || !current_user_can('manage_woocommerce')) return;
$dashboard = class_exists('AISmart_Content_Chat_Plugin') ? AISmart_Content_Chat_Plugin::api_base() : 'https://telewhats.com';
echo '';
}
public static function manual_catalog_sync() {
self::assert_manager('aismart_content_commerce_sync_catalog');
$result = self::sync_catalog();
self::redirect_notice(
'aismart-content-commerce-catalog',
is_wp_error($result) ? 'error' : 'catalog-synced',
is_wp_error($result) ? $result->get_error_message() : ''
);
}
private static function queue_async($hook, $args) {
if (function_exists('as_enqueue_async_action')) {
as_enqueue_async_action($hook, $args, 'aismart-content-commerce');
return;
}
if (!wp_next_scheduled($hook, $args)) {
wp_schedule_single_event(time() + 15, $hook, $args);
}
}
public static function queue_order_sync($order_id) {
if (empty(self::settings()['order_sync'])) {
return;
}
self::queue_async(self::ORDER_SYNC_HOOK, [absint($order_id)]);
}
public static function sync_order($order_id) {
if (empty(self::settings()['order_sync']) || !function_exists('wc_get_order')) {
return;
}
$order = wc_get_order(absint($order_id));
if (!$order) {
return;
}
$items = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = [
'id' => (string) ($product ? $product->get_id() : $item->get_product_id()),
'sku' => (string) ($product ? $product->get_sku() : ''),
'name' => (string) $item->get_name(),
'quantity' => (int) $item->get_quantity(),
'price' => (float) ($item->get_quantity() > 0 ? $item->get_total() / $item->get_quantity() : 0),
'url' => (string) ($product ? get_permalink($product->get_id()) : ''),
];
}
$result = self::remote_request('order', [
'siteUrl' => untrailingslashit(home_url('/')),
'id' => (string) $order->get_id(),
'number' => (string) $order->get_order_number(),
'status' => (string) $order->get_status(),
'total' => (float) $order->get_total(),
'currency' => (string) $order->get_currency(),
'customerName' => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
'customerEmail' => (string) $order->get_billing_email(),
'orderUrl' => (string) $order->get_edit_order_url(),
'updatedAt' => gmdate('c'),
'items' => $items,
]);
$settings = self::settings();
if (is_wp_error($result)) {
$settings['last_error'] = $result->get_error_message();
} else {
$settings['last_order_sync'] = gmdate('c');
$settings['last_error'] = '';
}
update_option(self::OPTION, $settings, false);
}
public static function queue_cart_sync() {
$settings = self::settings();
if (empty($settings['cart_recovery']) || !function_exists('WC') || !WC()->cart || WC()->cart->is_empty()) {
return;
}
$cart = WC()->cart;
$cart_id = (string) $cart->get_cart_hash();
if ($cart_id === '') {
return;
}
$customer = WC()->customer;
$items = [];
foreach ($cart->get_cart() as $line) {
$product = isset($line['data']) && $line['data'] instanceof WC_Product ? $line['data'] : null;
if (!$product) {
continue;
}
$items[] = [
'id' => (string) $product->get_id(),
'sku' => (string) $product->get_sku(),
'name' => (string) $product->get_name(),
'quantity' => absint($line['quantity'] ?? 0),
'price' => (float) $product->get_price(),
'url' => (string) get_permalink($product->get_id()),
];
}
set_transient('aismart_content_commerce_cart_' . md5($cart_id), [
'siteUrl' => untrailingslashit(home_url('/')),
'id' => $cart_id,
'total' => (float) $cart->get_total('edit'),
'currency' => get_woocommerce_currency(),
'customerName' => $customer ? trim($customer->get_first_name() . ' ' . $customer->get_last_name()) : '',
'customerEmail' => $customer ? (string) $customer->get_billing_email() : '',
'checkoutUrl' => (string) wc_get_checkout_url(),
'recoveryDelayMinutes' => absint($settings['recovery_delay_minutes']),
'updatedAt' => gmdate('c'),
'items' => $items,
], 2 * DAY_IN_SECONDS);
self::queue_async(self::CART_SYNC_HOOK, [$cart_id]);
}
public static function sync_cart_snapshot($cart_id) {
$payload = get_transient('aismart_content_commerce_cart_' . md5((string) $cart_id));
if (!is_array($payload)) {
return;
}
$result = self::remote_request('cart', $payload);
$settings = self::settings();
if (is_wp_error($result)) {
$settings['last_error'] = $result->get_error_message();
} else {
$settings['last_cart_sync'] = gmdate('c');
$settings['last_error'] = '';
delete_transient('aismart_content_commerce_cart_' . md5((string) $cart_id));
}
update_option(self::OPTION, $settings, false);
}
private static function header($title, $description) {
$ready = self::dependencies_ready();
?>
' . esc_html($message ?: 'WooCommerce sync failed.') . '
';
} elseif ($notice === 'saved') {
echo '';
} elseif ($notice === 'catalog-synced') {
echo 'Product catalog synchronized with AISmart Content.
';
}
}
private static function metric($label, $value, $detail) {
?>
false, 'workspace_id' => 0];
?>
One shared WordPress widgetThis companion uses the AISmart Content Chat connection for workspace . It does not create another storefront widget.
Open Chat Settings
publish) ? (int) $counts->publish : 0;
?>
10, 'orderby' => 'date', 'order' => 'DESC']) : [];
?>
Automatic order updates
New orders and status changes are queued through WooCommerce Action Scheduler.
Recovery workflows
Cart snapshots share the WordPress installation identity and can be paired with an AISmart Content automation.
Open Cart Recovery