versa 1.9.0

Versa types and utilities for developing Versa client applications in Rust
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Sender-specific functionality for services that send receipts.
//!
//! This module provides the [`VersaSendingClient`] and [`VersaSender`] trait
//! for services that need to send receipts to customers through the Versa Protocol.
//!
//! ## Workflow
//!
//! 1. Create a [`VersaSendingClient`] with your credentials and schema version
//! 2. Upload any assets (images, PDFs) using [`register_asset`](VersaSender::register_asset)
//! 3. Register the receipt with the Versa registry using [`register_receipt`](VersaSender::register_receipt)
//! 4. Encrypt and send the receipt to each receiver using [`encrypt_and_send`](VersaSender::encrypt_and_send)
//!
//! ## Example
//!
//! ```rust,no_run
//! use versa::client::{VersaClient, ClientError};
//! use versa::client_sender::VersaSender;
//! use versa::protocol::TransactionHandles;
//! use versa::schema::receipt::Receipt;
//!
//! # async fn example() -> Result<(), ClientError> {
//! // Create a sending client
//! let client = VersaClient::new("client_id".to_string(), "secret".to_string())
//!     .sending_client("2.2.0".to_string());
//!
//! // Upload an asset
//! let file_data = vec![0u8; 1024]; // Example file data
//! let asset_response = client.register_asset(file_data, "invoice.pdf".to_string()).await?;
//! let asset_id = asset_response.asset_id;
//!
//! // Register the receipt
//! let handles = TransactionHandles::new()
//!     .with_customer_email("customer@example.com".to_string());
//!     
//! let response = client.register_receipt(handles, None).await?;
//! let (encryption_key, summary, receivers) = response.ready_for_delivery();
//!
//! // Create your receipt (you can use the asset_id in appropriate fields)
//! let receipt = Receipt {
//!     // Use asset_id in fields like logo, receipt_image, etc.
//!     # schema_version: versa::schema::current::SCHEMA_VERSION.parse().unwrap(),
//!     # header: versa::schema::receipt::Header::builder().try_into().unwrap(),
//!     # itemization: versa::schema::receipt::Itemization::builder().try_into().unwrap(),
//!     # payments: None,
//!     # footer: None,
//! };
//!
//! // Send to each receiver
//! for receiver in receivers {
//!     client.encrypt_and_send(receiver, summary.clone().into(), encryption_key.clone(), &receipt).await?;
//! }
//! # Ok(())
//! # }
//! ```

use std::future::Future;

use base64::prelude::*;
use serde::Serialize;
use std::time::SystemTime;

use crate::{
  client::{ClientError, VersaClient, customer_registration::CustomerRegistration},
  protocol::{
    AssetRegistrationResponse, ClientMetadata, EncryptionKey, EventRegistrationRequest,
    EventRegistrationResponse, EventRegistrationSummary, ReceiptRegistrationRequest,
    ReceiptRegistrationResponse, ReceiverFilter, ReceiverInstruction, ReceiverQueryRequest,
    ReceiverQueryResponse, TransactionHandles,
    customer_registration::CustomerRef,
    event::{EventType, InitialEventType, UpdateEventType},
    webhook::WebhookEvent,
  },
};

/// Trait for sending receipts through the Versa Protocol.
///
/// This trait is implemented by [`VersaSendingClient`] and provides the core
/// functionality for registering and sending receipts.
pub trait VersaSender {
  /// Registers an event with the Versa registry.
  ///
  /// Returns encryption keys and a list of receivers that should receive the event.
  ///
  /// # Arguments
  ///
  /// * `event_type` - The type of the event to register
  /// * `handles` - Optional transaction handles for routing the event if no transaction ID provided
  /// * `transaction_id` - Optional transaction ID if updating an existing event
  fn register_event(
    &self,
    event_type: EventType,
    handles: Option<TransactionHandles>,
    transaction_id: Option<String>,
  ) -> impl Future<Output = Result<EventRegistrationResponse, ClientError>> + Send;

  /// Registers a new initial event with the Versa registry.
  ///
  /// Returns encryption keys and a list of receivers that should receive the event.
  ///
  /// # Arguments
  ///
  /// * `event_type` - The type of the initial event to register
  /// * `handles` - required transaction handles for routing the event if no transaction ID provided
  fn register_initial_event(
    &self,
    event_type: InitialEventType,
    handles: TransactionHandles,
  ) -> impl Future<Output = Result<EventRegistrationResponse, ClientError>> + Send;

  /// Registers an update event with the Versa registry.
  ///
  /// Returns encryption keys and a list of receivers that should receive the event.
  ///
  /// # Arguments
  ///
  /// * `event_type` - The type of the update event to register
  /// * `handles` - required transaction handles for routing the event if no transaction ID provided
  fn register_update_event(
    &self,
    event_type: UpdateEventType,
    transaction_id: String,
  ) -> impl Future<Output = Result<EventRegistrationResponse, ClientError>> + Send;

  /// Registers a receipt with the Versa registry.
  ///
  /// Returns encryption keys and a list of receivers that should receive the receipt.
  ///
  /// # Arguments
  ///
  /// * `handles` - Transaction handles for routing the receipt
  /// * `transaction_id` - Optional transaction ID if updating an existing receipt
  #[deprecated(since = "1.6.0", note = "please use `register_event()` instead")]
  fn register_receipt(
    &self,
    handles: TransactionHandles,
    transaction_id: Option<String>,
  ) -> impl Future<Output = Result<ReceiptRegistrationResponse, ClientError>> + Send;

  /// Encrypts and sends data to a receiver.
  ///
  /// This method encrypts the provided data using the encryption key from the
  /// registry and sends it to the specified receiver's webhook endpoint.
  ///
  /// # Arguments
  ///
  /// * `receiver` - Receiver instruction from the registry response
  /// * `summary` - Registration summary from the registry response
  /// * `encryption_key` - Encryption key from the registry response
  /// * `data` - The receipt or itinerary data to send
  fn encrypt_and_send<T>(
    &self,
    receiver: ReceiverInstruction,
    summary: EventRegistrationSummary,
    encryption_key: EncryptionKey,
    data: T,
  ) -> impl Future<Output = Result<(), ClientError>>
  where
    T: Serialize;
  /// Registers an asset (image or PDF) with the Versa registry.
  ///
  /// Uploads a file to the Versa registry and returns an asset ID that can be
  /// used to reference the file in receipts and other Versa data structures.
  ///
  /// # Arguments
  ///
  /// * `file_data` - The raw bytes of the file to upload
  /// * `filename` - The original filename (used for content type detection)
  ///
  /// # Supported File Types
  ///
  /// * PDF files
  /// * PNG images
  /// * JPEG images
  /// * WEBP images
  ///
  /// Files must be under 50MB in size.
  fn register_asset(
    &self,
    file_data: Vec<u8>,
    filename: String,
  ) -> impl Future<Output = Result<AssetRegistrationResponse, ClientError>> + Send;

  /// Queries available receivers based on optional filters and transaction handles.
  ///
  /// Returns a list of receivers that match the specified criteria. If transaction
  /// handles are provided, the response will include handling information indicating
  /// whether the sender is registered with each receiver.
  ///
  /// # Arguments
  ///
  /// * `filters` - Optional filters to narrow the receiver list (e.g., by category or region)
  /// * `handles` - Optional transaction handles to check registration status
  ///
  /// # Example
  ///
  /// ```rust,no_run
  /// # use versa::client::{VersaClient, ClientError};
  /// # use versa::client_sender::VersaSender;
  /// # use versa::protocol::{ReceiverFilter, ReceiverCategory, TransactionHandles};
  /// # async fn example() -> Result<(), ClientError> {
  /// # let client = VersaClient::new("id".to_string(), "secret".to_string())
  /// #     .sending_client("2.2.0".to_string());
  /// // Query all expense receivers
  /// let filters = vec![ReceiverFilter::Category(vec![ReceiverCategory::Expense])];
  /// let response = client.query_receivers(Some(filters), None).await?;
  ///
  /// // Query receivers with handling info for a specific customer
  /// let handles = TransactionHandles::new()
  ///     .with_customer_email("customer@example.com".to_string());
  /// let response = client.query_receivers(None, Some(handles)).await?;
  /// # Ok(())
  /// # }
  /// ```
  fn query_receivers(
    &self,
    filters: Option<Vec<ReceiverFilter>>,
    handles: Option<TransactionHandles>,
  ) -> impl Future<Output = Result<ReceiverQueryResponse, ClientError>> + Send;
}

/// Client for sending receipts through the Versa Protocol.
///
/// Created by calling [`sending_client`](VersaClient::sending_client) on a [`VersaClient`].
pub struct VersaSendingClient {
  base_client: VersaClient,
  /// The schema version to use for receipts (e.g., "2.2.0")
  pub schema_version: String,
}

#[cfg(feature = "client_sender")]
impl VersaClient {
  /// Access sending APIs by configuring a Versa sending client with a schema version
  pub fn sending_client(self, schema_version: String) -> VersaSendingClient {
    VersaSendingClient {
      base_client: self,
      schema_version,
    }
  }
}

impl VersaSendingClient {
  pub fn client_id(&self) -> String {
    self.base_client.client_id()
  }
}

#[cfg(feature = "client_sender")]
impl VersaSender for VersaSendingClient {
  async fn register_event(
    &self,
    event_type: EventType,
    handles: Option<TransactionHandles>,
    transaction_id: Option<String>,
  ) -> Result<EventRegistrationResponse, ClientError> {
    let credential = self.base_client.authorization_header_val();
    let schema_version = self.schema_version.clone();

    let payload = EventRegistrationRequest {
      event_type: Some(event_type),
      schema_version,
      handles,
      transaction_id,
      client_metadata: Some(ClientMetadata {
        client_string: self.base_client.client_string(),
      }),
      transaction_event_filter: None,
    };

    let payload_json = serde_json::to_string(&payload).unwrap();

    let url = format!("{}/register", self.base_client.registry_url);
    let client = reqwest::Client::new();
    let response_result = client
      .post(url)
      .header("Accept", "application/json")
      .header("Authorization", credential)
      .header("Content-Type", "application/json")
      .body(payload_json)
      .send()
      .await;

    let res = match response_result {
      Ok(res) => res,
      Err(e) => {
        return Err(ClientError::NetworkError(e));
      }
    };

    if res.status().is_success() {
      let data: EventRegistrationResponse = match res.json().await {
        Ok(val) => val,
        Err(e) => {
          return Err(ClientError::DeserializationError(e));
        }
      };
      return Ok(data);
    } else {
      return Err(ClientError::RegistryError(
        res.status(),
        res.text().await.unwrap_or_default(),
      ));
    }
  }

  async fn register_initial_event(
    &self,
    event_type: InitialEventType,
    handles: TransactionHandles,
  ) -> Result<EventRegistrationResponse, ClientError> {
    self
      .register_event(event_type.into(), Some(handles), None)
      .await
  }

  async fn register_update_event(
    &self,
    event_type: UpdateEventType,
    transaction_id: String,
  ) -> Result<EventRegistrationResponse, ClientError> {
    self
      .register_event(event_type.into(), None, Some(transaction_id))
      .await
  }

  async fn register_receipt(
    &self,
    handles: TransactionHandles,
    transaction_id: Option<String>,
  ) -> Result<ReceiptRegistrationResponse, ClientError> {
    let credential = self.base_client.authorization_header_val();
    let schema_version = self.schema_version.clone();

    let payload = ReceiptRegistrationRequest {
      event_type: None,
      schema_version,
      handles: Some(handles),
      transaction_id,
      client_metadata: Some(ClientMetadata {
        client_string: self.base_client.client_string(),
      }),
      transaction_event_filter: None,
    };

    let payload_json = serde_json::to_string(&payload).unwrap();

    let url = format!("{}/register", self.base_client.registry_url);
    let client = reqwest::Client::new();
    let response_result = client
      .post(url)
      .header("Accept", "application/json")
      .header("Authorization", credential)
      .header("Content-Type", "application/json")
      .body(payload_json)
      .send()
      .await;

    let res = match response_result {
      Ok(res) => res,
      Err(e) => {
        return Err(ClientError::NetworkError(e));
      }
    };

    if res.status().is_success() {
      let data: ReceiptRegistrationResponse = match res.json().await {
        Ok(val) => val,
        Err(e) => {
          return Err(ClientError::DeserializationError(e));
        }
      };
      return Ok(data);
    } else {
      return Err(ClientError::RegistryError(
        res.status(),
        res.text().await.unwrap_or_default(),
      ));
    }
  }

  async fn encrypt_and_send<T>(
    &self,
    receiver: ReceiverInstruction,
    summary: EventRegistrationSummary,
    encryption_key: EncryptionKey,
    data: T,
  ) -> Result<(), ClientError>
  where
    T: Serialize,
  {
    let envelope = crate::encryption::encrypt_envelope(
      &data,
      &BASE64_STANDARD.decode(encryption_key.0).unwrap(),
    );

    let EventRegistrationSummary {
      mode: _,
      event_id: _,
      receipt_id,
      transaction_id: _,
    } = summary;

    let data = crate::protocol::ReceiverPayload {
      sender_client_id: self.base_client.client_id(),
      receipt_id,
      envelope,
    };

    let timestamp = std::time::SystemTime::now()
      .duration_since(SystemTime::UNIX_EPOCH)
      .unwrap()
      .as_secs() as i64;

    let payload = WebhookEvent {
      data,
      event_id: Some(receiver.event_id),
      event_at: Some(timestamp),
      delivery_id: None, // TODO generate and return this
      delivery_at: Some(timestamp),
      event: receiver.event_type.into(),
    };

    let payload_json = serde_json::to_string(&payload).unwrap();
    let byte_body = bytes::Bytes::from(payload_json.clone());
    let token = crate::hmac_util::generate_token(byte_body, receiver.secret);
    let client = reqwest::Client::new();
    let response_result = client
      .post(&receiver.address)
      .header("Content-Type", "application/json")
      .header("X-Request-Signature", token)
      .body(payload_json)
      .send()
      .await;

    let res = match response_result {
      Ok(res) => res,
      Err(e) => {
        return Err(ClientError::NetworkError(e));
      }
    };

    if res.status().is_success() {
      // info!("Successfully sent data to receiver: {}", receiver.address);
      // TODO: process response from each receiver
      return Ok(());
    } else {
      return Err(ClientError::RemoteClientError(
        res.status(),
        res.text().await.unwrap_or_default(),
      ));
    }
  }

  async fn register_asset(
    &self,
    file_data: Vec<u8>,
    filename: String,
  ) -> Result<AssetRegistrationResponse, ClientError> {
    let credential = self.base_client.authorization_header_val();
    let url = format!("{}/asset", self.base_client.registry_url);

    let client = reqwest::Client::new();
    let form = reqwest::multipart::Form::new().part(
      "file",
      reqwest::multipart::Part::bytes(file_data).file_name(filename),
    );

    let response_result = client
      .post(url)
      .header("Authorization", credential)
      .multipart(form)
      .send()
      .await;

    let res = match response_result {
      Ok(res) => res,
      Err(e) => {
        return Err(ClientError::NetworkError(e));
      }
    };

    if res.status().is_success() {
      let data: AssetRegistrationResponse = match res.json().await {
        Ok(val) => val,
        Err(e) => {
          return Err(ClientError::DeserializationError(e));
        }
      };
      return Ok(data);
    } else {
      return Err(ClientError::RegistryError(
        res.status(),
        res.text().await.unwrap_or_default(),
      ));
    }
  }

  async fn query_receivers(
    &self,
    filters: Option<Vec<ReceiverFilter>>,
    handles: Option<TransactionHandles>,
  ) -> Result<ReceiverQueryResponse, ClientError> {
    let credential = self.base_client.authorization_header_val();

    let payload = ReceiverQueryRequest { filters, handles };
    let payload_json = serde_json::to_string(&payload).unwrap();

    let url = format!("{}/receiver/query", self.base_client.registry_url);
    let client = reqwest::Client::new();
    let response_result = client
      .post(url)
      .header("Accept", "application/json")
      .header("Authorization", credential)
      .header("Content-Type", "application/json")
      .body(payload_json)
      .send()
      .await;

    let res = match response_result {
      Ok(res) => res,
      Err(e) => {
        return Err(ClientError::NetworkError(e));
      }
    };

    if res.status().is_success() {
      let data: ReceiverQueryResponse = match res.json().await {
        Ok(val) => val,
        Err(e) => {
          return Err(ClientError::DeserializationError(e));
        }
      };
      return Ok(data);
    } else {
      return Err(ClientError::RegistryError(
        res.status(),
        res.text().await.unwrap_or_default(),
      ));
    }
  }
}

// TODO: could use the typestate pattern with a generic type to constrain the customer reference
impl CustomerRegistration for VersaSendingClient {
  async fn register_customer_reference(
    &self,
    customer_reference: CustomerRef,
  ) -> Result<(), ClientError> {
    self
      .base_client
      .register_customer_reference(customer_reference)
      .await
  }

  async fn deregister_customer_reference(
    &self,
    customer_reference: CustomerRef,
  ) -> Result<(), ClientError> {
    self
      .base_client
      .register_customer_reference(customer_reference)
      .await
  }
}