| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
use sqlx::PgPool; |
| 7 |
|
| 8 |
use super::enums::DiscountType; |
| 9 |
use super::models::{DbPromoCode, DbPromoCodeWithNames}; |
| 10 |
use super::{CodePurpose, ItemId, ProjectId, PromoCodeId, SubscriptionTierId, UserId}; |
| 11 |
use crate::error::{AppError, Result}; |
| 12 |
|
| 13 |
|
| 14 |
#[allow(clippy::too_many_arguments)] |
| 15 |
#[tracing::instrument(skip_all)] |
| 16 |
pub(crate) async fn create_promo_code( |
| 17 |
pool: &PgPool, |
| 18 |
creator_id: UserId, |
| 19 |
code: &str, |
| 20 |
code_purpose: super::CodePurpose, |
| 21 |
discount_type: Option<DiscountType>, |
| 22 |
discount_value: Option<i32>, |
| 23 |
min_price_cents: i32, |
| 24 |
trial_days: Option<i32>, |
| 25 |
max_uses: Option<i32>, |
| 26 |
expires_at: Option<chrono::DateTime<chrono::Utc>>, |
| 27 |
starts_at: Option<chrono::DateTime<chrono::Utc>>, |
| 28 |
item_id: Option<ItemId>, |
| 29 |
project_id: Option<ProjectId>, |
| 30 |
tier_id: Option<SubscriptionTierId>, |
| 31 |
) -> Result<DbPromoCode> { |
| 32 |
|
| 33 |
let promo_code = sqlx::query_as::<_, DbPromoCode>( |
| 34 |
r" |
| 35 |
INSERT INTO promo_codes (creator_id, code, code_purpose, discount_type, discount_value, |
| 36 |
min_price_cents, trial_days, max_uses, expires_at, starts_at, item_id, project_id, tier_id) |
| 37 |
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) |
| 38 |
RETURNING * |
| 39 |
", |
| 40 |
) |
| 41 |
.bind(creator_id) |
| 42 |
.bind(code) |
| 43 |
.bind(code_purpose) |
| 44 |
.bind(discount_type) |
| 45 |
.bind(discount_value) |
| 46 |
.bind(min_price_cents) |
| 47 |
.bind(trial_days) |
| 48 |
.bind(max_uses) |
| 49 |
.bind(expires_at) |
| 50 |
.bind(starts_at) |
| 51 |
.bind(item_id) |
| 52 |
.bind(project_id) |
| 53 |
.bind(tier_id) |
| 54 |
.fetch_one(pool) |
| 55 |
.await?; |
| 56 |
|
| 57 |
Ok(promo_code) |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
#[tracing::instrument(skip_all)] |
| 62 |
pub(crate) async fn get_promo_code_by_id( |
| 63 |
pool: &PgPool, |
| 64 |
id: PromoCodeId, |
| 65 |
) -> Result<Option<DbPromoCode>> { |
| 66 |
let code = sqlx::query_as!( |
| 67 |
DbPromoCode, |
| 68 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 69 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 70 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 71 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 72 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 73 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 74 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 75 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 76 |
FROM promo_codes WHERE id = $1"#, |
| 77 |
id as PromoCodeId, |
| 78 |
) |
| 79 |
.fetch_optional(pool) |
| 80 |
.await?; |
| 81 |
|
| 82 |
Ok(code) |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
#[tracing::instrument(skip_all)] |
| 88 |
pub(crate) async fn get_promo_code_by_creator_and_code( |
| 89 |
pool: &PgPool, |
| 90 |
creator_id: UserId, |
| 91 |
code: &str, |
| 92 |
) -> Result<Option<DbPromoCode>> { |
| 93 |
let promo_code = sqlx::query_as!( |
| 94 |
DbPromoCode, |
| 95 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 96 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 97 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 98 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 99 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 100 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 101 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 102 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 103 |
FROM promo_codes WHERE creator_id = $1 AND upper(code) = upper($2)"#, |
| 104 |
creator_id as UserId, |
| 105 |
code, |
| 106 |
) |
| 107 |
.fetch_optional(pool) |
| 108 |
.await?; |
| 109 |
|
| 110 |
Ok(promo_code) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
#[tracing::instrument(skip_all)] |
| 117 |
pub(crate) async fn get_promo_code_by_code( |
| 118 |
pool: &PgPool, |
| 119 |
code: &str, |
| 120 |
) -> Result<Option<DbPromoCode>> { |
| 121 |
let promo_code = sqlx::query_as!( |
| 122 |
DbPromoCode, |
| 123 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 124 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 125 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 126 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 127 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 128 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 129 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 130 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 131 |
FROM promo_codes WHERE upper(code) = upper($1) AND code_purpose = 'free_access'"#, |
| 132 |
code, |
| 133 |
) |
| 134 |
.fetch_optional(pool) |
| 135 |
.await?; |
| 136 |
|
| 137 |
Ok(promo_code) |
| 138 |
} |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
const PROMO_CODE_WITH_NAMES_SELECT: &str = r" |
| 143 |
SELECT pc.*, i.title AS item_title, p.title AS project_title |
| 144 |
FROM promo_codes pc |
| 145 |
LEFT JOIN items i ON pc.item_id = i.id |
| 146 |
LEFT JOIN projects p ON pc.project_id = p.id |
| 147 |
"; |
| 148 |
|
| 149 |
|
| 150 |
#[tracing::instrument(skip_all)] |
| 151 |
pub(crate) async fn get_promo_codes_by_creator( |
| 152 |
pool: &PgPool, |
| 153 |
creator_id: UserId, |
| 154 |
) -> Result<Vec<DbPromoCodeWithNames>> { |
| 155 |
|
| 156 |
let query = format!( |
| 157 |
"{PROMO_CODE_WITH_NAMES_SELECT} WHERE pc.creator_id = $1 ORDER BY pc.created_at DESC LIMIT 500" |
| 158 |
); |
| 159 |
let codes = sqlx::query_as::<_, DbPromoCodeWithNames>(&query) |
| 160 |
.bind(creator_id) |
| 161 |
.fetch_all(pool) |
| 162 |
.await?; |
| 163 |
|
| 164 |
Ok(codes) |
| 165 |
} |
| 166 |
|
| 167 |
|
| 168 |
#[tracing::instrument(skip_all)] |
| 169 |
pub(crate) async fn get_promo_codes_by_project( |
| 170 |
pool: &PgPool, |
| 171 |
project_id: ProjectId, |
| 172 |
) -> Result<Vec<DbPromoCodeWithNames>> { |
| 173 |
|
| 174 |
let query = format!( |
| 175 |
"{PROMO_CODE_WITH_NAMES_SELECT} WHERE pc.project_id = $1 ORDER BY pc.created_at DESC LIMIT 500" |
| 176 |
); |
| 177 |
let codes = sqlx::query_as::<_, DbPromoCodeWithNames>(&query) |
| 178 |
.bind(project_id) |
| 179 |
.fetch_all(pool) |
| 180 |
.await?; |
| 181 |
|
| 182 |
Ok(codes) |
| 183 |
} |
| 184 |
|
| 185 |
|
| 186 |
#[tracing::instrument(skip_all)] |
| 187 |
pub(crate) async fn get_promo_codes_by_item( |
| 188 |
pool: &PgPool, |
| 189 |
item_id: ItemId, |
| 190 |
) -> Result<Vec<DbPromoCodeWithNames>> { |
| 191 |
|
| 192 |
let query = format!( |
| 193 |
"{PROMO_CODE_WITH_NAMES_SELECT} WHERE pc.item_id = $1 ORDER BY pc.created_at DESC LIMIT 500" |
| 194 |
); |
| 195 |
let codes = sqlx::query_as::<_, DbPromoCodeWithNames>(&query) |
| 196 |
.bind(item_id) |
| 197 |
.fetch_all(pool) |
| 198 |
.await?; |
| 199 |
|
| 200 |
Ok(codes) |
| 201 |
} |
| 202 |
|
| 203 |
|
| 204 |
#[tracing::instrument(skip_all)] |
| 205 |
pub(crate) async fn get_promo_codes_by_items( |
| 206 |
pool: &PgPool, |
| 207 |
item_ids: &[ItemId], |
| 208 |
) -> Result<std::collections::HashMap<ItemId, Vec<DbPromoCodeWithNames>>> { |
| 209 |
|
| 210 |
let query = format!( |
| 211 |
"{PROMO_CODE_WITH_NAMES_SELECT} WHERE pc.item_id = ANY($1) ORDER BY pc.item_id, pc.created_at DESC" |
| 212 |
); |
| 213 |
let codes = sqlx::query_as::<_, DbPromoCodeWithNames>(&query) |
| 214 |
.bind(item_ids) |
| 215 |
.fetch_all(pool) |
| 216 |
.await?; |
| 217 |
|
| 218 |
let mut map: std::collections::HashMap<ItemId, Vec<DbPromoCodeWithNames>> = |
| 219 |
std::collections::HashMap::new(); |
| 220 |
for pc in codes { |
| 221 |
if let Some(item_id) = pc.item_id { |
| 222 |
map.entry(item_id).or_default().push(pc); |
| 223 |
} |
| 224 |
} |
| 225 |
Ok(map) |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
#[tracing::instrument(skip_all)] |
| 237 |
pub(crate) async fn try_increment_use_count<'e>( |
| 238 |
executor: impl sqlx::PgExecutor<'e>, |
| 239 |
id: PromoCodeId, |
| 240 |
) -> Result<bool> { |
| 241 |
let result = sqlx::query!( |
| 242 |
"UPDATE promo_codes SET use_count = use_count + 1 \ |
| 243 |
WHERE id = $1 \ |
| 244 |
AND (max_uses IS NULL OR use_count < max_uses) \ |
| 245 |
AND (expires_at IS NULL OR expires_at > NOW()) \ |
| 246 |
AND (starts_at IS NULL OR starts_at <= NOW())", |
| 247 |
id as PromoCodeId, |
| 248 |
) |
| 249 |
.execute(executor) |
| 250 |
.await?; |
| 251 |
|
| 252 |
Ok(result.rows_affected() > 0) |
| 253 |
} |
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
#[tracing::instrument(skip_all)] |
| 273 |
pub(crate) async fn release_use_count(pool: &PgPool, id: PromoCodeId) -> Result<()> { |
| 274 |
sqlx::query!( |
| 275 |
"UPDATE promo_codes SET use_count = GREATEST(0, use_count - 1) WHERE id = $1", |
| 276 |
id as PromoCodeId, |
| 277 |
) |
| 278 |
.execute(pool) |
| 279 |
.await?; |
| 280 |
|
| 281 |
Ok(()) |
| 282 |
} |
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
#[tracing::instrument(skip_all)] |
| 294 |
pub(crate) async fn release_use_count_and_detach( |
| 295 |
pool: &PgPool, |
| 296 |
id: PromoCodeId, |
| 297 |
buyer_id: UserId, |
| 298 |
) -> Result<()> { |
| 299 |
let mut tx = pool.begin().await?; |
| 300 |
|
| 301 |
sqlx::query!( |
| 302 |
"UPDATE transactions SET promo_code_id = NULL \ |
| 303 |
WHERE buyer_id = $1 AND promo_code_id = $2 AND status = 'pending'", |
| 304 |
buyer_id as UserId, |
| 305 |
id as PromoCodeId, |
| 306 |
) |
| 307 |
.execute(&mut *tx) |
| 308 |
.await?; |
| 309 |
|
| 310 |
sqlx::query!( |
| 311 |
"UPDATE promo_codes SET use_count = GREATEST(0, use_count - 1) WHERE id = $1", |
| 312 |
id as PromoCodeId, |
| 313 |
) |
| 314 |
.execute(&mut *tx) |
| 315 |
.await?; |
| 316 |
|
| 317 |
tx.commit().await?; |
| 318 |
Ok(()) |
| 319 |
} |
| 320 |
|
| 321 |
|
| 322 |
#[tracing::instrument(skip_all)] |
| 323 |
#[allow( |
| 324 |
clippy::option_option, |
| 325 |
reason = "tri-state PATCH semantics: outer None = field absent (leave unchanged), Some(None) = set to SQL NULL, Some(Some(v)) = set to value" |
| 326 |
)] |
| 327 |
pub(crate) async fn update_promo_code( |
| 328 |
pool: &PgPool, |
| 329 |
id: PromoCodeId, |
| 330 |
expires_at: Option<Option<chrono::DateTime<chrono::Utc>>>, |
| 331 |
starts_at: Option<Option<chrono::DateTime<chrono::Utc>>>, |
| 332 |
max_uses: Option<Option<i32>>, |
| 333 |
) -> Result<DbPromoCode> { |
| 334 |
|
| 335 |
let mut sets = Vec::new(); |
| 336 |
let mut param_idx = 2u32; |
| 337 |
|
| 338 |
if expires_at.is_some() { |
| 339 |
sets.push(format!("expires_at = ${param_idx}")); |
| 340 |
param_idx += 1; |
| 341 |
} |
| 342 |
if starts_at.is_some() { |
| 343 |
sets.push(format!("starts_at = ${param_idx}")); |
| 344 |
param_idx += 1; |
| 345 |
} |
| 346 |
if max_uses.is_some() { |
| 347 |
sets.push(format!("max_uses = ${param_idx}")); |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
} |
| 352 |
|
| 353 |
if sets.is_empty() { |
| 354 |
|
| 355 |
return get_promo_code_by_id(pool, id) |
| 356 |
.await? |
| 357 |
.ok_or_else(|| crate::error::AppError::NotFound); |
| 358 |
} |
| 359 |
|
| 360 |
|
| 361 |
let sql = format!( |
| 362 |
"UPDATE promo_codes SET {} WHERE id = $1 RETURNING *", |
| 363 |
sets.join(", ") |
| 364 |
); |
| 365 |
let mut query = sqlx::query_as::<_, DbPromoCode>(&sql).bind(id); |
| 366 |
|
| 367 |
if let Some(val) = expires_at { |
| 368 |
query = query.bind(val); |
| 369 |
} |
| 370 |
if let Some(val) = starts_at { |
| 371 |
query = query.bind(val); |
| 372 |
} |
| 373 |
if let Some(val) = max_uses { |
| 374 |
query = query.bind(val); |
| 375 |
} |
| 376 |
|
| 377 |
let code = query.fetch_one(pool).await?; |
| 378 |
Ok(code) |
| 379 |
} |
| 380 |
|
| 381 |
|
| 382 |
#[tracing::instrument(skip_all)] |
| 383 |
pub(crate) async fn delete_expired_by_creator(pool: &PgPool, creator_id: UserId) -> Result<u64> { |
| 384 |
let result = sqlx::query!( |
| 385 |
"DELETE FROM promo_codes WHERE creator_id = $1 AND expires_at IS NOT NULL AND expires_at < NOW()", |
| 386 |
creator_id as UserId, |
| 387 |
) |
| 388 |
.execute(pool) |
| 389 |
.await?; |
| 390 |
|
| 391 |
Ok(result.rows_affected()) |
| 392 |
} |
| 393 |
|
| 394 |
|
| 395 |
#[tracing::instrument(skip_all)] |
| 396 |
pub(crate) async fn delete_promo_code(pool: &PgPool, id: PromoCodeId) -> Result<()> { |
| 397 |
sqlx::query!("DELETE FROM promo_codes WHERE id = $1", id as PromoCodeId) |
| 398 |
.execute(pool) |
| 399 |
.await?; |
| 400 |
|
| 401 |
Ok(()) |
| 402 |
} |
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
#[derive(Debug, sqlx::FromRow, serde::Serialize)] |
| 410 |
pub(crate) struct PromoRedemption { |
| 411 |
pub redeemed_at: chrono::DateTime<chrono::Utc>, |
| 412 |
pub display_name: Option<String>, |
| 413 |
pub username: Option<String>, |
| 414 |
pub guest_email: Option<String>, |
| 415 |
pub item_title: Option<String>, |
| 416 |
pub amount_cents: i32, |
| 417 |
} |
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
#[tracing::instrument(skip_all)] |
| 426 |
pub(crate) async fn list_redemptions( |
| 427 |
pool: &PgPool, |
| 428 |
id: PromoCodeId, |
| 429 |
) -> Result<Vec<PromoRedemption>> { |
| 430 |
let rows = sqlx::query_as!( |
| 431 |
PromoRedemption, |
| 432 |
r#" |
| 433 |
SELECT |
| 434 |
COALESCE(t.completed_at, t.created_at) AS "redeemed_at!: chrono::DateTime<chrono::Utc>", |
| 435 |
u.display_name AS display_name, |
| 436 |
u.username AS "username?", |
| 437 |
t.guest_email AS guest_email, |
| 438 |
t.item_title AS item_title, |
| 439 |
t.amount_cents AS amount_cents |
| 440 |
FROM transactions t |
| 441 |
LEFT JOIN users u ON u.id = t.buyer_id |
| 442 |
WHERE t.promo_code_id = $1 |
| 443 |
AND t.status = 'completed' |
| 444 |
ORDER BY COALESCE(t.completed_at, t.created_at) DESC |
| 445 |
LIMIT 500 |
| 446 |
"#, |
| 447 |
id as PromoCodeId, |
| 448 |
) |
| 449 |
.fetch_all(pool) |
| 450 |
.await?; |
| 451 |
|
| 452 |
Ok(rows) |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
#[allow(clippy::too_many_arguments)] |
| 460 |
#[tracing::instrument(skip_all)] |
| 461 |
pub(crate) async fn create_platform_promo_code( |
| 462 |
pool: &PgPool, |
| 463 |
creator_id: UserId, |
| 464 |
code: &str, |
| 465 |
code_purpose: super::CodePurpose, |
| 466 |
discount_type: Option<DiscountType>, |
| 467 |
discount_value: Option<i32>, |
| 468 |
min_price_cents: i32, |
| 469 |
trial_days: Option<i32>, |
| 470 |
max_uses: Option<i32>, |
| 471 |
expires_at: Option<chrono::DateTime<chrono::Utc>>, |
| 472 |
) -> Result<DbPromoCode> { |
| 473 |
|
| 474 |
let promo_code = sqlx::query_as::<_, DbPromoCode>( |
| 475 |
r" |
| 476 |
INSERT INTO promo_codes (creator_id, code, code_purpose, discount_type, discount_value, |
| 477 |
min_price_cents, trial_days, max_uses, expires_at, is_platform_wide) |
| 478 |
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, true) |
| 479 |
RETURNING * |
| 480 |
", |
| 481 |
) |
| 482 |
.bind(creator_id) |
| 483 |
.bind(code) |
| 484 |
.bind(code_purpose) |
| 485 |
.bind(discount_type) |
| 486 |
.bind(discount_value) |
| 487 |
.bind(min_price_cents) |
| 488 |
.bind(trial_days) |
| 489 |
.bind(max_uses) |
| 490 |
.bind(expires_at) |
| 491 |
.fetch_one(pool) |
| 492 |
.await?; |
| 493 |
|
| 494 |
Ok(promo_code) |
| 495 |
} |
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
#[must_use] |
| 509 |
pub(crate) struct FanPlusCreditClaim { |
| 510 |
_seal: (), |
| 511 |
} |
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
#[tracing::instrument(skip_all)] |
| 528 |
pub(crate) async fn try_claim_fan_plus_credit( |
| 529 |
pool: &PgPool, |
| 530 |
stripe_sub_id: &str, |
| 531 |
period_end: i64, |
| 532 |
) -> Result<Option<FanPlusCreditClaim>> { |
| 533 |
let result = sqlx::query!( |
| 534 |
"INSERT INTO fan_plus_credit_issuance (stripe_sub_id, period_end) \ |
| 535 |
VALUES ($1, $2) ON CONFLICT DO NOTHING", |
| 536 |
stripe_sub_id, |
| 537 |
period_end, |
| 538 |
) |
| 539 |
.execute(pool) |
| 540 |
.await?; |
| 541 |
|
| 542 |
Ok((result.rows_affected() == 1).then_some(FanPlusCreditClaim { _seal: () })) |
| 543 |
} |
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
#[tracing::instrument(skip_all)] |
| 553 |
pub(crate) async fn issue_fan_plus_credit_code( |
| 554 |
_claim: &FanPlusCreditClaim, |
| 555 |
pool: &PgPool, |
| 556 |
creator_id: UserId, |
| 557 |
code: &str, |
| 558 |
expires_at: Option<chrono::DateTime<chrono::Utc>>, |
| 559 |
) -> Result<DbPromoCode> { |
| 560 |
create_platform_promo_code( |
| 561 |
pool, |
| 562 |
creator_id, |
| 563 |
code, |
| 564 |
super::CodePurpose::Discount, |
| 565 |
Some(DiscountType::Fixed), |
| 566 |
Some(500), |
| 567 |
0, |
| 568 |
None, |
| 569 |
Some(1), |
| 570 |
expires_at, |
| 571 |
) |
| 572 |
.await |
| 573 |
} |
| 574 |
|
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
|
| 579 |
#[tracing::instrument(skip_all)] |
| 580 |
pub(crate) async fn get_platform_promo_code_by_user_and_code( |
| 581 |
pool: &PgPool, |
| 582 |
user_id: UserId, |
| 583 |
code: &str, |
| 584 |
) -> Result<Option<DbPromoCode>> { |
| 585 |
let promo_code = sqlx::query_as!( |
| 586 |
DbPromoCode, |
| 587 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 588 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 589 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 590 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 591 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 592 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 593 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 594 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 595 |
FROM promo_codes WHERE creator_id = $1 AND upper(code) = upper($2) AND is_platform_wide = true"#, |
| 596 |
user_id as UserId, code, |
| 597 |
) |
| 598 |
.fetch_optional(pool) |
| 599 |
.await?; |
| 600 |
|
| 601 |
Ok(promo_code) |
| 602 |
} |
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
#[tracing::instrument(skip_all)] |
| 612 |
pub(crate) async fn get_platform_trial_code_by_code( |
| 613 |
pool: &PgPool, |
| 614 |
code: &str, |
| 615 |
) -> Result<Option<DbPromoCode>> { |
| 616 |
let promo_code = sqlx::query_as!( |
| 617 |
DbPromoCode, |
| 618 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 619 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 620 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 621 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 622 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 623 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 624 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 625 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 626 |
FROM promo_codes |
| 627 |
WHERE upper(code) = upper($1) AND code_purpose = 'free_trial' AND is_platform_wide = true"#, |
| 628 |
code, |
| 629 |
) |
| 630 |
.fetch_optional(pool) |
| 631 |
.await?; |
| 632 |
|
| 633 |
Ok(promo_code) |
| 634 |
} |
| 635 |
|
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
#[tracing::instrument(skip_all)] |
| 643 |
pub(crate) async fn try_record_redemption( |
| 644 |
pool: &PgPool, |
| 645 |
code_id: PromoCodeId, |
| 646 |
user_id: UserId, |
| 647 |
) -> Result<bool> { |
| 648 |
let result = sqlx::query!( |
| 649 |
"INSERT INTO promo_code_redemptions (promo_code_id, user_id) \ |
| 650 |
VALUES ($1, $2) ON CONFLICT DO NOTHING", |
| 651 |
code_id as PromoCodeId, |
| 652 |
user_id as UserId, |
| 653 |
) |
| 654 |
.execute(pool) |
| 655 |
.await?; |
| 656 |
|
| 657 |
Ok(result.rows_affected() > 0) |
| 658 |
} |
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
#[tracing::instrument(skip_all)] |
| 664 |
pub(crate) async fn remove_redemption( |
| 665 |
pool: &PgPool, |
| 666 |
code_id: PromoCodeId, |
| 667 |
user_id: UserId, |
| 668 |
) -> Result<()> { |
| 669 |
sqlx::query!( |
| 670 |
"DELETE FROM promo_code_redemptions WHERE promo_code_id = $1 AND user_id = $2", |
| 671 |
code_id as PromoCodeId, |
| 672 |
user_id as UserId, |
| 673 |
) |
| 674 |
.execute(pool) |
| 675 |
.await?; |
| 676 |
Ok(()) |
| 677 |
} |
| 678 |
|
| 679 |
|
| 680 |
|
| 681 |
#[tracing::instrument(skip_all)] |
| 682 |
pub(crate) async fn get_platform_trial_codes(pool: &PgPool) -> Result<Vec<DbPromoCode>> { |
| 683 |
let codes = sqlx::query_as!( |
| 684 |
DbPromoCode, |
| 685 |
r#"SELECT id AS "id: PromoCodeId", creator_id AS "creator_id: UserId", code, |
| 686 |
code_purpose AS "code_purpose: super::CodePurpose", |
| 687 |
discount_type AS "discount_type: DiscountType", discount_value, min_price_cents, |
| 688 |
trial_days, item_id AS "item_id: ItemId", project_id AS "project_id: ProjectId", |
| 689 |
tier_id AS "tier_id: SubscriptionTierId", max_uses, use_count, |
| 690 |
expires_at AS "expires_at: chrono::DateTime<chrono::Utc>", |
| 691 |
starts_at AS "starts_at: chrono::DateTime<chrono::Utc>", |
| 692 |
created_at AS "created_at: chrono::DateTime<chrono::Utc>", is_platform_wide |
| 693 |
FROM promo_codes |
| 694 |
WHERE code_purpose = 'free_trial' AND is_platform_wide = true |
| 695 |
ORDER BY created_at DESC LIMIT 500"#, |
| 696 |
) |
| 697 |
.fetch_all(pool) |
| 698 |
.await?; |
| 699 |
|
| 700 |
Ok(codes) |
| 701 |
} |
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
#[tracing::instrument(skip_all)] |
| 706 |
pub(crate) fn apply_discount( |
| 707 |
price_cents: i32, |
| 708 |
discount_type: DiscountType, |
| 709 |
discount_value: i32, |
| 710 |
) -> i32 { |
| 711 |
let discount_value = discount_value.max(0); |
| 712 |
match discount_type { |
| 713 |
DiscountType::Percentage => { |
| 714 |
let discount = (price_cents as i64 * discount_value as i64) / 100; |
| 715 |
(price_cents as i64 - discount).max(0) as i32 |
| 716 |
} |
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
DiscountType::Fixed => (price_cents as i64 - discount_value as i64).max(0) as i32, |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
pub(crate) struct ValidatedPromo { |
| 737 |
pub code: DbPromoCode, |
| 738 |
|
| 739 |
|
| 740 |
pub is_platform_wide: bool, |
| 741 |
} |
| 742 |
|
| 743 |
impl ValidatedPromo { |
| 744 |
pub(crate) fn id(&self) -> PromoCodeId { |
| 745 |
self.code.id |
| 746 |
} |
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
pub(crate) fn platform_credit_budget_cents(&self) -> Option<i64> { |
| 761 |
if !self.is_platform_wide { |
| 762 |
return None; |
| 763 |
} |
| 764 |
match ( |
| 765 |
self.code.code_purpose, |
| 766 |
self.code.discount_type, |
| 767 |
self.code.discount_value, |
| 768 |
) { |
| 769 |
(CodePurpose::Discount, Some(DiscountType::Fixed), Some(value)) => { |
| 770 |
Some(i64::from(value.max(0))) |
| 771 |
} |
| 772 |
_ => None, |
| 773 |
} |
| 774 |
} |
| 775 |
} |
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
pub(crate) fn cap_line_to_credit_budget( |
| 784 |
applied: AppliedDiscount, |
| 785 |
budget: &mut Option<i64>, |
| 786 |
) -> (i32, i64) { |
| 787 |
let mut final_price = applied.price_cents; |
| 788 |
let mut credit = i64::from(applied.funding.platform_credit_cents()); |
| 789 |
if let Some(remaining) = budget.as_mut() { |
| 790 |
let granted = credit.min(*remaining); |
| 791 |
|
| 792 |
|
| 793 |
final_price += (credit - granted) as i32; |
| 794 |
credit = granted; |
| 795 |
*remaining -= granted; |
| 796 |
} |
| 797 |
(final_price, credit) |
| 798 |
} |
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
#[tracing::instrument(skip_all)] |
| 806 |
pub(crate) async fn lookup_and_validate_promo( |
| 807 |
pool: &PgPool, |
| 808 |
seller_id: UserId, |
| 809 |
buyer_id: Option<UserId>, |
| 810 |
raw_code: &str, |
| 811 |
) -> Result<Option<ValidatedPromo>> { |
| 812 |
let code_str = raw_code.trim().to_uppercase(); |
| 813 |
if code_str.is_empty() { |
| 814 |
return Ok(None); |
| 815 |
} |
| 816 |
|
| 817 |
let code = match get_promo_code_by_creator_and_code(pool, seller_id, &code_str).await? { |
| 818 |
Some(pc) => pc, |
| 819 |
None => match buyer_id { |
| 820 |
Some(uid) => get_platform_promo_code_by_user_and_code(pool, uid, &code_str) |
| 821 |
.await? |
| 822 |
.ok_or_else(|| AppError::BadRequest("Invalid promo code".to_string()))?, |
| 823 |
None => return Err(AppError::BadRequest("Invalid promo code".to_string())), |
| 824 |
}, |
| 825 |
}; |
| 826 |
|
| 827 |
if code.code_purpose == CodePurpose::FreeTrial { |
| 828 |
return Err(AppError::BadRequest( |
| 829 |
"Trial codes can only be used for subscriptions".to_string(), |
| 830 |
)); |
| 831 |
} |
| 832 |
let now = chrono::Utc::now(); |
| 833 |
if let Some(starts) = code.starts_at |
| 834 |
&& starts > now |
| 835 |
{ |
| 836 |
return Err(AppError::BadRequest( |
| 837 |
"This promo code is not yet active".to_string(), |
| 838 |
)); |
| 839 |
} |
| 840 |
if let Some(expires) = code.expires_at |
| 841 |
&& expires < now |
| 842 |
{ |
| 843 |
return Err(AppError::BadRequest( |
| 844 |
"This promo code has expired".to_string(), |
| 845 |
)); |
| 846 |
} |
| 847 |
if let Some(max) = code.max_uses |
| 848 |
&& code.use_count >= max |
| 849 |
{ |
| 850 |
return Err(AppError::BadRequest( |
| 851 |
"This promo code has reached its usage limit".to_string(), |
| 852 |
)); |
| 853 |
} |
| 854 |
|
| 855 |
let is_platform_wide = code.is_platform_wide; |
| 856 |
Ok(Some(ValidatedPromo { |
| 857 |
code, |
| 858 |
is_platform_wide, |
| 859 |
})) |
| 860 |
} |
| 861 |
|
| 862 |
|
| 863 |
pub(crate) enum PromoIneligible { |
| 864 |
|
| 865 |
ScopeMismatch, |
| 866 |
|
| 867 |
BelowMinPrice, |
| 868 |
} |
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 881 |
pub(crate) enum DiscountFunding { |
| 882 |
|
| 883 |
CreatorFunded, |
| 884 |
|
| 885 |
|
| 886 |
PlatformFunded { credit_cents: i32 }, |
| 887 |
} |
| 888 |
|
| 889 |
impl DiscountFunding { |
| 890 |
|
| 891 |
|
| 892 |
pub(crate) fn platform_credit_cents(self) -> i32 { |
| 893 |
match self { |
| 894 |
DiscountFunding::CreatorFunded => 0, |
| 895 |
DiscountFunding::PlatformFunded { credit_cents } => credit_cents, |
| 896 |
} |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
|
| 901 |
#[derive(Debug, Clone, Copy)] |
| 902 |
pub(crate) struct AppliedDiscount { |
| 903 |
|
| 904 |
pub price_cents: i32, |
| 905 |
|
| 906 |
pub funding: DiscountFunding, |
| 907 |
} |
| 908 |
|
| 909 |
|
| 910 |
pub(crate) enum PromoApplication { |
| 911 |
|
| 912 |
Apply(AppliedDiscount), |
| 913 |
|
| 914 |
Ineligible(PromoIneligible), |
| 915 |
} |
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
pub(crate) fn apply_promo_to_item( |
| 922 |
validated: &ValidatedPromo, |
| 923 |
item_id: ItemId, |
| 924 |
project_id: ProjectId, |
| 925 |
base_price_cents: i32, |
| 926 |
) -> Result<PromoApplication> { |
| 927 |
let code = &validated.code; |
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
if !validated.is_platform_wide { |
| 932 |
if let Some(scoped_item) = code.item_id |
| 933 |
&& scoped_item != item_id |
| 934 |
{ |
| 935 |
return Ok(PromoApplication::Ineligible(PromoIneligible::ScopeMismatch)); |
| 936 |
} |
| 937 |
if let Some(scoped_project) = code.project_id |
| 938 |
&& project_id != scoped_project |
| 939 |
{ |
| 940 |
return Ok(PromoApplication::Ineligible(PromoIneligible::ScopeMismatch)); |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
|
| 945 |
|
| 946 |
let funded = |price_cents: i32| -> AppliedDiscount { |
| 947 |
let funding = if validated.is_platform_wide { |
| 948 |
DiscountFunding::PlatformFunded { |
| 949 |
credit_cents: (base_price_cents - price_cents).max(0), |
| 950 |
} |
| 951 |
} else { |
| 952 |
DiscountFunding::CreatorFunded |
| 953 |
}; |
| 954 |
AppliedDiscount { |
| 955 |
price_cents, |
| 956 |
funding, |
| 957 |
} |
| 958 |
}; |
| 959 |
|
| 960 |
match code.code_purpose { |
| 961 |
CodePurpose::FreeAccess => Ok(PromoApplication::Apply(funded(0))), |
| 962 |
CodePurpose::Discount => { |
| 963 |
if !validated.is_platform_wide && base_price_cents < code.min_price_cents { |
| 964 |
return Ok(PromoApplication::Ineligible(PromoIneligible::BelowMinPrice)); |
| 965 |
} |
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
let (Some(dt), Some(dv)) = (code.discount_type, code.discount_value) else { |
| 975 |
return Err(AppError::BadRequest( |
| 976 |
"This promo code is misconfigured. Please contact the creator.".to_string(), |
| 977 |
)); |
| 978 |
}; |
| 979 |
Ok(PromoApplication::Apply(funded(apply_discount( |
| 980 |
base_price_cents, |
| 981 |
dt, |
| 982 |
dv, |
| 983 |
)))) |
| 984 |
} |
| 985 |
|
| 986 |
CodePurpose::FreeTrial => Ok(PromoApplication::Apply(funded(base_price_cents))), |
| 987 |
} |
| 988 |
} |
| 989 |
|
| 990 |
#[cfg(test)] |
| 991 |
mod tests { |
| 992 |
use super::*; |
| 993 |
|
| 994 |
#[test] |
| 995 |
fn percentage_discount_50() { |
| 996 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 50), 500); |
| 997 |
} |
| 998 |
|
| 999 |
#[test] |
| 1000 |
fn percentage_discount_100() { |
| 1001 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 100), 0); |
| 1002 |
} |
| 1003 |
|
| 1004 |
#[test] |
| 1005 |
fn percentage_discount_10() { |
| 1006 |
|
| 1007 |
assert_eq!(apply_discount(999, DiscountType::Percentage, 10), 900); |
| 1008 |
} |
| 1009 |
|
| 1010 |
#[test] |
| 1011 |
fn fixed_discount() { |
| 1012 |
assert_eq!(apply_discount(1000, DiscountType::Fixed, 300), 700); |
| 1013 |
} |
| 1014 |
|
| 1015 |
#[test] |
| 1016 |
fn fixed_discount_exceeds_price() { |
| 1017 |
assert_eq!(apply_discount(100, DiscountType::Fixed, 500), 0); |
| 1018 |
} |
| 1019 |
|
| 1020 |
|
| 1021 |
|
| 1022 |
#[test] |
| 1023 |
fn percentage_discount_0() { |
| 1024 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 0), 1000); |
| 1025 |
} |
| 1026 |
|
| 1027 |
#[test] |
| 1028 |
fn percentage_discount_over_100() { |
| 1029 |
|
| 1030 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 150), 0); |
| 1031 |
} |
| 1032 |
|
| 1033 |
#[test] |
| 1034 |
fn percentage_discount_1_percent() { |
| 1035 |
|
| 1036 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 1), 990); |
| 1037 |
} |
| 1038 |
|
| 1039 |
#[test] |
| 1040 |
fn percentage_discount_99_percent() { |
| 1041 |
|
| 1042 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, 99), 10); |
| 1043 |
} |
| 1044 |
|
| 1045 |
#[test] |
| 1046 |
fn percentage_discount_rounding() { |
| 1047 |
|
| 1048 |
assert_eq!(apply_discount(1, DiscountType::Percentage, 50), 1); |
| 1049 |
|
| 1050 |
assert_eq!(apply_discount(3, DiscountType::Percentage, 33), 3); |
| 1051 |
|
| 1052 |
assert_eq!(apply_discount(199, DiscountType::Percentage, 50), 100); |
| 1053 |
} |
| 1054 |
|
| 1055 |
|
| 1056 |
|
| 1057 |
#[test] |
| 1058 |
fn fixed_discount_exact_price() { |
| 1059 |
assert_eq!(apply_discount(500, DiscountType::Fixed, 500), 0); |
| 1060 |
} |
| 1061 |
|
| 1062 |
#[test] |
| 1063 |
fn fixed_discount_zero_value() { |
| 1064 |
assert_eq!(apply_discount(1000, DiscountType::Fixed, 0), 1000); |
| 1065 |
} |
| 1066 |
|
| 1067 |
#[test] |
| 1068 |
fn fixed_discount_one_cent() { |
| 1069 |
assert_eq!(apply_discount(1000, DiscountType::Fixed, 1), 999); |
| 1070 |
} |
| 1071 |
|
| 1072 |
|
| 1073 |
|
| 1074 |
#[test] |
| 1075 |
fn zero_price_percentage() { |
| 1076 |
assert_eq!(apply_discount(0, DiscountType::Percentage, 50), 0); |
| 1077 |
} |
| 1078 |
|
| 1079 |
#[test] |
| 1080 |
fn zero_price_fixed() { |
| 1081 |
assert_eq!(apply_discount(0, DiscountType::Fixed, 100), 0); |
| 1082 |
} |
| 1083 |
|
| 1084 |
|
| 1085 |
|
| 1086 |
#[test] |
| 1087 |
fn negative_discount_value_percentage() { |
| 1088 |
|
| 1089 |
assert_eq!(apply_discount(1000, DiscountType::Percentage, -50), 1000); |
| 1090 |
} |
| 1091 |
|
| 1092 |
#[test] |
| 1093 |
fn negative_discount_value_fixed() { |
| 1094 |
|
| 1095 |
assert_eq!(apply_discount(1000, DiscountType::Fixed, -500), 1000); |
| 1096 |
} |
| 1097 |
|
| 1098 |
#[test] |
| 1099 |
fn negative_price_percentage() { |
| 1100 |
|
| 1101 |
|
| 1102 |
assert_eq!(apply_discount(-1000, DiscountType::Percentage, 50), 0); |
| 1103 |
} |
| 1104 |
|
| 1105 |
#[test] |
| 1106 |
fn negative_price_fixed() { |
| 1107 |
|
| 1108 |
assert_eq!(apply_discount(-1000, DiscountType::Fixed, 500), 0); |
| 1109 |
} |
| 1110 |
|
| 1111 |
|
| 1112 |
|
| 1113 |
#[test] |
| 1114 |
fn large_price_percentage_no_overflow() { |
| 1115 |
|
| 1116 |
|
| 1117 |
let price = i32::MAX; |
| 1118 |
let result = apply_discount(price, DiscountType::Percentage, 50); |
| 1119 |
assert_eq!(result, 1_073_741_824); |
| 1120 |
} |
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
#[test] |
| 1125 |
fn adversarial_percentage_max_price_max_percentage() { |
| 1126 |
|
| 1127 |
let result = apply_discount(i32::MAX, DiscountType::Percentage, 100); |
| 1128 |
assert_eq!(result, 0, "100% discount on any price should be 0"); |
| 1129 |
} |
| 1130 |
|
| 1131 |
#[test] |
| 1132 |
fn adversarial_percentage_max_price_99_percent() { |
| 1133 |
let result = apply_discount(i32::MAX, DiscountType::Percentage, 99); |
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
assert_eq!(result, 21_474_837); |
| 1138 |
assert!(result > 0, "99% discount should leave some remaining"); |
| 1139 |
} |
| 1140 |
|
| 1141 |
#[test] |
| 1142 |
fn adversarial_fixed_max_price_max_discount() { |
| 1143 |
let result = apply_discount(i32::MAX, DiscountType::Fixed, i32::MAX); |
| 1144 |
assert_eq!(result, 0); |
| 1145 |
} |
| 1146 |
|
| 1147 |
#[test] |
| 1148 |
fn adversarial_both_negative() { |
| 1149 |
|
| 1150 |
let result = apply_discount(-100, DiscountType::Fixed, -100); |
| 1151 |
|
| 1152 |
assert_eq!(result, 0); |
| 1153 |
} |
| 1154 |
|
| 1155 |
#[test] |
| 1156 |
fn adversarial_percentage_discount_exactly_50_odd_price() { |
| 1157 |
|
| 1158 |
assert_eq!(apply_discount(1, DiscountType::Percentage, 50), 1); |
| 1159 |
|
| 1160 |
assert_eq!(apply_discount(3, DiscountType::Percentage, 50), 2); |
| 1161 |
} |
| 1162 |
|
| 1163 |
#[test] |
| 1164 |
fn adversarial_apply_discount_invariant() { |
| 1165 |
|
| 1166 |
|
| 1167 |
for price in [1, 50, 100, 999, 10000, 1_000_000] { |
| 1168 |
for pct in [0, 1, 10, 25, 33, 50, 75, 99, 100] { |
| 1169 |
let result = apply_discount(price, DiscountType::Percentage, pct); |
| 1170 |
assert!( |
| 1171 |
result >= 0 && result <= price, |
| 1172 |
"Invariant violated: price={price}, pct={pct}, result={result}" |
| 1173 |
); |
| 1174 |
} |
| 1175 |
} |
| 1176 |
} |
| 1177 |
|
| 1178 |
#[test] |
| 1179 |
fn adversarial_fixed_discount_invariant() { |
| 1180 |
|
| 1181 |
for price in [1, 50, 100, 999, 10000] { |
| 1182 |
for discount in [0, 1, 50, 100, 999, 10000, 999_999] { |
| 1183 |
let result = apply_discount(price, DiscountType::Fixed, discount); |
| 1184 |
assert!( |
| 1185 |
result >= 0 && result <= price, |
| 1186 |
"Invariant violated: price={price}, discount={discount}, result={result}" |
| 1187 |
); |
| 1188 |
} |
| 1189 |
} |
| 1190 |
} |
| 1191 |
|
| 1192 |
|
| 1193 |
|
| 1194 |
proptest::proptest! { |
| 1195 |
#[test] |
| 1196 |
fn prop_percentage_discount_in_range(price in 0..=1_000_000i32, pct in 0..=100i32) { |
| 1197 |
let result = apply_discount(price, DiscountType::Percentage, pct); |
| 1198 |
proptest::prop_assert!(result >= 0, "Result {} should be >= 0", result); |
| 1199 |
proptest::prop_assert!(result <= price, "Result {} should be <= price {}", result, price); |
| 1200 |
} |
| 1201 |
|
| 1202 |
#[test] |
| 1203 |
fn prop_fixed_discount_in_range(price in 0..=1_000_000i32, discount in 0..=1_000_000i32) { |
| 1204 |
let result = apply_discount(price, DiscountType::Fixed, discount); |
| 1205 |
proptest::prop_assert!(result >= 0, "Result {} should be >= 0", result); |
| 1206 |
proptest::prop_assert!(result <= price, "Result {} should be <= price {}", result, price); |
| 1207 |
} |
| 1208 |
|
| 1209 |
#[test] |
| 1210 |
fn prop_100_percent_discount_is_zero(price in 0..=1_000_000i32) { |
| 1211 |
proptest::prop_assert_eq!(apply_discount(price, DiscountType::Percentage, 100), 0); |
| 1212 |
} |
| 1213 |
|
| 1214 |
#[test] |
| 1215 |
fn prop_0_percent_discount_is_identity(price in 0..=1_000_000i32) { |
| 1216 |
proptest::prop_assert_eq!(apply_discount(price, DiscountType::Percentage, 0), price); |
| 1217 |
} |
| 1218 |
} |
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
|
| 1223 |
fn unscoped_discount_promo(max_uses: Option<i32>) -> ValidatedPromo { |
| 1224 |
ValidatedPromo { |
| 1225 |
code: DbPromoCode { |
| 1226 |
id: PromoCodeId::new(), |
| 1227 |
creator_id: UserId::new(), |
| 1228 |
code: "SAVE10".to_string(), |
| 1229 |
code_purpose: CodePurpose::Discount, |
| 1230 |
discount_type: Some(DiscountType::Percentage), |
| 1231 |
discount_value: Some(10), |
| 1232 |
min_price_cents: 0, |
| 1233 |
trial_days: None, |
| 1234 |
item_id: None, |
| 1235 |
project_id: None, |
| 1236 |
tier_id: None, |
| 1237 |
max_uses, |
| 1238 |
use_count: 0, |
| 1239 |
expires_at: None, |
| 1240 |
starts_at: None, |
| 1241 |
created_at: chrono::Utc::now(), |
| 1242 |
is_platform_wide: false, |
| 1243 |
}, |
| 1244 |
is_platform_wide: false, |
| 1245 |
} |
| 1246 |
} |
| 1247 |
|
| 1248 |
#[test] |
| 1249 |
fn single_use_code_discounts_every_eligible_cart_line() { |
| 1250 |
|
| 1251 |
|
| 1252 |
|
| 1253 |
|
| 1254 |
|
| 1255 |
let promo = unscoped_discount_promo(Some(1)); |
| 1256 |
for base in [1000, 2000, 4999] { |
| 1257 |
let result = |
| 1258 |
apply_promo_to_item(&promo, ItemId::new(), ProjectId::new(), base).unwrap(); |
| 1259 |
let PromoApplication::Apply(applied) = result else { |
| 1260 |
panic!("expected Apply for an eligible cart line at base {base}"); |
| 1261 |
}; |
| 1262 |
assert_eq!(applied.price_cents, base - base / 10); |
| 1263 |
|
| 1264 |
assert_eq!(applied.funding, DiscountFunding::CreatorFunded); |
| 1265 |
} |
| 1266 |
|
| 1267 |
|
| 1268 |
assert_eq!(promo.code.use_count, 0); |
| 1269 |
} |
| 1270 |
|
| 1271 |
|
| 1272 |
|
| 1273 |
|
| 1274 |
fn platform_fixed_credit(cents: i32) -> ValidatedPromo { |
| 1275 |
ValidatedPromo { |
| 1276 |
code: DbPromoCode { |
| 1277 |
id: PromoCodeId::new(), |
| 1278 |
creator_id: UserId::new(), |
| 1279 |
code: "FANPLUS".to_string(), |
| 1280 |
code_purpose: CodePurpose::Discount, |
| 1281 |
discount_type: Some(DiscountType::Fixed), |
| 1282 |
discount_value: Some(cents), |
| 1283 |
min_price_cents: 0, |
| 1284 |
trial_days: None, |
| 1285 |
item_id: None, |
| 1286 |
project_id: None, |
| 1287 |
tier_id: None, |
| 1288 |
max_uses: None, |
| 1289 |
use_count: 0, |
| 1290 |
expires_at: None, |
| 1291 |
starts_at: None, |
| 1292 |
created_at: chrono::Utc::now(), |
| 1293 |
is_platform_wide: true, |
| 1294 |
}, |
| 1295 |
is_platform_wide: true, |
| 1296 |
} |
| 1297 |
} |
| 1298 |
|
| 1299 |
#[test] |
| 1300 |
fn platform_fixed_credit_budget_is_face_value() { |
| 1301 |
assert_eq!( |
| 1302 |
platform_fixed_credit(500).platform_credit_budget_cents(), |
| 1303 |
Some(500) |
| 1304 |
); |
| 1305 |
} |
| 1306 |
|
| 1307 |
#[test] |
| 1308 |
fn seller_and_percentage_codes_have_no_credit_budget() { |
| 1309 |
|
| 1310 |
assert_eq!( |
| 1311 |
unscoped_discount_promo(None).platform_credit_budget_cents(), |
| 1312 |
None |
| 1313 |
); |
| 1314 |
|
| 1315 |
|
| 1316 |
let mut pct = platform_fixed_credit(500); |
| 1317 |
pct.code.discount_type = Some(DiscountType::Percentage); |
| 1318 |
pct.code.discount_value = Some(20); |
| 1319 |
assert_eq!(pct.platform_credit_budget_cents(), None); |
| 1320 |
} |
| 1321 |
|
| 1322 |
#[test] |
| 1323 |
fn platform_fixed_credit_spent_once_across_cart() { |
| 1324 |
|
| 1325 |
|
| 1326 |
|
| 1327 |
let promo = platform_fixed_credit(500); |
| 1328 |
let mut budget = promo.platform_credit_budget_cents(); |
| 1329 |
assert_eq!(budget, Some(500)); |
| 1330 |
|
| 1331 |
let mut total_credit = 0i64; |
| 1332 |
let mut total_buyer_paid = 0i64; |
| 1333 |
for _ in 0..3 { |
| 1334 |
let PromoApplication::Apply(applied) = |
| 1335 |
apply_promo_to_item(&promo, ItemId::new(), ProjectId::new(), 1000).unwrap() |
| 1336 |
else { |
| 1337 |
panic!("expected Apply for an eligible platform-credit line"); |
| 1338 |
}; |
| 1339 |
let (final_price, credit) = cap_line_to_credit_budget(applied, &mut budget); |
| 1340 |
total_credit += credit; |
| 1341 |
total_buyer_paid += i64::from(final_price); |
| 1342 |
} |
| 1343 |
assert_eq!( |
| 1344 |
total_credit, 500, |
| 1345 |
"MNW reimburses the seller exactly the face value, once" |
| 1346 |
); |
| 1347 |
assert_eq!( |
| 1348 |
total_buyer_paid, |
| 1349 |
3000 - 500, |
| 1350 |
"buyer gets the $5 credit exactly once" |
| 1351 |
); |
| 1352 |
assert_eq!(budget, Some(0), "balance fully spent"); |
| 1353 |
} |
| 1354 |
|
| 1355 |
#[test] |
| 1356 |
fn platform_fixed_credit_carries_balance_across_cheap_lines() { |
| 1357 |
|
| 1358 |
|
| 1359 |
let promo = platform_fixed_credit(500); |
| 1360 |
let mut budget = promo.platform_credit_budget_cents(); |
| 1361 |
let mut total_credit = 0i64; |
| 1362 |
for _ in 0..2 { |
| 1363 |
let PromoApplication::Apply(applied) = |
| 1364 |
apply_promo_to_item(&promo, ItemId::new(), ProjectId::new(), 100).unwrap() |
| 1365 |
else { |
| 1366 |
panic!("expected Apply"); |
| 1367 |
}; |
| 1368 |
let (final_price, credit) = cap_line_to_credit_budget(applied, &mut budget); |
| 1369 |
assert_eq!(final_price, 0, "a $1 item is fully covered by the credit"); |
| 1370 |
total_credit += credit; |
| 1371 |
} |
| 1372 |
assert_eq!(total_credit, 200); |
| 1373 |
assert_eq!( |
| 1374 |
budget, |
| 1375 |
Some(300), |
| 1376 |
"unspent balance carries to the rest of the cart" |
| 1377 |
); |
| 1378 |
} |
| 1379 |
} |
| 1380 |
|