# FortuneBet Backend

FortuneBet Backend is the server-side application that powers the FortuneBet system. It fetches and processes odds and results for various sports (e.g. football, basketball, ice hockey), manages upcoming events, evaluates bet outcomes, as well as managing the different branches and companies that will be using the system.

## Table of Contents

- [Installation](#installation)
- [Environment Configuration](#environment-configuration)
- [Running the Application](#running-the-application)
- [Database Management](#database-management)
- [Testing and Code Quality](#testing-and-code-quality)
- [API Documentation](#api-documentation)
- [Project Structure](#project-structure)
- [Core Services Overview](#core-services-overview)
- [Roles and Access Control](#roles-and-access-control)
- [Code Organization Guidelines](#code-organization-guidelines)
- [Further Details](#further-details)


## Installation
Before running the application, ensure you have the following installed:

- [Go](https://golang.org/doc/install) (1.20+ recommended)
- [Docker](https://www.docker.com/)
- [Air](https://github.com/cosmtrek/air) — for live reloading during development
- [SQLC](https://sqlc.dev)
- [Migrate](https://github.com/golang-migrate/migrate)
- [Swag](https://github.com/swaggo/swag)

Clone the repository:

```bash
git clone https://github.com/your-org/fortunebet-backend.git
cd fortunebet-backend
```

## Environment Configuration
Create a .env file in the root directory. This file is critical for running the application as it contains database credentials, secret keys, third-party integrations, and configuration flags.

Sample variables you might include:
```ini
ENV=development
PORT=8080
DB_URL=postgresql://root:secret@localhost:5422/gh?sslmode=disable
REFRESH_EXPIRY=
JWT_KEY=
ACCESS_EXPIRY=
LOG_LEVEL=debug
AFRO_SMS_API_KEY=
AFRO_SMS_SENDER_NAME=
AFRO_SMS_RECEIVER_PHONE_NUMBER=
BET365_TOKEN=
POPOK_CLIENT_ID=
POPOK_SECRET_KEY=
POPOK_BASE_URL=
POPOK_CALLBACK_URL=
```

## Running the Application
To run the application:
```bash
make run
```

To start the server with live reload (using air):
```bash
make air
```

To build the binary:
```bash
make build
```

## Database Management
Start the database using Docker Compose:
```bash
make db-up
```

Stop it:
```bash
make db-down
```

Create a new migration:
```bash
make migrations/new name=add_new_table
```
Apply all pending migrations:
```bash
make migrations/up
```

## Testing and Code Quality
Run all tests:

```bash
make test
```

Generate a coverage report:
```bash
make coverage
```

## API Documentation
Generate Swagger docs:

```bash
make swagger
```
This will output files to the docs/ directory.


## Project Structure

```bash
├── cmd/
│   └── main.go                  # Application entry point
├── internal/
│   ├── config/                  # Configuration and environment loading
│   │   └── config.go
│   ├── domain/                  # Domain models, constants, and roles
│   │   ├── sportmarket.go       # Market types (e.g., FootballMarket)
│   │   └── roles.go             # Role definitions (e.g., RoleSuperAdmin, RoleAdmin, etc.)
│   ├── repository/              # Database interaction layer
│   │   ├── branch.go            # Branch related queries and conversion functions
│   │   ├── company.go           # Company-related database functions
│   │   ├── user.go              # User repository methods
│   │   └── ...                  # Other repository files
│   ├── services/                # Business logic and core services
│   │   ├── odds/
│   │   │   └── service.go       # Fetching odds from external APIs
│   │   └── result/
│   │       ├── service.go       # Parsing and storing results
│   │       └── eval.go          # Evaluation logic for bet outcomes
│   └── web_server/              # HTTP handlers, routes, middleware, and cron jobs
│       ├── cron.go              # Scheduled background tasks
│       └── handlers/
│           ├── branch_handler.go  # Branch-related API endpoints
│           ├── manager.go         # Manager-related endpoints
│           └── ...                # Additional handlers (e.g., for companies, users, etc.)
├── db/
│   └── migrations/              # SQL migration files
│       ├── 000001_fortune.up.sql
│       └── ...                  # Further migration files
├── docs/
│   ├── swagger/                 # Swagger/OpenAPI documentation files
│   │   ├── swagger.yaml
│   │   └── swagger.json
│   └── docs.go                  # Swaggo-generated docs (do not edit manually)
├── gen/
│   └── db/                      # SQLC-generated Go code for database access
│       └── ...                  # Generated files (e.g., queries.go)
├── makefile                     # Development and operations commands
├── .env                         # Environment configuration file (not checked in)
└── README.md                    # Project documentation
```


## Core Services Overview

FortuneBet includes a wide suite of services for a modern betting platform:

- **Notification Service**: Sends alerts to users/admins about odds changes, results, etc.
- **Ticket System**: Manages bet tickets, results, and statuses.
- **Temporary Ticket QR/Shortcode System**: Fast bet placement and redemption.
- **Fraud Prevention**: Detects suspicious activity and prevents account abuse.
- **Bet Expiration**: Bets expire after one year; claims must be handled manually.
- **Self-Protection**: Limits bets based on user behavior to promote responsible betting.
- **Betting System**: Core logic for placing, modifying, and canceling bets.
- **Bet365 Odds Integration**: Real-time odds sync with Bet365.
- **Event Disabling**: Admins can disable events (e.g. suspicious or restricted).
- **Odds Management**: Admins can dynamically adjust odds.
- **Odds Update Log**: Track and audit all odds changes.
- **Game Management**: Remove games or leagues from the market.
- **Wallet System**: Handles transactions, deposits, and withdrawals.
- **Super Admin Panel**: Master control for the whole system.
- **Branch Manager Dashboard**: Local control for branches and terminals.
- **User Management**: User roles, activity tracking, limits.
- **Live Betting**: Real-time betting during live matches.
- **Cashout System**: Enables early bet redemption.
- **Bonus & Promotions**: Incentivize users with custom promotions.
- **Risk Analysis**: Detect high-risk bets and patterns.
- **Affiliate & Referrals**: Referral tracking and commission.
- **Reports & Analytics**: Generate operational insights.
- **Compliance Tools**: Support for KYC, AML, and legal requirements.


## Roles and Access Control
FortuneBet uses role-based access control to secure routes and platform features. The defined roles are:
```go
package domain

type Role string

const (
	RoleSuperAdmin    Role = "super_admin"
	RoleAdmin         Role = "admin"
	RoleBranchManager Role = "branch_manager"
	RoleCustomer      Role = "customer"
	RoleCashier       Role = "cashier"
)
```

Super Admin — Full system control

Admin — Represents a company admin that controls everything for company

Branch Manager — Handles local branch users and operations

Customer — Places and tracks bets

Cashier — Handles customer funds and transactions in branches

These roles determine route access and permissions in the admin interface.


## Code Organization Guidelines

- **Services**:  
  Add new business logic or functionality under the `/internal/services` directory.  
  For example, create a new service in `/internal/services/your_service/service.go`.

- **Routes and Handlers**:  
  Define new HTTP routes and API endpoint logic inside `/internal/web_server/handlers`.  
  Create separate files for different modules (e.g., users, companies, branches, etc.).

- **SQL Queries and Code Generation (SQLC)**:  
  Write your raw SQL queries in the `/db/query` directory.  
  Then generate type-safe Go code with SQLC by running:  
  ```bash
  make sqlc-gen
  ```

## Further Details
Our long-term goal is to become a trusted betting provider, offering white-label sportsbook solutions for other operators to use in their shops and platforms.

Planned Features:
- Multi-language and currency support
- Full virtual games integration
- Regulatory audit logging
