From 7ade5bbdf36e45e2d6f0fd4fec34e0d9cf073c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ya=C4=9F=C4=B1zhan=20Burak=20Yakar?= Date: Fri, 19 Jun 2026 21:01:52 +0300 Subject: [PATCH] Unify public tickets with client tickets (#3799) * Merge public ticket logic into regular client tickets * Unified email templates * Unified events and listeners * Remove passthrough service methods * Corrected phpDocs * Create a combined `author` array to replace `client`, `client_id`, `author_name`, `author_email` * Switch to using "Author" instead of "Requester" * Switch to using a single endpoint and single template for client and guest tickets Also left a redirect behind to make sure previously sent emails still have a working link * Add author_role parameter to onBeforeClientOpenTicket * Adjusted rate limit ordering * Update Twig templates and the update patcher * "Public ticket" -> "Guest ticket" * Addressed code review comments * Address code review comments * Also purge old pticket email templates * Fix email sending * Support: enforce auth, fix guest email links * Migrate mod_support config key name --------- Co-authored-by: Adam Daley --- src/install/sql/content.sql | 12 +- src/install/sql/structure.sql | 46 +- src/library/FOSSBilling/UpdatePatcher.php | 455 +++++++---- src/library/Model/SupportPTicket.php | 17 - src/library/Model/SupportPTicketMessage.php | 14 - src/modules/Antispam/Service.php | 6 +- .../Antispam/tests/Unit/ServiceTest.php | 24 +- src/modules/Cron/Service.php | 1 - .../client/mod_embed_contact.html.twig | 4 +- src/modules/Redirect/Controller/Client.php | 2 +- src/modules/Staff/Service.php | 64 +- .../email/mod_staff_pticket_close.html.twig | 47 -- .../email/mod_staff_pticket_open.html.twig | 49 -- .../email/mod_staff_pticket_reply.html.twig | 49 -- .../email/mod_staff_ticket_close.html.twig | 2 +- .../email/mod_staff_ticket_open.html.twig | 2 +- .../email/mod_staff_ticket_reply.html.twig | 2 +- src/modules/Staff/tests/Unit/ServiceTest.php | 68 +- src/modules/Support/Api/Admin.php | 164 ---- src/modules/Support/Api/Client.php | 2 +- src/modules/Support/Api/Guest.php | 70 +- src/modules/Support/Controller/Admin.php | 45 +- src/modules/Support/Controller/Client.php | 26 +- src/modules/Support/Service.php | 648 +++++----------- .../admin/mod_support_public_ticket.html.twig | 235 ------ .../mod_support_public_tickets.html.twig | 299 -------- .../admin/mod_support_settings.html.twig | 10 +- .../admin/mod_support_ticket.html.twig | 30 +- .../admin/mod_support_tickets.html.twig | 61 +- .../client/mod_support_contact_us.html.twig | 8 +- ..._support_contact_us_conversation.html.twig | 135 ---- .../client/mod_support_ticket.html.twig | 25 +- .../email/mod_support_pticket_open.html.twig | 51 -- .../mod_support_pticket_staff_close.html.twig | 51 -- .../mod_support_pticket_staff_open.html.twig | 51 -- .../mod_support_pticket_staff_reply.html.twig | 51 -- .../email/mod_support_ticket_open.html.twig | 13 +- .../mod_support_ticket_staff_close.html.twig | 11 +- .../mod_support_ticket_staff_open.html.twig | 11 +- .../mod_support_ticket_staff_reply.html.twig | 11 +- .../Support/tests/E2E/ApiGuestTest.php | 39 +- .../Support/tests/Unit/Api/AdminTest.php | 305 +------- .../Support/tests/Unit/Api/GuestTest.php | 29 +- .../Support/tests/Unit/ServiceTest.php | 708 ++---------------- .../huraga/html/layout_default.html.twig | 5 +- .../Twig/EdgeCaseRenderingTest.php | 3 + 46 files changed, 880 insertions(+), 3081 deletions(-) delete mode 100644 src/library/Model/SupportPTicket.php delete mode 100644 src/library/Model/SupportPTicketMessage.php delete mode 100644 src/modules/Staff/templates/email/mod_staff_pticket_close.html.twig delete mode 100644 src/modules/Staff/templates/email/mod_staff_pticket_open.html.twig delete mode 100644 src/modules/Staff/templates/email/mod_staff_pticket_reply.html.twig delete mode 100644 src/modules/Support/templates/admin/mod_support_public_ticket.html.twig delete mode 100644 src/modules/Support/templates/admin/mod_support_public_tickets.html.twig delete mode 100644 src/modules/Support/templates/client/mod_support_contact_us_conversation.html.twig delete mode 100644 src/modules/Support/templates/email/mod_support_pticket_open.html.twig delete mode 100644 src/modules/Support/templates/email/mod_support_pticket_staff_close.html.twig delete mode 100644 src/modules/Support/templates/email/mod_support_pticket_staff_open.html.twig delete mode 100644 src/modules/Support/templates/email/mod_support_pticket_staff_reply.html.twig diff --git a/src/install/sql/content.sql b/src/install/sql/content.sql index b61302094..bc72b44bd 100644 --- a/src/install/sql/content.sql +++ b/src/install/sql/content.sql @@ -303,7 +303,7 @@ LOCK TABLES `setting` WRITE; INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`) VALUES - (1,'last_patch','72',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), + (1,'last_patch','73',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), (2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), @@ -359,16 +359,6 @@ VALUES UNLOCK TABLES; -# Dump of table support_p_ticket -# ------------------------------------------------------------ - - - -# Dump of table support_p_ticket_message -# ------------------------------------------------------------ - - - # Dump of table support_pr # ------------------------------------------------------------ diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index 2888c0a3c..80c222400 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -1174,46 +1174,6 @@ CREATE TABLE `support_helpdesk` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `support_p_ticket` --- - -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `support_p_ticket` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `hash` varchar(255) DEFAULT NULL, - `author_name` varchar(255) DEFAULT NULL, - `author_email` varchar(255) DEFAULT NULL, - `subject` varchar(255) DEFAULT NULL, - `status` varchar(30) DEFAULT 'open', - `created_at` datetime DEFAULT NULL, - `updated_at` datetime DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `support_p_ticket_message` --- - -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `support_p_ticket_message` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `support_p_ticket_id` bigint(20) DEFAULT NULL, - `admin_id` bigint(20) DEFAULT NULL COMMENT 'Filled when message author is admin', - `content` text, - `ip` varchar(45) DEFAULT NULL, - `created_at` datetime DEFAULT NULL, - `updated_at` datetime DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `support_p_ticket_id_idx` (`support_p_ticket_id`), - KEY `admin_id_idx` (`admin_id`), - FULLTEXT KEY `content_idx` (`content`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `support_pr` -- @@ -1257,6 +1217,9 @@ CREATE TABLE `support_ticket` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `support_helpdesk_id` bigint(20) DEFAULT NULL, `client_id` bigint(20) DEFAULT NULL, + `access_hash` varchar(255) DEFAULT NULL, + `author_name` varchar(255) DEFAULT NULL, + `author_email` varchar(255) DEFAULT NULL, `priority` int(11) DEFAULT '100', `subject` varchar(255) DEFAULT NULL, `status` varchar(30) DEFAULT 'open' COMMENT 'open, closed, on_hold', @@ -1269,7 +1232,8 @@ CREATE TABLE `support_ticket` ( `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `support_helpdesk_id_idx` (`support_helpdesk_id`), - KEY `client_id_idx` (`client_id`) + KEY `client_id_idx` (`client_id`), + KEY `access_hash_idx` (`access_hash`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index 1b5ce7eff..67215a236 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -272,6 +272,14 @@ class UpdatePatcher implements InjectionAwareInterface return in_array($column, $this->getTableColumns($table), true); } + private function tableExists(string $table): bool + { + return (bool) $this->fetchOne( + 'SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table LIMIT 1', + ['table' => $table], + ); + } + private function getTableColumns(string $table): array { $columns = $this->fetchAll(sprintf('SHOW COLUMNS FROM `%s`', $this->quoteIdentifier($table))); @@ -459,6 +467,7 @@ class UpdatePatcher implements InjectionAwareInterface 70 => 'patch70', 71 => 'patch71', 72 => 'patch72', + 73 => 'patch73', ]; ksort($patches, SORT_NATURAL); @@ -1180,17 +1189,10 @@ class UpdatePatcher implements InjectionAwareInterface 'mod_staff_client_signup' => ['13018c8f888668bbf731367ca3388a34f7170ff213bf1fa07771c375c4aae775', 'a573783ce28183abe13257c5b2663f750f8e37eb9056aad0c6abf203573d2f83'], 'mod_staff_password_reset_approve' => ['f4e810c0a880b72dac35d7d7c1317fabdbc253c94b2c40387e72300fc502e75b', '8e3a3e5e4ffb9b393c08bcef9c07818a73c70d8c25a6cbed3f9ef339008e32bb'], 'mod_staff_password_reset_request' => ['7afb81438ba5fe02b0cb1de5e2a0adafa1d54163fa6db3c594b052ae41d7a702', 'f6b1527a328af6b4e1c7a0f4d96d4cea7fa328a053508dc614385d39d78cc925'], - 'mod_staff_pticket_close' => ['649f36bc186928c2581f27e017dcad39ee38a01100bb38e0458e02cab1d06cb8', '49b9aced9a16bb81ce961a097c945a9c6dd828b3d8aab3b3c3557bb5d12ec85e'], - 'mod_staff_pticket_open' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', 'd30deb555b30c5a85f25b23bb4c83a76e49d8a8379ad09d4aff9968888e637ce'], - 'mod_staff_pticket_reply' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '22bbf90befc02e3da6211c7036362fb296a38eb4be686d18752552b3cc0ae63d'], 'mod_staff_ticket_close' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', 'd54e0d97b88218404c731929eb2a39857ee422070e857802374626b72bf84b2f'], 'mod_staff_ticket_open' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', 'dbe1dee98606a36285a79d019e6180e62ee04cc7e3c3f16d34045d6c70aaf78e'], 'mod_staff_ticket_reply' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', '87238cbde59fd9faa31c8e0d6039924ad6068f1ca3858ad91b06cc4633243153'], 'mod_support_helpdesk_ticket_open' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '709e2ff17c01e1056ef4824e507e4474a6eeb1e3f35d5acd1c646074d98cc5d6'], - 'mod_support_pticket_open' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', '9735ea9dfe213f0880f95fabf82cc0530bac78feeeab9b6ec21fee501c3e9e3f'], - 'mod_support_pticket_staff_close' => ['649f36bc186928c2581f27e017dcad39ee38a01100bb38e0458e02cab1d06cb8', '40a10a0a559dd5e3f69d8464df979db6bc5109696c4a1df6f60ea6802ca3376f'], - 'mod_support_pticket_staff_open' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '7dcba8e4fae63dd9ef4815a5db8cfb0cf6a510d48b947ec64f9e8163b8078e03'], - 'mod_support_pticket_staff_reply' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '4afbeb7038d64bd1a53277902139019fa219554cdb32fb1ec74b07e85b40e83d'], 'mod_support_ticket_open' => ['5b80a40322052bccb1e00854c02fe4ad46be9dfbbdbf0b17a641af99175b72c5', '78fe28d46cba9f344b9a2045114b1a7d723dc8a62602690413ecac30287bcae2'], 'mod_support_ticket_staff_close' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '965d0369564e2edc832db28564e414b960f9559213750d7f1f1baf0b1cceb2a7'], 'mod_support_ticket_staff_open' => ['2fb0c49c240c05925211f0bd0e90b3de4ceab4287c1c89be6155f0a3d71d7811', '98ff5f36b64fb0f874048c7dd44310e98ecf2b08f49e8dab701d9d4bb5e81ba5'], @@ -1572,6 +1574,291 @@ class UpdatePatcher implements InjectionAwareInterface } } + private function patch72(): void + { + $this->executeFileActions([ + Path::join(PATH_LIBRARY, 'Model', 'Product.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductCategory.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductCustom.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDomain.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDomainTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductDownloadable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductHosting.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductLicense.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductPayment.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ProductTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'Promo.php') => 'unlink', + Path::join(PATH_CACHE, 'classMap.php') => 'unlink', + Path::join(PATH_CACHE, 'fallbackClassMap.php') => 'unlink', + ]); + + $schemaManager = $this->di['dbal']->createSchemaManager(); + if (!$schemaManager->tablesExist(['promo_redemption'])) { + $this->executeSql( + "CREATE TABLE `promo_redemption` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `promo_id` bigint(20) DEFAULT NULL, + `client_id` bigint(20) DEFAULT NULL, + `client_order_id` bigint(20) DEFAULT NULL, + `invoice_id` bigint(20) DEFAULT NULL, + `phase` varchar(30) NOT NULL DEFAULT 'checkout', + `status` varchar(30) NOT NULL DEFAULT 'reserved', + `discount_amount` decimal(18,2) DEFAULT NULL, + `currency` varchar(20) DEFAULT NULL, + `committed_at` datetime DEFAULT NULL, + `released_at` datetime DEFAULT NULL, + `release_reason` varchar(100) DEFAULT NULL, + `created_at` datetime DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `promo_id_idx` (`promo_id`), + KEY `client_id_idx` (`client_id`), + KEY `client_order_id_idx` (`client_order_id`), + KEY `invoice_id_idx` (`invoice_id`), + KEY `phase_idx` (`phase`), + KEY `status_idx` (`status`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8;" + ); + } + + $table = $schemaManager->introspectTable('promo_redemption'); + $columns = []; + + if (!$table->hasColumn('status')) { + $columns[] = "ADD COLUMN `status` varchar(30) NOT NULL DEFAULT 'reserved' AFTER `phase`"; + } + + if (!$table->hasColumn('committed_at')) { + $columns[] = 'ADD COLUMN `committed_at` datetime DEFAULT NULL AFTER `currency`'; + } + + if (!$table->hasColumn('released_at')) { + $columns[] = 'ADD COLUMN `released_at` datetime DEFAULT NULL AFTER `committed_at`'; + } + + if (!$table->hasColumn('release_reason')) { + $columns[] = 'ADD COLUMN `release_reason` varchar(100) DEFAULT NULL AFTER `released_at`'; + } + + if ($columns !== []) { + $this->executeSql('ALTER TABLE promo_redemption ' . implode(', ', $columns)); + } + + $table = $schemaManager->introspectTable('promo_redemption'); + $expectedIndexes = [ + 'promo_id_idx' => 'promo_id', + 'client_id_idx' => 'client_id', + 'client_order_id_idx' => 'client_order_id', + 'invoice_id_idx' => 'invoice_id', + 'phase_idx' => 'phase', + 'status_idx' => 'status', + ]; + + foreach ($expectedIndexes as $indexName => $columnName) { + if (!$table->hasIndex($indexName)) { + $this->executeSql(sprintf( + 'ALTER TABLE promo_redemption ADD INDEX `%s` (`%s`)', + $indexName, + $columnName + )); + } + } + + $existingRedemptions = (int) $this->di['dbal']->executeQuery('SELECT COUNT(id) FROM promo_redemption')->fetchOne(); + if ($existingRedemptions === 0) { + $orders = $this->di['dbal']->executeQuery( + 'SELECT id, promo_id, client_id, promo_used, discount, currency, created_at, updated_at + FROM client_order + WHERE promo_id IS NOT NULL' + )->fetchAllAssociative(); + + foreach ($orders as $order) { + $checkoutCreatedAt = $order['created_at'] ?? date('Y-m-d H:i:s'); + $renewalCreatedAt = $order['updated_at'] ?: $checkoutCreatedAt; + $discountAmount = $order['discount'] !== null ? (float) $order['discount'] : null; + + $this->di['dbal']->insert('promo_redemption', [ + 'promo_id' => $order['promo_id'], + 'client_id' => $order['client_id'], + 'client_order_id' => $order['id'], + 'invoice_id' => null, + 'phase' => 'checkout', + 'status' => 'committed', + 'discount_amount' => $discountAmount, + 'currency' => $order['currency'], + 'committed_at' => $checkoutCreatedAt, + 'released_at' => null, + 'release_reason' => null, + 'created_at' => $checkoutCreatedAt, + 'updated_at' => $checkoutCreatedAt, + ]); + + $renewalCount = max(0, ((int) ($order['promo_used'] ?? 1)) - 1); + for ($i = 0; $i < $renewalCount; ++$i) { + $this->di['dbal']->insert('promo_redemption', [ + 'promo_id' => $order['promo_id'], + 'client_id' => $order['client_id'], + 'client_order_id' => $order['id'], + 'invoice_id' => null, + 'phase' => 'renewal', + 'status' => 'committed', + 'discount_amount' => $discountAmount, + 'currency' => $order['currency'], + 'committed_at' => $renewalCreatedAt, + 'released_at' => null, + 'release_reason' => null, + 'created_at' => $renewalCreatedAt, + 'updated_at' => $renewalCreatedAt, + ]); + } + } + } + + // Normalize rows written by a previous partial migration run that pre-dated the + // status column; those rows have a NULL/empty status. Legitimate 'reserved' + // rows created by concurrent checkouts are left untouched so the payment flow + // can commit or release them normally. + $this->executeSql(" + UPDATE promo_redemption + SET + status = 'committed', + committed_at = COALESCE(committed_at, created_at), + release_reason = NULL + WHERE status IS NULL OR status = '' + "); + } + + private function patch73(): void + { + // Merge guest/public support tickets into the regular support ticket tables. + // See https://github.com/FOSSBilling/FOSSBilling/pull/3799 + if (!$this->tableHasColumn('support_ticket', 'access_hash')) { + $this->executeSql('ALTER TABLE `support_ticket` ADD COLUMN `access_hash` VARCHAR(255) DEFAULT NULL AFTER `client_id`;'); + } + + if (!$this->tableHasColumn('support_ticket', 'author_name')) { + $this->executeSql('ALTER TABLE `support_ticket` ADD COLUMN `author_name` VARCHAR(255) DEFAULT NULL AFTER `access_hash`;'); + } + + if (!$this->tableHasColumn('support_ticket', 'author_email')) { + $this->executeSql('ALTER TABLE `support_ticket` ADD COLUMN `author_email` VARCHAR(255) DEFAULT NULL AFTER `author_name`;'); + } + + if (!$this->tableHasIndex('support_ticket', 'access_hash_idx')) { + $this->executeSql('ALTER TABLE `support_ticket` ADD INDEX `access_hash_idx` (`access_hash`);'); + } + + $this->executeSql(" + DELETE FROM email_template + WHERE action_code IN ( + 'mod_staff_pticket_close', + 'mod_staff_pticket_open', + 'mod_staff_pticket_reply', + 'mod_support_pticket_open', + 'mod_support_pticket_staff_close', + 'mod_support_pticket_staff_open', + 'mod_support_pticket_staff_reply' + ) + "); + + // Remove obsolete guest/public ticket email templates from extracted update archives. + $this->executeFileActions([ + Path::join(PATH_MODS, 'Staff', 'templates', 'email', 'mod_staff_pticket_close.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Staff', 'templates', 'email', 'mod_staff_pticket_open.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Staff', 'templates', 'email', 'mod_staff_pticket_reply.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Support', 'templates', 'email', 'mod_support_pticket_open.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Support', 'templates', 'email', 'mod_support_pticket_staff_close.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Support', 'templates', 'email', 'mod_support_pticket_staff_open.html.twig') => 'unlink', + Path::join(PATH_MODS, 'Support', 'templates', 'email', 'mod_support_pticket_staff_reply.html.twig') => 'unlink', + ]); + + $row = $this->fetchOne( + "SELECT meta_value FROM extension_meta WHERE extension = 'mod_support' AND meta_key = 'config'", + ); + + if (is_string($row) && $row !== '') { + $configJson = $this->di['crypt']->decrypt($row, Config::getProperty('info.salt')); + if (is_string($configJson)) { + $config = json_decode($configJson, true); + if (is_array($config) && isset($config['disable_public_tickets']) && !isset($config['disable_guest_tickets'])) { + $config['disable_guest_tickets'] = $config['disable_public_tickets']; + unset($config['disable_public_tickets']); + $encrypted = $this->di['crypt']->encrypt(json_encode($config, JSON_THROW_ON_ERROR), Config::getProperty('info.salt')); + $this->executeSql( + "UPDATE extension_meta SET meta_value = :config WHERE extension = 'mod_support' AND meta_key = 'config'", + ['config' => $encrypted], + ); + } + } + } + + if (!$this->tableExists('support_p_ticket')) { + return; + } + + // Move legacy support_p_ticket rows into support_ticket, preserving guest access hashes. + $defaultHelpdeskId = $this->fetchOne('SELECT id FROM support_helpdesk ORDER BY id ASC LIMIT 1'); + if (!$defaultHelpdeskId) { + $now = date('Y-m-d H:i:s'); + $this->executeSql( + 'INSERT INTO support_helpdesk (name, close_after, can_reopen, created_at, updated_at) VALUES (:name, :close_after, :can_reopen, :created_at, :updated_at)', + [ + 'name' => 'General', + 'close_after' => 24, + 'can_reopen' => 0, + 'created_at' => $now, + 'updated_at' => $now, + ] + ); + $defaultHelpdeskId = $this->fetchOne('SELECT id FROM support_helpdesk ORDER BY id ASC LIMIT 1'); + } + + $publicTickets = $this->fetchAll('SELECT * FROM support_p_ticket ORDER BY id ASC'); + foreach ($publicTickets as $publicTicket) { + $this->executeSql( + 'INSERT INTO support_ticket (support_helpdesk_id, client_id, access_hash, author_name, author_email, subject, status, created_at, updated_at) + VALUES (:support_helpdesk_id, NULL, :access_hash, :author_name, :author_email, :subject, :status, :created_at, :updated_at)', + [ + 'support_helpdesk_id' => $defaultHelpdeskId, + 'access_hash' => $publicTicket['hash'], + 'author_name' => $publicTicket['author_name'], + 'author_email' => $publicTicket['author_email'], + 'subject' => $publicTicket['subject'], + 'status' => $publicTicket['status'], + 'created_at' => $publicTicket['created_at'], + 'updated_at' => $publicTicket['updated_at'], + ] + ); + + $ticketId = (int) $this->getPdo()->lastInsertId(); + $messages = $this->tableExists('support_p_ticket_message') + ? $this->fetchAll('SELECT * FROM support_p_ticket_message WHERE support_p_ticket_id = :id ORDER BY id ASC', [ + 'id' => $publicTicket['id'], + ]) : []; + + foreach ($messages as $message) { + $this->executeSql( + 'INSERT INTO support_ticket_message (support_ticket_id, admin_id, content, ip, created_at, updated_at) + VALUES (:support_ticket_id, :admin_id, :content, :ip, :created_at, :updated_at)', + [ + 'support_ticket_id' => $ticketId, + 'admin_id' => $message['admin_id'], + 'content' => $message['content'], + 'ip' => $message['ip'], + 'created_at' => $message['created_at'], + 'updated_at' => $message['updated_at'], + ] + ); + } + } + + if ($this->tableExists('support_p_ticket_message')) { + $this->executeSql('DROP TABLE `support_p_ticket_message`;'); + } + + $this->executeSql('DROP TABLE `support_p_ticket`;'); + } + private function generateDownloadableStoredFilename(): string { do { @@ -1759,158 +2046,4 @@ class UpdatePatcher implements InjectionAwareInterface ]); } } - - private function patch72(): void - { - $this->executeFileActions([ - Path::join(PATH_LIBRARY, 'Model', 'Product.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductCategory.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductCustom.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductDomain.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductDomainTable.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductDownloadable.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductHosting.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductLicense.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductPayment.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'ProductTable.php') => 'unlink', - Path::join(PATH_LIBRARY, 'Model', 'Promo.php') => 'unlink', - Path::join(PATH_CACHE, 'classMap.php') => 'unlink', - Path::join(PATH_CACHE, 'fallbackClassMap.php') => 'unlink', - ]); - - $schemaManager = $this->di['dbal']->createSchemaManager(); - if (!$schemaManager->tablesExist(['promo_redemption'])) { - $this->executeSql( - "CREATE TABLE `promo_redemption` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `promo_id` bigint(20) DEFAULT NULL, - `client_id` bigint(20) DEFAULT NULL, - `client_order_id` bigint(20) DEFAULT NULL, - `invoice_id` bigint(20) DEFAULT NULL, - `phase` varchar(30) NOT NULL DEFAULT 'checkout', - `status` varchar(30) NOT NULL DEFAULT 'reserved', - `discount_amount` decimal(18,2) DEFAULT NULL, - `currency` varchar(20) DEFAULT NULL, - `committed_at` datetime DEFAULT NULL, - `released_at` datetime DEFAULT NULL, - `release_reason` varchar(100) DEFAULT NULL, - `created_at` datetime DEFAULT NULL, - `updated_at` datetime DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `promo_id_idx` (`promo_id`), - KEY `client_id_idx` (`client_id`), - KEY `client_order_id_idx` (`client_order_id`), - KEY `invoice_id_idx` (`invoice_id`), - KEY `phase_idx` (`phase`), - KEY `status_idx` (`status`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8;" - ); - } - - $table = $schemaManager->introspectTable('promo_redemption'); - $columns = []; - - if (!$table->hasColumn('status')) { - $columns[] = "ADD COLUMN `status` varchar(30) NOT NULL DEFAULT 'reserved' AFTER `phase`"; - } - - if (!$table->hasColumn('committed_at')) { - $columns[] = 'ADD COLUMN `committed_at` datetime DEFAULT NULL AFTER `currency`'; - } - - if (!$table->hasColumn('released_at')) { - $columns[] = 'ADD COLUMN `released_at` datetime DEFAULT NULL AFTER `committed_at`'; - } - - if (!$table->hasColumn('release_reason')) { - $columns[] = 'ADD COLUMN `release_reason` varchar(100) DEFAULT NULL AFTER `released_at`'; - } - - if ($columns !== []) { - $this->executeSql('ALTER TABLE promo_redemption ' . implode(', ', $columns)); - } - - $table = $schemaManager->introspectTable('promo_redemption'); - $expectedIndexes = [ - 'promo_id_idx' => 'promo_id', - 'client_id_idx' => 'client_id', - 'client_order_id_idx' => 'client_order_id', - 'invoice_id_idx' => 'invoice_id', - 'phase_idx' => 'phase', - 'status_idx' => 'status', - ]; - - foreach ($expectedIndexes as $indexName => $columnName) { - if (!$table->hasIndex($indexName)) { - $this->executeSql(sprintf( - 'ALTER TABLE promo_redemption ADD INDEX `%s` (`%s`)', - $indexName, - $columnName - )); - } - } - - $existingRedemptions = (int) $this->di['dbal']->executeQuery('SELECT COUNT(id) FROM promo_redemption')->fetchOne(); - if ($existingRedemptions === 0) { - $orders = $this->di['dbal']->executeQuery( - 'SELECT id, promo_id, client_id, promo_used, discount, currency, created_at, updated_at - FROM client_order - WHERE promo_id IS NOT NULL' - )->fetchAllAssociative(); - - foreach ($orders as $order) { - $checkoutCreatedAt = $order['created_at'] ?? date('Y-m-d H:i:s'); - $renewalCreatedAt = $order['updated_at'] ?: $checkoutCreatedAt; - $discountAmount = $order['discount'] !== null ? (float) $order['discount'] : null; - - $this->di['dbal']->insert('promo_redemption', [ - 'promo_id' => $order['promo_id'], - 'client_id' => $order['client_id'], - 'client_order_id' => $order['id'], - 'invoice_id' => null, - 'phase' => 'checkout', - 'status' => 'committed', - 'discount_amount' => $discountAmount, - 'currency' => $order['currency'], - 'committed_at' => $checkoutCreatedAt, - 'released_at' => null, - 'release_reason' => null, - 'created_at' => $checkoutCreatedAt, - 'updated_at' => $checkoutCreatedAt, - ]); - - $renewalCount = max(0, ((int) ($order['promo_used'] ?? 1)) - 1); - for ($i = 0; $i < $renewalCount; ++$i) { - $this->di['dbal']->insert('promo_redemption', [ - 'promo_id' => $order['promo_id'], - 'client_id' => $order['client_id'], - 'client_order_id' => $order['id'], - 'invoice_id' => null, - 'phase' => 'renewal', - 'status' => 'committed', - 'discount_amount' => $discountAmount, - 'currency' => $order['currency'], - 'committed_at' => $renewalCreatedAt, - 'released_at' => null, - 'release_reason' => null, - 'created_at' => $renewalCreatedAt, - 'updated_at' => $renewalCreatedAt, - ]); - } - } - } - - // Normalize rows written by a previous partial migration run that pre-dated the - // status column; those rows have a NULL/empty status. Legitimate 'reserved' - // rows created by concurrent checkouts are left untouched so the payment flow - // can commit or release them normally. - $this->executeSql(" - UPDATE promo_redemption - SET - status = 'committed', - committed_at = COALESCE(committed_at, created_at), - release_reason = NULL - WHERE status IS NULL OR status = '' - "); - } } diff --git a/src/library/Model/SupportPTicket.php b/src/library/Model/SupportPTicket.php deleted file mode 100644 index 4d3b78173..000000000 --- a/src/library/Model/SupportPTicket.php +++ /dev/null @@ -1,17 +0,0 @@ -checkHoneypot($event); } - public static function onBeforeGuestPublicTicketOpen(\Box_Event $event): void + public static function onBeforeClientOpenTicket(\Box_Event $event): void { + if ($event->getParameters()['author_role'] !== 'guest') { + return; + } + $di = $event->getDi(); $antispamService = $di['mod_service']('Antispam'); $antispamService->isBlockedIp($event); diff --git a/src/modules/Antispam/tests/Unit/ServiceTest.php b/src/modules/Antispam/tests/Unit/ServiceTest.php index a3fbd7faa..bdba3110a 100644 --- a/src/modules/Antispam/tests/Unit/ServiceTest.php +++ b/src/modules/Antispam/tests/Unit/ServiceTest.php @@ -44,7 +44,7 @@ test('on before client sign up', function (): void { $service->onBeforeClientSignUp($boxEventMock); }); -test('on before guest public ticket open', function (): void { +test('on before client open ticket checks guest submissions', function (): void { $service = new Box\Mod\Antispam\Service(); $spamCheckerService = Mockery::mock(Box\Mod\Antispam\Service::class); $spamCheckerService->shouldReceive('isBlockedIp') @@ -60,8 +60,28 @@ test('on before guest public ticket open', function (): void { $boxEventMock->shouldReceive('getDi') ->atLeast()->once() ->andReturn($di); + $boxEventMock->shouldReceive('getParameters') + ->atLeast()->once() + ->andReturn(['author_role' => 'guest', 'email' => 'guest@example.com']); - $service->onBeforeGuestPublicTicketOpen($boxEventMock); + $service->onBeforeClientOpenTicket($boxEventMock); +}); + +test('on before client open ticket skips client submissions', function (): void { + $service = new Box\Mod\Antispam\Service(); + $spamCheckerService = Mockery::mock(Box\Mod\Antispam\Service::class); + $spamCheckerService->shouldReceive('isBlockedIp')->never(); + $spamCheckerService->shouldReceive('isSpam')->never(); + $spamCheckerService->shouldReceive('isTemp')->never(); + + $di = container(); + $di['mod_service'] = $di->protect(fn (): Mockery\MockInterface => $spamCheckerService); + $boxEventMock = Mockery::mock('\Box_Event'); + $boxEventMock->shouldReceive('getParameters') + ->atLeast()->once() + ->andReturn(['author_role' => 'client', 'client_id' => 1]); + + $service->onBeforeClientOpenTicket($boxEventMock); }); test('is blocked ip ip not blocked', function (): void { diff --git a/src/modules/Cron/Service.php b/src/modules/Cron/Service.php index d05705268..45f0f7f06 100644 --- a/src/modules/Cron/Service.php +++ b/src/modules/Cron/Service.php @@ -84,7 +84,6 @@ class Service $this->_exec($api, 'order_batch_suspend_expired'); $this->_exec($api, 'order_batch_cancel_suspended'); $this->_exec($api, 'support_batch_ticket_auto_close'); - $this->_exec($api, 'support_batch_public_ticket_auto_close'); $this->_exec($api, 'client_batch_expire_password_reminders'); $this->_exec($api, 'cart_batch_expire'); $this->_exec($api, 'email_batch_sendmail'); diff --git a/src/modules/Embed/templates/client/mod_embed_contact.html.twig b/src/modules/Embed/templates/client/mod_embed_contact.html.twig index 05dc98922..ee51f8723 100644 --- a/src/modules/Embed/templates/client/mod_embed_contact.html.twig +++ b/src/modules/Embed/templates/client/mod_embed_contact.html.twig @@ -65,7 +65,7 @@
- +
{{ include('mod_antispam_recaptcha.html.twig') }} @@ -99,7 +99,7 @@ if(json.error) { alert(json.error.message); } else { - parent.window.location = "{{ 'support/contact-us/conversation'|url }}" + '/' + json.result; + parent.window.location = "{{ 'support/ticket'|url }}" + '/' + json.result; } }) .catch(error => console.error('Error:', error)); diff --git a/src/modules/Redirect/Controller/Client.php b/src/modules/Redirect/Controller/Client.php index e1d65948b..3bc55eadb 100644 --- a/src/modules/Redirect/Controller/Client.php +++ b/src/modules/Redirect/Controller/Client.php @@ -38,7 +38,7 @@ class Client implements \FOSSBilling\InjectionAwareInterface $app->get('/service', 'get_orders', [], '\\' . \Box\Mod\Order\Controller\Client::class); $app->get('/service/manage/:id', 'get_order', ['id' => '[0-9]+'], '\\' . \Box\Mod\Order\Controller\Client::class); $app->get('/contact-us', 'get_contact_us', [], '\\' . \Box\Mod\Support\Controller\Client::class); - $app->get('/contact-us/conversation/:hash', 'get_contact_us_conversation', ['hash' => '[a-z0-9]+'], '\\' . \Box\Mod\Support\Controller\Client::class); + $app->get('/contact-us/conversation/:hash', 'get_ticket_redirect', ['hash' => '[a-z0-9]+'], '\\' . \Box\Mod\Support\Controller\Client::class); $service = $this->di['mod_service']('redirect'); $redirects = $service->getRedirects(); diff --git a/src/modules/Staff/Service.php b/src/modules/Staff/Service.php index 8658bb11e..a7f9c5780 100644 --- a/src/modules/Staff/Service.php +++ b/src/modules/Staff/Service.php @@ -369,9 +369,9 @@ class Service implements InjectionAwareInterface $ticketModel = $supportTicketService->getTicketById((int) $params['id']); $ticket = $supportTicketService->toApiArray($ticketModel, true); - $helpdeskModel = $di['db']->load('SupportHelpdesk', $ticketModel->support_helpdesk_id); + $helpdeskModel = isset($ticketModel->support_helpdesk_id) && $ticketModel->support_helpdesk_id ? $di['db']->load('SupportHelpdesk', $ticketModel->support_helpdesk_id) : null; $emailService = $di['mod_service']('email'); - if (!empty($helpdeskModel->email)) { + if ($helpdeskModel instanceof \Model_SupportHelpdesk && !empty($helpdeskModel->email)) { $email = []; $email['to'] = $helpdeskModel->email; $email['code'] = 'mod_support_helpdesk_ticket_open'; @@ -434,26 +434,6 @@ class Service implements InjectionAwareInterface } } - public static function onAfterGuestPublicTicketOpen(\Box_Event $event): void - { - $params = $event->getParameters(); - $di = $event->getDi(); - - try { - $supportTicketService = $di['mod_service']('support'); - $ticketModel = $supportTicketService->getPublicTicketById((int) $params['id']); - $ticket = $supportTicketService->publicToApiArray($ticketModel, true); - $email = []; - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_open'; - $email['ticket'] = $ticket; - $emailService = $di['mod_service']('email'); - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send staff public ticket notification email', ['exception' => $exc->getMessage()]); - } - } - public static function onAfterClientSignUp(\Box_Event $event): bool { $params = $event->getParameters(); @@ -475,46 +455,6 @@ class Service implements InjectionAwareInterface return true; } - public static function onAfterGuestPublicTicketReply(\Box_Event $event): void - { - $params = $event->getParameters(); - $di = $event->getDi(); - - try { - $supportTicketService = $di['mod_service']('support'); - $ticketModel = $supportTicketService->getPublicTicketById((int) $params['id']); - $ticket = $supportTicketService->publicToApiArray($ticketModel, true); - $email = []; - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_reply'; - $email['ticket'] = $ticket; - $emailService = $di['mod_service']('email'); - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send staff public ticket reply notification email', ['exception' => $exc->getMessage()]); - } - } - - public static function onAfterGuestPublicTicketClose(\Box_Event $event): void - { - $params = $event->getParameters(); - $di = $event->getDi(); - - try { - $supportService = $di['mod_service']('support'); - $publicTicket = $di['db']->load('SupportPTicket', $params['id']); - $ticket = $supportService->publicToApiArray($publicTicket); - $email = []; - $email['to_staff'] = true; - $email['code'] = 'mod_staff_pticket_close'; - $email['ticket'] = $ticket; - $emailService = $di['mod_service']('email'); - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send staff public ticket close notification email', ['exception' => $exc->getMessage()]); - } - } - public function getList($data) { $data['no_cron'] = true; diff --git a/src/modules/Staff/templates/email/mod_staff_pticket_close.html.twig b/src/modules/Staff/templates/email/mod_staff_pticket_close.html.twig deleted file mode 100644 index ede62b1e8..000000000 --- a/src/modules/Staff/templates/email/mod_staff_pticket_close.html.twig +++ /dev/null @@ -1,47 +0,0 @@ -{% block subject %}[{{ guest.system_company.name }}] {{ticket.subject|default('')}} [closed]{% endblock %} -{% block content %} - - - - - - - -

Ticket Closed

-

Hello {{ staff.name|default('') }},

-

Public ticket ID {{ ticket.id|default('') }} was closed by the client.

- -

You may login or edit your profile. - -

{{ guest.system_email.signature }}
- - -{% endblock %} diff --git a/src/modules/Staff/templates/email/mod_staff_pticket_open.html.twig b/src/modules/Staff/templates/email/mod_staff_pticket_open.html.twig deleted file mode 100644 index a22a0fdb9..000000000 --- a/src/modules/Staff/templates/email/mod_staff_pticket_open.html.twig +++ /dev/null @@ -1,49 +0,0 @@ -{% block subject %}[{{ guest.system_company.name }}] {{ ticket.subject|default('') }}{% endblock %} -{% block content %} - - - - - - - -

Ticket Opened

-

Hello {{ staff.name|default('') }},

-

New public ticket received.

- Reply here. -

Track the conversation here.

- -

You may login or edit your profile. - -

{{ guest.system_email.signature }}
- - -{% endblock %} diff --git a/src/modules/Staff/templates/email/mod_staff_pticket_reply.html.twig b/src/modules/Staff/templates/email/mod_staff_pticket_reply.html.twig deleted file mode 100644 index 6766120e6..000000000 --- a/src/modules/Staff/templates/email/mod_staff_pticket_reply.html.twig +++ /dev/null @@ -1,49 +0,0 @@ -{% block subject %}[{{ guest.system_company.name }}] {{ticket.subject|default('')}}{% endblock %} -{% block content %} - - - - - - - -

New Ticket Reply

-

Hello {{ staff.name|default('') }},

- -

Public ticket {{ticket.id|default('')}} has a new reply.

- Reply here.

- -

You may login or edit your profile. - -

{{ guest.system_email.signature }}
- - -{% endblock %} diff --git a/src/modules/Staff/templates/email/mod_staff_ticket_close.html.twig b/src/modules/Staff/templates/email/mod_staff_ticket_close.html.twig index 0ff13274e..ac4e04123 100644 --- a/src/modules/Staff/templates/email/mod_staff_ticket_close.html.twig +++ b/src/modules/Staff/templates/email/mod_staff_ticket_close.html.twig @@ -38,7 +38,7 @@

Ticket Closed

Hello {{ staff.name|default('') }},

-

{{ ticket.client.first_name|default('') }} {{ ticket.client.last_name|default('') }} closed support ticket #{{ ticket.id|default('') }}

+

{{ ticket.author.name|default('') }} closed support ticket #{{ ticket.id|default('') }}

Review the ticket

You may login or edit your profile. diff --git a/src/modules/Staff/templates/email/mod_staff_ticket_open.html.twig b/src/modules/Staff/templates/email/mod_staff_ticket_open.html.twig index 3b7b39e38..60b9e9081 100644 --- a/src/modules/Staff/templates/email/mod_staff_ticket_open.html.twig +++ b/src/modules/Staff/templates/email/mod_staff_ticket_open.html.twig @@ -38,7 +38,7 @@

Ticket Opened

Hello {{ staff.name|default('') }},

-

{{ ticket.client.first_name|default('') }} {{ ticket.client.last_name|default('') }} opened a new support ticket #{{ ticket.id|default('') }}

+

{{ ticket.author.name|default('') }} opened a new support ticket #{{ ticket.id|default('') }}

Review the ticket

Ticket contents

diff --git a/src/modules/Staff/templates/email/mod_staff_ticket_reply.html.twig b/src/modules/Staff/templates/email/mod_staff_ticket_reply.html.twig index 558cc04ca..01c5bd5cc 100644 --- a/src/modules/Staff/templates/email/mod_staff_ticket_reply.html.twig +++ b/src/modules/Staff/templates/email/mod_staff_ticket_reply.html.twig @@ -38,7 +38,7 @@

Ticket Reply

Hello {{ staff.name|default('') }},

-

{{ ticket.client.first_name|default('') }} {{ ticket.client.last_name|default('') }} replied to support ticket #{{ ticket.id|default('') }}

+

{{ ticket.author.name|default('') }} replied to support ticket #{{ ticket.id|default('') }}

Review the ticket

Ticket info

diff --git a/src/modules/Staff/tests/Unit/ServiceTest.php b/src/modules/Staff/tests/Unit/ServiceTest.php index 33eff50b7..e3d5d7a26 100644 --- a/src/modules/Staff/tests/Unit/ServiceTest.php +++ b/src/modules/Staff/tests/Unit/ServiceTest.php @@ -311,7 +311,8 @@ test('onAfterClientReplyTicket sends email notification', function (): void { ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once(); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once() + ->with(Mockery::on(fn ($email) => $email['code'] === 'mod_staff_ticket_reply')); $eventMock->shouldReceive('getparameters')->atLeast()->once() ->andReturn(['id' => random_int(1, 100)]); @@ -378,7 +379,8 @@ test('onAfterClientCloseTicket sends email notification', function (): void { ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once(); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once() + ->with(Mockery::on(fn ($email) => $email['code'] === 'mod_staff_ticket_close')); $eventMock->shouldReceive('getparameters')->atLeast()->once() ->andReturn(['id' => random_int(1, 100)]); @@ -435,17 +437,18 @@ test('onAfterClientCloseTicket handles email exception', function (): void { $service->onAfterClientCloseTicket($eventMock); }); -test('onAfterGuestPublicTicketOpen sends email notification', function (): void { +test('onAfterClientOpenTicket sends guest email notification', function (): void { $eventMock = Mockery::mock('\Box_Event'); $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); - $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once() - ->andReturn(new Model_SupportPTicket()); - $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once() + $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() + ->andReturn(new Model_SupportTicket()); + $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once() ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once(); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once() + ->with(Mockery::on(fn ($email) => $email['code'] === 'mod_staff_ticket_open')); $eventMock->shouldReceive('getparameters')->atLeast()->once() ->andReturn(['id' => random_int(1, 100)]); @@ -465,16 +468,16 @@ test('onAfterGuestPublicTicketOpen sends email notification', function (): void $eventMock->shouldReceive('getDi')->atLeast()->once() ->andReturn($di); $service->setDi($di); - $service->onAfterGuestPublicTicketOpen($eventMock); + $service->onAfterClientOpenTicket($eventMock); }); -test('onAfterGuestPublicTicketOpen handles email exception', function (): void { +test('onAfterClientOpenTicket handles guest email exception', function (): void { $eventMock = Mockery::mock('\Box_Event'); $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); - $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once() - ->andReturn(new Model_SupportPTicket()); - $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once() + $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() + ->andReturn(new Model_SupportTicket()); + $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once() ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); @@ -499,20 +502,21 @@ test('onAfterGuestPublicTicketOpen handles email exception', function (): void { $eventMock->shouldReceive('getDi')->atLeast()->once() ->andReturn($di); $service->setDi($di); - $service->onAfterGuestPublicTicketOpen($eventMock); + $service->onAfterClientOpenTicket($eventMock); }); -test('onAfterGuestPublicTicketReply sends email notification', function (): void { +test('onAfterClientReplyTicket sends guest email notification', function (): void { $eventMock = Mockery::mock('\Box_Event'); $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); - $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once() - ->andReturn(new Model_SupportPTicket()); - $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once() + $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() + ->andReturn(new Model_SupportTicket()); + $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once() ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); - $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once(); + $emailServiceMock->shouldReceive('sendTemplate')->atLeast()->once() + ->with(Mockery::on(fn ($email) => $email['code'] === 'mod_staff_ticket_reply')); $eventMock->shouldReceive('getparameters')->atLeast()->once() ->andReturn(['id' => random_int(1, 100)]); @@ -532,16 +536,16 @@ test('onAfterGuestPublicTicketReply sends email notification', function (): void $eventMock->shouldReceive('getDi')->atLeast()->once() ->andReturn($di); $service->setDi($di); - $service->onAfterGuestPublicTicketReply($eventMock); + $service->onAfterClientReplyTicket($eventMock); }); -test('onAfterGuestPublicTicketReply handles email exception', function (): void { +test('onAfterClientReplyTicket handles guest email exception', function (): void { $eventMock = Mockery::mock('\Box_Event'); $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); - $supportServiceMock->shouldReceive('getPublicTicketById')->atLeast()->once() - ->andReturn(new Model_SupportPTicket()); - $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once() + $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() + ->andReturn(new Model_SupportTicket()); + $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once() ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); @@ -566,7 +570,7 @@ test('onAfterGuestPublicTicketReply handles email exception', function (): void $eventMock->shouldReceive('getDi')->atLeast()->once() ->andReturn($di); $service->setDi($di); - $service->onAfterGuestPublicTicketReply($eventMock); + $service->onAfterClientReplyTicket($eventMock); }); test('onAfterClientSignUp sends email notification', function (): void { @@ -632,11 +636,13 @@ test('onAfterClientSignUp handles email exception', function (): void { $service->onAfterClientSignUp($eventMock); }); -test('onAfterGuestPublicTicketClose handles email exception', function (): void { +test('onAfterClientCloseTicket handles guest email exception', function (): void { $eventMock = Mockery::mock('\Box_Event'); $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); - $supportServiceMock->shouldReceive('publicToApiArray')->atLeast()->once() + $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() + ->andReturn(new Model_SupportTicket()); + $supportServiceMock->shouldReceive('toApiArray')->atLeast()->once() ->andReturn([]); $emailServiceMock = Mockery::mock(Box\Mod\Email\Service::class); @@ -646,10 +652,6 @@ test('onAfterGuestPublicTicketClose handles email exception', function (): void $eventMock->shouldReceive('getparameters')->atLeast()->once() ->andReturn(['id' => random_int(1, 100)]); - $dbMock = Mockery::mock('\Box_Database'); - $dbMock->shouldReceive('load')->atLeast()->once() - ->andReturn(new Model_SupportPTicket()); - $service = new Service(); $di = container(); @@ -661,12 +663,10 @@ test('onAfterGuestPublicTicketClose handles email exception', function (): void return $emailServiceMock; } }); - $di['db'] = $dbMock; - $eventMock->shouldReceive('getDi')->atLeast()->once() ->andReturn($di); $service->setDi($di); - $service->onAfterGuestPublicTicketClose($eventMock); + $service->onAfterClientCloseTicket($eventMock); }); test('onAfterClientOpenTicket sends mod_staff_ticket_open email', function (): void { @@ -674,6 +674,7 @@ test('onAfterClientOpenTicket sends mod_staff_ticket_open email', function (): v $ticketModel = new Model_SupportTicket(); $ticketModel->loadBean(new Tests\Helpers\DummyBean()); + $ticketModel->support_helpdesk_id = 1; $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() @@ -728,6 +729,7 @@ test('onAfterClientOpenTicket sends mod_support_helpdesk_ticket_open email', fun $ticketModel = new Model_SupportTicket(); $ticketModel->loadBean(new Tests\Helpers\DummyBean()); + $ticketModel->support_helpdesk_id = 1; $supportServiceMock = Mockery::mock(Box\Mod\Support\Service::class); $supportServiceMock->shouldReceive('getTicketById')->atLeast()->once() diff --git a/src/modules/Support/Api/Admin.php b/src/modules/Support/Api/Admin.php index 3732dc3ec..c7617b037 100644 --- a/src/modules/Support/Api/Admin.php +++ b/src/modules/Support/Api/Admin.php @@ -185,27 +185,6 @@ class Admin extends \FOSSBilling\Api\AbstractApi return true; } - /** - * Action to close all inquiries which have not received any replies for a - * time defined in helpdesk. - * - * Run by cron job - */ - public function batch_public_ticket_auto_close($data): bool - { - $this->checkPermissions('support', 'manage_tickets'); - - // Auto close public tickets - $expired = $this->getService()->publicGetExpired(); - foreach ($expired as $model) { - if (!$this->getService()->publicAutoClose($model)) { - $this->getDi()['logger']->info('Public Ticket %s was not closed', $model->id); - } - } - - return true; - } - /** * Return tickets statuses with counter. */ @@ -220,134 +199,6 @@ class Admin extends \FOSSBilling\Api\AbstractApi return $this->getService()->counter(); } - /** - * Get paginated list of inquiries. - */ - public function public_ticket_get_list(array $data): array - { - $this->checkPermissions('support', 'view'); - - [$sql, $bindings] = $this->getService()->publicGetSearchQuery($data); - $pager = $this->getDi()['pager']->getPaginatedResultSet($sql, $bindings, PaginationOptions::fromArray($data)); - - foreach ($pager['list'] as $key => $ticketArr) { - $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $ticketArr['id'], 'Ticket not found'); - $pager['list'][$key] = $this->getService()->publicToApiArray($ticket, true, $this->getIdentity()); - } - - return $pager; - } - - /** - * Create new public inquiry. - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['name' => 'Name is required', 'email' => 'Email is required', 'subject' => 'Subject is required', 'message' => 'Message is required'])] - public function public_ticket_create(array $data): int - { - $this->checkPermissions('support', 'manage_tickets'); - - $data['subject'] = \FOSSBilling\Tools::sanitizeContent($data['subject'], false); - $data['message'] = \FOSSBilling\Tools::sanitizeContent($data['message'], true); - - return $this->getService()->publicTicketCreate($data, $this->getIdentity()); - } - - /** - * Get inquiry details. - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['id' => 'Ticket ID is missing'])] - public function public_ticket_get(array $data): array - { - $this->checkPermissions('support', 'view'); - - $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); - - return $this->getService()->publicToApiArray($model, true, $this->getIdentity()); - } - - /** - * Delete inquiry. - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['id' => 'Ticket ID is missing'])] - public function public_ticket_delete(array $data): bool - { - $this->checkPermissions('support', 'manage_tickets'); - - $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); - - return $this->getService()->publicRm($model); - } - - /** - * Set id status to closed. - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['id' => 'Ticket ID is missing'])] - public function public_ticket_close(array $data): bool - { - $this->checkPermissions('support', 'manage_tickets'); - - $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); - - return $this->getService()->publicCloseTicket($ticket, $this->getIdentity()); - } - - /** - * Update inquiry details. - * - * @optional string $subject - subject - * @optional string $status - status - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['id' => 'Ticket ID is missing'])] - public function public_ticket_update(array $data): bool - { - $this->checkPermissions('support', 'manage_tickets'); - - $model = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); - - return $this->getService()->publicTicketUpdate($model, $data); - } - - /** - * Post new reply to inquiry. - * - * @throws \FOSSBilling\Exception - */ - #[RequiredParams(['id' => 'Ticket ID is missing', 'content' => 'Ticket content required'])] - public function public_ticket_reply(array $data): int - { - $this->checkPermissions('support', 'manage_tickets'); - - $data['content'] = \FOSSBilling\Tools::sanitizeContent($data['content'], true); - - $ticket = $this->getDi()['db']->getExistingModelById('SupportPTicket', $data['id'], 'Ticket not found'); - - return $this->getService()->publicTicketReply($ticket, $this->getIdentity(), $data['content']); - } - - /** - * Return tickets statuses with counter. - */ - public function public_ticket_get_statuses(array $data): array - { - $this->checkPermissions('support', 'view'); - - if (isset($data['titles'])) { - return $this->getService()->publicGetStatuses(); - } - - return $this->getService()->publicCounter(); - } - /** * Get helpdesk list. */ @@ -677,21 +528,6 @@ class Admin extends \FOSSBilling\Api\AbstractApi return true; } - /** - * Deletes tickets with given IDs. - */ - #[RequiredParams(['ids' => 'IDs were not passed'])] - public function batch_delete_public($data): bool - { - $this->checkPermissions('support', 'manage_tickets'); - - foreach ($data['ids'] as $id) { - $this->public_ticket_delete(['id' => $id]); - } - - return true; - } - /* * Support Knowledge Base. */ diff --git a/src/modules/Support/Api/Client.php b/src/modules/Support/Api/Client.php index d7c085bb1..c65f7bfe3 100644 --- a/src/modules/Support/Api/Client.php +++ b/src/modules/Support/Api/Client.php @@ -22,7 +22,7 @@ use FOSSBilling\Validation\Api\RequiredParams; class Client extends \FOSSBilling\Api\AbstractApi { /** - * Get client tickets list. + * Get the list of tickets for the logged in client. * * @optional string status - filter tickets by status * @optional string date_from - show tickets created since this day. Can be any string parsable by strtotime() diff --git a/src/modules/Support/Api/Guest.php b/src/modules/Support/Api/Guest.php index 91412bb0f..5da641733 100644 --- a/src/modules/Support/Api/Guest.php +++ b/src/modules/Support/Api/Guest.php @@ -10,10 +10,6 @@ declare(strict_types=1); * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ -/** - * Public tickets management. - */ - namespace Box\Mod\Support\Api; use FOSSBilling\PaginationOptions; @@ -22,7 +18,7 @@ use FOSSBilling\Validation\Api\RequiredParams; class Guest extends \FOSSBilling\Api\AbstractApi { /** - * Submit new public ticket. + * Submit new ticket. * * @return string - ticket hash */ @@ -30,72 +26,88 @@ class Guest extends \FOSSBilling\Api\AbstractApi 'name' => 'Please enter your name', 'email' => 'Please enter your email address', 'subject' => 'Please enter the subject', - 'message' => 'Please enter your message', ])] public function ticket_create(array $data): string { - $this->getDi()['rate_limiter']->consumeOrThrow('guest_ticket_create', (string) $this->getIp()); - - if (!is_string($data['message']) || strlen($data['message']) < 4) { + // Deprecated 0.9.0 The 'message' parameter will be dropped. Update your themes to use 'content' instead. + $content = $data['content'] ?? $data['message'] ?? null; + if (!is_string($content) || strlen($content) < 4) { throw new \FOSSBilling\InformationException('Please enter your message'); } + $data['email'] = $this->getDi()['tools']->validateAndSanitizeEmail($data['email']); + $this->getDi()['rate_limiter']->consumeOrThrow('guest_ticket_create', (string) $this->getIp()); + // Sanitize message to prevent XSS attacks - $data['message'] = \FOSSBilling\Tools::sanitizeContent($data['message'], true); + $data['content'] = \FOSSBilling\Tools::sanitizeContent($content, true); return $this->getService()->ticketCreateForGuest($data); } /** - * Get public ticket. + * Get ticket. * * @return array - ticket details */ - #[RequiredParams(['hash' => 'Public ticket hash required'])] + #[RequiredParams(['hash' => 'Ticket hash required'])] public function ticket_get(array $data): array { - $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); + $guestTicket = $this->getService()->findOneByHash($data['hash']); - return $this->getService()->publicToApiArray($publicTicket); + return $this->getService()->toApiArray($guestTicket); } /** - * Close public ticket. + * Close ticket. */ - #[RequiredParams(['hash' => 'Public ticket hash required'])] + #[RequiredParams(['hash' => 'Ticket hash required'])] public function ticket_close(array $data): bool { - $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); + $guestTicket = $this->getService()->findOneByHash($data['hash']); - return $this->getService()->publicCloseTicket($publicTicket, $this->getIdentity()); + return $this->getService()->closeTicket($guestTicket, $this->getIdentity()); } /** - * Reply to public ticket. - * - * @return string - ticket hash + * Reply to ticket. */ - #[RequiredParams(['hash' => 'Public ticket hash required', 'message' => 'Message cannot be empty'])] - public function ticket_reply(array $data): string + #[RequiredParams(['hash' => 'Ticket hash required'])] + public function ticket_reply(array $data): int { - $publicTicket = $this->getService()->publicFindOneByHash($data['hash']); + $guestTicket = $this->getService()->findOneByHash($data['hash']); + // Deprecated 0.9.0 The 'message' parameter will be dropped. Update your themes to use 'content' instead. + $message = $data['content'] ?? $data['message'] ?? null; - if (!is_string($data['message'])) { + if (!is_string($message)) { throw new \FOSSBilling\InformationException('Message cannot be empty'); } // Sanitize message to prevent XSS attacks - $data['message'] = \FOSSBilling\Tools::sanitizeContent($data['message'], true); + $message = \FOSSBilling\Tools::sanitizeContent($message, true); - return $this->getService()->publicTicketReplyForGuest($publicTicket, $data['message']); + return $this->getService()->ticketReply($guestTicket, new \Model_Guest(), $message); } /** - * Get whether public tickets are enabled for guests. + * Get whether guest tickets are enabled. */ + public function guest_tickets_enabled(): bool + { + return $this->getService()->guestTicketsEnabled(); + } + public function public_tickets_enabled(): bool { - return $this->getService()->publicTicketsEnabled(); + // @deprecated 0.9.0 Use guest_tickets_enabled instead. + return $this->guest_tickets_enabled(); + } + + /** + * Return pairs for support helpdesks. Can be used to populate the select box. + */ + public function helpdesk_get_pairs(): array + { + return $this->getService()->helpdeskGetPairs(); } /* diff --git a/src/modules/Support/Controller/Admin.php b/src/modules/Support/Controller/Admin.php index e788d0892..3811a17fb 100644 --- a/src/modules/Support/Controller/Admin.php +++ b/src/modules/Support/Controller/Admin.php @@ -38,18 +38,11 @@ class Admin implements \FOSSBilling\InjectionAwareInterface 'subpages' => [ [ 'location' => 'support', - 'label' => __trans('Client Tickets'), + 'label' => __trans('Support Tickets'), 'uri' => $this->di['url']->adminLink('support', ['status' => 'open']), 'index' => 100, 'class' => '', ], - [ - 'location' => 'support', - 'label' => __trans('Public Tickets'), - 'uri' => $this->di['url']->adminLink('support/public-tickets', ['status' => 'open']), - 'index' => 200, - 'class' => '', - ], [ 'location' => 'support', 'label' => __trans('Canned Responses'), @@ -81,8 +74,6 @@ class Admin implements \FOSSBilling\InjectionAwareInterface $app->get('/support/index', 'get_index', [], static::class); $app->get('/support/ticket/:id', 'get_ticket', ['id' => '[0-9]+'], static::class); $app->get('/support/ticket/:id/message/:messageid', 'get_ticket', ['id' => '[0-9]+', 'messageid' => '[0-9]+'], static::class); - $app->get('/support/public-tickets', 'get_public_tickets', [], static::class); - $app->get('/support/public-ticket/:id', 'get_public_ticket', ['id' => '[0-9]+'], static::class); $app->get('/support/helpdesks', 'get_helpdesks', [], static::class); $app->get('/support/helpdesk/:id', 'get_helpdesk', ['id' => '[0-9]+'], static::class); $app->get('/support/canned-responses', 'get_canned_list', [], static::class); @@ -130,40 +121,6 @@ class Admin implements \FOSSBilling\InjectionAwareInterface return $app->render('mod_support_ticket', ['ticket' => $ticket, 'canned_delay_message' => $cdm, 'request_message' => $messageid]); } - public function get_public_tickets(\Box_App $app): string - { - $this->di['is_admin_logged']; - - return $app->render('mod_support_public_tickets'); - } - - public function get_public_ticket(\Box_App $app, $id): string - { - $api = $this->di['api_admin']; - $ticket = $api->support_public_ticket_get(['id' => $id]); - - $cdm = ''; - $mod = $this->di['mod']('support'); - $config = $mod->getConfig(); - - try { - if (isset($config['delay_enable']) && $config['delay_enable'] && isset($config['delay_hours']) && $config['delay_hours'] >= 0) { - $last_message = end($ticket['messages']); - reset($ticket); - - $hours_passed = (round((time() - strtotime((string) $last_message['created_at'])) / 3600) > $config['delay_hours']); - if ($hours_passed) { - $delay_canned = $api->support_canned_get(['id' => $config['delay_message_id']]); - $cdm = $delay_canned['content']; - } - } - } catch (\Exception $e) { - $this->di['logger']->error($e->getMessage()); - } - - return $app->render('mod_support_public_ticket', ['ticket' => $ticket, 'canned_delay_message' => $cdm]); - } - public function get_helpdesk(\Box_App $app, $id): string { $api = $this->di['api_admin']; diff --git a/src/modules/Support/Controller/Client.php b/src/modules/Support/Controller/Client.php index e524b41ec..c6895f43a 100644 --- a/src/modules/Support/Controller/Client.php +++ b/src/modules/Support/Controller/Client.php @@ -31,7 +31,7 @@ class Client implements \FOSSBilling\InjectionAwareInterface $app->get('/support', 'get_tickets', [], static::class); $app->get('/support/ticket/:id', 'get_ticket', [], static::class); $app->get('/support/contact-us', 'get_contact_us', [], static::class); - $app->get('/support/contact-us/conversation/:hash', 'get_contact_us_conversation', ['hash' => '[a-z0-9]+'], static::class); + $app->get('/support/contact-us/conversation/:hash', 'get_ticket_redirect', ['hash' => '[a-z0-9]+'], static::class); if ($this->di['mod']('support')->getService()->kbEnabled()) { $app->get('/support/kb', 'get_kb_index', [], static::class); @@ -49,8 +49,13 @@ class Client implements \FOSSBilling\InjectionAwareInterface public function get_ticket(\Box_App $app, $id): string { - $api = $this->di['api_client']; - $ticket = $api->support_ticket_get(['id' => $id]); + $id = (string) $id; + if (ctype_digit($id) && strlen($id) < 30) { + $this->di['is_client_logged']; + $ticket = $this->di['api_client']->support_ticket_get(['id' => $id]); + } else { + $ticket = $this->di['api_guest']->support_ticket_get(['hash' => $id]); + } return $app->render('mod_support_ticket', ['ticket' => $ticket]); } @@ -60,15 +65,14 @@ class Client implements \FOSSBilling\InjectionAwareInterface return $app->render('mod_support_contact_us'); } - public function get_contact_us_conversation(\Box_App $app, $hash): string + /** + * A redirect to keep old guest ticket links working. + * + * /support/contact-us/conversation/:hash -> /support/ticket/:hash + */ + public function get_ticket_redirect(\Box_App $app, $hash): never { - $api = $this->di['api_guest']; - $data = [ - 'hash' => $hash, - ]; - $array = $api->support_ticket_get($data); - - return $app->render('mod_support_contact_us_conversation', ['ticket' => $array]); + $app->redirect('support/ticket/' . $hash); } /* diff --git a/src/modules/Support/Service.php b/src/modules/Support/Service.php index 76a3ec05e..3d415151c 100644 --- a/src/modules/Support/Service.php +++ b/src/modules/Support/Service.php @@ -69,11 +69,17 @@ class Service implements \FOSSBilling\InjectionAwareInterface try { $ticketObj = $supportService->getTicketById((int) $params['id']); - $identity = $di['loggedin_client']; + $isGuestTicket = $supportService->isGuestTicket($ticketObj); + $identity = $isGuestTicket ? null : $di['loggedin_client']; $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); $email = []; - $email['to_client'] = $ticketObj->client_id; + if ($isGuestTicket) { + $email['to'] = $ticketObj->author_email; + $email['to_name'] = $ticketObj->author_name; + } else { + $email['to_client'] = $ticketObj->client_id; + } $email['code'] = 'mod_support_ticket_open'; $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); @@ -95,7 +101,12 @@ class Service implements \FOSSBilling\InjectionAwareInterface $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); $email = []; - $email['to_client'] = $ticketObj->client_id; + if ($supportService->isGuestTicket($ticketObj)) { + $email['to'] = $ticketObj->author_email; + $email['to_name'] = $ticketObj->author_name; + } else { + $email['to_client'] = $ticketObj->client_id; + } $email['code'] = 'mod_support_ticket_staff_open'; $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); @@ -117,7 +128,12 @@ class Service implements \FOSSBilling\InjectionAwareInterface $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); $email = []; - $email['to_client'] = $ticketObj->client_id; + if ($supportService->isGuestTicket($ticketObj)) { + $email['to'] = $ticketObj->author_email; + $email['to_name'] = $ticketObj->author_name; + } else { + $email['to_client'] = $ticketObj->client_id; + } $email['code'] = 'mod_support_ticket_staff_close'; $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); @@ -139,7 +155,12 @@ class Service implements \FOSSBilling\InjectionAwareInterface $ticketArr = $supportService->toApiArray($ticketObj, true, $identity); $email = []; - $email['to_client'] = $ticketObj->client_id; + if ($supportService->isGuestTicket($ticketObj)) { + $email['to'] = $ticketObj->author_email; + $email['to_name'] = $ticketObj->author_name; + } else { + $email['to_client'] = $ticketObj->client_id; + } $email['code'] = 'mod_support_ticket_staff_reply'; $email['ticket'] = $ticketArr; $emailService->sendTemplate($email); @@ -148,105 +169,19 @@ class Service implements \FOSSBilling\InjectionAwareInterface } } - public static function onAfterGuestPublicTicketOpen(\Box_Event $event): void - { - $di = $event->getDi(); - $supportService = $di['mod_service']('support'); - $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); - - try { - $ticketObj = $supportService->getPublicTicketById((int) $params['id']); - $ticketArr = $supportService->publicToApiArray($ticketObj, true); - - $email = []; - $email['to'] = $ticketObj->author_email; - $email['to_name'] = $ticketObj->author_name; - $email['code'] = 'mod_support_pticket_open'; - $email['ticket'] = $ticketArr; - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send public ticket open email', ['exception' => $exc->getMessage()]); - } - } - - public static function onAfterAdminPublicTicketOpen(\Box_Event $event): void - { - $di = $event->getDi(); - $supportService = $di['mod_service']('support'); - $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); - - try { - $ticketObj = $supportService->getPublicTicketById((int) $params['id']); - $identity = $di['loggedin_admin']; - $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - - $email = []; - $email['to'] = $ticketArr['author_email']; - $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_open'; - $email['ticket'] = $ticketArr; - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send admin public ticket open email', ['exception' => $exc->getMessage()]); - } - } - - public static function onAfterAdminPublicTicketReply(\Box_Event $event): void - { - $di = $event->getDi(); - $supportService = $di['mod_service']('support'); - $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); - - try { - $ticketObj = $supportService->getPublicTicketById((int) $params['id']); - $identity = $di['loggedin_admin']; - $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - - $email = []; - $email['to'] = $ticketArr['author_email']; - $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_reply'; - $email['ticket'] = $ticketArr; - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send admin public ticket reply email', ['exception' => $exc->getMessage()]); - } - } - - public static function onAfterAdminPublicTicketClose(\Box_Event $event): void - { - $di = $event->getDi(); - $supportService = $di['mod_service']('support'); - $emailService = $di['mod_service']('email'); - $params = $event->getParameters(); - - try { - $ticketObj = $supportService->getPublicTicketById((int) $params['id']); - $identity = $di['loggedin_admin']; - $ticketArr = $supportService->publicToApiArray($ticketObj, true, $identity); - - $email = []; - $email['to'] = $ticketArr['author_email']; - $email['to_name'] = $ticketArr['author_name']; - $email['code'] = 'mod_support_pticket_staff_close'; - $email['ticket'] = $ticketArr; - $emailService->sendTemplate($email); - } catch (\Exception $exc) { - $di['logger']->setChannel('email')->error('Failed to send admin public ticket close email', ['exception' => $exc->getMessage()]); - } - } - public function getTicketById(int $id): \Model_SupportTicket { return $this->di['db']->getExistingModelById('SupportTicket', $id, 'Ticket not found'); } - public function getPublicTicketById(int $id): \Model_SupportPTicket + /** + * Determine if the provided ticket is a guest ticket + * + * @todo Doctrine: Move this to the Entity when migrating to Doctrine + */ + public function isGuestTicket(\Model_SupportTicket $ticket): bool { - return $this->di['db']->getExistingModelById('SupportPTicket', $id, 'Ticket not found'); + return empty($ticket->client_id) && !empty($ticket->access_hash); } /** @@ -300,6 +235,9 @@ class Service implements \FOSSBilling\InjectionAwareInterface $date_from = $data['date_from'] ?? null; $date_to = $data['date_to'] ?? null; $priority = $data['priority'] ?? null; + $auth = $data['auth'] ?? null; + $name = $data['name'] ?? null; + $email = $data['email'] ?? null; $where = []; $bindings = []; @@ -331,6 +269,22 @@ class Service implements \FOSSBilling\InjectionAwareInterface $bindings[':client_id'] = $client_id; } + if ($auth === 'guest') { + $where[] = 'st.client_id IS NULL AND st.access_hash IS NOT NULL'; + } elseif ($auth === 'client') { + $where[] = 'st.client_id IS NOT NULL'; + } + + if ($name) { + $where[] = 'st.author_name LIKE :filter_author_name'; + $bindings[':filter_author_name'] = '%' . $name . '%'; + } + + if ($email) { + $where[] = 'st.author_email LIKE :filter_author_email'; + $bindings[':filter_author_email'] = '%' . $email . '%'; + } + if ($content) { $where[] = 'stm.content LIKE :content'; $bindings[':content'] = '%' . $content . '%'; @@ -373,9 +327,11 @@ class Service implements \FOSSBilling\InjectionAwareInterface $bindings[':ticket_id'] = $search; } else { $search = '%' . $search . '%'; - $where[] = '(stm.content LIKE :content OR st.subject LIKE :subject)'; + $where[] = '(stm.content LIKE :content OR st.subject LIKE :subject OR st.author_name LIKE :author_name OR st.author_email LIKE :author_email)'; $bindings[':content'] = $search; $bindings[':subject'] = $search; + $bindings[':author_name'] = $search; + $bindings[':author_email'] = $search; } } @@ -472,7 +428,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface return $ticket instanceof \Model_SupportTicket; } - public function closeTicket(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client $identity): bool + public function closeTicket(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client|\Model_Guest $identity): bool { $ticket->status = \Model_SupportTicket::CLOSED; $ticket->updated_at = date('Y-m-d H:i:s'); @@ -481,7 +437,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface if ($identity instanceof \Model_Admin) { $this->di['events_manager']->fire(['event' => 'onAfterAdminCloseTicket', 'params' => ['id' => $ticket->id]]); - } elseif ($identity instanceof \Model_Client) { + } else { $this->di['events_manager']->fire(['event' => 'onAfterClientCloseTicket', 'params' => ['id' => $ticket->id]]); } @@ -574,12 +530,14 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function toApiArray(\Model_SupportTicket $model, bool $deep = true, \Model_Admin|\Model_Client|null $identity = null): array { $firstSupportTicketMessage = $this->di['db']->findOne('SupportTicketMessage', 'support_ticket_id = :support_ticket_id ORDER by id ASC LIMIT 1', [':support_ticket_id' => $model->id]); - $supportHelpdesk = $this->di['db']->load('SupportHelpdesk', $model->support_helpdesk_id); + $supportHelpdesk = $model->support_helpdesk_id ? $this->di['db']->load('SupportHelpdesk', $model->support_helpdesk_id) : null; $data = $this->ticketToApiArray($this->di['db']->toArray($model), $identity); $data['replies'] = $this->messageGetRepliesCount($model); $data['first'] = $firstSupportTicketMessage instanceof \Model_SupportTicketMessage ? $this->messageToApiArray($firstSupportTicketMessage, true, $identity) : null; - $data['helpdesk'] = $this->helpdeskToApiArray($supportHelpdesk, $identity); + $data['helpdesk'] = $supportHelpdesk instanceof \Model_SupportHelpdesk ? $this->helpdeskToApiArray($supportHelpdesk, $identity) : null; + $data['author'] = $this->getTicketAuthor($model, $identity); + // @deprecated 0.9.0 Use author instead. $data['client'] = $this->getClientApiArrayForTicket($model, $identity); if ($deep) { @@ -605,14 +563,21 @@ class Service implements \FOSSBilling\InjectionAwareInterface private function ticketToApiArray(array $data, \Model_Admin|\Model_Client|null $identity = null): array { + if (!empty($data['access_hash'])) { + $data['hash'] = $data['access_hash']; + } + if ($identity instanceof \Model_Admin) { return $data; } + // @deprecated 0.9.0 Use author.id/name/email instead of client_id/author_name/author_email. + unset( $data['support_helpdesk_id'], $data['client_id'], $data['priority'], + $data['access_hash'], $data['rel_type'], $data['rel_id'], $data['rel_task'], @@ -699,11 +664,13 @@ class Service implements \FOSSBilling\InjectionAwareInterface } $clients = []; + $clientAuthors = []; if (!empty($clientIds)) { $placeholders = implode(',', array_fill(0, count($clientIds), '?')); $clientModels = $this->di['db']->find('Client', "id IN ($placeholders)", $clientIds); foreach ($clientModels as $client) { $clients[$client->id] = $this->clientToTicketApiArray($client, $identity); + $clientAuthors[$client->id] = $this->clientToTicketAuthorArray($client); } } @@ -716,10 +683,22 @@ class Service implements \FOSSBilling\InjectionAwareInterface $helpdesk = $helpdesks[$ticket['support_helpdesk_id']] ?? null; $data['helpdesk'] = $helpdesk ? $this->helpdeskToApiArray($helpdesk, $identity) : null; - if (!isset($clients[$ticket['client_id']])) { + if (empty($ticket['client_id']) && !empty($ticket['access_hash'])) { + $data['author'] = [ + 'name' => $ticket['author_name'], + 'email' => $ticket['author_email'], + 'role' => 'guest', + ]; + // @deprecated 0.9.0 Use author instead. + $data['client'] = []; + } elseif (!isset($clients[$ticket['client_id']])) { $this->di['logger']->error('Missing client for ticket ' . $ticket['id']); + $data['author'] = []; + // @deprecated 0.9.0 Use author instead. $data['client'] = []; } else { + $data['author'] = $clientAuthors[$ticket['client_id']]; + // @deprecated 0.9.0 Use author instead. $data['client'] = $clients[$ticket['client_id']]; } @@ -774,8 +753,12 @@ class Service implements \FOSSBilling\InjectionAwareInterface return $ordered; } - public function getClientApiArrayForTicket(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client|null $identity = null): array + private function getClientApiArrayForTicket(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client|null $identity = null): array { + if ($this->isGuestTicket($ticket)) { + return []; + } + $client = $this->di['db']->load('Client', $ticket->client_id); if ($client instanceof \Model_Client) { @@ -786,6 +769,43 @@ class Service implements \FOSSBilling\InjectionAwareInterface return []; } + private function getTicketAuthor(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client|null $identity = null): array + { + if ($this->isGuestTicket($ticket)) { + $author = [ + 'name' => $ticket->author_name, + 'role' => 'guest', + ]; + + if ($identity instanceof \Model_Admin || $identity === null) { + $author['email'] = $ticket->author_email; + } + + return $author; + } + + $client = $this->di['db']->load('Client', $ticket->client_id); + + if ($client instanceof \Model_Client) { + return $this->clientToTicketAuthorArray($client); + } + $this->di['logger']->error('Missing client for ticket ' . $ticket->id); + + return []; + } + + private function clientToTicketAuthorArray(\Model_Client $client): array + { + return [ + 'id' => $client->id, + 'name' => $client->getFullName(), + 'first_name' => $client->first_name, + 'last_name' => $client->last_name, + 'email' => $client->email, + 'role' => 'client', + ]; + } + private function clientToTicketApiArray(\Model_Client $client, \Model_Admin|\Model_Client|null $identity = null): array { if ($identity instanceof \Model_Admin) { @@ -910,9 +930,21 @@ class Service implements \FOSSBilling\InjectionAwareInterface if ($model->admin_id) { $author = $this->di['db']->load('Admin', $model->admin_id); $role = 'admin'; - } else { + } elseif ($model->client_id) { $author = $this->di['db']->load('Client', $model->client_id); $role = 'client'; + } else { + $ticket = $this->di['db']->load('SupportTicket', $model->support_ticket_id); + + if ($ticket instanceof \Model_SupportTicket && $this->isGuestTicket($ticket)) { + return [ + 'name' => $ticket->author_name, + 'email' => $ticket->author_email, + 'role' => 'guest', + ]; + } + + return []; } if (!$author) { @@ -978,7 +1010,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface /** * @param \Model_Admin $identity */ - public function ticketReply(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client $identity, string $content): int + public function ticketReply(\Model_SupportTicket $ticket, \Model_Admin|\Model_Client|\Model_Guest $identity, string $content): int { $msg = $this->di['db']->dispense('SupportTicketMessage'); $msg->support_ticket_id = $ticket->id; @@ -995,7 +1027,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface if ($identity instanceof \Model_Admin) { $ticket->status = \Model_SupportTicket::ONHOLD; - } elseif ($identity instanceof \Model_Client) { + } else { $ticket->status = \Model_SupportTicket::OPENED; } @@ -1004,7 +1036,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface if ($identity instanceof \Model_Admin) { $this->di['events_manager']->fire(['event' => 'onAfterAdminReplyTicket', 'params' => ['id' => $ticket->id]]); - } elseif ($identity instanceof \Model_Client) { + } else { $this->di['events_manager']->fire(['event' => 'onAfterClientReplyTicket', 'params' => ['id' => $ticket->id]]); } @@ -1046,28 +1078,35 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function ticketCreateForGuest(array $data): string { - if (!$this->publicTicketsEnabled()) { + if (!$this->guestTicketsEnabled()) { throw new InformationException("We currently aren't accepting support tickets from unregistered users. Please use another contact method."); } $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']); + $data['content'] = $data['content'] ?? $data['message'] ?? null; + + SupportTicketValidator::validateTicketCreation($data); $event_params = $data; + $event_params['author_role'] = 'guest'; $event_params['ip'] = $this->di['request']->getClientIp(); - $altered = $this->di['events_manager']->fire(['event' => 'onBeforeGuestPublicTicketOpen', 'params' => $event_params]); + $altered = $this->di['events_manager']->fire(['event' => 'onBeforeClientOpenTicket', 'params' => $event_params]); $status = 'open'; $subject = $data['subject'] ?? null; - $message = $data['message'] ?? null; + $message = $data['content'] ?? null; if (is_array($altered)) { $status = $altered['status'] ?? null; $subject = $altered['subject'] ?? null; - $message = $altered['message'] ?? null; + $message = $altered['content'] ?? $altered['message'] ?? null; } - $ticket = $this->di['db']->dispense('SupportPTicket'); - $ticket->hash = bin2hex(random_bytes(random_int(15, 30))); + $helpdesk = isset($data['support_helpdesk_id']) ? $this->di['db']->getExistingModelById('SupportHelpdesk', $data['support_helpdesk_id'], 'Helpdesk invalid') : $this->getDefaultHelpdesk(); + + $ticket = $this->di['db']->dispense('SupportTicket'); + $ticket->access_hash = bin2hex(random_bytes(random_int(15, 30))); + $ticket->support_helpdesk_id = $helpdesk->id; $ticket->author_name = $data['name']; $ticket->author_email = $data['email']; $ticket->subject = $subject; @@ -1076,27 +1115,48 @@ class Service implements \FOSSBilling\InjectionAwareInterface $ticket->updated_at = date('Y-m-d H:i:s'); $ticketId = $this->di['db']->store($ticket); - $msg = $this->di['db']->dispense('SupportPTicketMessage'); - $msg->support_p_ticket_id = $ticket->id; + $msg = $this->di['db']->dispense('SupportTicketMessage'); + $msg->support_ticket_id = $ticket->id; $msg->content = $message; $msg->ip = $this->di['request']->getClientIp(); $msg->created_at = date('Y-m-d H:i:s'); $msg->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($msg); - $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketOpen', 'params' => ['id' => $ticketId]]); + $this->di['events_manager']->fire(['event' => 'onAfterClientOpenTicket', 'params' => ['id' => $ticketId]]); - $this->di['logger']->info('"%s" opened public ticket "%s"', $ticket->author_email, $ticketId); + $this->di['logger']->info('"%s" opened guest ticket "%s"', $ticket->author_email, $ticketId); - return $ticket->hash; + return $ticket->access_hash; } - public function publicTicketsEnabled(): bool + private function getDefaultHelpdesk(): \Model_SupportHelpdesk + { + $helpdesk = $this->di['db']->findOne('SupportHelpdesk', 'ORDER BY id ASC LIMIT 1'); + if ($helpdesk instanceof \Model_SupportHelpdesk) { + return $helpdesk; + } + + $helpdesk = $this->di['db']->dispense('SupportHelpdesk'); + $helpdesk->name = 'General'; + $helpdesk->close_after = 24; + $helpdesk->can_reopen = 0; + $helpdesk->created_at = date('Y-m-d H:i:s'); + $helpdesk->updated_at = date('Y-m-d H:i:s'); + $this->di['db']->store($helpdesk); + + return $helpdesk; + } + + public function guestTicketsEnabled(): bool { $extensionService = $this->di['mod_service']('extension'); $config = $extensionService->getConfig('mod_support'); - return !(isset($config['disable_public_tickets']) && $config['disable_public_tickets']); + // @deprecated 0.9.0 Use disable_guest_tickets instead. + $disableGuestTickets = $config['disable_guest_tickets'] ?? $config['disable_public_tickets'] ?? false; + + return !$disableGuestTickets; } public function canClientSubmitNewTicket(\Model_Client $client, array $config): bool @@ -1171,6 +1231,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface } $event_params = $data; + $event_params['author_role'] = 'client'; $event_params['client_id'] = $client->id; $this->di['events_manager']->fire(['event' => 'onBeforeClientOpenTicket', 'params' => $event_params]); @@ -1245,347 +1306,14 @@ class Service implements \FOSSBilling\InjectionAwareInterface return $this->di['db']->store($msg); } - public function publicGetStatuses(): array + public function findOneByHash(string $hash): \Model_SupportTicket { - return [ - \Model_SupportPTicket::OPENED => 'Open', - \Model_SupportPTicket::ONHOLD => 'On Hold', - \Model_SupportPTicket::CLOSED => 'Closed', - ]; - } - - public function publicFindOneByHash(string $hash): \Model_SupportPTicket - { - $bindings = [ - ':hash' => $hash, - ]; - - $publicTicket = $this->di['db']->findOne('SupportPTicket', 'hash = :hash', $bindings); - if (!$publicTicket instanceof \Model_SupportPTicket) { - throw new \FOSSBilling\Exception('Public ticket not found'); + $guestTicket = $this->di['db']->findOne('SupportTicket', 'access_hash = :hash AND client_id IS NULL', [':hash' => $hash]); + if (!$guestTicket instanceof \Model_SupportTicket) { + throw new \FOSSBilling\Exception('Guest ticket not found'); } - return $publicTicket; - } - - public function publicGetSearchQuery(array $data): array - { - $query = 'SELECT spt.* FROM support_p_ticket spt - LEFT JOIN support_p_ticket_message sptm - ON spt.id = sptm.support_p_ticket_id'; - - $search = $data['search'] ?? null; - - $id = $data['id'] ?? null; - $status = $data['status'] ?? null; - $name = $data['name'] ?? null; - $email = $data['email'] ?? null; - $subject = $data['subject'] ?? null; - $content = $data['content'] ?? null; - - $where = []; - $bindings = []; - - if ($id) { - $where[] = 'spt.id = :p_ticket_id'; - $bindings[':p_ticket_id'] = $id; - } - - if ($status) { - $where[] = 'spt.status = :p_ticket_status'; - $bindings[':p_ticket_status'] = $status; - } - - if ($email) { - $where[] = 'spt.author_email = :p_ticket_author_email'; - $bindings[':p_ticket_author_email'] = $email; - } - - if ($name) { - $where[] = 'spt.author_name = :p_ticket_author_name'; - $bindings[':p_ticket_author_name'] = $name; - } - - if ($content) { - $where[] = 'spt.content LIKE :p_ticket_content'; - $bindings[':p_ticket_content'] = "%$content%"; - } - - if ($subject) { - $where[] = 'spt.subject LIKE :p_ticket_subject'; - $bindings[':p_ticket_subject'] = "%$subject%"; - } - - // smartSearch - if ($search) { - if (is_numeric($search)) { - $where[] = 'spt.id = :p_ticket_id'; - $bindings[':p_ticket_id'] = $search; - } else { - $search = '%' . $search . '%'; - $where[] = '(sptm.content LIKE :p_message_content OR spt.subject LIKE :p_ticket_subject)'; - $bindings[':p_message_content'] = $search; - $bindings[':p_ticket_subject'] = $search; - } - } - - if (!empty($where)) { - $query = $query . ' WHERE ' . implode(' AND ', $where); - } - - $query .= ' GROUP BY spt.id, sptm.id ORDER BY spt.id DESC, sptm.id ASC'; - - return [$query, $bindings]; - } - - public function publicCounter(): array - { - $query = 'SELECT status, COUNT(id) as counter - FROM support_p_ticket - GROUP BY status'; - - $data = $this->di['db']->getAssoc($query); - - return [ - 'total' => array_sum($data), - \Model_SupportPTicket::OPENED => $data[\Model_SupportPTicket::OPENED] ?? 0, - \Model_SupportPTicket::CLOSED => $data[\Model_SupportPTicket::CLOSED] ?? 0, - \Model_SupportPTicket::ONHOLD => $data[\Model_SupportPTicket::ONHOLD] ?? 0, - ]; - } - - public function publicGetLatest(): array - { - return $this->di['db']->find('SupportPTicket', 'ORDER BY id DESC Limit 10'); - } - - public function publicCountByStatus(string $status): int - { - $query = 'SELECT COUNT(id) as counter - FROM support_p_ticket - WHERE status = :status - GROUP BY status'; - - return (int) $this->di['db']->getCell($query, [':status' => $status]); - } - - public function publicGetExpired(): array - { - $bindings = [ - ':status' => \Model_SupportPTicket::ONHOLD, - ]; - - return $this->di['db']->find('SupportPTicket', 'status = :status AND DATE_ADD(updated_at, INTERVAL 48 HOUR) < NOW() ORDER BY id ASC', $bindings); - } - - public function publicCloseTicket(\Model_SupportPTicket $model, \Model_Admin|\Model_Guest $identity): bool - { - $model->status = 'closed'; - $model->updated_at = date('Y-m-d H:i:s'); - - $this->di['db']->store($model); - - if ($identity instanceof \Model_Admin) { - $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketClose', 'params' => ['id' => $model->id]]); - $this->di['logger']->info('Public Ticket %s was closed', $model->id); - } elseif ($identity instanceof \Model_Guest) { - $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketClose', 'params' => ['id' => $model->id]]); - $this->di['logger']->info('"%s" closed public ticket "%s"', $model->author_email, $model->id); - } - - return true; - } - - public function publicAutoClose(\Model_SupportPTicket $model): bool - { - $model->status = 'closed'; - $model->updated_at = date('Y-m-d H:i:s'); - - $this->di['db']->store($model); - - $this->di['logger']->info('Public Ticket %s was closed', $model->id); - - return true; - } - - public function publicRm(\Model_SupportPTicket $model): bool - { - $id = $model->id; - $bindings = [ - ':support_p_ticket_id' => $model->id, - ]; - $messages = $this->di['db']->find('SupportPTicketMessage', 'support_p_ticket_id = :support_p_ticket_id', $bindings); - - foreach ($messages as $message) { - $this->di['db']->trash($message); - } - - $this->di['db']->trash($model); - - $this->di['logger']->info('Deleted public ticket #%s', $id); - - return true; - } - - public function publicToApiArray(\Model_SupportPTicket $model, bool $deep = true, $identity = null): array - { - $data = $this->di['db']->toArray($model); - - if (!$identity instanceof \Model_Admin) { - unset($data['author_email']); - } - - $messages = []; - $messagesArr = $this->di['db']->find('SupportPTicketMessage', 'support_p_ticket_id = :support_p_ticket_id ORDER BY id', [':support_p_ticket_id' => $model->id]); - foreach ($messagesArr as $msg) { - $messages[] = $this->publicMessageToApiArray($msg, true, $identity); - } - - $first = reset($messagesArr); - if ($first instanceof \Model_SupportPTicketMessage) { - $data['author'] = $this->publicMessageGetAuthorDetails($first, $identity); - } else { - $data['author'] = []; - } - $data['messages'] = $messages; - - return $data; - } - - public function publicMessageGetAuthorDetails(\Model_SupportPTicketMessage $model, $identity = null): array - { - if ($model->admin_id) { - $author = $this->di['db']->getExistingModelById('Admin', $model->admin_id); - - $result = [ - 'name' => $author->getFullName(), - ]; - - if ($identity instanceof \Model_Admin) { - $result['email'] = $author->email; - } - - return $result; - } - - $ticket = $this->di['db']->getExistingModelById('SupportPTicket', $model->support_p_ticket_id); - - $result = [ - 'name' => $ticket->author_name, - ]; - - if ($identity instanceof \Model_Admin) { - $result['email'] = $ticket->author_email; - } - - return $result; - } - - public function publicMessageToApiArray(\Model_SupportPTicketMessage $model, bool $deep = true, $identity = null): array - { - $data = [ - 'id' => $model->id, - 'content' => $model->content, - 'created_at' => $model->created_at, - 'updated_at' => $model->updated_at, - ]; - - if ($identity instanceof \Model_Admin) { - $data['support_p_ticket_id'] = $model->support_p_ticket_id; - $data['admin_id'] = $model->admin_id; - $data['ip'] = $model->ip; - } - - $data['author'] = $this->publicMessageGetAuthorDetails($model, $identity); - - return $data; - } - - public function publicTicketCreate(array $data, \Model_Admin $identity): int - { - $data['email'] = $this->di['tools']->validateAndSanitizeEmail($data['email']); - - $this->di['events_manager']->fire(['event' => 'onBeforeAdminPublicTicketOpen', 'params' => $data]); - - $ticket = $this->di['db']->dispense('SupportPTicket'); - $ticket->hash = bin2hex(random_bytes(random_int(15, 30))); - $ticket->author_name = $data['name']; - $ticket->author_email = $data['email']; - $ticket->subject = $data['subject']; - $ticket->status = 'open'; - $ticket->created_at = date('Y-m-d H:i:s'); - $ticket->updated_at = date('Y-m-d H:i:s'); - $ticketId = $this->di['db']->store($ticket); - - $msg = $this->di['db']->dispense('SupportPTicketMessage'); - $msg->support_p_ticket_id = $ticketId; - $msg->admin_id = $identity->id; - $msg->content = $data['message']; - $msg->ip = $this->di['request']->getClientIp(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($msg); - - $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketOpen', 'params' => ['id' => $ticketId]]); - - $this->di['logger']->info('Opened public ticket for email "%s"', $ticket->author_email); - - return $ticketId; - } - - public function publicTicketUpdate(\Model_SupportPTicket $model, $data): bool - { - $model->subject = $data['subject'] ?? $model->subject; - $model->status = $data['status'] ?? $model->status; - $model->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($model); - - $this->di['logger']->info('Updated public ticket #%s', $model->id); - - return true; - } - - public function publicTicketReply(\Model_SupportPTicket $ticket, \Model_Admin $identity, string $content): int - { - $msg = $this->di['db']->dispense('SupportPTicketMessage'); - $msg->support_p_ticket_id = $ticket->id; - $msg->admin_id = $identity->id; - $msg->content = $content; - $msg->ip = $this->di['request']->getClientIp(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); - $messageId = $this->di['db']->store($msg); - - $ticket->status = \Model_SupportPTicket::ONHOLD; - $ticket->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($ticket); - - $this->di['events_manager']->fire(['event' => 'onAfterAdminPublicTicketReply', 'params' => ['id' => $ticket->id]]); - - $this->di['logger']->info('Replied to public ticket "%s"', $ticket->id); - - return $messageId; - } - - public function publicTicketReplyForGuest(\Model_SupportPTicket $ticket, string $message): string - { - $msg = $this->di['db']->dispense('SupportPTicketMessage'); - $msg->support_p_ticket_id = $ticket->id; - $msg->content = $message; - $msg->ip = $this->di['request']->getClientIp(); - $msg->created_at = date('Y-m-d H:i:s'); - $msg->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($msg); - - $ticket->status = \Model_SupportPTicket::OPENED; - $ticket->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($ticket); - - $this->di['events_manager']->fire(['event' => 'onAfterGuestPublicTicketReply', 'params' => ['id' => $ticket->id]]); - - $this->di['logger']->info('Client "%s" replied to public ticket "%s"', $ticket->author_email, $ticket->id); - - return $ticket->hash; + return $guestTicket; } public function helpdeskUpdate(\Model_SupportHelpdesk $model, array $data): bool diff --git a/src/modules/Support/templates/admin/mod_support_public_ticket.html.twig b/src/modules/Support/templates/admin/mod_support_public_ticket.html.twig deleted file mode 100644 index 1f9dedfd0..000000000 --- a/src/modules/Support/templates/admin/mod_support_public_ticket.html.twig +++ /dev/null @@ -1,235 +0,0 @@ -{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %} - -{% import 'macro_functions.html.twig' as mf %} - -{% block meta_title %}{{ ticket.subject }}{% endblock %} - -{% set active_menu = 'support' %} - -{% block breadcrumbs %} - -{% endblock %} - -{% block content %} -{% embed 'partial_admin_detail_tabs.html.twig' with { - title: ticket.subject, - subtitle: 'Review public ticket details, adjust its status, and respond as staff.'|trans, - outer_card_class: 'mb-3' -} %} - {% block detail_tabs %} - - - {% endblock %} - - {% block detail_tab_content %} - {% import 'macro_functions.html.twig' as mf %} -
-
- {% embed 'partial_admin_summary_card.html.twig' with { - title: 'Public Ticket Summary'|trans, - subtitle: 'Review the author details, current state, and message timing for this public ticket.'|trans, - centered_actions: true, - card_class: 'mb-0' - } %} - {% import 'macro_functions.html.twig' as mf %} - {% block summary_content %} -
- - - - - - - - - {% if ticket.created_at != ticket.updated_at %} - - {% endif %} - -
{{ 'Ticket ID'|trans }}:#{{ ticket.id }}
{{ 'Subject'|trans }}:{{ ticket.subject }}
{{ 'Author'|trans }}:{{ ticket.author_name }}
{{ 'Email'|trans }}:{{ ticket.author_email }}
{{ 'Status'|trans }}:{{ mf.status_badge(ticket.status, 'ticket') }}
{{ 'Time Opened'|trans }}:{{ ticket.created_at|format_date }}
{{ 'Last Updated'|trans }}:{{ ticket.updated_at|timeago }} {{ 'ago'|trans }}
-
- {% endblock %} - - {% block summary_actions %} - {% if ticket.status != 'closed' %} - - - {{ 'Close'|trans }} - - {% endif %} - - - {{ 'Delete'|trans }} - - - - {{ 'View as Author'|trans }} - - {% endblock %} - {% endembed %} - -
-
-
-
-
{{ 'Conversation'|trans }}
-

{{ 'Review the public message history and expand replies when needed.'|trans }}

-
- - - - - {{ 'Show/Hide Messages'|trans }} - -
-
-
-
- {% for i, message in ticket.messages %} -
-
- {{ avatar(message.author.email, 20, 'avatar avatar-xs me-2') }} - {{ message.author.name }} - {{ message.created_at|format_datetime }} -
-
- {{ (message.content ?? '')|markdown_to_html }} -
-
- {% endfor %} -
-
-
- -
-
-
- {% set public_ticket_recipient = ticket.author_name ? ticket.author_name : ticket.author_email %} -
-
-
{{ 'Respond as'|trans }} {{ profile.name }}
-

{{ 'Compose a staff reply and close the public ticket when appropriate.'|trans }}

-
-
{{ include('mod_support_canned_selector.html.twig') }}
-
- - -
- - -
-
-
-
- -
-
-
- {% embed 'partial_admin_form_card.html.twig' with { - title: 'Public Ticket Settings'|trans, - subtitle: 'Update the subject and current workflow status for this public ticket.'|trans - } %} - {% import 'macro_functions.html.twig' as mf %} - {% block form_content %} -
-
- - -
-
- - {{ mf.selectbox('status', admin.support_ticket_get_statuses({ 'titles': 1 }), ticket.status, 1) }} -
-
- - {% endblock %} - - {% block form_actions %} - - {% endblock %} - {% endembed %} -
-
-
- {% endblock %} -{% endembed %} - -{% set canned_response_selector %} -
- -
-{% endset %} -{% endblock %} - -{% block js%} - -{% endblock %} - -{% block head %}{{ wysiwyg('.editor-textarea') }}{% endblock %} diff --git a/src/modules/Support/templates/admin/mod_support_public_tickets.html.twig b/src/modules/Support/templates/admin/mod_support_public_tickets.html.twig deleted file mode 100644 index b29020be6..000000000 --- a/src/modules/Support/templates/admin/mod_support_public_tickets.html.twig +++ /dev/null @@ -1,299 +0,0 @@ -{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %} - -{% import 'macro_functions.html.twig' as mf %} - -{% block meta_title %}{{ 'Public Tickets'|trans }}{% endblock %} - -{% block breadcrumbs %} - -{% endblock %} - -{% set active_menu = 'support' %} -{% set has_filter_panel = true %} -{% set filter_panel_id = 'page-search-filters' %} -{% set filter_panel_open = request_has_filters %} -{% set public_ticket_toolbar_actions %} - -{% endset %} - -{% block content %} - {% if not filter_panel_open %} - {% set statuses = admin.support_public_ticket_get_statuses %} -
- - - - -
- {% endif %} - -
-
-
-

{{ 'Public Tickets'|trans }}

-

{{ 'Review support tickets submitted without a client account and manage public conversations.'|trans }}

-
-
- - {{ include('partial_search.html.twig', { - search_body_class: filter_panel_open ? 'pb-2 border-bottom-0' : '', - search_toolbar_actions: public_ticket_toolbar_actions - }) }} -
-
- {% if request.search %} - - {% endif %} -
-
-
- - -
-
-
-
- - -
-
-
-
- - -
-
-
- -
- - - - - - - - - - - -
-
-
-
- - -
-
-
-
- - -
-
-
-
- {{ 'Reset'|trans }} - -
-
-
-
- - - - - - - - - - - - - {% set tickets = admin.support_public_ticket_get_list({ 'per_page': 25, 'page': request.page }|merge(request)) %} - {% for i, ticket in tickets.list %} - - - - - - - - - {% else %} - - - - {% endfor %} - -
- - {{ 'Subject'|trans }}{{ 'Email'|trans }}{{ 'Status'|trans }}{{ 'Date'|trans }}
- - - #{{ ticket.id }} - {{ ticket.subject }} ({{ ticket.messages|length }}) - {{ ticket.author_email }}{{ mf.status_badge(ticket.status, 'ticket') }}{{ ticket.updated_at|format_date }} - - - - - -
{{ 'The list is empty'|trans }}
-
- - - - -
-{% endblock %} - -{% block js %} - -{% endblock %} - -{% block head %}{{ wysiwyg('.editor-textarea') }}{% endblock %} diff --git a/src/modules/Support/templates/admin/mod_support_settings.html.twig b/src/modules/Support/templates/admin/mod_support_settings.html.twig index d2db0fb26..84d32b49b 100644 --- a/src/modules/Support/templates/admin/mod_support_settings.html.twig +++ b/src/modules/Support/templates/admin/mod_support_settings.html.twig @@ -25,7 +25,7 @@

{{ 'Support Settings'|trans }}

-

{{ 'Manage support automation, knowledge base availability, public tickets, and helpdesk configuration.'|trans }}

+

{{ 'Manage support automation, knowledge base availability, guest tickets, and helpdesk configuration.'|trans }}

@@ -108,11 +108,11 @@
-

{{ 'Public Tickets'|trans }}

-

{{ 'Control whether non-client visitors may open public support tickets.'|trans }}

+

{{ 'Guest Tickets'|trans }}

+

{{ 'Control whether non-client visitors may open support tickets.'|trans }}