use std::sync::Arc;
use adk_auth::{ScopeGuard, StaticScopeResolver};
use adk_core::{Result, Tool};
use adk_kernel::PartitionId;
use adk_kernel::charter::{KpiSource, SignalFilter, SignalStore};
use adk_payments::auth::PAYMENT_EXECUTE_SCOPE;
use adk_payments::wallet::{CommerceOutcomes, Wallet, WalletKpiSource, WalletToolset};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use uuid::Uuid;
pub fn finance_tools(wallet: Wallet) -> Vec<Arc<dyn Tool>> {
let guard = ScopeGuard::new(StaticScopeResolver::new(vec![PAYMENT_EXECUTE_SCOPE.to_string()]));
WalletToolset::new(wallet).with_scope_guard(guard).tools()
}
pub struct WalletKpi(pub WalletKpiSource);
impl WalletKpi {
pub fn new(source: WalletKpiSource) -> Self {
Self(source)
}
}
#[async_trait]
impl KpiSource for WalletKpi {
fn name(&self) -> &str {
self.0.name()
}
async fn read(
&self,
site: Uuid,
metric: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> adk_kernel::Result<Option<f64>> {
self.0.read(site, metric, from, to).await.map_err(|error| adk_kernel::KernelError::Store {
backend: "wallet",
reason: error.to_string(),
})
}
}
pub struct SiteOutcomes {
signals: Arc<dyn SignalStore>,
partition: PartitionId,
commerce: Option<Arc<dyn CommerceOutcomes>>,
}
impl SiteOutcomes {
pub fn new(signals: Arc<dyn SignalStore>, partition: impl Into<PartitionId>) -> Self {
Self { signals, partition: partition.into(), commerce: None }
}
#[must_use]
pub fn with_commerce(mut self, commerce: Arc<dyn CommerceOutcomes>) -> Self {
self.commerce = Some(commerce);
self
}
}
#[async_trait]
impl CommerceOutcomes for SiteOutcomes {
async fn revenue(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
match &self.commerce {
Some(commerce) => commerce.revenue(from, to).await,
None => Ok(0),
}
}
async fn leads(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
let filter =
SignalFilter::default().partition(self.partition.clone()).kind("lead_captured");
let records = self
.signals
.list(&filter)
.await
.map_err(|error| adk_core::AdkError::config(error.to_string()))?;
Ok(records
.iter()
.filter(|record| record.last_at >= from && record.last_at < to)
.map(|record| u64::from(record.count.max(1)))
.sum())
}
async fn sales(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<u64> {
match &self.commerce {
Some(commerce) => commerce.sales(from, to).await,
None => Ok(0),
}
}
}