Skip to main content

Tax

Struct Tax 

Source
pub struct Tax { /* private fields */ }
Expand description

Tax calculation and management interface.

Provides tax rate management, exemption handling, and tax calculation for commerce operations.

§Example

use stateset_embedded::{Commerce, TaxAddress, TaxCalculationRequest, TaxLineItem, ProductTaxCategory};
use rust_decimal_macros::dec;

let commerce = Commerce::new("./store.db")?;

// Calculate tax for a transaction
let result = commerce.tax().calculate(TaxCalculationRequest {
    line_items: vec![TaxLineItem {
        id: "item-1".into(),
        quantity: dec!(2),
        unit_price: dec!(29.99),
        tax_category: ProductTaxCategory::Standard,
        ..Default::default()
    }],
    shipping_address: TaxAddress {
        country: "US".into(),
        state: Some("CA".into()),
        postal_code: Some("90210".into()),
        ..Default::default()
    },
    ..Default::default()
})?;

println!("Subtotal: ${}", result.subtotal);
println!("Tax: ${}", result.total_tax);
println!("Total: ${}", result.total);

Implementations§

Source§

impl Tax

Source

pub fn calculate( &self, request: TaxCalculationRequest, ) -> Result<TaxCalculationResult>

Calculate tax for a transaction.

Given line items and shipping address, calculates applicable taxes based on jurisdiction rules, product categories, and customer exemptions.

§Example
use rust_decimal_macros::dec;

let result = commerce.tax().calculate(TaxCalculationRequest {
    line_items: vec![TaxLineItem {
        id: "item-1".into(),
        quantity: dec!(2),
        unit_price: dec!(29.99),
        tax_category: ProductTaxCategory::Standard,
        ..Default::default()
    }],
    shipping_address: TaxAddress {
        country: "US".into(),
        state: Some("CA".into()),
        ..Default::default()
    },
    ..Default::default()
})?;

println!("Tax breakdown:");
for breakdown in &result.tax_breakdown {
    println!("  {}: {}% = ${}", breakdown.rate_name, breakdown.rate * dec!(100), breakdown.tax_amount);
}
Source

pub fn calculate_for_item( &self, unit_price: Decimal, quantity: Decimal, category: ProductTaxCategory, shipping_address: &TaxAddress, ) -> Result<Decimal>

Calculate tax for a single item (convenience method).

§Example
use rust_decimal_macros::dec;

let tax = commerce.tax().calculate_for_item(
    dec!(99.99),                    // unit price
    dec!(2),                        // quantity
    ProductTaxCategory::Standard,    // category
    &TaxAddress {
        country: "US".into(),
        state: Some("TX".into()),
        ..Default::default()
    },
)?;

println!("Tax: ${}", tax);
Source

pub fn get_effective_rate( &self, address: &TaxAddress, category: ProductTaxCategory, ) -> Result<Decimal>

Get the effective tax rate for an address and category.

Returns the combined tax rate that would apply to a standard purchase.

§Example
let rate = commerce.tax().get_effective_rate(
    &TaxAddress {
        country: "US".into(),
        state: Some("CA".into()),
        city: Some("Los Angeles".into()),
        ..Default::default()
    },
    ProductTaxCategory::Standard,
)?;

println!("Effective tax rate: {}%", rate * rust_decimal_macros::dec!(100));
Source

pub fn get_jurisdiction(&self, id: Uuid) -> Result<Option<TaxJurisdiction>>

Get a tax jurisdiction by ID.

Source

pub fn get_jurisdiction_by_code( &self, code: &str, ) -> Result<Option<TaxJurisdiction>>

Get a tax jurisdiction by code (e.g., “US-CA”).

§Example
if let Some(jurisdiction) = commerce.tax().get_jurisdiction_by_code("US-CA")? {
    println!("{}: {}", jurisdiction.code, jurisdiction.name);
}
Source

pub fn list_jurisdictions( &self, filter: TaxJurisdictionFilter, ) -> Result<Vec<TaxJurisdiction>>

List tax jurisdictions with optional filtering.

§Example
// List all US state jurisdictions
let states = commerce.tax().list_jurisdictions(TaxJurisdictionFilter {
    country_code: Some("US".into()),
    level: Some(JurisdictionLevel::State),
    active_only: true,
    ..Default::default()
})?;

for state in states {
    println!("{}: {}", state.code, state.name);
}
Source

pub fn create_jurisdiction( &self, input: CreateTaxJurisdiction, ) -> Result<TaxJurisdiction>

Create a new tax jurisdiction.

§Example
let jurisdiction = commerce.tax().create_jurisdiction(CreateTaxJurisdiction {
    name: "Los Angeles".into(),
    code: "US-CA-LA".into(),
    level: JurisdictionLevel::City,
    country_code: "US".into(),
    state_code: Some("CA".into()),
    city: Some("Los Angeles".into()),
    ..Default::default()
})?;
Source

pub fn get_rate(&self, id: Uuid) -> Result<Option<TaxRate>>

Get a tax rate by ID.

Source

pub fn list_rates(&self, filter: TaxRateFilter) -> Result<Vec<TaxRate>>

List tax rates with optional filtering.

§Example
// Get all active rates for a jurisdiction
let rates = commerce.tax().list_rates(TaxRateFilter {
    jurisdiction_id: Some(jurisdiction_id),
    active_only: true,
    ..Default::default()
})?;

for rate in rates {
    println!("{}: {}%", rate.name, rate.rate * rust_decimal_macros::dec!(100));
}
Source

pub fn create_rate(&self, input: CreateTaxRate) -> Result<TaxRate>

Create a new tax rate.

§Example
use rust_decimal_macros::dec;

let rate = commerce.tax().create_rate(CreateTaxRate {
    jurisdiction_id,
    tax_type: TaxType::SalesTax,
    product_category: ProductTaxCategory::Standard,
    rate: dec!(0.0825),  // 8.25%
    name: "City Sales Tax".into(),
    effective_from: chrono::Utc::now().date_naive(),
    ..Default::default()
})?;
Source

pub fn get_rates_for_address( &self, address: &TaxAddress, category: ProductTaxCategory, date: NaiveDate, ) -> Result<Vec<TaxRate>>

Get rates for a specific address and product category.

Returns all applicable tax rates sorted by priority.

Source

pub fn get_exemption(&self, id: Uuid) -> Result<Option<TaxExemption>>

Get an exemption by ID.

Source

pub fn get_customer_exemptions( &self, customer_id: Uuid, ) -> Result<Vec<TaxExemption>>

Get active exemptions for a customer.

§Example
let exemptions = commerce.tax().get_customer_exemptions(customer_id)?;

for exemption in exemptions {
    println!("Type: {:?}", exemption.exemption_type);
    if let Some(cert) = &exemption.certificate_number {
        println!("Certificate: {}", cert);
    }
}
Source

pub fn create_exemption( &self, input: CreateTaxExemption, ) -> Result<TaxExemption>

Create a tax exemption for a customer.

§Example
let exemption = commerce.tax().create_exemption(CreateTaxExemption {
    customer_id,
    exemption_type: ExemptionType::Resale,
    certificate_number: Some("RS-12345".into()),
    issuing_authority: Some("California".into()),
    effective_from: chrono::Utc::now().date_naive(),
    expires_at: Some(chrono::Utc::now().date_naive() + chrono::Duration::days(365)),
    ..Default::default()
})?;
Source

pub fn customer_is_exempt(&self, customer_id: Uuid) -> Result<bool>

Check if a customer has an active exemption.

§Example
if commerce.tax().customer_is_exempt(customer_id)? {
    println!("Customer has tax exemption");
}
Source

pub fn get_settings(&self) -> Result<TaxSettings>

Get tax settings.

§Example
let settings = commerce.tax().get_settings()?;

println!("Tax enabled: {}", settings.enabled);
println!("Tax shipping: {}", settings.tax_shipping);
println!("Calculation method: {:?}", settings.calculation_method);
Source

pub fn update_settings(&self, settings: TaxSettings) -> Result<TaxSettings>

Update tax settings.

§Example
let mut settings = commerce.tax().get_settings()?;
settings.tax_shipping = true;
settings.decimal_places = 2;

commerce.tax().update_settings(settings)?;
Source

pub fn set_enabled(&self, enabled: bool) -> Result<TaxSettings>

Enable or disable tax calculation.

Source

pub fn is_enabled(&self) -> Result<bool>

Check if tax calculation is enabled.

Source

pub fn get_us_state_info(state_code: &str) -> Option<UsStateTaxInfo>

Get US state tax information.

Returns pre-configured tax information for a US state.

§Example
if let Some(info) = stateset_core::get_us_state_tax_info("CA") {
    println!("California state rate: {}%", info.state_rate * rust_decimal_macros::dec!(100));
    println!("Has local taxes: {}", info.has_local_taxes);
    println!("Tax shipping: {}", info.tax_shipping);
}
Source

pub fn get_eu_vat_info(country_code: &str) -> Option<EuVatInfo>

Get EU VAT information.

Returns pre-configured VAT rates for an EU country.

§Example
if let Some(info) = stateset_core::get_eu_vat_info("DE") {
    println!("Germany standard VAT: {}%", info.standard_rate * rust_decimal_macros::dec!(100));
    if let Some(reduced) = info.reduced_rate {
        println!("Reduced rate: {}%", reduced * rust_decimal_macros::dec!(100));
    }
}
Source

pub fn get_canadian_tax_info(province_code: &str) -> Option<CanadianTaxInfo>

Get Canadian tax information.

Returns pre-configured tax rates for a Canadian province.

§Example
if let Some(info) = stateset_core::get_canadian_tax_info("ON") {
    println!("Ontario total rate: {}%", info.total_rate * rust_decimal_macros::dec!(100));
    if let Some(hst) = info.hst_rate {
        println!("HST: {}%", hst * rust_decimal_macros::dec!(100));
    }
}
Source

pub fn is_eu_country(country_code: &str) -> bool

Check if a country is in the EU.

Trait Implementations§

Source§

impl Debug for Tax

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Tax

§

impl !UnwindSafe for Tax

§

impl Freeze for Tax

§

impl Send for Tax

§

impl Sync for Tax

§

impl Unpin for Tax

§

impl UnsafeUnpin for Tax

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more