1use crate::{
2 ConsumeHandoffRequest, ConsumedHandoff, CreateTicketInput, ExternalMessageIdentity,
3 IngestExternalMessageRequest, RequesterTicket, Ticket, TicketActivityIntent, TicketAiContext,
4 TicketAttachment, TicketFromHandoffInput, TicketId, TicketListFilter, TicketPriority,
5 TicketStatus, TicketStoreError, TicketingStoreService,
6};
7use chrono::{DateTime, TimeDelta, Utc};
8use minco_interaction::{
9 AttachmentMetadata, SupportContext, SupportHandoffGrant, SupportLocationPolicy, SupportSurface,
10 issue_support_handoff,
11};
12use minco_plugin_identity::Identity;
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::collections::BTreeMap;
16use uuid::Uuid;
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct TicketingConfig {
21 pub project_id: String,
22 pub portal_origin: String,
23 #[serde(default)]
24 pub allowed_return_paths: BTreeMap<String, Vec<String>>,
25 #[serde(default = "default_handoff_ttl_seconds")]
26 pub handoff_ttl_seconds: i64,
27 #[serde(default = "default_support_label")]
28 pub support_label: String,
29 #[serde(default = "default_support_brand")]
30 pub support_brand: String,
31 #[serde(default = "default_privacy_notice")]
32 pub privacy_notice: String,
33}
34
35impl Default for TicketingConfig {
36 fn default() -> Self {
37 Self {
38 project_id: "default".into(),
39 portal_origin: "https://support.example.invalid".into(),
40 allowed_return_paths: BTreeMap::new(),
41 handoff_ttl_seconds: default_handoff_ttl_seconds(),
42 support_label: default_support_label(),
43 support_brand: default_support_brand(),
44 privacy_notice: default_privacy_notice(),
45 }
46 }
47}
48
49impl TicketingConfig {
50 pub fn validate(&self) -> Result<(), TicketingServiceError> {
51 validate_text("project_id", &self.project_id, 100)?;
52 validate_text("support_label", &self.support_label, 80)?;
53 validate_text("support_brand", &self.support_brand, 80)?;
54 validate_text("privacy_notice", &self.privacy_notice, 2_000)?;
55 if !(1..=900).contains(&self.handoff_ttl_seconds) {
56 return Err(TicketingServiceError::Configuration(
57 "handoff_ttl_seconds must be between 1 and 900".into(),
58 ));
59 }
60 self.location_policy().validate()?;
61 Ok(())
62 }
63
64 #[must_use]
65 pub fn location_policy(&self) -> SupportLocationPolicy {
66 SupportLocationPolicy {
67 portal_origin: self.portal_origin.clone(),
68 allowed_return_paths: self.allowed_return_paths.clone(),
69 }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct IssueTicketingHandoffInput {
75 pub project_id: String,
76 pub requester_subject: String,
77 pub requester_permissions: Vec<String>,
78 pub surface: SupportSurface,
79 pub context: SupportContext,
80 pub return_location: String,
81 pub correlation_id: Uuid,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85pub struct TicketingWarning {
86 pub code: String,
87 pub detail: String,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct TicketingMutationResult {
92 pub ticket: Ticket,
93 #[serde(default, skip_serializing_if = "Vec::is_empty")]
94 pub warnings: Vec<TicketingWarning>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct RequesterTicketResult {
99 pub ticket: RequesterTicket,
100 #[serde(default, skip_serializing_if = "Vec::is_empty")]
101 pub warnings: Vec<TicketingWarning>,
102}
103
104#[derive(Debug, Clone)]
105pub struct TicketingService {
106 store: TicketingStoreService,
107 config: TicketingConfig,
108}
109
110impl TicketingService {
111 pub fn new(
112 store: TicketingStoreService,
113 config: TicketingConfig,
114 ) -> Result<Self, TicketingServiceError> {
115 config.validate()?;
116 Ok(Self { store, config })
117 }
118
119 #[must_use]
120 pub const fn config(&self) -> &TicketingConfig {
121 &self.config
122 }
123
124 pub async fn issue_ticketing_handoff(
125 &self,
126 principal: &Identity,
127 input: IssueTicketingHandoffInput,
128 now: DateTime<Utc>,
129 ) -> Result<SupportHandoffGrant, TicketingServiceError> {
130 authorize(principal, "ticketing.integrate")?;
131 self.require_project(&input.project_id)?;
132 let (handoff, grant) = issue_support_handoff(
133 input.project_id,
134 input.requester_subject,
135 input.requester_permissions,
136 input.surface,
137 input.context,
138 &input.return_location,
139 input.correlation_id,
140 &self.config.location_policy(),
141 now,
142 TimeDelta::seconds(self.config.handoff_ttl_seconds),
143 )?;
144 self.store.insert_handoff(handoff).await?;
145 Ok(grant)
146 }
147
148 pub async fn create_ticket_from_handoff(
149 &self,
150 token: minco_interaction::SupportHandoffToken,
151 project_id: &str,
152 portal_origin: &str,
153 input: TicketFromHandoffInput,
154 now: DateTime<Utc>,
155 ) -> Result<ConsumedHandoff, TicketingServiceError> {
156 self.require_project(project_id)?;
157 Ok(self
158 .store
159 .consume_and_create_ticket(ConsumeHandoffRequest::new(
160 token,
161 project_id,
162 portal_origin,
163 input,
164 now,
165 )?)
166 .await?)
167 }
168
169 pub async fn create_ticket(
170 &self,
171 principal: &Identity,
172 input: CreateTicketInput,
173 correlation_id: Uuid,
174 now: DateTime<Utc>,
175 ) -> Result<TicketingMutationResult, TicketingServiceError> {
176 authorize(principal, "ticketing.create")?;
177 self.require_project(&input.project_id)?;
178 if input.requester.subject != principal.subject
179 && !principal.has_permission("ticketing.manage")
180 {
181 return Err(TicketingServiceError::RequesterMismatch);
182 }
183 let id = Uuid::now_v7();
184 let display_reference = format!("TKT-{}", &id.simple().to_string()[..12]);
185 let ticket = Ticket::create(input, display_reference, now)?;
186 let intent = activity(&ticket, "ticketing.created", correlation_id, now);
187 self.store.create(ticket.clone(), intent).await?;
188 Ok(result(ticket))
189 }
190
191 pub async fn get_ticket_for_requester(
192 &self,
193 principal: &Identity,
194 project_id: &str,
195 id: TicketId,
196 ) -> Result<RequesterTicket, TicketingServiceError> {
197 authorize(principal, "ticketing.read")?;
198 let ticket = self.load(project_id, id).await?;
199 if ticket.requester.subject != principal.subject
200 && !principal.has_permission("ticketing.manage")
201 {
202 return Err(TicketingServiceError::RequesterMismatch);
203 }
204 Ok(ticket.requester_projection())
205 }
206
207 pub async fn get_ticket_for_agent(
208 &self,
209 principal: &Identity,
210 project_id: &str,
211 id: TicketId,
212 ) -> Result<Ticket, TicketingServiceError> {
213 authorize(principal, "ticketing.read")?;
214 self.load(project_id, id).await
215 }
216
217 pub async fn list_tickets(
218 &self,
219 principal: &Identity,
220 filter: TicketListFilter,
221 ) -> Result<Vec<Ticket>, TicketingServiceError> {
222 authorize(principal, "ticketing.read")?;
223 self.require_project(&filter.project_id)?;
224 Ok(self.store.list(filter).await?)
225 }
226
227 #[allow(clippy::too_many_arguments)]
228 pub async fn reply_as_requester(
229 &self,
230 principal: &Identity,
231 project_id: &str,
232 id: TicketId,
233 body: String,
234 expected_revision: u64,
235 correlation_id: Uuid,
236 now: DateTime<Utc>,
237 ) -> Result<RequesterTicketResult, TicketingServiceError> {
238 authorize(principal, "ticketing.reply")?;
239 let mut ticket = self.load(project_id, id).await?;
240 if ticket.requester.subject != principal.subject {
241 return Err(TicketingServiceError::RequesterMismatch);
242 }
243 require_revision(&ticket, expected_revision)?;
244 ticket.reply_as_requester(body, now)?;
245 self.save(
246 ticket.clone(),
247 expected_revision,
248 "ticketing.requester_replied",
249 correlation_id,
250 now,
251 )
252 .await?;
253 Ok(RequesterTicketResult {
254 ticket: ticket.requester_projection(),
255 warnings: Vec::new(),
256 })
257 }
258
259 #[allow(clippy::too_many_arguments)]
260 pub async fn reply_as_agent(
261 &self,
262 principal: &Identity,
263 project_id: &str,
264 id: TicketId,
265 body: String,
266 expected_revision: u64,
267 correlation_id: Uuid,
268 now: DateTime<Utc>,
269 ) -> Result<TicketingMutationResult, TicketingServiceError> {
270 authorize(principal, "ticketing.reply")?;
271 let mut ticket = self.load(project_id, id).await?;
272 require_revision(&ticket, expected_revision)?;
273 ticket.reply_as_agent(principal.subject.clone(), body, now)?;
274 self.save(
275 ticket.clone(),
276 expected_revision,
277 "ticketing.agent_replied",
278 correlation_id,
279 now,
280 )
281 .await?;
282 Ok(result(ticket))
283 }
284
285 #[allow(clippy::too_many_arguments)]
286 pub async fn add_internal_note(
287 &self,
288 principal: &Identity,
289 project_id: &str,
290 id: TicketId,
291 body: String,
292 expected_revision: u64,
293 correlation_id: Uuid,
294 now: DateTime<Utc>,
295 ) -> Result<TicketingMutationResult, TicketingServiceError> {
296 authorize(principal, "ticketing.manage")?;
297 let mut ticket = self.load(project_id, id).await?;
298 require_revision(&ticket, expected_revision)?;
299 ticket.add_internal_note(principal.subject.clone(), body, now)?;
300 self.save(
301 ticket.clone(),
302 expected_revision,
303 "ticketing.internal_note_added",
304 correlation_id,
305 now,
306 )
307 .await?;
308 Ok(result(ticket))
309 }
310
311 #[allow(clippy::too_many_arguments)]
312 pub async fn assign_ticket(
313 &self,
314 principal: &Identity,
315 project_id: &str,
316 id: TicketId,
317 assignee: String,
318 expected_revision: u64,
319 correlation_id: Uuid,
320 now: DateTime<Utc>,
321 ) -> Result<TicketingMutationResult, TicketingServiceError> {
322 self.change_assignment(
323 principal,
324 project_id,
325 id,
326 Some(assignee),
327 expected_revision,
328 correlation_id,
329 now,
330 )
331 .await
332 }
333
334 pub async fn unassign_ticket(
335 &self,
336 principal: &Identity,
337 project_id: &str,
338 id: TicketId,
339 expected_revision: u64,
340 correlation_id: Uuid,
341 now: DateTime<Utc>,
342 ) -> Result<TicketingMutationResult, TicketingServiceError> {
343 self.change_assignment(
344 principal,
345 project_id,
346 id,
347 None,
348 expected_revision,
349 correlation_id,
350 now,
351 )
352 .await
353 }
354
355 #[allow(clippy::too_many_arguments)]
356 async fn change_assignment(
357 &self,
358 principal: &Identity,
359 project_id: &str,
360 id: TicketId,
361 assignee: Option<String>,
362 expected_revision: u64,
363 correlation_id: Uuid,
364 now: DateTime<Utc>,
365 ) -> Result<TicketingMutationResult, TicketingServiceError> {
366 authorize(principal, "ticketing.manage")?;
367 let mut ticket = self.load(project_id, id).await?;
368 require_revision(&ticket, expected_revision)?;
369 ticket.assign(assignee, now)?;
370 self.save(
371 ticket.clone(),
372 expected_revision,
373 "ticketing.assignment_changed",
374 correlation_id,
375 now,
376 )
377 .await?;
378 Ok(result(ticket))
379 }
380
381 #[allow(clippy::too_many_arguments)]
382 pub async fn transfer_queue(
383 &self,
384 principal: &Identity,
385 project_id: &str,
386 id: TicketId,
387 queue_id: String,
388 expected_revision: u64,
389 correlation_id: Uuid,
390 now: DateTime<Utc>,
391 ) -> Result<TicketingMutationResult, TicketingServiceError> {
392 authorize(principal, "ticketing.manage")?;
393 let mut ticket = self.load(project_id, id).await?;
394 require_revision(&ticket, expected_revision)?;
395 ticket.transfer_queue(queue_id, now)?;
396 self.save(
397 ticket.clone(),
398 expected_revision,
399 "ticketing.queue_transferred",
400 correlation_id,
401 now,
402 )
403 .await?;
404 Ok(result(ticket))
405 }
406
407 #[allow(clippy::too_many_arguments)]
408 pub async fn change_priority(
409 &self,
410 principal: &Identity,
411 project_id: &str,
412 id: TicketId,
413 priority: TicketPriority,
414 expected_revision: u64,
415 correlation_id: Uuid,
416 now: DateTime<Utc>,
417 ) -> Result<TicketingMutationResult, TicketingServiceError> {
418 authorize(principal, "ticketing.manage")?;
419 let mut ticket = self.load(project_id, id).await?;
420 require_revision(&ticket, expected_revision)?;
421 ticket.change_priority(priority, now);
422 self.save(
423 ticket.clone(),
424 expected_revision,
425 "ticketing.priority_changed",
426 correlation_id,
427 now,
428 )
429 .await?;
430 Ok(result(ticket))
431 }
432
433 #[allow(clippy::too_many_arguments)]
434 pub async fn change_status(
435 &self,
436 principal: &Identity,
437 project_id: &str,
438 id: TicketId,
439 status: TicketStatus,
440 resolution: Option<String>,
441 close_reason: Option<String>,
442 expected_revision: u64,
443 correlation_id: Uuid,
444 now: DateTime<Utc>,
445 ) -> Result<TicketingMutationResult, TicketingServiceError> {
446 authorize(principal, "ticketing.manage")?;
447 let mut ticket = self.load(project_id, id).await?;
448 require_revision(&ticket, expected_revision)?;
449 ticket.change_status(status, resolution, close_reason, now)?;
450 self.save(
451 ticket.clone(),
452 expected_revision,
453 "ticketing.status_changed",
454 correlation_id,
455 now,
456 )
457 .await?;
458 Ok(result(ticket))
459 }
460
461 #[allow(clippy::too_many_arguments)]
462 pub async fn add_verified_attachment(
463 &self,
464 principal: &Identity,
465 project_id: &str,
466 id: TicketId,
467 attachment: AttachmentMetadata,
468 expected_revision: u64,
469 correlation_id: Uuid,
470 now: DateTime<Utc>,
471 ) -> Result<TicketingMutationResult, TicketingServiceError> {
472 authorize(principal, "ticketing.manage")?;
473 let mut ticket = self.load(project_id, id).await?;
474 require_revision(&ticket, expected_revision)?;
475 ticket.add_attachment(TicketAttachment::from(attachment), now);
476 self.save(
477 ticket.clone(),
478 expected_revision,
479 "ticketing.attachment_added",
480 correlation_id,
481 now,
482 )
483 .await?;
484 Ok(result(ticket))
485 }
486
487 #[allow(clippy::too_many_arguments)]
488 pub async fn ingest_external_message(
489 &self,
490 principal: &Identity,
491 mut identity: ExternalMessageIdentity,
492 id: TicketId,
493 body: String,
494 expected_revision: u64,
495 correlation_id: Uuid,
496 now: DateTime<Utc>,
497 ) -> Result<TicketingMutationResult, TicketingServiceError> {
498 authorize(principal, "ticketing.ingest")?;
499 self.require_project(&identity.project_id)?;
500 validate_sha256(&identity.content_sha256)?;
501 identity.content_sha256.make_ascii_lowercase();
502 if !valid_external_text(&identity.provider, 100)
503 || !valid_external_text(&identity.mailbox_scope, 300)
504 || !valid_external_text(&identity.external_id, 500)
505 || identity.references.len() > 64
506 {
507 return Err(TicketingServiceError::InvalidExternalIdentity);
508 }
509 for value in [
510 identity.raw_message_object_key.as_deref(),
511 identity.internet_message_id.as_deref(),
512 identity.in_reply_to.as_deref(),
513 ]
514 .into_iter()
515 .flatten()
516 .chain(identity.references.iter().map(String::as_str))
517 {
518 if value.trim().is_empty()
519 || value.chars().count() > 1_000
520 || value.chars().any(char::is_control)
521 {
522 return Err(TicketingServiceError::InvalidExternalIdentity);
523 }
524 }
525 let outcome = self
526 .store
527 .ingest_external_message(IngestExternalMessageRequest {
528 identity,
529 ticket_id: id,
530 body,
531 expected_revision,
532 correlation_id,
533 now,
534 })
535 .await?;
536 Ok(result(outcome.ticket))
537 }
538
539 pub async fn export_ai_context(
540 &self,
541 principal: &Identity,
542 project_id: &str,
543 id: TicketId,
544 ) -> Result<TicketAiContext, TicketingServiceError> {
545 authorize(principal, "ticketing.ai-context")?;
546 Ok(self.load(project_id, id).await?.export_ai_context())
547 }
548
549 pub async fn ready(&self) -> Result<(), TicketingServiceError> {
550 Ok(self.store.ready().await?)
551 }
552
553 async fn load(&self, project_id: &str, id: TicketId) -> Result<Ticket, TicketingServiceError> {
554 self.require_project(project_id)?;
555 self.store
556 .get(project_id, id)
557 .await?
558 .ok_or(TicketingServiceError::NotFound(id))
559 }
560
561 async fn save(
562 &self,
563 ticket: Ticket,
564 expected_revision: u64,
565 kind: &str,
566 correlation_id: Uuid,
567 now: DateTime<Utc>,
568 ) -> Result<(), TicketingServiceError> {
569 let intent = activity(&ticket, kind, correlation_id, now);
570 Ok(self.store.save(ticket, expected_revision, intent).await?)
571 }
572
573 fn require_project(&self, project_id: &str) -> Result<(), TicketingServiceError> {
574 if project_id == self.config.project_id {
575 Ok(())
576 } else {
577 Err(TicketingServiceError::ProjectDenied)
578 }
579 }
580}
581
582fn activity(
583 ticket: &Ticket,
584 kind: &str,
585 correlation_id: Uuid,
586 now: DateTime<Utc>,
587) -> TicketActivityIntent {
588 TicketActivityIntent::new(
589 ticket.project_id.clone(),
590 ticket.id,
591 kind,
592 correlation_id,
593 serde_json::json!({ "ticket_id": ticket.id, "revision": ticket.revision, "status": ticket.status }),
594 now,
595 )
596}
597
598fn authorize(principal: &Identity, permission: &str) -> Result<(), TicketingServiceError> {
599 principal
600 .has_permission(permission)
601 .then_some(())
602 .ok_or_else(|| TicketingServiceError::PermissionDenied(permission.into()))
603}
604
605const fn require_revision(ticket: &Ticket, expected: u64) -> Result<(), TicketingServiceError> {
606 if ticket.revision == expected {
607 Ok(())
608 } else {
609 Err(TicketingServiceError::StaleRevision {
610 expected,
611 actual: ticket.revision,
612 })
613 }
614}
615
616fn validate_text(
617 field: &'static str,
618 value: &str,
619 maximum: usize,
620) -> Result<(), TicketingServiceError> {
621 if value.trim().is_empty()
622 || value.chars().count() > maximum
623 || value.chars().any(char::is_control)
624 {
625 Err(TicketingServiceError::Configuration(format!(
626 "{field} must contain 1-{maximum} visible characters"
627 )))
628 } else {
629 Ok(())
630 }
631}
632
633fn validate_sha256(value: &str) -> Result<(), TicketingServiceError> {
634 if value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
635 Ok(())
636 } else {
637 Err(TicketingServiceError::InvalidContentDigest)
638 }
639}
640
641fn valid_external_text(value: &str, maximum: usize) -> bool {
642 !value.trim().is_empty()
643 && value.chars().count() <= maximum
644 && !value.chars().any(char::is_control)
645}
646
647const fn result(ticket: Ticket) -> TicketingMutationResult {
648 TicketingMutationResult {
649 ticket,
650 warnings: Vec::new(),
651 }
652}
653
654const fn default_handoff_ttl_seconds() -> i64 {
655 120
656}
657fn default_support_label() -> String {
658 "Get support".into()
659}
660fn default_support_brand() -> String {
661 "Support".into()
662}
663fn default_privacy_notice() -> String {
664 "Share only information needed to resolve this request.".into()
665}
666
667#[derive(Debug, thiserror::Error)]
668pub enum TicketingServiceError {
669 #[error("permission denied: {0}")]
670 PermissionDenied(String),
671 #[error("ticketing project is not available to this operation")]
672 ProjectDenied,
673 #[error("the requester does not match the authenticated subject")]
674 RequesterMismatch,
675 #[error("ticket was not found: {0}")]
676 NotFound(TicketId),
677 #[error("ticket revision is stale: expected {expected}, actual {actual}")]
678 StaleRevision { expected: u64, actual: u64 },
679 #[error("external message content digest must be hexadecimal SHA-256")]
680 InvalidContentDigest,
681 #[error("external message identity is invalid")]
682 InvalidExternalIdentity,
683 #[error("invalid ticketing configuration: {0}")]
684 Configuration(String),
685 #[error(transparent)]
686 SupportEntry(#[from] minco_interaction::SupportEntryError),
687 #[error(transparent)]
688 Validation(#[from] crate::TicketValidationError),
689 #[error(transparent)]
690 Store(#[from] TicketStoreError),
691}
692
693#[must_use]
694pub fn external_content_sha256(bytes: &[u8]) -> String {
695 hex::encode(Sha256::digest(bytes))
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701 use crate::{MemoryTicketingStore, TicketChannel, TicketRequester};
702 use std::{collections::BTreeSet, sync::Arc};
703
704 fn identity(subject: &str, permissions: &[&str]) -> Identity {
705 Identity {
706 subject: subject.into(),
707 permissions: permissions
708 .iter()
709 .map(|value| (*value).into())
710 .collect::<BTreeSet<_>>(),
711 scopes: BTreeSet::new(),
712 claims: BTreeMap::new(),
713 }
714 }
715
716 fn service() -> TicketingService {
717 TicketingService::new(
718 TicketingStoreService::new(Arc::new(MemoryTicketingStore::default())),
719 TicketingConfig {
720 project_id: "project-a".into(),
721 portal_origin: "https://support.example.test".into(),
722 allowed_return_paths: BTreeMap::from([(
723 "https://app.example.test".into(),
724 vec!["/orders".into()],
725 )]),
726 ..TicketingConfig::default()
727 },
728 )
729 .unwrap()
730 }
731
732 #[tokio::test]
733 async fn authorization_precedes_persistence_and_requesters_are_isolated() {
734 let service = service();
735 let input = CreateTicketInput {
736 project_id: "project-a".into(),
737 subject: "Help".into(),
738 description: "Broken".into(),
739 requester: TicketRequester {
740 subject: "user-a".into(),
741 display_name: None,
742 email: None,
743 },
744 channel: TicketChannel::Api,
745 priority: TicketPriority::Normal,
746 resource_references: Vec::new(),
747 };
748 assert!(matches!(
749 service
750 .create_ticket(
751 &identity("user-a", &[]),
752 input.clone(),
753 Uuid::now_v7(),
754 Utc::now()
755 )
756 .await,
757 Err(TicketingServiceError::PermissionDenied(_))
758 ));
759 let created = service
760 .create_ticket(
761 &identity("user-a", &["ticketing.create"]),
762 input,
763 Uuid::now_v7(),
764 Utc::now(),
765 )
766 .await
767 .unwrap();
768 assert!(matches!(
769 service
770 .get_ticket_for_requester(
771 &identity("user-b", &["ticketing.read"]),
772 "project-a",
773 created.ticket.id
774 )
775 .await,
776 Err(TicketingServiceError::RequesterMismatch)
777 ));
778 }
779
780 #[tokio::test]
781 async fn external_content_digest_is_canonical_before_idempotency() {
782 let service = service();
783 let now = Utc::now();
784 let created = service
785 .create_ticket(
786 &identity("user-a", &["ticketing.create"]),
787 CreateTicketInput {
788 project_id: "project-a".into(),
789 subject: "Help".into(),
790 description: "Broken".into(),
791 requester: TicketRequester {
792 subject: "user-a".into(),
793 display_name: None,
794 email: None,
795 },
796 channel: TicketChannel::Api,
797 priority: TicketPriority::Normal,
798 resource_references: Vec::new(),
799 },
800 Uuid::now_v7(),
801 now,
802 )
803 .await
804 .unwrap();
805 let digest = external_content_sha256(b"same message");
806 let external = |content_sha256: String| ExternalMessageIdentity {
807 project_id: "project-a".into(),
808 provider: "mail".into(),
809 mailbox_scope: "support@example.test".into(),
810 external_id: "message-1".into(),
811 content_sha256,
812 raw_message_object_key: None,
813 internet_message_id: None,
814 in_reply_to: None,
815 references: Vec::new(),
816 };
817 let first = service
818 .ingest_external_message(
819 &identity("ingress", &["ticketing.ingest"]),
820 external(digest.to_ascii_uppercase()),
821 created.ticket.id,
822 "Reply".into(),
823 0,
824 Uuid::now_v7(),
825 now,
826 )
827 .await
828 .unwrap();
829 let replay = service
830 .ingest_external_message(
831 &identity("ingress", &["ticketing.ingest"]),
832 external(digest),
833 created.ticket.id,
834 "Reply".into(),
835 0,
836 Uuid::now_v7(),
837 now,
838 )
839 .await
840 .unwrap();
841
842 assert_eq!(replay.ticket, first.ticket);
843 }
844}