# Adimsayar

This repository implements a comprehensive rewards system for the app. It combines a referral and points accrual mechanism with a step-based reward system that enables users to earn virtual currency—which can then be spent in the app's virtual store. In short, users get rewarded for:

- Registering with a referral code.
- Recording their daily physical activity (step tracking).
- Engaging in additional activities, such as watching ads and competing on leaderboards.

---

## System Overview

### 1. User Registration & Referral System

- **Referral Code Usage:**  
  When a new user registers and provides a referral code (via the `reference_code_used` field), a record is created in the `UserReferral` table linking the new (referred) user to the referrer. Note that at this stage, **no points are awarded immediately**.

- **One-Time Referral Bonus:**  
  Once the referred user meets a specific activity condition (such as recording their first step), the system triggers the `award_referral_bonus()` method:

  - A point transaction (e.g., 500 bonus points) is created for the referred user.
  - The user's cumulative points (in the `UserPoints` table) are updated.
  - The referral record's `awarded` flag is set to `True` to prevent duplicate bonuses.

- **Referral Chain Bonus:**  
  Every time a user earns points via activity, the `award_referral_chain_bonus()` method may distribute a percentage of the earned points to the referrer(s) in the chain (e.g., the direct referrer might earn 10% of the user's earned points). This bonus may be extended to multiple referral levels based on configurable rules.

---

### 2. Converting Steps into Points

- **Step Tracking:**  
  Users' daily steps are tracked in real time. Each user can set a daily step goal, and the recorded steps are stored in the `StepRecord` table.

- **Conversion to Points:**  
  Steps are converted into points using a predefined conversion rate (for example, \(1\) step = \(0.01\) points). Additionally, if users walk more than a threshold (e.g., 6,000 steps), they may receive double points or other bonuses.

- **Storing Earned Points:**  
  The points earned through step tracking are accumulated in the user's "point wallet." These points are recorded via transactions in the `PointTransaction` table and aggregated in the `UserPoints` table.

- **Triggering Bonus Functions:**
  - **First Activity Bonus:** Upon the first qualifying activity (e.g., first step record), the system calls:
    ```python
    UserService.award_referral_bonus(db, referred_user_id=new_user_id, bonus_points=500)
    ```
  - **Chain Bonus on Activity:** For every subsequent activity record, the system calls:
    ```python
    UserService.award_referral_chain_bonus(db, user_id, earned_points)
    ```
    This ensures that both the one-time and recurring rewards are applied correctly.

---

### 3. Using Points to Shop in the App

- **Virtual Store:**  
  The app's virtual store offers a variety of products such as fitness equipment, healthy food items, and sportswear. Users can add items to the cart and choose to pay with their earned points.

- **Points Deduction and Order Processing:**  
  When a purchase is made:
  - The required amount of points is automatically deducted from the user's point wallet.
  - Order status and delivery progress can be tracked via the app.
  - If a user's points are insufficient, they may purchase additional points through an integrated online payment system.

---

### 4. Additional Ways to Earn Points

- **Referral Bonuses:**  
  In addition to the registration bonus, users can earn extra points when their referred friends start walking.

- **Watching Advertisements:**  
  Users can earn bonus points by watching in-app ads (e.g., "Watch 10 ads and receive 10 points").

- **Weekly/Monthly Leaderboards:**  
  Users who log the highest number of steps in a week or month can win additional bonus points (for example, a 500-point bonus for first place, and lower bonuses for subsequent positions).

---

### 5. Point Wallet & Security Management

- **Point Wallet Management:**  
  Users can view their total points along with detailed earning and spending history.  
  Administrators can monitor and, if necessary, adjust users' point transactions.

- **Fraud Prevention:**  
  The system includes security measures to detect and prevent fraudulent point accumulation (for example, by flagging unnatural step increases or VPN usage). In suspicious cases, point accumulation may be temporarily suspended pending further verification.

---

### 6. Online Payment System Integration

- **Purchasing Points:**  
  If a user's available points are insufficient for a purchase, additional points can be bought via an integrated online payment gateway (e.g., Esnekpos or Iyzico).

- **Administrative Control:**  
  Administrators have the ability to set point prices, define discount strategies, and run promotions.

---

## Key Components & Data Models

- **User:**  
  Contains core user data along with fields such as `total_points`, `reference_code`, and `reference_code_used`.

- **UserReferral:**  
  Records the referral relationship between the referrer and the referred user and includes an `awarded` flag.

- **UserPoints:**  
  Maintains a cumulative total of each user's points.

- **PointTransaction:**  
  Logs all point transactions (credit or debit) with various transaction types including "step", "referral", "redeem" and others.

- **StepRecord:**  
  Stores daily step counts and related metrics, which are then used to calculate earned points.

- **Reward & RewardRedemption:**  
  Define the items available in the virtual store and track redemption details.

---

## Implementation Notes

### Correct Usage of Service Methods

- **Static Method Calls:**  
  The `UserService` class is designed as a utility containing static methods. **Do not instantiate** the class. Instead, call its methods directly as shown:
  ```python
  UserService.award_referral_bonus(db, referred_user_id=new_user_id, bonus_points=500)
  ```
  ```python
  UserService.award_referral_chain_bonus(db, user_id, earned_points)
  ```

### Transaction & Concurrency Management

- **DB Transactions:**  
  Each service method should include robust commit/rollback logic to prevent race conditions or duplicate awards.
- **Concurrency Considerations:**  
  In high-traffic scenarios, consider safeguards such as row-level locking to avoid conflicts.

### Operational Policies & Scalability

- **Customizable Parameters:**  
  Define and manage parameters such as bonus percentages, maximum referral chain levels, step-to-point conversion rates, and thresholds (e.g., double point thresholds) in a configurable manner.

### Testing & Validation

- **Testing:**  
  Utilize seed data and integration tests to ensure that:
  - Referral records are correctly created at registration.
  - Both one-time and chain bonus logic update the `UserPoints` and log appropriate transactions.
  - Points are accurately deducted during virtual store purchases.
  - No duplicate bonuses are awarded.

---

## Important Notes

1. **SSL Services:**

   - SSL services are not included in the base package but can be purchased separately through the after-sales service.

2. **Online Payment Integration:**

   - The system supports integration with Esnekpos or Iyzico payment gateways.
   - One API integration is included with the system.
   - Integration with other payment providers requires additional service engagement.

3. **Content Management:**

   - All content must be managed through the admin panel by the client.
   - The development team is not responsible for content creation.

4. **Country-Based Multipliers:**

   - Point conversion rates can be configured based on user's country.
   - Default multiplier (e.g., 1.0 for Turkey) applies if country is not specifically configured.
   - Country detection is based on user selection during registration.

5. **Legal Compliance:**
   - The system explicitly prohibits:
     - Gambling
     - Child exploitation
     - Pornography
     - Tobacco/alcohol marketing
     - Drug sales
     - Sexual exploitation
     - Human trafficking
     - Ponzi schemes and fraud
   - All legal responsibility for content rests with the content creators (clients).

---

## Conclusion

This system is designed to:

- Encourage new user registrations via referral bonuses.
- Reward user engagement continuously through a step-based points accrual system.
- Provide a seamless and interactive virtual store experience for point-based shopping.
- Ensure security and transparency with detailed transaction logging and robust data management.
- Support multiple revenue streams (ads, point purchases)

The implementation follows best practices for security, scalability, and maintainability while providing flexibility for future enhancements.

Happy coding!
