diff --git a/api.php b/api.php index 8b424a2..14b007f 100644 --- a/api.php +++ b/api.php @@ -2906,8 +2906,9 @@ switch ($action) { $threadedCount = 0; $errors = []; - // Collect all existing message IDs for duplicate detection - $existingMsgIds = []; + // Collect all previously fetched message IDs (persists even after ticket deletion) + $existingMsgIds = dbGetFetchedMessageIds($companyId); + // Also include message IDs from current tickets (for backward compatibility) foreach ($tickets as $t) { if ($t['message_id']) $existingMsgIds[$t['message_id']] = true; foreach ($t['messages'] ?? [] as $m) { @@ -3016,7 +3017,7 @@ switch ($action) { ]; // Apply auto-rules - $toAddresses = implode(' ', $email['to'] ?? []); + $toAddresses = $email['to'] ?? ''; foreach ($rules as $rule) { if (empty($rule['enabled'])) continue; $match = true; @@ -3094,7 +3095,11 @@ switch ($action) { $newCount++; } - if ($email['message_id']) $existingMsgIds[$email['message_id']] = true; + // Merkitse haetuksi pysyvästi + if ($email['message_id']) { + dbMarkMessageIdFetched($companyId, $email['message_id']); + $existingMsgIds[$email['message_id']] = true; + } } } diff --git a/db.php b/db.php index 410c02c..7584667 100644 --- a/db.php +++ b/db.php @@ -358,6 +358,16 @@ function initDatabase(): void { INDEX idx_company (company_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", + "CREATE TABLE IF NOT EXISTS fetched_message_ids ( + id INT AUTO_INCREMENT PRIMARY KEY, + company_id VARCHAR(50) NOT NULL, + message_id VARCHAR(512) NOT NULL, + fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_company_msgid (company_id, message_id), + FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE, + INDEX idx_company (company_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", + "CREATE TABLE IF NOT EXISTS customer_priority_emails ( id INT AUTO_INCREMENT PRIMARY KEY, company_id VARCHAR(50) NOT NULL, @@ -1640,6 +1650,22 @@ function dbDeleteTicketType(string $companyId, string $value): void { _dbExecute("DELETE FROM ticket_types WHERE company_id = ? AND value = ?", [$companyId, $value]); } +// ==================== HAETUT MESSAGE-ID:T (duplikaattien esto) ==================== + +function dbGetFetchedMessageIds(string $companyId): array { + $rows = _dbFetchAll("SELECT message_id FROM fetched_message_ids WHERE company_id = ?", [$companyId]); + $ids = []; + foreach ($rows as $r) { $ids[$r['message_id']] = true; } + return $ids; +} + +function dbMarkMessageIdFetched(string $companyId, string $messageId): void { + if (empty($messageId)) return; + try { + _dbExecute("INSERT IGNORE INTO fetched_message_ids (company_id, message_id) VALUES (?, ?)", [$companyId, $messageId]); + } catch (\Throwable $e) { /* duplicate, ok */ } +} + // ==================== YRITYKSEN API-ASETUKSET ==================== function dbGetCompanyConfig(string $companyId): array {