cedros-login-server 0.0.43

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! PostgreSQL referral payout repository implementation

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use uuid::Uuid;

use crate::errors::AppError;
use crate::repositories::{ReferralPayoutEntity, ReferralPayoutRepository, ReferrerPayoutSummary};

/// PostgreSQL referral payout repository
pub struct PostgresReferralPayoutRepository {
    pool: PgPool,
}

impl PostgresReferralPayoutRepository {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

#[derive(sqlx::FromRow)]
struct ReferralPayoutRow {
    id: Uuid,
    referrer_id: Uuid,
    referred_user_id: Uuid,
    trigger_type: String,
    amount: i64,
    currency: String,
    status: String,
    tx_signature: Option<String>,
    error_message: Option<String>,
    spend_transaction_id: Option<Uuid>,
    created_at: DateTime<Utc>,
    completed_at: Option<DateTime<Utc>>,
}

impl From<ReferralPayoutRow> for ReferralPayoutEntity {
    fn from(row: ReferralPayoutRow) -> Self {
        Self {
            id: row.id,
            referrer_id: row.referrer_id,
            referred_user_id: row.referred_user_id,
            trigger_type: row.trigger_type,
            amount: row.amount,
            currency: row.currency,
            status: row.status,
            tx_signature: row.tx_signature,
            error_message: row.error_message,
            spend_transaction_id: row.spend_transaction_id,
            created_at: row.created_at,
            completed_at: row.completed_at,
        }
    }
}

#[derive(sqlx::FromRow)]
struct ReferrerPayoutSummaryRow {
    referrer_id: Uuid,
    payout_wallet_address: Option<String>,
    total_pending_amount: i64,
    pending_count: i64,
    currency: String,
}

#[async_trait]
impl ReferralPayoutRepository for PostgresReferralPayoutRepository {
    async fn create(&self, payout: ReferralPayoutEntity) -> Result<ReferralPayoutEntity, AppError> {
        let row: ReferralPayoutRow = sqlx::query_as(
            r#"
            INSERT INTO referral_payouts (
                id, referrer_id, referred_user_id, trigger_type,
                amount, currency, status, tx_signature, error_message,
                spend_transaction_id, created_at, completed_at
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
            RETURNING id, referrer_id, referred_user_id, trigger_type,
                      amount, currency, status, tx_signature, error_message,
                      created_at, completed_at
            "#,
        )
        .bind(payout.id)
        .bind(payout.referrer_id)
        .bind(payout.referred_user_id)
        .bind(&payout.trigger_type)
        .bind(payout.amount)
        .bind(&payout.currency)
        .bind(&payout.status)
        .bind(&payout.tx_signature)
        .bind(&payout.error_message)
        .bind(payout.spend_transaction_id)
        .bind(payout.created_at)
        .bind(payout.completed_at)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        Ok(row.into())
    }

    async fn list_pending(
        &self,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<ReferralPayoutEntity>, AppError> {
        let rows: Vec<ReferralPayoutRow> = sqlx::query_as(
            r#"
            SELECT id, referrer_id, referred_user_id, trigger_type,
                   amount, currency, status, tx_signature, error_message,
                   created_at, completed_at
            FROM referral_payouts
            WHERE status = 'pending'
            ORDER BY created_at ASC
            LIMIT $1 OFFSET $2
            "#,
        )
        .bind(limit as i64)
        .bind(offset as i64)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn count_pending(&self) -> Result<u64, AppError> {
        let count: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM referral_payouts WHERE status = 'pending'")
                .fetch_one(&self.pool)
                .await
                .map_err(|e| AppError::Internal(e.into()))?;
        Ok(count.max(0) as u64)
    }

    async fn mark_completed(&self, id: Uuid, tx_signature: &str) -> Result<bool, AppError> {
        let result = sqlx::query(
            r#"
            UPDATE referral_payouts
            SET status = 'completed', tx_signature = $2, completed_at = NOW()
            WHERE id = $1 AND status IN ('pending', 'processing')
            "#,
        )
        .bind(id)
        .bind(tx_signature)
        .execute(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(result.rows_affected() > 0)
    }

    async fn mark_failed(&self, id: Uuid, error: &str) -> Result<bool, AppError> {
        let result = sqlx::query(
            r#"
            UPDATE referral_payouts
            SET status = 'failed', error_message = $2
            WHERE id = $1 AND status IN ('pending', 'processing')
            "#,
        )
        .bind(id)
        .bind(error)
        .execute(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(result.rows_affected() > 0)
    }

    async fn claim_for_processing(&self, ids: &[Uuid]) -> Result<Vec<Uuid>, AppError> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }
        let claimed: Vec<(Uuid,)> = sqlx::query_as(
            r#"
            UPDATE referral_payouts
            SET status = 'processing'
            WHERE id = ANY($1) AND status = 'pending'
            RETURNING id
            "#,
        )
        .bind(ids)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(claimed.into_iter().map(|(id,)| id).collect())
    }

    async fn pending_by_referrer(
        &self,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<ReferrerPayoutSummary>, AppError> {
        let rows: Vec<ReferrerPayoutSummaryRow> = sqlx::query_as(
            r#"
            SELECT rp.referrer_id,
                   u.payout_wallet_address,
                   SUM(rp.amount) AS total_pending_amount,
                   COUNT(*) AS pending_count,
                   rp.currency
            FROM referral_payouts rp
            JOIN users u ON u.id = rp.referrer_id
            WHERE rp.status = 'pending'
            GROUP BY rp.referrer_id, u.payout_wallet_address, rp.currency
            ORDER BY total_pending_amount DESC
            LIMIT $1 OFFSET $2
            "#,
        )
        .bind(limit as i64)
        .bind(offset as i64)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;

        Ok(rows
            .into_iter()
            .map(|r| ReferrerPayoutSummary {
                referrer_id: r.referrer_id,
                payout_wallet_address: r.payout_wallet_address,
                total_pending_amount: r.total_pending_amount,
                pending_count: r.pending_count.max(0) as u64,
                currency: r.currency,
            })
            .collect())
    }

    async fn count_pending_referrers(&self) -> Result<u64, AppError> {
        let count: i64 = sqlx::query_scalar(
            "SELECT COUNT(DISTINCT referrer_id) FROM referral_payouts WHERE status = 'pending'",
        )
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(count.max(0) as u64)
    }

    async fn sum_for_referrer(&self, referrer_id: Uuid) -> Result<i64, AppError> {
        let sum: Option<i64> = sqlx::query_scalar(
            "SELECT COALESCE(SUM(amount), 0) FROM referral_payouts WHERE referrer_id = $1 AND status != 'failed'",
        )
        .bind(referrer_id)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(sum.unwrap_or(0))
    }

    async fn reset_failed(&self) -> Result<u64, AppError> {
        let result = sqlx::query(
            "UPDATE referral_payouts SET status = 'pending', error_message = NULL WHERE status = 'failed'",
        )
        .execute(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(result.rows_affected())
    }

    async fn exists_for_spend_transaction(
        &self,
        referrer_id: Uuid,
        spend_transaction_id: Uuid,
    ) -> Result<bool, AppError> {
        let exists: bool = sqlx::query_scalar(
            r#"
            SELECT EXISTS(
                SELECT 1 FROM referral_payouts
                WHERE referrer_id = $1
                  AND spend_transaction_id = $2
            )
            "#,
        )
        .bind(referrer_id)
        .bind(spend_transaction_id)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(exists)
    }

    async fn exists_for_pair(
        &self,
        referrer_id: Uuid,
        referred_user_id: Uuid,
        trigger_type: &str,
    ) -> Result<bool, AppError> {
        let exists: bool = sqlx::query_scalar(
            r#"
            SELECT EXISTS(
                SELECT 1 FROM referral_payouts
                WHERE referrer_id = $1
                  AND referred_user_id = $2
                  AND trigger_type = $3
            )
            "#,
        )
        .bind(referrer_id)
        .bind(referred_user_id)
        .bind(trigger_type)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(exists)
    }

    async fn sum_by_status(&self, status: &str) -> Result<i64, AppError> {
        let sum: Option<i64> = sqlx::query_scalar(
            "SELECT COALESCE(SUM(amount), 0) FROM referral_payouts WHERE status = $1",
        )
        .bind(status)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(sum.unwrap_or(0))
    }

    async fn find_by_id(&self, id: Uuid) -> Result<Option<ReferralPayoutEntity>, AppError> {
        let row: Option<ReferralPayoutRow> = sqlx::query_as(
            r#"
            SELECT id, referrer_id, referred_user_id, trigger_type,
                   amount, currency, status, tx_signature, error_message,
                   spend_transaction_id, created_at, completed_at
            FROM referral_payouts
            WHERE id = $1
            "#,
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(row.map(Into::into))
    }

    async fn cancel(&self, id: Uuid) -> Result<bool, AppError> {
        let result = sqlx::query(
            "UPDATE referral_payouts SET status = 'cancelled' WHERE id = $1 AND status = 'pending'",
        )
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(result.rows_affected() > 0)
    }

    async fn list_all(
        &self,
        status_filter: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<ReferralPayoutEntity>, AppError> {
        let rows: Vec<ReferralPayoutRow> = if let Some(status) = status_filter {
            sqlx::query_as(
                r#"
                SELECT id, referrer_id, referred_user_id, trigger_type,
                       amount, currency, status, tx_signature, error_message,
                       spend_transaction_id, created_at, completed_at
                FROM referral_payouts
                WHERE status = $1
                ORDER BY created_at DESC
                LIMIT $2 OFFSET $3
                "#,
            )
            .bind(status)
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| AppError::Internal(e.into()))?
        } else {
            sqlx::query_as(
                r#"
                SELECT id, referrer_id, referred_user_id, trigger_type,
                       amount, currency, status, tx_signature, error_message,
                       spend_transaction_id, created_at, completed_at
                FROM referral_payouts
                ORDER BY created_at DESC
                LIMIT $1 OFFSET $2
                "#,
            )
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| AppError::Internal(e.into()))?
        };
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn count_all(&self, status_filter: Option<&str>) -> Result<u64, AppError> {
        let count: i64 = if let Some(status) = status_filter {
            sqlx::query_scalar("SELECT COUNT(*) FROM referral_payouts WHERE status = $1")
                .bind(status)
                .fetch_one(&self.pool)
                .await
                .map_err(|e| AppError::Internal(e.into()))?
        } else {
            sqlx::query_scalar("SELECT COUNT(*) FROM referral_payouts")
                .fetch_one(&self.pool)
                .await
                .map_err(|e| AppError::Internal(e.into()))?
        };
        Ok(count.max(0) as u64)
    }

    async fn list_by_referrer(
        &self,
        referrer_id: Uuid,
        status_filter: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<ReferralPayoutEntity>, AppError> {
        let rows: Vec<ReferralPayoutRow> = if let Some(status) = status_filter {
            sqlx::query_as(
                r#"
                SELECT id, referrer_id, referred_user_id, trigger_type,
                       amount, currency, status, tx_signature, error_message,
                       spend_transaction_id, created_at, completed_at
                FROM referral_payouts
                WHERE referrer_id = $1 AND status = $2
                ORDER BY created_at DESC
                LIMIT $3 OFFSET $4
                "#,
            )
            .bind(referrer_id)
            .bind(status)
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| AppError::Internal(e.into()))?
        } else {
            sqlx::query_as(
                r#"
                SELECT id, referrer_id, referred_user_id, trigger_type,
                       amount, currency, status, tx_signature, error_message,
                       spend_transaction_id, created_at, completed_at
                FROM referral_payouts
                WHERE referrer_id = $1
                ORDER BY created_at DESC
                LIMIT $2 OFFSET $3
                "#,
            )
            .bind(referrer_id)
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| AppError::Internal(e.into()))?
        };
        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn count_by_referrer(
        &self,
        referrer_id: Uuid,
        status_filter: Option<&str>,
    ) -> Result<u64, AppError> {
        let count: i64 = if let Some(status) = status_filter {
            sqlx::query_scalar(
                "SELECT COUNT(*) FROM referral_payouts WHERE referrer_id = $1 AND status = $2",
            )
            .bind(referrer_id)
            .bind(status)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| AppError::Internal(e.into()))?
        } else {
            sqlx::query_scalar("SELECT COUNT(*) FROM referral_payouts WHERE referrer_id = $1")
                .bind(referrer_id)
                .fetch_one(&self.pool)
                .await
                .map_err(|e| AppError::Internal(e.into()))?
        };
        Ok(count.max(0) as u64)
    }

    async fn sum_by_status_for_referrer(
        &self,
        referrer_id: Uuid,
        status: &str,
    ) -> Result<i64, AppError> {
        let sum: Option<i64> = sqlx::query_scalar(
            "SELECT COALESCE(SUM(amount), 0) FROM referral_payouts WHERE referrer_id = $1 AND status = $2",
        )
        .bind(referrer_id)
        .bind(status)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| AppError::Internal(e.into()))?;
        Ok(sum.unwrap_or(0))
    }
}