| @@ -26,9 +26,9 @@ | ||
| 26 | 26 | self::setupChatHistoryTable(); |
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 29 | /** |
| 30 | - * Get the last 150 messages | |
| 30 | + * Get the last 250 messages | |
| 31 | 31 | * |
| 32 | 32 | * @return array |
| 33 | 33 | */ |
| 34 | 34 | public static function getChatHistory($user_id = null) |
| @@ -38,9 +38,9 @@ | ||
| 38 | 38 | $user_id = $user_id ?: get_current_user_id(); |
| 39 | 39 | |
| 40 | 40 | $results = $wpdb->get_results( |
| 41 | 41 | $wpdb->prepare( |
| 42 | - "SELECT * FROM $table WHERE user_id = %d ORDER BY id DESC LIMIT 150", | |
| 42 | + "SELECT * FROM $table WHERE user_id = %d ORDER BY id DESC LIMIT 250", | |
| 43 | 43 | $user_id |
| 44 | 44 | ), |
| 45 | 45 | ARRAY_A |
| 46 | 46 | ); |
| @@ -52,9 +52,29 @@ | ||
| 52 | 52 | ]; |
| 53 | 53 | }, $results); |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | + /** | |
| 57 | + * Delete the user's chat history, if the table exists. | |
| 58 | + * | |
| 59 | + * @param int|null $user_id The user ID, defaults to the current user. | |
| 60 | + * @return void | |
| 61 | + */ | |
| 62 | + public static function clear($user_id = null) | |
| 63 | + { | |
| 64 | + global $wpdb; | |
| 65 | + $table = $wpdb->prefix . 'extendify_agent_events'; | |
| 66 | + $user_id = $user_id ?: get_current_user_id(); | |
| 56 | 67 | |
| 68 | + if (!$wpdb->get_var("SHOW TABLES LIKE '$table'")) { | |
| 69 | + return; | |
| 70 | + } | |
| 71 | + | |
| 72 | + $wpdb->query( | |
| 73 | + $wpdb->prepare("DELETE FROM $table WHERE user_id = %d", $user_id) | |
| 74 | + ); | |
| 75 | + } | |
| 76 | + | |
| 57 | 77 | /** |
| 58 | 78 | * Return the data |
| 59 | 79 | * |
| 60 | 80 | * @return \WP_REST_Response |
| @@ -94,10 +114,11 @@ | ||
| 94 | 114 | ); |
| 95 | 115 | $startIndex = 0; |
| 96 | 116 | if ($latest) { |
| 97 | 117 | foreach ($messages as $i => $msg) { |
| 118 | + // Tool results land on the newest row after insert; skipping it loses them. | |
| 98 | 119 | if ($msg['id'] === $latest) { |
| 99 | - $startIndex = $i + 1; | |
| 120 | + $startIndex = $i; | |
| 100 | 121 | break; |
| 101 | 122 | } |
| 102 | 123 | } |
| 103 | 124 | } |
| @@ -167,9 +188,10 @@ | ||
| 167 | 188 | $cols = []; |
| 168 | 189 | foreach ($columns as $name => $type) { |
| 169 | 190 | $cols[] = "$name $type"; |
| 170 | 191 | } |
| 171 | - $sql = "CREATE TABLE $table (" . implode(',', $cols) . ", INDEX(user_id))"; | |
| 192 | + $indexes = "INDEX(user_id), UNIQUE INDEX unique_event_id (event_id, user_id)"; | |
| 193 | + $sql = "CREATE TABLE $table (" . implode(',', $cols) . ", $indexes)"; | |
| 172 | 194 | $sql .= " " . $wpdb->get_charset_collate() . ";"; |
| 173 | 195 | $wpdb->query($sql); |
| 174 | 196 | return; |
| 175 | 197 | } |