*/ private static $document_types = array( 'invoice' => array( 'label' => 'Invoice', 'admin' => true, 'user' => true, 'download' => true ), 'packinglist' => array( 'label' => 'Packing Slip', 'admin' => true, 'user' => false, 'download' => true ), 'deliverynote' => array( 'label' => 'Delivery Note', 'admin' => true, 'user' => false, 'download' => false ), 'shippinglabel' => array( 'label' => 'Shipping Label', 'admin' => true, 'user' => false, 'download' => false ), 'dispatchlabel' => array( 'label' => 'Dispatch Label', 'admin' => true, 'user' => false, 'download' => false ), ); // ------------------------------------------------------------------------- // Plugin detection // ------------------------------------------------------------------------- /** * Returns true when the WebToffee Print Invoices plugin is active and loaded. * * @return bool */ public static function is_active() { return class_exists( self::PRINT_CLASS ); } /** * Returns true if the admin print class is available (it is lazily loaded * by the print plugin, so it may not exist on all requests). * * @return bool */ private static function has_admin_class() { return class_exists( self::PRINT_ADMIN_CLASS ); } // ------------------------------------------------------------------------- // Action routing // ------------------------------------------------------------------------- /** * Returns true when this module should handle the given action name. * * @param string $action * @return bool */ public static function handles( $action ) { return 'get_print_links' === $action; } /** * Dispatches a chatbot JSON action block to the correct handler. * * @param string $action Sanitized action name. * @param array $json Decoded JSON block from the AI response. * @param bool $is_admin Whether the current user is an admin/shop-manager. * @return array|WP_Error */ public static function dispatch( $action, array $json, $is_admin ) { if ( ! self::is_active() ) { return new WP_Error( 'print_inactive', __( 'The "Print Invoices & Packing Slips" plugin is not active.', 'ai-content-generator-for-woocommerce' ) ); } if ( 'get_print_links' === $action ) { return self::execute_get_print_links( $json, $is_admin ); } return new WP_Error( 'print_invalid_action', __( 'Invalid print action.', 'ai-content-generator-for-woocommerce' ) ); } // ------------------------------------------------------------------------- // System prompt // ------------------------------------------------------------------------- /** * Returns the print section of the admin abilities system prompt. * Injected into the admin prompt when the print plugin is active. * * @return string */ public static function get_admin_abilities_prompt() { if ( ! self::is_active() ) { return ''; } $p = "\nPRINT / DOWNLOAD ACTIONS (WebToffee Print Invoices plugin is active):\n"; $p .= "- {\"_action\":\"get_print_links\",\"order_id\":\"123\",\"documents\":[\"invoice\",\"packinglist\",\"deliverynote\",\"shippinglabel\",\"dispatchlabel\"]}\n"; $p .= " documents: invoice (print+download), packinglist (print+download), deliverynote (print only), shippinglabel (print only), dispatchlabel (print only).\n"; $p .= " Omit documents key to return all available types.\n"; $p .= "RULE: Use get_print_links when user asks to print, download, or view a document for an order.\n"; $p .= "RULE: For customers, only 'invoice' is available.\n"; $p .= "RULE: PRESERVE EXACT FORMAT. Do NOT strip leading zeros from order IDs (e.g., if user says '002', pass \"002\").\n"; // <--- ADD THIS LINE return $p; } /** * Returns the customer-facing print section of the chatbot system prompt. * Injected into the customer prompt when the print plugin is active. * * @return string */ public static function get_customer_abilities_prompt() { if ( ! self::is_active() ) { return ''; } $p = "\nPRINT ACTIONS (invoice printing is available):\n"; $p .= "- {\"_action\":\"get_print_links\",\"order_id\":\"123\",\"documents\":[\"invoice\",\"packinglist\",\"deliverynote\",\"shippinglabel\",\"dispatchlabel\"]}\n"; $p .= " Use when the customer asks to print, download, or view their invoice for an order.\n"; $p .= "RULE: PRESERVE EXACT FORMAT. Do NOT strip leading zeros from order IDs (e.g., if user says '002', pass \"002\").\n"; // <--- ADD THIS LINE return $p; } // ------------------------------------------------------------------------- // Action implementations // ------------------------------------------------------------------------- /** * Generates print and download links for the requested documents on an order. * Returns an HTML chatbot reply with buttons for each document. * * For admin users, uses Wf_Woocommerce_Packing_List_Admin::get_print_url() * which produces a nonce-protected admin URL. * * For customers, uses Wf_Woocommerce_Packing_List::generate_print_url_for_user() * which includes access_key + nonce so the customer does not need to be logged in * at print time (mirrors how the print plugin works on the My Account page). * * @param array $json Decoded JSON params from the AI. * @param bool $is_admin Whether the current user is an admin/shop-manager. * @return array|WP_Error */ private static function execute_get_print_links( array $json, $is_admin ) { $order_id = sanitize_text_field( $json['order_id'] ?? '' ); if ( empty( $order_id ) ) { return new WP_Error( 'missing_order_id', __( 'Please specify an order ID.', 'ai-content-generator-for-woocommerce' ) ); } $order = null; if ( class_exists( 'Wt_Advanced_Order_Number' ) ) { // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value $orders = wc_get_orders([ 'limit' => 1, 'meta_key' => '_order_number', 'meta_value' => $order_id, ]); // phpcs:enable $order = !empty($orders) ? $orders[0] : null; } else { $order = wc_get_order( $order_id ); } if ( ! $order ) { return new WP_Error( 'order_not_found', sprintf( /* translators: %s: order ID */ __( 'Order #%s was not found.', 'ai-content-generator-for-woocommerce' ), $order_id ) ); } // Customers can only print their own orders. if ( ! $is_admin ) { $current_user_id = get_current_user_id(); if ( $current_user_id && (int) $order->get_customer_id() !== $current_user_id ) { return new WP_Error( 'order_access_denied', __( 'You do not have permission to print documents for this order.', 'ai-content-generator-for-woocommerce' ) ); } } // Determine which document types to generate. $requested = isset( $json['documents'] ) && is_array( $json['documents'] ) ? array_map( 'sanitize_key', $json['documents'] ) : array_keys( self::$document_types ); // Customers are limited to invoice only. if ( ! $is_admin ) { $requested = array_intersect( $requested, array( 'invoice' ) ); } $order_id_old = $order->get_id(); $links = self::build_links( $order_id_old, $requested, $is_admin ); if ( empty( $links ) ) { return new WP_Error( 'no_documents', __( 'No printable documents are available for this order.', 'ai-content-generator-for-woocommerce' ) ); } $html = self::build_reply_html( $order_id, $links ); return array( 'success' => true, 'html' => $html, 'order_id' => $order_id, 'documents' => array_keys( $links ), ); } /** * Builds an associative array of [ document_type => [ print_url, download_url ] ] * for all requested document types on the given order. * * IMPORTANT: this does NOT generate real nonce URLs. It emits inert * placeholder fragments (#wtofe-print-...) that get swapped for a live, * freshly-nonced URL by resolve_placeholders() right before the HTML is * ever shown to a browser (on first reply AND on every later history * load). This is what's actually persisted to the chat history DB, so * a link never "goes stale" — only the resolve step's output can. * * @param int $order_id * @param string[] $requested List of document type slugs to include. * @param bool $is_admin * @return array */ private static function build_links( $order_id, array $requested, $is_admin ) { $links = array(); foreach ( $requested as $type ) { if ( ! isset( self::$document_types[ $type ] ) ) { continue; } $doc = self::$document_types[ $type ]; if ( $is_admin ) { if ( ! $doc['admin'] ) { continue; } } else { if ( ! $doc['user'] ) { continue; } } $supports_download = ! empty( $doc['download'] ); $links[ $type ] = array( 'print_url' => self::placeholder( $order_id, $type, 'print', $is_admin ), 'download_url' => $supports_download ? self::placeholder( $order_id, $type, 'download', $is_admin ) : '', ); } return $links; } /** * Builds an inert placeholder fragment for a print/download link. * Safe to pass through esc_url() unchanged (letters, digits, dashes only). * * @param int $order_id * @param string $type Document type slug. * @param string $mode 'print' or 'download'. * @param bool $is_admin Whether this link was generated in an admin context. * @return string */ private static function placeholder( $order_id, $type, $mode, $is_admin ) { return sprintf( '#wtofe-print-%d-%s-%s-%d', (int) $order_id, $type, $mode, $is_admin ? 1 : 0 ); } /** * Replaces every print-link placeholder in an HTML string with a freshly * generated, currently-valid URL. Safe to call repeatedly / idempotently * on the same string — call this: * - right after dispatch_ability() builds the live chat reply (so the * user sees working links immediately), and * - every time a stored message is served from history (REST endpoint * and admin AJAX endpoint), using the CURRENT viewer's session. * * Never re-resolves and stores the result back to the DB — the DB always * keeps the placeholder form so it can be resolved fresh again later. * * @param string $html HTML that may contain placeholders. * @param bool $trusted_admin_viewer True when the current viewer is an * authenticated admin/shop-manager * (either using the chatbot as admin, * or browsing another user's history * from the admin panel). * @param int $current_user_id Current viewer's user ID, used to * re-check order ownership for * customer-scoped placeholders. * @return string */ public static function resolve_placeholders( $html, $trusted_admin_viewer, $current_user_id ) { if ( ! is_string( $html ) || false === strpos( $html, '#wtofe-print-' ) ) { return $html; } if ( ! self::is_active() ) { // Print plugin isn't active/loaded right now — leave dead links inert // instead of pointing at a URL that will 404 or misbehave. return preg_replace( self::PLACEHOLDER_REGEX, '#', $html ); } return preg_replace_callback( self::PLACEHOLDER_REGEX, function ( $m ) use ( $trusted_admin_viewer, $current_user_id ) { $order_id = absint( $m[1] ); $type = sanitize_key( $m[2] ); $mode = $m[3]; $was_admin_link = '1' === $m[4]; $order = wc_get_order( $order_id ); if ( ! $order ) { return '#'; } if ( $was_admin_link ) { // Admin-scoped placeholders only ever get resolved for an // authenticated admin/shop-manager viewer. if ( ! $trusted_admin_viewer ) { return '#'; } $url = self::resolve_admin_url( $order_id, $type, $mode ); } else { // Customer-scoped placeholders resolve for the order owner, // or for a trusted admin browsing that customer's history. if ( ! $trusted_admin_viewer && (int) $order->get_customer_id() !== (int) $current_user_id ) { return '#'; } $url = self::resolve_customer_url( $order, $order_id, $type, $mode ); } return $url ? esc_url_raw( $url ) : '#'; }, $html ); } /** * Generates a live admin print/download URL for a document type. * Uses Wf_Woocommerce_Packing_List_Admin::get_print_url() when available, * falls back to building the URL directly (same logic) when the class isn't loaded. * * @param int $order_id * @param string $type Document type slug. * @param string $mode 'print' or 'download'. * @return string */ private static function resolve_admin_url( $order_id, $type, $mode ) { $action_type = $mode . '_' . $type; if ( self::has_admin_class() ) { return Wf_Woocommerce_Packing_List_Admin::get_print_url( $order_id, $action_type ); } return wp_nonce_url( admin_url( '?print_packinglist=true&post=' . $order_id . '&type=' . $action_type ), WF_PKLIST_PLUGIN_NAME ); } /** * Generates a live customer print/download URL for a document type. * Uses Wf_Woocommerce_Packing_List::generate_print_url_for_user() which * embeds the order access_key + nonce for secure guest-safe access. * * @param WC_Order $order * @param int $order_id * @param string $type Document type slug. * @param string $mode 'print' or 'download'. * @return string */ private static function resolve_customer_url( $order, $order_id, $type, $mode ) { return Wf_Woocommerce_Packing_List::generate_print_url_for_user( $order, $order_id, $type, $mode ); } // ------------------------------------------------------------------------- // HTML reply builder // ------------------------------------------------------------------------- /** * Builds the HTML chatbot reply containing print/download buttons * for each document type. * * @param int $order_id * @param array $links [ type => [ print_url, download_url ] ] * @return string HTML string safe to echo in the chatbot bubble. */ private static function build_reply_html( $order_id, array $links ) { $btn = 'display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:5px;font-size:12px;font-weight:500;text-decoration:none;white-space:nowrap;line-height:1.4;'; $html = '

Order #' . $order_id . ' — Documents

'; $html .= ''; foreach ( $links as $type => $urls ) { $label = isset( self::$document_types[ $type ]['label'] ) ? self::$document_types[ $type ]['label'] : ucfirst( $type ); $html .= ''; $html .= ''; } $html .= '
' . esc_html( $label ) . ''; if ( ! empty( $urls['print_url'] ) ) { $html .= '' . 'Print'; } if ( ! empty( $urls['download_url'] ) ) { $html .= '' . 'Download'; } $html .= '
'; return $html; } }