Skip to content

Commit

Permalink
chore: Use local_id in subscription rest api
Browse files Browse the repository at this point in the history
  • Loading branch information
azhur committed Dec 8, 2024
1 parent 97b442d commit e428da9
Show file tree
Hide file tree
Showing 13 changed files with 126 additions and 90 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci-rust.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,6 @@ jobs:
run: |
cargo run -p meteroid --bin openapi-generate
if [[ -n "$(git status --porcelain spec/api/v1/openapi.json)" ]]; then
echo "openapi.json has uncommitted changes. Please commit the changes."
echo "openapi.json is not up to date. Please run `cargo run -p meteroid --bin openapi-generate` and commit changes."
exit 1
fi
5 changes: 5 additions & 0 deletions modules/meteroid/crates/diesel-models/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,8 @@ pub mod subscriptions;
pub mod tenants;
pub mod users;
pub mod webhooks;

pub enum IdentityDb {
UUID(uuid::Uuid),
LOCAL(String),
}
40 changes: 32 additions & 8 deletions modules/meteroid/crates/diesel-models/src/query/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use crate::extend::cursor_pagination::{
CursorPaginate, CursorPaginatedVec, CursorPaginationRequest,
};
use crate::extend::pagination::{Paginate, PaginatedVec, PaginationRequest};
use crate::query::IdentityDb;
use error_stack::ResultExt;
use uuid::Uuid;

Expand Down Expand Up @@ -58,21 +59,30 @@ impl SubscriptionRow {
pub async fn get_subscription_by_id(
conn: &mut PgConn,
tenant_id_param: &uuid::Uuid,
subscription_id: &uuid::Uuid,
subscription_id_param: IdentityDb,
) -> DbResult<SubscriptionForDisplayRow> {
use crate::schema::subscription::dsl::*;

use crate::schema::plan::dsl as p_dsl;
use crate::schema::plan_version::dsl as pv_dsl;

let query = subscription
.filter(id.eq(subscription_id))
let mut query = subscription
.filter(tenant_id.eq(tenant_id_param))
.inner_join(crate::schema::customer::table)
.inner_join(
pv_dsl::plan_version.inner_join(p_dsl::plan.on(p_dsl::id.eq(pv_dsl::plan_id))),
)
.select(SubscriptionForDisplayRow::as_select());
.select(SubscriptionForDisplayRow::as_select())
.into_boxed();

match subscription_id_param {
IdentityDb::UUID(id_param) => {
query = query.filter(id.eq(id_param));
}
IdentityDb::LOCAL(local_id_param) => {
query = query.filter(local_id.eq(local_id_param));
}
}

log::debug!("{}", debug_query::<diesel::pg::Pg, _>(&query).to_string());

Expand Down Expand Up @@ -188,8 +198,8 @@ impl SubscriptionRow {
pub async fn list_subscriptions(
conn: &mut PgConn,
tenant_id_param: uuid::Uuid,
customer_id_opt: Option<uuid::Uuid>,
plan_id_param_opt: Option<uuid::Uuid>,
customer_id_opt: Option<IdentityDb>,
plan_id_param_opt: Option<IdentityDb>,
pagination: PaginationRequest,
) -> DbResult<PaginatedVec<SubscriptionForDisplayRow>> {
use crate::schema::plan::dsl as p_dsl;
Expand All @@ -205,11 +215,25 @@ impl SubscriptionRow {
.into_boxed();

if let Some(customer_id_param) = customer_id_opt {
query = query.filter(customer_id.eq(customer_id_param));
match customer_id_param {
IdentityDb::UUID(customer_id_param) => {
query = query.filter(customer_id.eq(customer_id_param));
}
IdentityDb::LOCAL(customer_local_id) => {
query = query.filter(crate::schema::customer::local_id.eq(customer_local_id));
}
}
}

if let Some(plan_id_param) = plan_id_param_opt {
query = query.filter(crate::schema::plan::id.eq(plan_id_param));
match plan_id_param {
IdentityDb::UUID(plan_id) => {
query = query.filter(p_dsl::id.eq(plan_id));
}
IdentityDb::LOCAL(plan_local_id) => {
query = query.filter(p_dsl::local_id.eq(plan_local_id));
}
}
}

//
Expand Down
10 changes: 10 additions & 0 deletions modules/meteroid/crates/meteroid-store/src/domain/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
pub use api_tokens::*;
pub use billable_metrics::*;
pub use customers::*;
use diesel_models::query::IdentityDb;
pub use invoice_lines::*;
pub use invoices::*;
pub use invoicing_entities::*;
pub use misc::*;
use o2o::o2o;
pub use organizations::*;
pub use plans::*;
pub use price_components::*;
Expand All @@ -16,6 +18,7 @@ pub use subscription_components::*;
pub use subscription_coupons::*;
pub use subscriptions::*;
pub use tenants::*;
use uuid::Uuid;

pub mod customers;
pub mod invoices;
Expand Down Expand Up @@ -47,3 +50,10 @@ pub mod subscription_coupons;
pub mod subscriptions;
pub mod users;
pub mod webhooks;

#[derive(Debug, Clone, PartialEq, Eq, o2o)]
#[owned_into(IdentityDb)]
pub enum Identity {
UUID(Uuid),
LOCAL(String),
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ use error_stack::{Report, ResultExt};
use crate::compute::InvoiceLineInterface;
use crate::domain::outbox_event::OutboxEvent;
use crate::domain::{
CursorPaginatedVec, CursorPaginationRequest, DetailedInvoice, Invoice, InvoiceLinesPatch,
InvoiceNew, InvoiceWithCustomer, OrderByRequest, PaginatedVec, PaginationRequest,
CursorPaginatedVec, CursorPaginationRequest, DetailedInvoice, Identity, Invoice,
InvoiceLinesPatch, InvoiceNew, InvoiceWithCustomer, OrderByRequest, PaginatedVec,
PaginationRequest,
};
use crate::repositories::customer_balance::CustomerBalance;
use crate::repositories::SubscriptionInterface;
Expand Down Expand Up @@ -564,7 +565,7 @@ async fn compute_invoice_patch(
.into()),
Some(subscription_id) => {
let subscription_details = store
.get_subscription_details(tenant_id, subscription_id)
.get_subscription_details(tenant_id, Identity::UUID(subscription_id))
.await?;
let lines = store
.compute_dated_invoice_lines(&invoice.invoice.invoice_date, &subscription_details)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use crate::domain::enums::{
use crate::domain::{
BillableMetric, BillingConfig, CreateSubscription, CreateSubscriptionAddOns,
CreateSubscriptionComponents, CreateSubscriptionCoupons, CreatedSubscription,
CursorPaginatedVec, CursorPaginationRequest, Customer, InlineCustomer, InlineInvoicingEntity,
InvoicingEntity, PaginatedVec, PaginationRequest, PriceComponent, Schedule, Subscription,
SubscriptionAddOnCustomization, SubscriptionAddOnNew, SubscriptionAddOnNewInternal,
SubscriptionComponent, SubscriptionComponentNew, SubscriptionComponentNewInternal,
SubscriptionDetails, SubscriptionFee, SubscriptionInvoiceCandidate, SubscriptionNew,
CursorPaginatedVec, CursorPaginationRequest, Customer, Identity, InlineCustomer,
InlineInvoicingEntity, InvoicingEntity, PaginatedVec, PaginationRequest, PriceComponent,
Schedule, Subscription, SubscriptionAddOnCustomization, SubscriptionAddOnNew,
SubscriptionAddOnNewInternal, SubscriptionComponent, SubscriptionComponentNew,
SubscriptionComponentNewInternal, SubscriptionDetails, SubscriptionFee,
SubscriptionInvoiceCandidate, SubscriptionNew,
};
use crate::errors::StoreError;
use crate::store::{PgConn, Store};
Expand Down Expand Up @@ -40,6 +41,7 @@ use diesel_models::billable_metrics::BillableMetricRow;
use diesel_models::coupons::CouponRow;
use diesel_models::price_components::PriceComponentRow;
use diesel_models::query::plans::get_plan_names_by_version_ids;
use diesel_models::query::IdentityDb;
use diesel_models::schedules::ScheduleRow;
use diesel_models::slot_transactions::SlotTransactionRow;
use diesel_models::subscription_add_ons::{SubscriptionAddOnRow, SubscriptionAddOnRowNew};
Expand Down Expand Up @@ -73,7 +75,7 @@ pub trait SubscriptionInterface {
async fn get_subscription_details(
&self,
tenant_id: Uuid,
subscription_id: Uuid,
subscription_id: Identity,
) -> StoreResult<SubscriptionDetails>;

async fn insert_subscription_components(
Expand All @@ -93,8 +95,8 @@ pub trait SubscriptionInterface {
async fn list_subscriptions(
&self,
tenant_id: Uuid,
customer_id: Option<Uuid>,
plan_id: Option<Uuid>,
customer_id: Option<Identity>,
plan_id: Option<Identity>,
pagination: PaginationRequest,
) -> StoreResult<PaginatedVec<Subscription>>;

Expand Down Expand Up @@ -569,19 +571,19 @@ impl SubscriptionInterface for Store {
async fn get_subscription_details(
&self,
tenant_id: Uuid,
subscription_id: Uuid,
subscription_id: Identity,
) -> StoreResult<SubscriptionDetails> {
let mut conn = self.get_conn().await?;

let db_subscription =
SubscriptionRow::get_subscription_by_id(&mut conn, &tenant_id, &subscription_id)
SubscriptionRow::get_subscription_by_id(&mut conn, &tenant_id, subscription_id.into())
.await
.map_err(Into::<Report<StoreError>>::into)?;

let subscription: Subscription = db_subscription.into();

let schedules: Vec<Schedule> =
ScheduleRow::list_schedules_by_subscription(&mut conn, &tenant_id, &subscription_id)
ScheduleRow::list_schedules_by_subscription(&mut conn, &tenant_id, &subscription.id)
.await
.map_err(Into::<Report<StoreError>>::into)?
.into_iter()
Expand All @@ -592,7 +594,7 @@ impl SubscriptionInterface for Store {
SubscriptionComponentRow::list_subscription_components_by_subscription(
&mut conn,
&tenant_id,
&subscription_id,
&subscription.id,
)
.await
.map_err(Into::<Report<StoreError>>::into)?
Expand All @@ -601,7 +603,7 @@ impl SubscriptionInterface for Store {
.collect::<Result<Vec<_>, _>>()?;

let subscription_add_ons: Vec<SubscriptionAddOn> =
SubscriptionAddOnRow::list_by_subscription_id(&mut conn, &tenant_id, &subscription_id)
SubscriptionAddOnRow::list_by_subscription_id(&mut conn, &tenant_id, &subscription.id)
.await
.map_err(Into::<Report<StoreError>>::into)?
.into_iter()
Expand All @@ -623,7 +625,7 @@ impl SubscriptionInterface for Store {
metric_ids = metric_ids.into_iter().unique().collect::<Vec<_>>();

let applied_coupons =
AppliedCouponDetailedRow::list_by_subscription_id(&mut conn, &subscription_id)
AppliedCouponDetailedRow::list_by_subscription_id(&mut conn, &subscription.id)
.await
.map_err(Into::<Report<StoreError>>::into)?
.into_iter()
Expand Down Expand Up @@ -711,7 +713,10 @@ impl SubscriptionInterface for Store {
.transaction(|conn| {
async move {
let subscription: SubscriptionDetails = self
.get_subscription_details(context.tenant_id, subscription_id)
.get_subscription_details(
context.tenant_id,
Identity::UUID(subscription_id),
)
.await?;

let now = chrono::Utc::now().naive_utc();
Expand Down Expand Up @@ -739,7 +744,7 @@ impl SubscriptionInterface for Store {
let res = SubscriptionRow::get_subscription_by_id(
conn,
&context.tenant_id,
&subscription_id,
IdentityDb::UUID(subscription_id),
)
.await
.map_err(Into::<Report<StoreError>>::into)?;
Expand Down Expand Up @@ -785,17 +790,17 @@ impl SubscriptionInterface for Store {
async fn list_subscriptions(
&self,
tenant_id: Uuid,
customer_id: Option<Uuid>,
plan_id: Option<Uuid>,
customer_id: Option<Identity>,
plan_id: Option<Identity>,
pagination: PaginationRequest,
) -> StoreResult<PaginatedVec<Subscription>> {
let mut conn = self.get_conn().await?;

let db_subscriptions = SubscriptionRow::list_subscriptions(
&mut conn,
tenant_id,
customer_id,
plan_id,
customer_id.map(Into::into),
plan_id.map(Into::into),
pagination.into(),
)
.await
Expand Down
10 changes: 7 additions & 3 deletions modules/meteroid/src/api/subscriptions/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use meteroid_grpc::meteroid::api::subscriptions::v1::{
};

use meteroid_store::domain;
use meteroid_store::domain::Identity;
use meteroid_store::repositories::subscriptions::{
CancellationEffectiveAt, SubscriptionSlotsInterface,
};
Expand Down Expand Up @@ -101,7 +102,10 @@ impl SubscriptionsService for SubscriptionServiceComponents {

let subscription = self
.store
.get_subscription_details(tenant_id, parse_uuid!(inner.subscription_id)?)
.get_subscription_details(
tenant_id,
Identity::UUID(parse_uuid!(inner.subscription_id)?),
)
.await
.map_err(Into::<SubscriptionApiError>::into)
.map_err(Into::<Status>::into)
Expand All @@ -125,8 +129,8 @@ impl SubscriptionsService for SubscriptionServiceComponents {
.store
.list_subscriptions(
tenant_id,
customer_id,
plan_id,
customer_id.map(|id| Identity::UUID(id)),
plan_id.map(|id| Identity::UUID(id)),
domain::PaginationRequest {
page: inner.pagination.as_ref().map(|p| p.page).unwrap_or(0),
per_page: inner.pagination.as_ref().map(|p| p.per_page),
Expand Down
9 changes: 4 additions & 5 deletions modules/meteroid/src/api_rest/subscriptions/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@ use meteroid_store::domain;

pub fn domain_to_rest(s: domain::Subscription) -> Subscription {
Subscription {
id: s.id,
customer_id: s.customer_id,
id: s.local_id,
customer_id: s.customer_local_id,
customer_name: s.customer_name,
customer_alias: s.customer_alias,
billing_day: s.billing_day,
tenant_id: s.tenant_id,
currency: s.currency,
}
}

pub fn domain_to_rest_details(s: domain::SubscriptionDetails) -> SubscriptionDetails {
SubscriptionDetails {
id: s.id,
customer_id: s.customer_id,
id: s.local_id,
customer_id: s.customer_local_id,
customer_name: s.customer_name,
customer_alias: s.customer_alias,
billing_day: s.billing_day,
Expand Down
14 changes: 6 additions & 8 deletions modules/meteroid/src/api_rest/subscriptions/model.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
use crate::api_rest::model::PaginatedRequest;
use utoipa::ToSchema;
use uuid::Uuid;

#[derive(ToSchema, serde::Serialize, serde::Deserialize)]
pub struct SubscriptionRequest {
#[serde(flatten)]
pub pagination: PaginatedRequest,
pub customer_id: Option<Uuid>,
pub plan_id: Option<Uuid>,
pub customer_id: Option<String>,
pub plan_id: Option<String>,
}

#[derive(Clone, ToSchema, serde::Serialize, serde::Deserialize)]
pub struct Subscription {
pub id: Uuid,
pub customer_id: Uuid,
pub id: String,
pub customer_id: String,
pub customer_name: String,
pub customer_alias: Option<String>,
pub billing_day: i16,
pub tenant_id: Uuid,
pub currency: String,
}

#[derive(Clone, ToSchema, serde::Serialize, serde::Deserialize)]
pub struct SubscriptionDetails {
pub id: Uuid,
pub customer_id: Uuid,
pub id: String,
pub customer_id: String,
pub customer_name: String,
pub customer_alias: Option<String>,
pub billing_day: i16,
Expand Down
Loading

0 comments on commit e428da9

Please sign in to comment.