1use serde::{Deserialize, Serialize};
2
3use crate::locale::Currency;
4
5#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
11#[serde(rename_all = "snake_case")]
12pub enum Plan {
13 Free,
16 #[default]
18 Paid,
19}
20
21impl Plan {
22 pub fn as_str(self) -> &'static str {
23 match self {
24 Plan::Free => "free",
25 Plan::Paid => "paid",
26 }
27 }
28
29 pub fn from_wire(s: &str) -> Option<Self> {
30 match s {
31 "free" => Some(Plan::Free),
32 "paid" => Some(Plan::Paid),
33 _ => None,
34 }
35 }
36
37 pub fn is_metered(self) -> bool {
39 matches!(self, Plan::Paid)
40 }
41}
42
43#[derive(Serialize, Deserialize, Clone, Debug, Default)]
44pub struct Tenant {
45 pub id: String,
46 pub email: String,
47 pub name: Option<String>,
48 #[serde(default)]
49 pub facebook_id: Option<String>,
50 #[serde(default)]
51 pub plan: Plan,
52 #[serde(default = "default_locale")]
53 pub locale: String,
54 #[serde(default)]
55 pub currency: Currency,
56 pub created_at: String,
57 pub updated_at: String,
58}
59
60fn default_locale() -> String {
61 "en-IN".to_string()
62}
63
64#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
69#[serde(rename_all = "snake_case")]
70pub enum SafetyStatus {
71 #[default]
72 Pending,
73 Approved,
74 Rejected,
75}
76
77impl SafetyStatus {
78 pub fn as_str(&self) -> &'static str {
79 match self {
80 SafetyStatus::Pending => "pending",
81 SafetyStatus::Approved => "approved",
82 SafetyStatus::Rejected => "rejected",
83 }
84 }
85}
86
87#[derive(Serialize, Deserialize, Clone, Debug, Default)]
88pub struct SafetyState {
89 #[serde(default)]
90 pub status: SafetyStatus,
91 #[serde(default)]
92 pub content_hash: Option<String>,
93 #[serde(default)]
94 pub checked_at: Option<String>,
95 #[serde(default)]
96 pub vague_reason: Option<String>,
97}
98
99impl SafetyState {
100 pub fn is_approved_for(&self, content: &str) -> bool {
102 matches!(self.status, SafetyStatus::Approved)
103 && self.content_hash.as_deref() == Some(crate::helpers::sha256_hex(content).as_str())
104 }
105}
106
107#[derive(Serialize, Deserialize, Clone, Debug)]
112pub struct WhatsAppAccount {
113 pub id: String,
114 pub tenant_id: String,
115 pub name: String,
116 pub phone_number: String,
117 pub phone_number_id: String,
118 #[serde(default)]
119 pub waba_id: Option<String>,
120 pub auto_reply: ReplyConfig,
121 #[serde(default)]
122 pub canned_safety: SafetyState,
123 pub created_at: String,
124 pub updated_at: String,
125}
126
127#[derive(Serialize, Deserialize, Clone, Debug)]
129pub struct ReplyConfig {
130 pub enabled: bool,
131 #[serde(default = "default_response")]
132 pub response: ReplyResponse,
133 #[serde(default = "default_wait_seconds")]
136 pub wait_seconds: u32,
137 #[serde(default = "crate::prompt::default_bot_prompt")]
140 pub bot_prompt: String,
141}
142
143impl Default for ReplyConfig {
144 fn default() -> Self {
145 Self {
146 enabled: true,
147 response: default_response(),
148 wait_seconds: default_wait_seconds(),
149 bot_prompt: crate::prompt::default_bot_prompt(),
150 }
151 }
152}
153
154impl ReplyConfig {
155 pub fn is_canned(&self) -> bool {
157 matches!(self.response, ReplyResponse::Canned { .. })
158 }
159
160 pub fn canned_text(&self) -> &str {
162 match &self.response {
163 ReplyResponse::Ai => "",
164 ReplyResponse::Canned { text } => text,
165 }
166 }
167}
168
169pub fn default_response() -> ReplyResponse {
170 ReplyResponse::Ai
171}
172
173pub fn default_wait_seconds() -> u32 {
174 3
175}
176
177#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
179#[serde(tag = "mode", rename_all = "snake_case")]
180pub enum ReplyResponse {
181 Ai,
183 Canned { text: String },
185}
186
187#[derive(Debug, Deserialize)]
192pub struct WhatsAppWebhook {
193 pub object: String,
194 #[serde(default)]
195 pub entry: Vec<WebhookEntry>,
196}
197
198#[derive(Debug, Deserialize)]
199pub struct WebhookEntry {
200 #[allow(dead_code)]
201 pub id: String,
202 #[serde(default)]
203 pub changes: Vec<WebhookChange>,
204}
205
206#[derive(Debug, Deserialize)]
207pub struct WebhookChange {
208 pub field: String,
209 pub value: WebhookValue,
210}
211
212#[derive(Debug, Deserialize)]
213pub struct WebhookValue {
214 #[allow(dead_code)]
215 pub messaging_product: String,
216 pub metadata: WebhookMetadata,
217 #[serde(default)]
218 pub contacts: Vec<WebhookContact>,
219 #[serde(default)]
220 pub messages: Vec<WhatsAppMessage>,
221}
222
223#[derive(Debug, Deserialize)]
224pub struct WebhookMetadata {
225 #[allow(dead_code)]
226 pub display_phone_number: String,
227 pub phone_number_id: String,
228}
229
230#[derive(Debug, Deserialize)]
231pub struct WebhookContact {
232 pub wa_id: String,
233 pub profile: ContactProfile,
234}
235
236#[derive(Debug, Deserialize)]
237pub struct ContactProfile {
238 pub name: String,
239}
240
241#[derive(Debug, Deserialize)]
242pub struct WhatsAppMessage {
243 pub from: String,
244 pub id: String,
245 #[allow(dead_code)]
246 pub timestamp: String,
247 #[serde(rename = "type")]
248 #[allow(dead_code)]
249 pub message_type: String,
250 #[serde(default)]
251 pub text: Option<TextMessage>,
252}
253
254#[derive(Debug, Deserialize)]
255pub struct TextMessage {
256 pub body: String,
257}
258
259#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
269#[serde(rename_all = "lowercase")]
270pub enum Channel {
271 WhatsApp,
272}
273
274impl Channel {
275 pub fn as_str(&self) -> &'static str {
277 match self {
278 Channel::WhatsApp => "whatsapp",
279 }
280 }
281
282 pub fn label(&self) -> &'static str {
284 match self {
285 Channel::WhatsApp => "WhatsApp",
286 }
287 }
288}
289
290#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
292#[serde(rename_all = "snake_case")]
293pub enum MessageDirection {
294 Inbound,
295 Outbound,
296}
297
298impl MessageDirection {
299 pub fn as_str(self) -> &'static str {
300 match self {
301 MessageDirection::Inbound => "inbound",
302 MessageDirection::Outbound => "outbound",
303 }
304 }
305}
306
307#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
309#[serde(rename_all = "snake_case")]
310pub enum MessageAction {
311 AutoReply,
313 HandedOff,
315 NoCredits,
317}
318
319impl MessageAction {
320 pub fn as_str(self) -> &'static str {
321 match self {
322 MessageAction::AutoReply => "auto_reply",
323 MessageAction::HandedOff => "handed_off",
324 MessageAction::NoCredits => "no_credits",
325 }
326 }
327}
328
329#[derive(Serialize, Deserialize, Clone, Debug)]
331pub struct InboundMessage {
332 pub id: String,
333 pub channel: Channel,
334 pub sender: String,
335 pub sender_name: Option<String>,
336 pub recipient: String,
337 #[serde(default)]
340 pub reply_to: String,
341 pub body: String,
342 pub has_attachment: bool,
343 pub tenant_id: String,
344 pub channel_account_id: String,
345 pub raw_metadata: serde_json::Value,
346}
347
348impl InboundMessage {
349 pub fn conversation_key(&self) -> String {
352 if self.reply_to.is_empty() {
353 self.sender.clone()
354 } else {
355 self.reply_to.clone()
356 }
357 }
358}
359
360#[derive(Serialize, Deserialize, Clone, Debug, Default)]
362pub struct Session {
363 #[serde(default)]
364 pub last_inbound_at: String,
365 #[serde(default)]
366 pub handoff: Option<HandoffState>,
367 #[serde(default)]
368 pub conversation_id: String,
369 #[serde(default)]
370 pub messages: Vec<ConversationMessage>,
371}
372
373#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
375pub struct ConversationMessage {
376 pub role: ConversationRole,
377 pub content: String,
378 pub at: String,
379}
380
381#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
382#[serde(rename_all = "snake_case")]
383pub enum ConversationRole {
384 User,
385 Assistant,
386}
387
388impl ConversationRole {
389 pub fn as_wire(self) -> &'static str {
390 match self {
391 ConversationRole::User => "user",
392 ConversationRole::Assistant => "assistant",
393 }
394 }
395}
396
397#[derive(Serialize, Deserialize, Clone, Debug)]
399pub struct HandoffState {
400 pub signaled_at: String,
401 #[serde(default)]
402 pub notified: bool,
403}
404
405#[derive(Serialize, Deserialize, Clone, Debug, Default)]
407pub struct ConversationConfig {
408 #[serde(default)]
409 pub idle_gap_mins: Option<u32>,
410 #[serde(default)]
411 pub handoff_cooldown_mins: Option<u32>,
412 #[serde(default)]
413 pub max_history_messages: Option<u32>,
414}
415
416impl ConversationConfig {
417 pub fn resolve(&self) -> ConversationWindow {
418 ConversationWindow {
419 idle_gap_mins: self
420 .idle_gap_mins
421 .map(|v| v as i64)
422 .unwrap_or(crate::prompt::DEFAULT_CONVERSATION_IDLE_GAP_MINS),
423 handoff_cooldown_mins: self
424 .handoff_cooldown_mins
425 .map(|v| v as i64)
426 .unwrap_or(crate::prompt::DEFAULT_HANDOFF_COOLDOWN_MINS),
427 max_history_messages: self
428 .max_history_messages
429 .unwrap_or(crate::prompt::DEFAULT_CONVERSATION_MAX_MESSAGES),
430 }
431 }
432}
433
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435pub struct ConversationWindow {
436 pub idle_gap_mins: i64,
437 pub handoff_cooldown_mins: i64,
438 pub max_history_messages: u32,
439}
440
441#[derive(Serialize, Deserialize, Clone, Debug, Default)]
443pub struct BusinessInfo {
444 #[serde(default)]
445 pub name: String,
446 #[serde(default)]
447 pub contact_name: String,
448 #[serde(default)]
449 pub phone: String,
450 #[serde(default)]
451 pub business_type: String,
452 #[serde(default)]
453 pub pan: String,
454 #[serde(default)]
455 pub gstin: String,
456 #[serde(default)]
457 pub address: String,
458 #[serde(default)]
459 pub state: String,
460 #[serde(default)]
461 pub pincode: String,
462}
463
464#[derive(Serialize, Deserialize, Clone, Debug)]
466pub struct NotificationConfig {
467 #[serde(default = "default_true", alias = "approval_email")]
468 pub handoff_email: bool,
469}
470
471impl Default for NotificationConfig {
472 fn default() -> Self {
473 Self {
474 handoff_email: true,
475 }
476 }
477}
478
479fn default_true() -> bool {
480 true
481}
482
483#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
485#[serde(rename_all = "snake_case")]
486pub enum OnboardingStep {
487 #[default]
488 Basics,
489 Channels,
490 Launch,
491}
492
493impl OnboardingStep {
494 pub const ALL: [OnboardingStep; 3] = [
495 OnboardingStep::Basics,
496 OnboardingStep::Channels,
497 OnboardingStep::Launch,
498 ];
499
500 pub fn as_str(self) -> &'static str {
501 match self {
502 OnboardingStep::Basics => "basics",
503 OnboardingStep::Channels => "channels",
504 OnboardingStep::Launch => "launch",
505 }
506 }
507
508 pub fn from_wire(s: &str) -> Option<Self> {
509 match s {
510 "basics" => Some(OnboardingStep::Basics),
511 "channels" => Some(OnboardingStep::Channels),
512 "launch" => Some(OnboardingStep::Launch),
513 _ => None,
514 }
515 }
516
517 pub fn index(self) -> usize {
518 match self {
519 OnboardingStep::Basics => 0,
520 OnboardingStep::Channels => 1,
521 OnboardingStep::Launch => 2,
522 }
523 }
524}
525
526#[derive(Serialize, Deserialize, Clone, Debug)]
528pub struct OnboardingState {
529 #[serde(default)]
530 pub step: OnboardingStep,
531 #[serde(default)]
532 pub business: BusinessInfo,
533 #[serde(default)]
534 pub notifications: NotificationConfig,
535 #[serde(default)]
536 pub conversation: ConversationConfig,
537 #[serde(default)]
538 pub profile_safety: SafetyState,
539 #[serde(default = "default_wait_seconds")]
540 pub default_wait_seconds: u32,
541 #[serde(default)]
542 pub completed: bool,
543}
544
545impl Default for OnboardingState {
546 fn default() -> Self {
547 Self {
548 step: OnboardingStep::default(),
549 business: BusinessInfo::default(),
550 notifications: NotificationConfig::default(),
551 conversation: ConversationConfig::default(),
552 profile_safety: SafetyState::default(),
553 default_wait_seconds: default_wait_seconds(),
554 completed: false,
555 }
556 }
557}
558
559#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
564#[serde(rename_all = "snake_case")]
565pub enum CreditSource {
566 Purchase,
567 Grant,
568}
569
570#[derive(Serialize, Deserialize, Clone, Debug)]
571pub struct CreditEntry {
572 pub amount: i64,
573 pub source: CreditSource,
574 pub expires_at: Option<String>,
575 pub granted_at: String,
576}
577
578#[derive(Serialize, Deserialize, Clone, Debug, Default)]
579pub struct TenantBilling {
580 #[serde(default)]
581 pub credits: Vec<CreditEntry>,
582 #[serde(default)]
583 pub replies_used: i64,
584}
585
586impl TenantBilling {
587 pub fn has_credits(&self) -> bool {
588 self.total_remaining() > 0
589 }
590
591 pub fn total_remaining(&self) -> i64 {
592 self.credits.iter().map(|e| e.amount).sum()
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599
600 #[test]
601 fn onboarding_step_round_trip_and_index() {
602 for step in OnboardingStep::ALL {
603 assert_eq!(OnboardingStep::from_wire(step.as_str()), Some(step));
604 }
605 assert_eq!(OnboardingStep::from_wire("persona"), None);
606 for (i, step) in OnboardingStep::ALL.iter().enumerate() {
607 assert_eq!(step.index(), i);
608 }
609 }
610
611 #[test]
612 fn plan_from_wire_rejects_unknown() {
613 assert_eq!(Plan::from_wire("free"), Some(Plan::Free));
614 assert_eq!(Plan::from_wire("paid"), Some(Plan::Paid));
615 assert_eq!(Plan::from_wire("enterprise"), None);
616 }
617
618 #[test]
619 fn plan_is_metered_only_for_paid() {
620 assert!(Plan::Paid.is_metered());
621 assert!(!Plan::Free.is_metered());
622 }
623
624 #[test]
625 fn test_reply_response_serialization() {
626 let canned = ReplyResponse::Canned {
627 text: "hi".to_string(),
628 };
629 let s = serde_json::to_string(&canned).unwrap();
630 assert!(s.contains("\"mode\":\"canned\""));
631 assert!(s.contains("\"text\":\"hi\""));
632
633 let ai = ReplyResponse::Ai;
634 let s = serde_json::to_string(&ai).unwrap();
635 assert_eq!(s, "{\"mode\":\"ai\"}");
636 }
637
638 #[test]
639 fn reply_config_deserializes_legacy_json_without_bot_prompt() {
640 let legacy = r#"{"enabled":true,"response":{"mode":"ai"},"wait_seconds":3}"#;
641 let parsed: ReplyConfig = serde_json::from_str(legacy).unwrap();
642 assert!(parsed.enabled);
643 assert_eq!(parsed.response, ReplyResponse::Ai);
644 assert_eq!(parsed.wait_seconds, 3);
645 assert_eq!(parsed.bot_prompt, crate::prompt::DEFAULT_BOT_PROMPT);
646 }
647
648 #[test]
649 fn channel_serde_and_wire_strings_match() {
650 assert_eq!(Channel::WhatsApp.as_str(), "whatsapp");
651 assert_eq!(
652 serde_json::to_string(&Channel::WhatsApp).unwrap(),
653 "\"whatsapp\""
654 );
655 let parsed: Channel = serde_json::from_str("\"whatsapp\"").unwrap();
656 assert_eq!(parsed, Channel::WhatsApp);
657 }
658
659 #[test]
660 fn test_whatsapp_webhook_deserialization() {
661 let json = r#"{
662 "object": "whatsapp_business_account",
663 "entry": [{
664 "id": "123456789",
665 "changes": [{
666 "field": "messages",
667 "value": {
668 "messaging_product": "whatsapp",
669 "metadata": {
670 "display_phone_number": "+1234567890",
671 "phone_number_id": "phone-123"
672 },
673 "contacts": [{
674 "wa_id": "user123",
675 "profile": {"name": "Test User"}
676 }],
677 "messages": [{
678 "from": "user123",
679 "id": "msg-123",
680 "timestamp": "1234567890",
681 "type": "text",
682 "text": {"body": "Hello!"}
683 }]
684 }
685 }]
686 }]
687 }"#;
688
689 let webhook: WhatsAppWebhook = serde_json::from_str(json).unwrap();
690 assert_eq!(webhook.object, "whatsapp_business_account");
691 assert_eq!(
692 webhook.entry[0].changes[0].value.messages[0].from,
693 "user123"
694 );
695 }
696
697 #[test]
698 fn conversation_config_resolve_uses_defaults_when_unset() {
699 let cfg = ConversationConfig::default();
700 let win = cfg.resolve();
701 assert_eq!(
702 win.idle_gap_mins,
703 crate::prompt::DEFAULT_CONVERSATION_IDLE_GAP_MINS
704 );
705 assert_eq!(
706 win.handoff_cooldown_mins,
707 crate::prompt::DEFAULT_HANDOFF_COOLDOWN_MINS
708 );
709 assert_eq!(
710 win.max_history_messages,
711 crate::prompt::DEFAULT_CONVERSATION_MAX_MESSAGES
712 );
713 }
714
715 #[test]
716 fn conversation_config_resolve_honors_overrides() {
717 let cfg = ConversationConfig {
718 idle_gap_mins: Some(30),
719 handoff_cooldown_mins: Some(15),
720 max_history_messages: Some(8),
721 };
722 let win = cfg.resolve();
723 assert_eq!(win.idle_gap_mins, 30);
724 assert_eq!(win.handoff_cooldown_mins, 15);
725 assert_eq!(win.max_history_messages, 8);
726 }
727
728 #[test]
729 fn session_round_trips_with_messages_and_conversation_id() {
730 let session = Session {
731 last_inbound_at: "2026-05-04T12:00:00.000Z".to_string(),
732 handoff: None,
733 conversation_id: "conv-abc".to_string(),
734 messages: vec![
735 ConversationMessage {
736 role: ConversationRole::User,
737 content: "hi there".to_string(),
738 at: "2026-05-04T12:00:00.000Z".to_string(),
739 },
740 ConversationMessage {
741 role: ConversationRole::Assistant,
742 content: "hello!".to_string(),
743 at: "2026-05-04T12:00:01.000Z".to_string(),
744 },
745 ],
746 };
747 let s = serde_json::to_string(&session).unwrap();
748 let back: Session = serde_json::from_str(&s).unwrap();
749 assert_eq!(back.conversation_id, "conv-abc");
750 assert_eq!(back.messages.len(), 2);
751 assert_eq!(back.messages[0].role, ConversationRole::User);
752 assert_eq!(back.messages[1].role, ConversationRole::Assistant);
753 }
754}