Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(dss): remove affiliate tracking (#144)

Will Hutchinson398c74ce60ba
diff --git a/infra/stacks/cloud-storage-service/cloud-storage-service.ts b/infra/stacks/cloud-storage-service/cloud-storage-service.ts
index a419d9badc..6a559259f5 100644
--- a/infra/stacks/cloud-storage-service/cloud-storage-service.ts
+++ b/infra/stacks/cloud-storage-service/cloud-storage-service.ts
@@ -41,7 +41,6 @@ type CreateCloudStorageServiceServiceArgs = {
secretKeyArns: (pulumi.Output<string> | string)[];
notificationQueueArn: pulumi.Output<string> | string;
searchEventQueueArn: pulumi.Output<string> | string;
- affiliateTrackingTableArn: pulumi.Output<string> | string;
tags: { [key: string]: string };
};
@@ -75,7 +74,6 @@ export class CloudStorageService extends pulumi.ComponentResource {
secretKeyArns,
notificationQueueArn,
searchEventQueueArn,
- affiliateTrackingTableArn,
tags,
}: CreateCloudStorageServiceServiceArgs,
opts?: pulumi.ComponentResourceOptions
@@ -86,25 +84,6 @@ export class CloudStorageService extends pulumi.ComponentResource {
this.cloudStorageClusterName = cloudStorageClusterName;
// role
- const affiliateTrackingTablePolicy = new aws.iam.Policy(
- `${BASE_NAME}-affiliate-tracking-table-policy`,
- {
- name: `${BASE_NAME}-affiliate-tracking-table-policy-${stack}`,
- policy: {
- Version: '2012-10-17',
- Statement: [
- {
- Action: ['dynamodb:*'],
- Resource: [affiliateTrackingTableArn],
- Effect: 'Allow',
- },
- ],
- },
- tags: this.tags,
- },
- { parent: this }
- );
-
const frecencyTablePolicy = createFrecencyTablePolicy(
`${BASE_NAME}-frecency-table-policy`,
{ parent: this }
@@ -206,15 +185,6 @@ export class CloudStorageService extends pulumi.ComponentResource {
{ parent: this }
);
- new aws.iam.RolePolicyAttachment(
- `${BASE_NAME}-role-affiliate-tracking-att`,
- {
- role: this.role,
- policyArn: affiliateTrackingTablePolicy.arn,
- },
- { parent: this, dependsOn: [affiliateTrackingTablePolicy, this.role] }
- );
-
attachFrecencyTablePolicy(
`${BASE_NAME}-role-frecency-table-att`,
this.role,
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index 7feec8a3e9..fd34c3ee23 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -1,6 +1,6 @@
import * as aws from '@pulumi/aws';
import * as pulumi from '@pulumi/pulumi';
-import { createBucket, DynamoDBTable } from '@resources';
+import { createBucket } from '@resources';
import {
config,
getMacroApiToken,
@@ -199,17 +199,6 @@ export const deleteChatHandlerLambdaName = deleteChatHandler.lambda.name;
export const deleteChatQueueArn = deleteChatHandler.queue.arn;
export const deleteChatQueueName = deleteChatHandler.queue.name;
-/// Affiliate Tracking
-const affiliateTrackingTable = new DynamoDBTable('affiliate-tracking-table', {
- baseName: 'affiliate-tracking-table',
- attributes: [
- { name: 'PK', type: 'S' },
- { name: 'SK', type: 'S' },
- ] as aws.types.input.dynamodb.TableAttribute[],
- hashKey: 'PK',
- rangeKey: 'SK',
-});
-
const MACRO_API_TOKENS = getMacroApiToken();
const cloudStorageService = new CloudStorageService(
@@ -237,7 +226,6 @@ const cloudStorageService = new CloudStorageService(
MACRO_API_TOKENS.macroApiTokenPublicKeyArn,
],
notificationQueueArn,
- affiliateTrackingTableArn: affiliateTrackingTable.table.arn,
containerEnvVars: [
{
name: 'DATABASE_URL',
@@ -332,10 +320,6 @@ const cloudStorageService = new CloudStorageService(
name: 'DOCUMENT_PERMISSION_JWT_SECRET_KEY',
value: pulumi.interpolate`${DOCUMENT_STORAGE_PERMISSIONS_KEY}`,
},
- {
- name: 'AFFILIATE_USERS_TABLE',
- value: pulumi.interpolate`${affiliateTrackingTable.table.name}`,
- },
{
name: 'INTERNAL_API_SECRET_KEY',
value: pulumi.interpolate`${INTERNAL_API_SECRET_KEY}`,
diff --git a/rust/cloud-storage/document_storage_service/src/api/affiliate/affiliate_user.rs b/rust/cloud-storage/document_storage_service/src/api/affiliate/affiliate_user.rs
deleted file mode 100644
index bc2195f777..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/affiliate/affiliate_user.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::{
- extract::{Extension, Path, State},
- http::StatusCode,
- response::{IntoResponse, Json, Response},
-};
-use model::{
- response::{EmptyResponse, ErrorResponse, GenericErrorResponse},
- user::UserContext,
-};
-
-#[derive(serde::Deserialize)]
-pub struct Params {
- pub affiliate_code: String,
-}
-
-/// Affiliates a user with a given affiliate code
-#[utoipa::path(
- post,
- path = "/affiliate/{affiliate_code}",
- operation_id = "affiliate_user",
- params(
- ("affiliate_code" = String, Path, description = "Affiliate code")
- ),
- responses(
- (status = 200, body=EmptyResponse),
- (status = 400, body=GenericErrorResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.user_id))]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- Path(Params { affiliate_code }): Path<Params>,
-) -> Result<Response, Response> {
- tracing::trace!("affiliate_user");
-
- // check if user for affiliate code already exists
- macro_db_client::user::get_user_email::get_user_by_email(ctx.db.clone(), &affiliate_code)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get user email");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get user email",
- }),
- )
- .into_response()
- })?;
-
- let mut transaction = ctx.db.begin().await.map_err(|e| {
- tracing::error!(error=?e, "failed to begin transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to begin transaction",
- }),
- )
- .into_response()
- })?;
-
- let user_email = macro_db_client::user::get_user_email::get_user_email(
- &mut transaction,
- &user_context.user_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get user email");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get user email",
- }),
- )
- .into_response()
- })?;
-
- transaction.commit().await.map_err(|e| {
- tracing::error!(error=?e, "failed to commit transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to commit transaction",
- }),
- )
- .into_response()
- })?;
-
- // check if user is already affiliated
- let is_user_already_referred = ctx
- .dynamodb_client
- .affiliate_users
- .is_user_already_referred(&user_email)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to check if user is already affiliated");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to check if user is already affiliated",
- }),
- )
- .into_response()
- })?;
-
- if is_user_already_referred {
- return Ok((
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "user is already affiliated",
- }),
- )
- .into_response());
- }
-
- // If the users email is = the affiliate code then we can't affiliate them
- // remove the email from + to @ then compare
- if compare_emails(&user_email, &affiliate_code) {
- return Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "affiliate email matches user email",
- }),
- )
- .into_response());
- }
-
- // affiliate user
- ctx.dynamodb_client
- .affiliate_users
- .affiliate_user(&affiliate_code, &user_email)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to affiliate user");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to affiliate user",
- }),
- )
- .into_response()
- })?;
-
- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())
-}
-
-/// Compares two emails to see if they're the same
-/// Returns true if they're the same, false otherwise
-fn compare_emails(user_email: &str, affiliate_code: &str) -> bool {
- // Trim and convert both emails to lowercase
- let stripped_user_email = user_email.trim().to_lowercase();
- let stripped_affiliate_code = affiliate_code.trim().to_lowercase();
-
- // Split both emails at the @ symbol
- let user_parts: Vec<&str> = stripped_user_email.split('@').collect();
- let affiliate_parts: Vec<&str> = stripped_affiliate_code.split('@').collect();
-
- // Only proceed if both strings have an @ symbol
- if user_parts.len() > 1 && affiliate_parts.len() > 1 {
- // Get everything before the + in the local part of the email
- let user_base = user_parts[0].split('+').next().unwrap_or("");
- let affiliate_base = affiliate_parts[0].split('+').next().unwrap_or("");
-
- // Compare the base part and domain part
- return user_base == affiliate_base && user_parts[1] == affiliate_parts[1];
- }
-
- // If one of the strings doesn't have an @ symbol, they're not comparable emails
- false
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_compare_emails() {
- assert!(compare_emails("[email protected]", "[email protected]"));
- assert!(compare_emails(
- ));
- assert!(compare_emails("[email protected]", "[email protected]"));
- assert!(compare_emails("[email protected]", "[email protected]"));
-
- assert!(compare_emails(
- ));
-
- assert!(!compare_emails("[email protected]", "[email protected]"));
- }
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_referred_by.rs b/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_referred_by.rs
deleted file mode 100644
index b95d4263d1..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_referred_by.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::{
- extract::{Extension, State},
- http::StatusCode,
- response::{IntoResponse, Json, Response},
-};
-use model::{
- affiliate::AffiliateUser,
- response::{ErrorResponse, GenericErrorResponse},
- user::UserContext,
-};
-use utoipa::ToSchema;
-
-#[derive(serde::Deserialize, serde::Serialize, ToSchema)]
-pub struct GetUsersAffiliateResponse {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub affiliate: Option<AffiliateUser>,
-}
-
-/// Gets who the affiliate code the user was referred by
-#[utoipa::path(
- get,
- path = "/affiliate/referred_by",
- operation_id = "get_affiliate_referred_by",
- responses(
- (status = 200, body=GetUsersAffiliateResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.user_id))]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
-) -> Result<Response, Response> {
- tracing::trace!("get_affiliate_referred_by");
-
- let mut transaction = ctx.db.begin().await.map_err(|e| {
- tracing::error!(error=?e, "failed to begin transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to begin transaction",
- }),
- )
- .into_response()
- })?;
- let user_email = macro_db_client::user::get_user_email::get_user_email(
- &mut transaction,
- &user_context.user_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get user email");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get user email",
- }),
- )
- .into_response()
- })?;
-
- transaction.commit().await.map_err(|e| {
- tracing::error!(error=?e, "failed to commit transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to commit transaction",
- }),
- )
- .into_response()
- })?;
-
- let affiliate = ctx
- .dynamodb_client
- .affiliate_users
- .get_user_referred(&user_email)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get user referred");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get user referred",
- }),
- )
- .into_response()
- })?;
-
- Ok((
- StatusCode::OK,
- Json(GetUsersAffiliateResponse { affiliate }),
- )
- .into_response())
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_users.rs b/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_users.rs
deleted file mode 100644
index a145fd11ba..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/affiliate/get_affiliate_users.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::{
- extract::{Extension, State},
- http::StatusCode,
- response::{IntoResponse, Json, Response},
-};
-use model::{
- affiliate::AffiliateUser,
- response::{ErrorResponse, GenericErrorResponse},
- user::UserContext,
-};
-use utoipa::ToSchema;
-
-#[derive(serde::Deserialize, serde::Serialize, ToSchema)]
-pub struct GetAffiliateUsersResponse {
- pub users: Vec<AffiliateUser>,
-}
-
-/// Gets the users that have been affiliated with your code
-#[utoipa::path(
- get,
- path = "/affiliate",
- operation_id = "get_affiliate_users",
- responses(
- (status = 200, body=GetAffiliateUsersResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(ctx, user_context), fields(user_id=%user_context.user_id))]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
-) -> Result<Response, Response> {
- tracing::trace!("affiliate_user");
-
- let mut transaction = ctx.db.begin().await.map_err(|e| {
- tracing::error!(error=?e, "failed to begin transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to begin transaction",
- }),
- )
- .into_response()
- })?;
- let user_email = macro_db_client::user::get_user_email::get_user_email(
- &mut transaction,
- &user_context.user_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get user email");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get user email",
- }),
- )
- .into_response()
- })?;
-
- transaction.commit().await.map_err(|e| {
- tracing::error!(error=?e, "failed to commit transaction");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to commit transaction",
- }),
- )
- .into_response()
- })?;
-
- let users = ctx
- .dynamodb_client
- .affiliate_users
- .get_affiliate_users(&user_email)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to get affiliate users");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "failed to get affiliate users",
- }),
- )
- .into_response()
- })?;
-
- Ok((StatusCode::OK, Json(GetAffiliateUsersResponse { users })).into_response())
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/affiliate/mod.rs b/rust/cloud-storage/document_storage_service/src/api/affiliate/mod.rs
deleted file mode 100644
index 3c0fd21f38..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/affiliate/mod.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::{
- Router,
- routing::{get, post},
-};
-
-pub(in crate::api) mod affiliate_user;
-pub(in crate::api) mod get_affiliate_referred_by;
-pub(in crate::api) mod get_affiliate_users;
-
-pub fn router(state: ApiContext) -> Router<ApiContext> {
- Router::new()
- .route("/:affiliate_code", post(affiliate_user::handler))
- .route("/", get(get_affiliate_users::handler))
- .route("/referred_by", get(get_affiliate_referred_by::handler))
- .layer(axum::middleware::from_fn_with_state(
- state,
- macro_middleware::auth::ensure_user_exists::handler,
- ))
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rs
index 26210e74ab..25813a2054 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs
@@ -23,7 +23,6 @@ mod middleware;
// Routes
mod activity;
-mod affiliate;
mod annotations;
mod channel;
mod documents;
@@ -87,7 +86,6 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {
fn api_router(state: ApiContext) -> Router {
let internal_router = Router::new()
- .nest("/affiliate", affiliate::router(state.clone()))
.nest(
"/documents",
documents::router(state.clone()).layer(ServiceBuilder::new().layer(
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 54f2e992e1..58d5c3c89c 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -36,12 +36,7 @@ use soup::inbound::axum_router::{SoupApiItem, SoupApiSort, SoupPage};
use crate::{
api::{
- activity,
- affiliate::{
- self, get_affiliate_referred_by::GetUsersAffiliateResponse,
- get_affiliate_users::GetAffiliateUsersResponse,
- },
- annotations,
+ activity, annotations,
documents::{
self,
export_document::ExportDocumentResponse,
@@ -211,11 +206,6 @@ use utoipa::OpenApi;
// threads
threads::edit_thread::edit_thread_handler,
- // /affiliate
- affiliate::affiliate_user::handler,
- affiliate::get_affiliate_users::handler,
- affiliate::get_affiliate_referred_by::handler,
-
// /recents
recents::recently_deleted::handler,
@@ -332,10 +322,6 @@ use utoipa::OpenApi;
// Mentions
UpsertUserMentionsRequest,
- // Affiliate
- GetAffiliateUsersResponse,
- GetUsersAffiliateResponse,
-
// Annotations
AnnotationIncrementalUpdate,
diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rs
index f6b0fc93f5..cccffa5dd4 100644
--- a/rust/cloud-storage/document_storage_service/src/config.rs
+++ b/rust/cloud-storage/document_storage_service/src/config.rs
@@ -43,7 +43,6 @@ env_var! {
pub SearchEventQueue,
pub CommsServiceUrl,
pub EmailServiceUrl,
- pub AffiliateUsersTable,
pub ConnectionGatewayUrl,
pub BulkUploadRequestsTable,
pub UploadStagingBucket,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 2939f56900..fd7ed77798 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -97,7 +97,6 @@ async fn main() -> anyhow::Result<()> {
let dynamodb_client = DynamodbClient::new_from_client(
dynamo_db.clone(),
- Some(config.vars.affiliate_users_table.as_ref().to_string()),
Some(config.vars.bulk_upload_requests_table.as_ref().to_string()),
);
tracing::trace!("initialized dynamodb client");
diff --git a/rust/cloud-storage/dynamodb_client/src/affiliate_user.rs b/rust/cloud-storage/dynamodb_client/src/affiliate_user.rs
deleted file mode 100644
index 4e2b06f26f..0000000000
--- a/rust/cloud-storage/dynamodb_client/src/affiliate_user.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-use anyhow::Context;
-use aws_sdk_dynamodb::Client;
-use aws_sdk_dynamodb::types::AttributeValue;
-
-/// Affiliates a user with a given affiliate code
-#[tracing::instrument(skip(client))]
-pub async fn affiliate_user(
- client: &Client,
- table: &str,
- affiliate_code: &str,
- user_id: &str,
-) -> anyhow::Result<()> {
- let pk = format!("CODE#{}", affiliate_code);
- let sk = format!("REFERRED#{}", user_id);
-
- client
- .put_item()
- .table_name(table)
- .item("PK", AttributeValue::S(pk))
- .item("SK", AttributeValue::S(sk))
- .item(
- "CreatedAt",
- AttributeValue::N(chrono::Utc::now().timestamp().to_string()),
- )
- .send()
- .await
- .context("failed to insert affiliate referral into DynamoDB")?;
-
- Ok(())
-}
-
-#[tracing::instrument(skip(client))]
-pub async fn insert_referral(
- client: &Client,
- table: &str,
- affiliate_code: &str,
- user_id: &str,
-) -> anyhow::Result<()> {
- let pk = format!("REFERRED#{}", user_id);
- let sk = format!("CODE#{}", affiliate_code);
-
- client
- .put_item()
- .table_name(table)
- .item("PK", AttributeValue::S(pk))
- .item("SK", AttributeValue::S(sk))
- .item(
- "CreatedAt",
- AttributeValue::N(chrono::Utc::now().timestamp().to_string()),
- )
- .send()
- .await
- .context("failed to insert affiliate referral into DynamoDB")?;
-
- Ok(())
-}
diff --git a/rust/cloud-storage/dynamodb_client/src/get_affiliate_users.rs b/rust/cloud-storage/dynamodb_client/src/get_affiliate_users.rs
deleted file mode 100644
index 9922e92aac..0000000000
--- a/rust/cloud-storage/dynamodb_client/src/get_affiliate_users.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-use std::collections::HashMap;
-
-use anyhow::Context;
-use aws_sdk_dynamodb::Client;
-use aws_sdk_dynamodb::types::AttributeValue;
-use model::affiliate::AffiliateUser;
-
-/// Gets the users that have been affiliated with the give affiliate code
-#[tracing::instrument(skip(client))]
-pub async fn get_affiliate_users(
- client: &Client,
- table: &str,
- affiliate_code: &str,
-) -> anyhow::Result<Vec<AffiliateUser>> {
- let mut users: Vec<AffiliateUser> = Vec::new();
- let mut last_evaluated_key: Option<HashMap<String, AttributeValue>> = None;
-
- // Loop until all pages are processed
- loop {
- // Build the query with pagination support
- let mut query = client
- .query()
- .table_name(table)
- .key_condition_expression("PK = :pk AND begins_with(SK, :sk_prefix)")
- .expression_attribute_values(
- ":pk",
- AttributeValue::S(format!("CODE#{}", affiliate_code)),
- )
- .expression_attribute_values(":sk_prefix", AttributeValue::S("REFERRED#".to_string()));
-
- // Add exclusive start key if we have one from a previous query
- query = query.set_exclusive_start_key(last_evaluated_key);
-
- // Execute the query
- let query_output = query
- .send()
- .await
- .context("Failed to query DynamoDB for affiliate users")?;
-
- // Process the current page of results
- if let Some(items) = &query_output.items {
- for item in items {
- let email = if let Some(AttributeValue::S(sk)) = item.get("SK") {
- sk.strip_prefix("REFERRED#").unwrap().to_string()
- } else {
- return Err(anyhow::anyhow!("Invalid SK value in DynamoDB response"));
- };
-
- let created_at = if let Some(AttributeValue::N(created_at)) = item.get("CreatedAt")
- {
- created_at.parse::<i64>().unwrap()
- } else {
- return Err(anyhow::anyhow!(
- "Invalid CreatedAt value in DynamoDB response"
- ));
- };
-
- users.push(AffiliateUser { email, created_at });
- }
- }
-
- // Check if there are more results to fetch
- last_evaluated_key = query_output.last_evaluated_key;
-
- // Exit the loop if no more results
- if last_evaluated_key.is_none() {
- break;
- }
- }
-
- Ok(users)
-}
-
-#[tracing::instrument(skip(client))]
-pub async fn is_user_already_referred(
- client: &Client,
- table: &str,
- user_email: &str,
-) -> anyhow::Result<bool> {
- let query_output = client
- .query()
- .table_name(table)
- .key_condition_expression("PK = :pk")
- .expression_attribute_values(":pk", AttributeValue::S(format!("REFERRED#{}", user_email)))
- .send()
- .await
- .context("failed to query DynamoDB for affiliate users")?;
-
- if let Some(items) = query_output.items
- && !items.is_empty()
- {
- return Ok(true);
- }
-
- Ok(false)
-}
-
-/// Gets the user who referred you given your user email
-#[tracing::instrument(skip(client))]
-pub async fn get_user_referred(
- client: &Client,
- table: &str,
- user_email: &str,
-) -> anyhow::Result<Option<AffiliateUser>> {
- let query_output = client
- .query()
- .table_name(table)
- .key_condition_expression("PK = :pk")
- .expression_attribute_values(":pk", AttributeValue::S(format!("REFERRED#{}", user_email)))
- .send()
- .await
- .context("failed to query DynamoDB for affiliate users")?;
-
- if let Some(items) = query_output.items {
- // this code does not actually check beyond the first vec element
- // TODO verify this behaviour
- if let Some(item) = items.into_iter().next() {
- let email = if let Some(AttributeValue::S(sk)) = item.get("SK") {
- sk.strip_prefix("CODE#").unwrap().to_string()
- } else {
- return Err(anyhow::anyhow!("Invalid SK value in DynamoDB response"));
- };
-
- let created_at = if let Some(AttributeValue::N(created_at)) = item.get("CreatedAt") {
- created_at.parse::<i64>().unwrap()
- } else {
- return Err(anyhow::anyhow!(
- "Invalid CreatedAt value in DynamoDB response"
- ));
- };
-
- return Ok(Some(AffiliateUser { email, created_at }));
- }
- }
-
- Ok(None)
-}
diff --git a/rust/cloud-storage/dynamodb_client/src/lib.rs b/rust/cloud-storage/dynamodb_client/src/lib.rs
index fde364ed8f..d7c0e09e63 100644
--- a/rust/cloud-storage/dynamodb_client/src/lib.rs
+++ b/rust/cloud-storage/dynamodb_client/src/lib.rs
@@ -1,10 +1,7 @@
use aws_config::SdkConfig;
-mod affiliate_user;
mod bulk_upload;
-mod get_affiliate_users;
-use model::affiliate::AffiliateUser;
use models_bulk_upload::{
BulkUploadRequest, BulkUploadRequestDocuments, EXTRACT_UPLOAD_FOLDER, UploadDocumentStatus,
UploadFolderStatus,
@@ -12,31 +9,21 @@ use models_bulk_upload::{
#[derive(Debug, Clone)]
pub struct DynamodbClient {
- pub affiliate_users: AffiliateUsers,
pub bulk_upload: BulkUpload,
}
impl DynamodbClient {
- pub fn new(
- aws_config: &SdkConfig,
- affiliate_users_table: Option<String>,
- bulk_upload_requests_table: Option<String>,
- ) -> Self {
+ pub fn new(aws_config: &SdkConfig, bulk_upload_requests_table: Option<String>) -> Self {
let client = aws_sdk_dynamodb::Client::new(aws_config);
- Self::new_from_client(client, affiliate_users_table, bulk_upload_requests_table)
+ Self::new_from_client(client, bulk_upload_requests_table)
}
pub fn new_from_client(
client: aws_sdk_dynamodb::Client,
- affiliate_users_table: Option<String>,
bulk_upload_requests_table: Option<String>,
) -> Self {
Self {
- affiliate_users: AffiliateUsers {
- table: affiliate_users_table,
- client: client.clone(),
- },
bulk_upload: BulkUpload {
table: bulk_upload_requests_table,
client,
@@ -45,52 +32,6 @@ impl DynamodbClient {
}
}
-#[derive(Debug, Clone)]
-pub struct AffiliateUsers {
- table: Option<String>,
- client: aws_sdk_dynamodb::Client,
-}
-
-impl AffiliateUsers {
- fn table(&self) -> anyhow::Result<&str> {
- self.table
- .as_deref()
- .ok_or_else(|| anyhow::anyhow!("affiliate_users_table is not configured"))
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn affiliate_user(&self, affiliate_code: &str, email: &str) -> anyhow::Result<()> {
- let table = self.table()?;
- affiliate_user::affiliate_user(&self.client, table, affiliate_code, email).await?;
- affiliate_user::insert_referral(&self.client, table, affiliate_code, email).await?;
- Ok(())
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn is_user_already_referred(&self, user_email: &str) -> anyhow::Result<bool> {
- let table = self.table()?;
- get_affiliate_users::is_user_already_referred(&self.client, table, user_email).await
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn get_user_referred(
- &self,
- user_email: &str,
- ) -> anyhow::Result<Option<AffiliateUser>> {
- let table = self.table()?;
- get_affiliate_users::get_user_referred(&self.client, table, user_email).await
- }
-
- #[tracing::instrument(skip(self))]
- pub async fn get_affiliate_users(
- &self,
- affiliate_code: &str,
- ) -> anyhow::Result<Vec<AffiliateUser>> {
- let table = self.table()?;
- get_affiliate_users::get_affiliate_users(&self.client, table, affiliate_code).await
- }
-}
-
#[derive(Debug, Clone)]
pub struct BulkUpload {
table: Option<String>,
diff --git a/rust/cloud-storage/model/src/affiliate/mod.rs b/rust/cloud-storage/model/src/affiliate/mod.rs
deleted file mode 100644
index 42313ae7a6..0000000000
--- a/rust/cloud-storage/model/src/affiliate/mod.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-#[derive(Debug, Deserialize, Serialize, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct AffiliateUser {
- pub email: String,
- pub created_at: i64,
-}
diff --git a/rust/cloud-storage/model/src/lib.rs b/rust/cloud-storage/model/src/lib.rs
index 32b7c9b59a..7c9a8411c5 100644
--- a/rust/cloud-storage/model/src/lib.rs
+++ b/rust/cloud-storage/model/src/lib.rs
@@ -1,7 +1,6 @@
use chrono::serde::ts_seconds_option;
use serde::{Deserialize, Serialize};
pub mod activity;
-pub mod affiliate;
pub mod annotations;
pub mod authentication;
pub mod chat;
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip
index 278db119fc..c21ab7d5c8 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip
index 054628855a..0f314a1473 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip differ
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
index 165d73c563..374f2c8728 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
@@ -603,7 +603,7 @@ async fn main() -> Result<(), Error> {
let dss_client = DocumentStorageServiceClient::new(dss_auth_key.clone(), dss_url);
- let dynamodb_client = DynamodbClient::new(&config, None, Some(dynamo_table_name.clone()));
+ let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.clone()));
let conn_gateway_client = ConnectionGatewayClient::new(dss_auth_key, connection_gateway_url);
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
index 3e6578f0ba..2d78f98a3a 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/src/main.rs
@@ -102,7 +102,7 @@ async fn main() -> Result<(), Error> {
let region_provider = RegionProviderChain::default_provider().or_else(Region::new("us-east-1"));
let config = aws_config::from_env().region(region_provider).load().await;
- let dynamodb_client = DynamodbClient::new(&config, None, Some(dynamo_table_name.clone()));
+ let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.clone()));
tracing::trace!("initialized dynamodb client");