cal-core 0.2.158

Callable core lib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// File: cal-core/src/rest/contact.rs

use crate::RecordReference;
use crate::contact::{Contact, ContactDevice};
use crate::rest::common::{
    ApiError, Id, ListRequest, PaginationParams, SearchParams, SortOrder, SortParams,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
#[cfg(feature = "openapi")]
use utoipa::ToSchema;

/// Request to create a new contact
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Request payload for creating a new contact",
    example = json!({
        "organisation": {
            "id": "507f1f77bcf86cd799439011",
            "name": "Acme Org"
        },
        "account": {
            "id": "507f1f77bcf86cd799439012",
            "name": "Acme Account"
        },
        "primary": "+1234567890",
        "name": "John Doe",
        "email": "john.doe@example.com",
        "capabilities": ["sms", "voice"],
        "groups": ["sales", "support"]
    })
))]
pub struct CreateContactRequest {
    /// Organisation this contact belongs to
    pub organisation: RecordReference,

    /// Account this contact belongs to
    pub account: RecordReference,

    /// Primary phone number (required)
    #[cfg_attr(
        feature = "openapi",
        schema(example = "+1234567890", pattern = r"^\+?[1-9]\d{1,14}$")
    )]
    pub primary: String,

    /// Secondary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "+0987654321"))]
    pub secondary: Option<String>,

    /// Tertiary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "+1122334455"))]
    pub tertiary: Option<String>,

    /// Contact's full name
    #[cfg_attr(feature = "openapi", schema(example = "John Doe", min_length = 1))]
    pub name: String,

    /// Contact's nickname or preferred name
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "Johnny"))]
    pub nickname: Option<String>,

    /// Contact's email address
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "openapi",
        schema(example = "john.doe@example.com", format = "email")
    )]
    pub email: Option<String>,

    /// Communication capabilities (e.g., sms, voice, video)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(feature = "openapi", schema(example = json!(["sms", "voice", "email"])))]
    pub capabilities: Vec<String>,

    /// Groups this contact belongs to
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(feature = "openapi", schema(example = json!(["sales", "vip", "support"])))]
    pub groups: Vec<String>,

    /// Associated device information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device: Option<ContactDevice>,

    /// Primary group (deprecated - use groups instead)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,

    /// Whether the contact has opted out of communications
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = false))]
    pub opt_out: Option<bool>,
}

/// Request to update an existing contact
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(
    feature = "openapi",
    schema(title = "Request payload for updating a contact. All fields are optional.")
)]
#[serde(rename_all = "camelCase")]
pub struct UpdateContactRequest {
    /// Update organisation reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organisation: Option<RecordReference>,

    /// Update account reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account: Option<RecordReference>,

    /// Update primary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "+1234567890"))]
    pub primary: Option<String>,

    /// Update secondary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secondary: Option<String>,

    /// Update tertiary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tertiary: Option<String>,

    /// Update contact's name
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "Jane Doe"))]
    pub name: Option<String>,

    /// Update nickname
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nickname: Option<String>,

    /// Update email address
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "jane.doe@example.com"))]
    pub email: Option<String>,

    /// Update capabilities
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<String>>,

    /// Update groups
    #[serde(skip_serializing_if = "Option::is_none")]
    pub groups: Option<Vec<String>>,

    /// Update device information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device: Option<ContactDevice>,

    /// Update primary group
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,

    /// Update opt-out status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub opt_out: Option<bool>,
}

/// Request parameters for listing contacts
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(
    feature = "openapi",
    schema(title = "Query parameters for listing contacts with filtering and pagination")
)]
#[serde(rename_all = "camelCase")]
pub struct ContactListRequest {
    /// Common list parameters (pagination, sorting, search)
    #[serde(flatten)]
    pub common: ListRequest,

    /// Filter by account ID
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "507f1f77bcf86cd799439011"))]
    pub account_id: Option<String>,

    /// Filter by organisation ID
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "507f1f77bcf86cd799439012"))]
    pub organisation_id: Option<String>,

    /// Filter by name (partial match)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "John"))]
    pub name: Option<String>,

    /// Filter by primary phone number
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "+1234567890"))]
    pub primary: Option<String>,

    /// Filter by email address
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "john@example.com"))]
    pub email: Option<String>,

    /// Filter by group membership
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "sales"))]
    pub group: Option<String>,

    /// Filter by capability
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "sms"))]
    pub capability: Option<String>,

    /// Filter by device ID
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(example = "dev_123456"))]
    pub device_id: Option<String>,
}

/// Request to create multiple contacts in a single operation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Request to create multiple contacts in batch",
    example = json!({
        "contacts": [
            {
                "organisation": {"id": "org_1", "name": "Org 1"},
                "account": {"id": "acc_1", "name": "Account 1"},
                "primary": "+1234567890",
                "name": "John Doe",
                "email": "john@example.com"
            },
            {
                "organisation": {"id": "org_1", "name": "Org 1"},
                "account": {"id": "acc_1", "name": "Account 1"},
                "primary": "+0987654321",
                "name": "Jane Doe",
                "email": "jane@example.com"
            }
        ]
    })
))]
#[serde(rename_all = "camelCase")]
pub struct BatchCreateContactsRequest {
    /// Array of contacts to create
    #[cfg_attr(feature = "openapi", schema(min_items = 1, max_items = 1000))]
    pub contacts: Vec<CreateContactRequest>,
}

/// Request to update multiple contacts in a single operation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(
    feature = "openapi",
    schema(title = "Request to update multiple contacts in batch")
)]
#[serde(rename_all = "camelCase")]
pub struct BatchUpdateContactsRequest {
    /// Array of contact updates
    #[cfg_attr(feature = "openapi", schema(min_items = 1, max_items = 1000))]
    pub updates: Vec<ContactUpdate>,
}

/// Individual contact update in a batch operation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(
    feature = "openapi",
    schema(title = "Update operation for a single contact in a batch")
)]
#[serde(rename_all = "camelCase")]
pub struct ContactUpdate {
    /// ID of the contact to update
    #[cfg_attr(feature = "openapi", schema(example = "507f1f77bcf86cd799439011"))]
    pub id: String,

    /// Update fields
    #[serde(flatten)]
    pub update: UpdateContactRequest,
}

/// Request to delete multiple contacts in a single operation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(
    title ="Request to delete multiple contacts in batch",
    example = json!({
        "ids": [
            "507f1f77bcf86cd799439011",
            "507f1f77bcf86cd799439012",
            "507f1f77bcf86cd799439013"
        ]
    })
))]
#[serde(rename_all = "camelCase")]
pub struct BatchDeleteContactsRequest {
    /// Array of contact IDs to delete
    #[cfg_attr(feature = "openapi", schema(min_items = 1, max_items = 1000))]
    pub ids: Vec<String>,
}

/// Contact-specific error codes
#[derive(Debug, Clone)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub enum ContactErrorCode {
    /// Contact not found
    NotFound,
    /// Primary number already exists
    DuplicatePrimary,
    /// Invalid email format
    InvalidEmail,
    /// Invalid phone number format
    InvalidPhone,
    /// Required field is missing
    MissingRequiredField,
    /// Invalid organisation reference
    InvalidOrganisation,
    /// Invalid account reference
    InvalidAccount,
}

impl ContactErrorCode {
    /// Convert error code to string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NotFound => "CONTACT_NOT_FOUND",
            Self::DuplicatePrimary => "DUPLICATE_PRIMARY_NUMBER",
            Self::InvalidEmail => "INVALID_EMAIL_FORMAT",
            Self::InvalidPhone => "INVALID_PHONE_FORMAT",
            Self::MissingRequiredField => "MISSING_REQUIRED_FIELD",
            Self::InvalidOrganisation => "INVALID_ORGANISATION",
            Self::InvalidAccount => "INVALID_ACCOUNT",
        }
    }
}

// Helper implementations
impl CreateContactRequest {
    /// Validate the create contact request
    pub fn validate(&self) -> Result<(), ApiError> {
        if self.name.trim().is_empty() {
            return Err(ApiError::new(
                ContactErrorCode::MissingRequiredField.as_str(),
                "Contact name is required",
            )
            .with_field("name"));
        }

        if self.primary.trim().is_empty() {
            return Err(ApiError::new(
                ContactErrorCode::MissingRequiredField.as_str(),
                "Primary contact number is required",
            )
            .with_field("primary"));
        }

        if let Some(email) = &self.email {
            if !email.is_empty() && !email.contains('@') {
                return Err(ApiError::new(
                    ContactErrorCode::InvalidEmail.as_str(),
                    "Invalid email format",
                )
                .with_field("email"));
            }
        }

        Ok(())
    }
}

impl UpdateContactRequest {
    /// Apply updates to an existing contact
    pub fn apply_to(self, contact: &mut Contact) {
        if let Some(organisation) = self.organisation {
            contact.organisation = Some(organisation);
        }
        if let Some(account) = self.account {
            contact.account = account;
        }
        if let Some(primary) = self.primary {
            contact.primary = primary;
        }
        if let Some(secondary) = self.secondary {
            contact.secondary = Some(secondary);
        }
        if let Some(tertiary) = self.tertiary {
            contact.tertiary = Some(tertiary);
        }
        if let Some(name) = self.name {
            contact.name = name;
        }
        if let Some(nickname) = self.nickname {
            contact.nickname = Some(nickname);
        }
        if let Some(email) = self.email {
            contact.email = Some(email);
        }
        if let Some(capabilities) = self.capabilities {
            contact.capabilities = capabilities;
        }
        if let Some(groups) = self.groups {
            contact.groups = groups;
        }
        if let Some(device) = self.device {
            contact.device = Some(device);
        }
        if let Some(opt_out) = self.opt_out {
            contact.opt_out = Some(opt_out);
        }
        if let Some(group) = self.group {
            contact.group = Some(group);
        }
    }

    /// Check if the update request has any fields to update
    pub fn is_empty(&self) -> bool {
        self.organisation.is_none()
            && self.account.is_none()
            && self.primary.is_none()
            && self.secondary.is_none()
            && self.tertiary.is_none()
            && self.name.is_none()
            && self.nickname.is_none()
            && self.email.is_none()
            && self.capabilities.is_none()
            && self.groups.is_none()
            && self.device.is_none()
            && self.group.is_none()
            && self.opt_out.is_none()
    }
}

impl Default for ContactListRequest {
    fn default() -> Self {
        Self {
            common: ListRequest {
                pagination: PaginationParams::default(),
                sort: SortParams::default(),
                search: None,
                time_range: None,
                filters: None,
            },
            account_id: None,
            organisation_id: None,
            name: None,
            primary: None,
            email: None,
            group: None,
            capability: None,
            device_id: None,
        }
    }
}

// Convenience builders
impl ContactListRequest {
    /// Create a new contact list request with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set pagination parameters
    pub fn with_pagination(mut self, page: u32, page_size: u32) -> Self {
        self.common.pagination = PaginationParams::new(page, page_size);
        self
    }

    /// Set sorting parameters
    pub fn with_sorting(mut self, sort_by: String, sort_order: SortOrder) -> Self {
        self.common.sort = SortParams {
            sort_by: Some(sort_by),
            sort_order,
        };
        self
    }

    /// Set search parameters
    pub fn with_search(mut self, query: String) -> Self {
        self.common.search = Some(SearchParams {
            query,
            fields: None,
            fuzzy: false,
            highlight: None,
        });
        self
    }

    /// Filter by account ID
    pub fn with_account_id(mut self, account_id: String) -> Self {
        self.account_id = Some(account_id);
        self
    }

    /// Filter by organisation ID
    pub fn with_organisation_id(mut self, organisation_id: String) -> Self {
        self.organisation_id = Some(organisation_id);
        self
    }
}