force 0.2.0

Production-ready Salesforce Platform API client with REST and Bulk API 2.0 support
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
//! Salesforce SObject types and traits.
//!
//! This module provides types for working with Salesforce SObjects (Standard Objects),
//! including dynamic field access and typed SObject representations.

use crate::types::SalesforceId;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Standard attributes present on all SObjects.
///
/// These fields are automatically included by Salesforce in query results
/// and provide metadata about the record.
///
/// # Examples
///
/// ```
/// use force::types::Attributes;
///
/// let attrs = Attributes {
///     type_: "Account".to_string(),
///     url: "/services/data/v60.0/sobjects/Account/001000000000001AAA".to_string(),
/// };
/// assert_eq!(attrs.type_, "Account");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attributes {
    /// The SObject type name (e.g., "Account", "Contact").
    #[serde(rename = "type")]
    pub type_: String,

    /// The resource URL for this record.
    pub url: String,
}

impl Attributes {
    /// Creates new attributes for the given SObject type and ID.
    ///
    /// The URL format follows Salesforce's REST API convention.
    #[must_use]
    pub fn new(type_name: impl Into<String>, id: &SalesforceId, api_version: &str) -> Self {
        let type_ = type_name.into();
        let url = format!(
            "/services/data/{}/sobjects/{}/{}",
            api_version,
            type_,
            id.as_str()
        );
        Self { type_, url }
    }

    /// Returns the `SObject` type name.
    #[must_use]
    pub fn object_type(&self) -> &str {
        &self.type_
    }
}

/// A dynamic SObject that can hold any Salesforce record.
///
/// This type uses a JSON map internally to store fields dynamically,
/// allowing you to work with any SObject type without compile-time knowledge
/// of its structure.
///
/// # Examples
///
/// ```
/// use force::types::{DynamicSObject, SalesforceId, Attributes};
/// use serde_json::json;
///
/// let id = SalesforceId::new("001000000000001AAA").unwrap();
/// let attrs = Attributes::new("Account", &id, "v60.0");
///
/// let mut account = DynamicSObject::new(attrs);
/// account.set_field("Name", "Acme Corp");
/// account.set_field("Industry", "Technology");
///
/// assert_eq!(account.get_field("Name").and_then(|v| v.as_str()), Some("Acme Corp"));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DynamicSObject {
    /// Standard SObject attributes.
    pub attributes: Attributes,

    /// Dynamic fields stored as a JSON map.
    #[serde(flatten)]
    pub fields: Map<String, Value>,
}

impl DynamicSObject {
    /// Creates a new dynamic SObject with the given attributes.
    #[must_use]
    pub fn new(attributes: Attributes) -> Self {
        Self {
            attributes,
            fields: Map::new(),
        }
    }

    /// Creates a new dynamic SObject from a JSON value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is not a valid SObject (missing attributes).
    pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
        serde_json::from_value(value)
    }

    /// Gets a field value by name.
    #[must_use]
    pub fn get_field(&self, name: &str) -> Option<&Value> {
        self.fields.get(name)
    }

    /// Gets a field value as a specific type.
    ///
    /// Performance: Deserializes directly from the borrowed `&Value` using
    /// `T::deserialize(value)` to avoid an expensive `.clone()` on the JSON value.
    ///
    /// # Errors
    ///
    /// Returns an error if the field cannot be deserialized to type T.
    pub fn get_field_as<T: for<'de> Deserialize<'de>>(
        &self,
        name: &str,
    ) -> Result<Option<T>, serde_json::Error> {
        match self.fields.get(name) {
            Some(value) => T::deserialize(value).map(Some),
            None => Ok(None),
        }
    }

    /// Sets a field value.
    pub fn set_field(&mut self, name: impl Into<String>, value: impl Serialize) {
        if let Ok(json_value) = serde_json::to_value(value) {
            self.fields.insert(name.into(), json_value);
        }
    }

    /// Removes a field by name.
    ///
    /// Returns the removed value, if it existed.
    pub fn remove_field(&mut self, name: &str) -> Option<Value> {
        self.fields.remove(name)
    }

    /// Returns true if the SObject has a field with the given name.
    #[must_use]
    pub fn has_field(&self, name: &str) -> bool {
        self.fields.contains_key(name)
    }

    /// Returns the `SObject` type name.
    #[must_use]
    pub fn object_type(&self) -> &str {
        &self.attributes.type_
    }

    /// Returns an iterator over field names.
    pub fn field_names(&self) -> impl Iterator<Item = &String> {
        self.fields.keys()
    }

    /// Returns the number of fields (excluding attributes).
    #[must_use]
    pub fn field_count(&self) -> usize {
        self.fields.len()
    }

    /// Converts the `SObject` to a JSON value.
    ///
    /// # Errors
    ///
    /// Returns an error if serialization fails (unlikely for standard field types).
    pub fn to_value(&self) -> Result<Value, serde_json::Error> {
        serde_json::to_value(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::Must;
    use serde_json::json;

    // RED PHASE - Write failing tests first

    #[test]
    fn test_attributes_new() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");

        assert_eq!(attrs.type_, "Account");
        assert_eq!(
            attrs.url,
            "/services/data/v60.0/sobjects/Account/001000000000001AAA"
        );
    }

    #[test]
    fn test_attributes_object_type() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Contact", &id, "v60.0");

        assert_eq!(attrs.object_type(), "Contact");
    }

    #[test]
    fn test_attributes_serialize() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");

        let json = serde_json::to_string(&attrs).must();
        assert!(json.contains("\"type\":\"Account\""));
        assert!(json.contains("\"url\":"));
    }

    #[test]
    fn test_attributes_deserialize() {
        let json = r#"{
            "type": "Account",
            "url": "/services/data/v60.0/sobjects/Account/001000000000001AAA"
        }"#;

        let attrs: Attributes = serde_json::from_str(json).must();
        assert_eq!(attrs.type_, "Account");
    }

    #[test]
    fn test_dynamic_sobject_new() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let sobject = DynamicSObject::new(attrs);

        assert_eq!(sobject.object_type(), "Account");
        assert_eq!(sobject.field_count(), 0);
    }

    #[test]
    fn test_dynamic_sobject_set_and_get_field() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("Name", "Acme Corp");
        sobject.set_field("Industry", "Technology");

        assert_eq!(
            sobject.get_field("Name").and_then(|v| v.as_str()),
            Some("Acme Corp")
        );
        assert_eq!(
            sobject.get_field("Industry").and_then(|v| v.as_str()),
            Some("Technology")
        );
    }

    #[test]
    fn test_dynamic_sobject_get_field_as() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("AnnualRevenue", 1_000_000);

        let revenue: Option<i64> = sobject.get_field_as("AnnualRevenue").must();
        assert_eq!(revenue, Some(1_000_000));
    }

    #[test]
    fn test_dynamic_sobject_get_field_as_type_mismatch() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("Name", "Acme Corp");

        // Try to get string field as integer
        let result: Result<Option<i64>, _> = sobject.get_field_as("Name");
        let Err(err) = result else {
            panic!("Expected an error");
        };
        assert!(err.to_string().contains(""));
    }

    #[test]
    fn test_dynamic_sobject_has_field() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("Name", "Acme Corp");

        assert!(sobject.has_field("Name"));
        assert!(!sobject.has_field("Industry"));
    }

    #[test]
    fn test_dynamic_sobject_remove_field() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("Name", "Acme Corp");
        assert!(sobject.has_field("Name"));

        let removed = sobject.remove_field("Name");
        assert!(removed.is_some());
        assert!(!sobject.has_field("Name"));
    }

    #[test]
    fn test_dynamic_sobject_field_names() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        sobject.set_field("Name", "Acme Corp");
        sobject.set_field("Industry", "Technology");

        let names: Vec<&String> = sobject.field_names().collect();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&&"Name".to_string()));
        assert!(names.contains(&&"Industry".to_string()));
    }

    #[test]
    fn test_dynamic_sobject_field_count() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        assert_eq!(sobject.field_count(), 0);

        sobject.set_field("Name", "Acme Corp");
        assert_eq!(sobject.field_count(), 1);

        sobject.set_field("Industry", "Technology");
        assert_eq!(sobject.field_count(), 2);
    }

    #[test]
    fn test_dynamic_sobject_serialize() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);
        sobject.set_field("Name", "Acme Corp");

        let json = serde_json::to_string(&sobject).must();
        assert!(json.contains("\"attributes\""));
        assert!(json.contains("\"Name\":\"Acme Corp\""));
    }

    #[test]
    fn test_dynamic_sobject_deserialize() {
        let json = json!({
            "attributes": {
                "type": "Account",
                "url": "/services/data/v60.0/sobjects/Account/001000000000001AAA"
            },
            "Name": "Acme Corp",
            "Industry": "Technology"
        });

        let sobject: DynamicSObject = serde_json::from_value(json).must();
        assert_eq!(sobject.object_type(), "Account");
        assert_eq!(
            sobject.get_field("Name").and_then(|v| v.as_str()),
            Some("Acme Corp")
        );
    }

    #[test]
    fn test_dynamic_sobject_from_value() {
        let json = json!({
            "attributes": {
                "type": "Contact",
                "url": "/services/data/v60.0/sobjects/Contact/003000000000001AAA"
            },
            "FirstName": "John",
            "LastName": "Doe"
        });

        let sobject = DynamicSObject::from_value(json).must();
        assert_eq!(sobject.object_type(), "Contact");
        assert_eq!(sobject.field_count(), 2);
    }

    #[test]
    fn test_dynamic_sobject_to_value() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);
        sobject.set_field("Name", "Acme Corp");

        let value = sobject.to_value().must();
        assert!(value.is_object());
        assert!(value.get("attributes").is_some());
        assert!(value.get("Name").is_some());
    }

    #[test]
    fn test_manual_construction_basic() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut account = DynamicSObject::new(attrs);
        account.set_field("Name", "Acme Corp");

        assert_eq!(account.object_type(), "Account");
        assert_eq!(
            account.get_field("Name").and_then(|v| v.as_str()),
            Some("Acme Corp")
        );
    }

    #[test]
    fn test_manual_construction_multiple_fields() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut account = DynamicSObject::new(attrs);
        account.set_field("Name", "Acme Corp");
        account.set_field("Industry", "Technology");
        account.set_field("AnnualRevenue", 1_000_000);

        assert_eq!(account.field_count(), 3);
    }

    #[test]
    fn test_manual_construction_empty() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let account = DynamicSObject::new(attrs);

        assert_eq!(account.field_count(), 0);
        assert_eq!(account.object_type(), "Account");
    }

    #[test]
    fn test_dynamic_sobject_from_value_missing_attributes() {
        // from_value should fail when attributes are missing
        let json = json!({
            "Name": "Acme Corp",
            "Industry": "Technology"
        });
        let result = DynamicSObject::from_value(json);
        assert!(result.is_err(), "Expected error for missing attributes");
    }

    #[test]
    fn test_dynamic_sobject_remove_field_nonexistent() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut sobject = DynamicSObject::new(attrs);

        // Removing a field that doesn't exist should return None
        let removed = sobject.remove_field("NonexistentField");
        assert!(removed.is_none());
    }

    #[test]
    fn test_dynamic_sobject_get_field_nonexistent() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let sobject = DynamicSObject::new(attrs);

        assert!(sobject.get_field("NonexistentField").is_none());
        let result: Result<Option<String>, _> = sobject.get_field_as("NonexistentField");
        assert_eq!(result.must(), None);
    }

    #[test]
    fn test_roundtrip_serialization() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let attrs = Attributes::new("Account", &id, "v60.0");
        let mut original = DynamicSObject::new(attrs);
        original.set_field("Name", "Acme Corp");
        original.set_field("Industry", "Technology");

        let json = serde_json::to_string(&original).must();
        let deserialized: DynamicSObject = serde_json::from_str(&json).must();

        assert_eq!(original, deserialized);
    }
}