Functional Weave
Code in Rust

retail.gift-card-balance@1.0.0

impl/rust.rs

1,488 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::money_add::subtract_money;  ← from money.add ^1.0.0 · built alongside by fune
use super::money_amount::{money_from_value, money_to_value, Money};  ← from money.amount ^1.0.0 · built alongside by fune
use super::money_compare::min_money;  ← from money.compare ^1.0.0 · built alongside by fune

/// Pay as much of `amount_due` as the card's balance allows.
///
/// # Panics
/// Panics on a negative balance or amount due, or mixed currencies.
pub fn redeem_gift_card(balance: &Money, amount_due: &Money) -> GiftCardRedemption {
    if balance.minor < 0 {
        panic!("balance must not be negative, received {}", balance.minor);
    }
    if amount_due.minor < 0 {
        panic!(
            "amountDue must not be negative, received {}; a refund to a gift card is a top-up",
            amount_due.minor
        );
    }
    let applied = min_money(balance, amount_due);
    let still_due = subtract_money(amount_due, &applied);
    GiftCardRedemption {
        remaining_balance: subtract_money(balance, &applied),
        fully_paid: still_due.minor == 0,
        applied,
        still_due,
    }
}

pub fn gift_card_redemption_to_value(r: &GiftCardRedemption) -> Value {
    Value::obj(vec![
        ("applied", money_to_value(&r.applied)),
        ("remainingBalance", money_to_value(&r.remaining_balance)),
        ("stillDue", money_to_value(&r.still_due)),
        ("fullyPaid", Value::Bool(r.fully_paid)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    gift_card_redemption_to_value(&redeem_gift_card(
        &money_from_value(&args[0]),
        &money_from_value(&args[1]),
    ))
}