user and auth service refactoring, notification service SQL + repository adjustment

This commit is contained in:
Yared Yemane 2025-12-16 18:05:57 +03:00
parent 13c470079c
commit 5e9046eb76
402 changed files with 6126 additions and 105078 deletions

219
README.md
View File

@ -1,6 +1,6 @@
# FortuneBet Backend # Yimaru 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. Yimaru Backend is the server-side application that powers the Yimaru online learning system. It manages courses, lessons, quizzes, student progress, instructor content, and administrative operations for institutions and users on the platform.
## Table of Contents ## Table of Contents
@ -16,6 +16,7 @@ FortuneBet Backend is the server-side application that powers the FortuneBet sys
- [Code Organization Guidelines](#code-organization-guidelines) - [Code Organization Guidelines](#code-organization-guidelines)
- [Further Details](#further-details) - [Further Details](#further-details)
---
## Installation ## Installation
Before running the application, ensure you have the following installed: Before running the application, ensure you have the following installed:
@ -30,223 +31,41 @@ Before running the application, ensure you have the following installed:
Clone the repository: Clone the repository:
```bash ```bash
git clone https://github.com/your-org/fortunebet-backend.git git clone https://github.com/your-org/Yimaru-backend.git
cd fortunebet-backend cd Yimaru-backend
```
Then you will need to setup the database, which you can do using:
```bash
make db-up
```
You will also need to setup the necessary seed_data using:
```bash
make seed_data
```
## 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/ ├── cmd/
│ └── main.go # Application entry point │ └── main.go # Application entry point
├── internal/ ├── internal/
│ ├── config/ # Configuration and environment loading │ ├── config/ # Configuration and environment loading
│ │ └── config.go │ │ └── config.go
│ ├── domain/ # Domain models, constants, and roles │ ├── domain/ # Domain models, constants, and roles
│ │ ├── sportmarket.go # Market types (e.g., FootballMarket) │ │ ├── course.go # Course and lesson structures
│ │ └── roles.go # Role definitions (e.g., RoleSuperAdmin, RoleAdmin, etc.) │ │ └── roles.go # Role definitions (e.g., RoleAdmin, RoleInstructor)
│ ├── repository/ # Database interaction layer │ ├── repository/ # Database interaction layer
│ │ ├── branch.go # Branch related queries and conversion functions │ │ ├── course.go # Course-related queries
│ │ ├── company.go # Company-related database functions │ │ ├── lesson.go # Lesson-related database functions
│ │ ├── user.go # User repository methods │ │ ├── user.go # User repository methods
│ │ └── ... # Other repository files │ │ └── ... # Other repository files
│ ├── services/ # Business logic and core services │ ├── services/ # Business logic and core services
│ │ ├── odds/ │ │ ├── course/
│ │ │ └── service.go # Fetching odds from external APIs │ │ │ └── service.go # Course management logic
│ │ └── result/ │ │ └── quiz/
│ │ ├── service.go # Parsing and storing results │ │ ├── service.go # Quiz management and evaluation logic
│ │ └── eval.go # Evaluation logic for bet outcomes │ │ └── eval.go # Evaluation logic for student progress
│ └── web_server/ # HTTP handlers, routes, middleware, and cron jobs │ └── web_server/ # HTTP handlers, routes, middleware, and cron jobs
│ ├── cron.go # Scheduled background tasks │ ├── cron.go # Scheduled background tasks
│ └── handlers/ │ └── handlers/
│ ├── branch_handler.go # Branch-related API endpoints │ ├── course_handler.go # Course-related API endpoints
│ ├── manager.go # Manager-related endpoints │ ├── user_handler.go # User-related endpoints
│ └── ... # Additional handlers (e.g., for companies, users, etc.) │ └── ... # Additional handlers
├── db/ ├── db/
│ └── migrations/ # SQL migration files │ └── migrations/ # SQL migration files
│ ├── 000001_fortune.up.sql
│ └── ... # Further migration files
├── docs/ ├── docs/
│ ├── swagger/ # Swagger/OpenAPI documentation files │ ├── swagger/ # Swagger/OpenAPI documentation files
│ │ ├── swagger.yaml │ └── docs.go # Swaggo-generated docs
│ │ └── swagger.json
│ └── docs.go # Swaggo-generated docs (do not edit manually)
├── gen/ ├── gen/
│ └── db/ # SQLC-generated Go code for database access │ └── db/ # SQLC-generated Go code for database access
│ └── ... # Generated files (e.g., queries.go)
├── makefile # Development and operations commands ├── makefile # Development and operations commands
├── .env # Environment configuration file (not checked in) ├── .env # Environment configuration file
└── README.md # Project documentation └── 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

View File

@ -4,7 +4,22 @@ import (
// "context" // "context"
// "context" // "context"
"context" "Yimaru-Backend/internal/config"
"Yimaru-Backend/internal/domain"
customlogger "Yimaru-Backend/internal/logger"
"Yimaru-Backend/internal/logger/mongoLogger"
"Yimaru-Backend/internal/repository"
"Yimaru-Backend/internal/services/arifpay"
"Yimaru-Backend/internal/services/authentication"
"Yimaru-Backend/internal/services/currency"
notificationservice "Yimaru-Backend/internal/services/notification"
"Yimaru-Backend/internal/services/recommendation"
referralservice "Yimaru-Backend/internal/services/referal"
"Yimaru-Backend/internal/services/transaction"
"Yimaru-Backend/internal/services/user"
httpserver "Yimaru-Backend/internal/web_server"
jwtutil "Yimaru-Backend/internal/web_server/jwt"
customvalidator "Yimaru-Backend/internal/web_server/validator"
"fmt" "fmt"
"log" "log"
"log/slog" "log/slog"
@ -14,66 +29,11 @@ import (
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"go.uber.org/zap" "go.uber.org/zap"
// "github.com/gofiber/fiber/v2"
"github.com/SamuelTariku/FortuneBet-Backend/internal/config"
"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
customlogger "github.com/SamuelTariku/FortuneBet-Backend/internal/logger"
"github.com/SamuelTariku/FortuneBet-Backend/internal/logger/mongoLogger"
// mongologger "github.com/SamuelTariku/FortuneBet-Backend/internal/logger/mongoLogger"
// "github.com/SamuelTariku/FortuneBet-Backend/internal/logger/mongoLogger"
"github.com/SamuelTariku/FortuneBet-Backend/internal/repository"
// "github.com/SamuelTariku/FortuneBet-Backend/internal/router"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/arifpay"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/authentication"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/bet"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/bonus"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/branch"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/chapa"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/company"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/currency"
directdeposit "github.com/SamuelTariku/FortuneBet-Backend/internal/services/direct_deposit"
enetpulse "github.com/SamuelTariku/FortuneBet-Backend/internal/services/enet_pulse"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/event"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/institutions"
issuereporting "github.com/SamuelTariku/FortuneBet-Backend/internal/services/issue_reporting"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/league"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/messenger"
notificationservice "github.com/SamuelTariku/FortuneBet-Backend/internal/services/notification"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/odds"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/raffle"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/recommendation"
referralservice "github.com/SamuelTariku/FortuneBet-Backend/internal/services/referal"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/result"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/santimpay"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/settings"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/stats"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/telebirr"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/ticket"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/transaction"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/user"
virtualgameservice "github.com/SamuelTariku/FortuneBet-Backend/internal/services/virtualGame"
alea "github.com/SamuelTariku/FortuneBet-Backend/internal/services/virtualGame/Alea"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/virtualGame/atlas"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/virtualGame/orchestration"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/virtualGame/veli"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/wallet"
"github.com/SamuelTariku/FortuneBet-Backend/internal/services/wallet/monitor"
// "github.com/SamuelTariku/FortuneBet-Backend/internal/utils"
httpserver "github.com/SamuelTariku/FortuneBet-Backend/internal/web_server"
jwtutil "github.com/SamuelTariku/FortuneBet-Backend/internal/web_server/jwt"
customvalidator "github.com/SamuelTariku/FortuneBet-Backend/internal/web_server/validator"
) )
// @title FortuneBet API // @title Yimaru API
// @version 1.0.1 // @version 1.0.1
// @description This is server for FortuneBet. // @description This is server for Yimaru.
// @termsOfService http://swagger.io/terms/ // @termsOfService http://swagger.io/terms/
// @contact.name API Support // @contact.name API Support
// @contact.url http://www.swagger.io/support // @contact.url http://www.swagger.io/support
@ -111,21 +71,18 @@ func main() {
v := customvalidator.NewCustomValidator(validator.New()) v := customvalidator.NewCustomValidator(validator.New())
// Initialize services // Initialize services
settingRepo := repository.NewSettingStore(store) // settingRepo := repository.NewSettingStore(store)
if err := settingRepo.EnsureAllSettingsExist(context.Background()); err != nil { // if err := settingRepo.EnsureAllSettingsExist(context.Background()); err != nil {
log.Fatalf("failed to ensure settings: %v", err) // log.Fatalf("failed to ensure settings: %v", err)
} // }
settingSvc := settings.NewService(settingRepo) // settingSvc := settings.NewService(settingRepo)
messengerSvc := messenger.NewService(settingSvc, cfg) // messengerSvc := messenger.NewService(settingSvc, cfg)
statSvc := stats.NewService( // statSvc := stats.NewService(
repository.NewCompanyStatStore(store), // repository.NewCompanyStatStore(store),
repository.NewBranchStatStore(store), // repository.NewBranchStatStore(store),
repository.NewEventStatStore(store), // )
repository.NewBetStatStore(store),
repository.NewWalletStatStore(store),
)
authSvc := authentication.NewService( authSvc := authentication.NewService(
repository.NewUserStore(store), repository.NewUserStore(store),
@ -135,34 +92,34 @@ func main() {
userSvc := user.NewService( userSvc := user.NewService(
repository.NewUserStore(store), repository.NewUserStore(store),
repository.NewOTPStore(store), repository.NewOTPStore(store),
messengerSvc, // messengerSvc,
cfg,
)
leagueSvc := league.New(repository.NewLeagueStore(store))
eventSvc := event.New(
cfg.Bet365Token,
repository.NewEventStore(store),
repository.NewEventHistoryStore(store),
*leagueSvc,
settingSvc,
domain.MongoDBLogger,
cfg, cfg,
) )
// leagueSvc := league.New(repository.NewLeagueStore(store))
// eventSvc := event.New(
// cfg.Bet365Token,
// repository.NewEventStore(store),
// repository.NewEventHistoryStore(store),
// *leagueSvc,
// settingSvc,
// domain.MongoDBLogger,
// cfg,
// )
marketSettingRepo := repository.NewMarketSettingStore(store) // marketSettingRepo := repository.NewMarketSettingStore(store)
if err := marketSettingRepo.EnsureAllMarketSettingsExist(context.Background()); err != nil { // if err := marketSettingRepo.EnsureAllMarketSettingsExist(context.Background()); err != nil {
log.Fatalf("failed to ensure market settings: %v", err) // log.Fatalf("failed to ensure market settings: %v", err)
} // }
oddsSvc := odds.New( // oddsSvc := odds.New(
repository.NewOddStore(store), // repository.NewOddStore(store),
marketSettingRepo, // marketSettingRepo,
cfg, // cfg,
eventSvc, // eventSvc,
logger, // logger,
domain.MongoDBLogger, // domain.MongoDBLogger,
) // )
// virtuaGamesRepo := repository.NewVirtualGameRepository(store) // virtuaGamesRepo := repository.NewVirtualGameRepository(store)
@ -179,67 +136,65 @@ func main() {
userSvc, userSvc,
) )
walletSvc := wallet.NewService( // / := wallet.NewService(
repository.NewWalletStore(store), // repository.NewWalletStore(store),
repository.NewTransferStore(store), // repository.NewTransferStore(store),
// repository.NewDirectDepositStore(store), // // repository.NewDirectDepositStore(store),
notificationSvc, // notificationSvc,
userSvc, // userSvc,
domain.MongoDBLogger, // domain.MongoDBLogger,
logger, // logger,
) // )
branchSvc := branch.NewService(repository.NewBranchStore(store)) branchSvc := branch.NewService(repository.NewBranchStore(store))
companySvc := company.NewService(repository.NewCompanyStore(store)) companySvc := company.NewService(repository.NewCompanyStore(store))
ticketSvc := ticket.NewService( // ticketSvc := ticke.NewService(
repository.NewTicketStore(store), // repository.NewTicketStore(store),
eventSvc, // // eventSvc,
*oddsSvc, // // *oddsSvc,
domain.MongoDBLogger, // domain.MongoDBLogger,
settingSvc, // settingSvc,
) // )
betSvc := bet.NewService( // betSvc := bet.NewService(
repository.NewBetStore(store), // repository.NewBetStore(store),
eventSvc, // eventSvc,
*oddsSvc, // *oddsSvc,
*walletSvc, // ,
*branchSvc, // *branchSvc,
*companySvc, // *companySvc,
*settingSvc, // *settingSvc,
*userSvc, // *userSvc,
notificationSvc, // notificationSvc,
logger, // logger,
domain.MongoDBLogger, // domain.MongoDBLogger,
) // )
resultSvc := result.NewService( // resultSvc := result.NewService(
repository.NewResultLogStore(store), // repository.NewResultLogStore(store),
cfg, // cfg,
logger, // logger,
domain.MongoDBLogger, // domain.MongoDBLogger,
*betSvc, // // *betSvc,
*oddsSvc, // // *oddsSvc,
eventSvc, // // eventSvc,
leagueSvc, // // leagueSvc,
notificationSvc, // notificationSvc,
messengerSvc, // messengerSvc,
*userSvc, // *userSvc,
) // )
bonusSvc := bonus.NewService( bonusSvc := bonus.NewService(
repository.NewBonusStore(store), repository.NewBonusStore(store),
walletSvc,
settingSvc, settingSvc,
notificationSvc, notificationSvc,
domain.MongoDBLogger, domain.MongoDBLogger,
) )
virtualGamesRepo := repository.NewVirtualGameRepository(store) // virtualGamesRepo := repository.NewVirtualGameRepository(store)
recommendationRepo := repository.NewRecommendationRepository(store) recommendationRepo := repository.NewRecommendationRepository(store)
referalSvc := referralservice.New( referalSvc := referralservice.New(
repository.NewReferralStore(store), repository.NewReferralStore(store),
*walletSvc,
*settingSvc, *settingSvc,
cfg, cfg,
logger, logger,
@ -248,28 +203,26 @@ func main() {
raffleSvc := raffle.NewService( raffleSvc := raffle.NewService(
repository.NewRaffleStore(store), repository.NewRaffleStore(store),
) )
virtualGameSvc := virtualgameservice.New(virtualGamesRepo, *walletSvc, store, cfg, logger) // virtualGameSvc := virtualgameservice.New(virtualGamesRepo,, store, cfg, logger)
aleaService := alea.NewAleaPlayService(virtualGamesRepo, *walletSvc, cfg, logger) // aleaService := alea.NewAleaPlayService(virtualGamesRepo,, cfg, logger)
veliCLient := veli.NewClient(cfg, walletSvc) // veliCLient := veli.NewClient(cfg)
veliVirtualGameService := veli.New(virtualGameSvc, virtualGamesRepo, *store, veliCLient, walletSvc, repository.NewTransferStore(store), domain.MongoDBLogger, cfg) // veliVirtualGameService := veli.New(virtualGameSvc, virtualGamesRepo, *store, veliCLient, repository.NewTransferStore(store), domain.MongoDBLogger, cfg)
orchestrationSvc := orchestration.New( // orchestrationSvc := orchestration.New(
virtualGameSvc, // virtualGameSvc,
virtualGamesRepo, // virtualGamesRepo,
cfg, // cfg,
veliCLient, // veliCLient,
) // )
atlasClient := atlas.NewClient(cfg, walletSvc) // atlasClient := atlas.NewClient(cfg)
atlasVirtualGameService := atlas.New(virtualGameSvc, virtualGamesRepo, atlasClient, walletSvc, repository.NewTransferStore(store), cfg) // atlasVirtualGameService := atlas.New(virtualGameSvc, virtualGamesRepo, atlasClient, repository.NewTransferStore(store), cfg)
recommendationSvc := recommendation.NewService(recommendationRepo) recommendationSvc := recommendation.NewService(recommendationRepo)
chapaClient := chapa.NewClient(cfg.CHAPA_BASE_URL, cfg.CHAPA_SECRET_KEY) // chapaClient := chapa.NewClient(cfg.CHAPA_BASE_URL, cfg.CHAPA_SECRET_KEY)
chapaSvc := chapa.NewService( // chapaSvc := chapa.NewService(
repository.NewTransferStore(store), // repository.NewUserStore(store),
*walletSvc, // cfg,
repository.NewUserStore(store), // chapaClient,
cfg, // )
chapaClient,
)
currRepo := repository.NewCurrencyPostgresRepository(store) currRepo := repository.NewCurrencyPostgresRepository(store)
@ -280,8 +233,6 @@ func main() {
transactionSvc := transaction.NewService( transactionSvc := transaction.NewService(
repository.NewTransactionStore(store), repository.NewTransactionStore(store),
*branchSvc, *branchSvc,
*betSvc,
*walletSvc,
*userSvc, *userSvc,
) )
@ -303,14 +254,14 @@ func main() {
// cfg, // cfg,
// ) // )
enePulseSvc := enetpulse.New( // enePulseSvc := enetpulse.New(
*cfg, // *cfg,
store, // store,
) // )
go httpserver.StartEnetPulseCron(enePulseSvc, domain.MongoDBLogger) // go httpserver.StartEnetPulseCron(enePulseSvc, domain.MongoDBLogger)
// go httpserver.SetupReportandVirtualGameCronJobs(context.Background(), reportSvc, orchestrationSvc, "C:/Users/User/Desktop") // go httpserver.SetupReportandVirtualGameCronJobs(context.Background(), reportSvc, orchestrationSvc, "C:/Users/User/Desktop")
go httpserver.ProcessBetCashback(context.TODO(), betSvc) // go httpserver.ProcessBetCashback(context.TODO(), betSvc)
bankRepository := repository.NewBankRepository(store) bankRepository := repository.NewBankRepository(store)
instSvc := institutions.New(bankRepository) instSvc := institutions.New(bankRepository)
@ -326,27 +277,25 @@ func main() {
// Start cron jobs for automated reporting // Start cron jobs for automated reporting
directdeposit := directdeposit.NewService( // directdeposit := directdeposit.NewService(
*walletSvc, // repository.NewDirectDepositRepository(store),
repository.NewTransferStore(store), // notificationSvc,
repository.NewDirectDepositRepository(store), // userSvc,
notificationSvc, // )
userSvc,
)
enetPulseSvc := enetpulse.New( // enetPulseSvc := enetpulse.New(
*cfg, // *cfg,
store, // store,
) // )
// Initialize wallet monitoring service // Initialize wallet monitoring service
walletMonitorSvc := monitor.NewService( // walletMonitorSvc := monitor.NewService(
*walletSvc, // ,
*branchSvc, // *branchSvc,
notificationSvc, // notificationSvc,
logger, // logger,
5*time.Minute, // 5*time.Minute,
) // )
currSvc := currency.NewService( currSvc := currency.NewService(
currRepo, currRepo,
@ -357,38 +306,34 @@ func main() {
// exchangeWorker := currency.NewExchangeRateWorker(fixerFertcherSvc, logger, cfg) // exchangeWorker := currency.NewExchangeRateWorker(fixerFertcherSvc, logger, cfg)
// exchangeWorker.Start(context.Background()) // exchangeWorker.Start(context.Background())
// defer exchangeWorker.Stop() // defer exchangeWorker.Stop()
go walletMonitorSvc.Start() // go walletMonitorSvc.Start()
httpserver.StartBetAPIDataFetchingCrons(eventSvc, *oddsSvc, resultSvc, domain.MongoDBLogger) // // httpserver.StartBetAPIDataFetchingCrons(eventSvc, *oddsSvc, resultSvc, domain.MongoDBLogger)
httpserver.StartCleanupCrons(*ticketSvc, notificationSvc, domain.MongoDBLogger) // httpserver.StartCleanupCrons(*ticketSvc, notificationSvc, domain.MongoDBLogger)
httpserver.StartStatCrons(statSvc, domain.MongoDBLogger) // httpserver.StartStatCrons(statSvc, domain.MongoDBLogger)
// httpserver.StartReportCrons(reportSvc, domain.MongoDBLogger) // httpserver.StartReportCrons(reportSvc, domain.MongoDBLogger)
issueReportingRepo := repository.NewReportedIssueRepository(store) issueReportingRepo := repository.NewReportedIssueRepository(store)
issueReportingSvc := issuereporting.New(issueReportingRepo) issueReportingSvc := issuereporting.New(issueReportingRepo)
transferStore := repository.NewTransferStore(store) // transferStore := repository.NewTransferStore(store)
// walletStore := wallet.WalletStore(store) // walletStore := wallet.WalletStore(store)
arifpaySvc := arifpay.NewArifpayService(cfg, transferStore, walletSvc, &http.Client{ arifpaySvc := arifpay.NewArifpayService(cfg, *transactionSvc, &http.Client{
Timeout: 30 * time.Second}) Timeout: 30 * time.Second})
santimpayClient := santimpay.NewSantimPayClient(cfg) // santimpayClient := santimpay.NewSantimPayClient(cfg)
santimpaySvc := santimpay.NewSantimPayService(santimpayClient, cfg, transferStore, walletSvc) // santimpaySvc := santimpay.NewSantimPayService(santimpayClient, cfg, transferStore)
telebirrSvc := telebirr.NewTelebirrService(cfg, transferStore, walletSvc) // telebirrSvc := telebirr.NewTelebirrService(cfg, transferStore)
// Initialize and start HTTP server // Initialize and start HTTP server
app := httpserver.NewApp( app := httpserver.NewApp(
directdeposit, // directdeposit,
enetPulseSvc, // telebirrSvc,
atlasVirtualGameService,
veliVirtualGameService,
orchestrationSvc,
telebirrSvc,
arifpaySvc, arifpaySvc,
santimpaySvc, // santimpaySvc,
issueReportingSvc, issueReportingSvc,
instSvc, instSvc,
currSvc, currSvc,
@ -402,26 +347,15 @@ func main() {
JwtAccessExpiry: cfg.AccessExpiry, JwtAccessExpiry: cfg.AccessExpiry,
}, },
userSvc, userSvc,
ticketSvc, // chapaSvc,
betSvc,
// reportSvc, // Make sure httpserver.NewApp accepts this parameter
chapaSvc,
walletSvc,
transactionSvc, transactionSvc,
branchSvc, branchSvc,
companySvc, companySvc,
notificationSvc, notificationSvc,
oddsSvc,
eventSvc,
leagueSvc,
referalSvc, referalSvc,
raffleSvc, raffleSvc,
bonusSvc, bonusSvc,
virtualGameSvc,
aleaService,
// veliService,
recommendationSvc, recommendationSvc,
resultSvc,
statSvc, statSvc,
cfg, cfg,
domain.MongoDBLogger, domain.MongoDBLogger,

View File

@ -1,381 +1,260 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto; CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Locations Initial Data
INSERT INTO branch_locations (key, value) -- ======================================================
VALUES ('addis_ababa', 'Addis Ababa'), -- Global Settings (LMS)
('dire_dawa', 'Dire Dawa'), -- ======================================================
('mekelle', 'Mekelle'),
('adama', 'Adama'),
('awassa', 'Awassa'),
('bahir_dar', 'Bahir Dar'),
('gonder', 'Gonder'),
('dessie', 'Dessie'),
('jimma', 'Jimma'),
('jijiga', 'Jijiga'),
('shashamane', 'Shashamane'),
('bishoftu', 'Bishoftu'),
('sodo', 'Sodo'),
('arba_minch', 'Arba Minch'),
('hosaena', 'Hosaena'),
('harar', 'Harar'),
('dilla', 'Dilla'),
('nekemte', 'Nekemte'),
('debre_birhan', 'Debre Birhan'),
('asella', 'Asella'),
('debre_markos', 'Debre Markos'),
('kombolcha', 'Kombolcha'),
('debre_tabor', 'Debre Tabor'),
('adigrat', 'Adigrat'),
('areka', 'Areka'),
('weldiya', 'Weldiya'),
('sebeta', 'Sebeta'),
('burayu', 'Burayu'),
('shire', 'Shire'),
('ambo', 'Ambo'),
('arsi_negele', 'Arsi Negele'),
('aksum', 'Aksum'),
('gambela', 'Gambela'),
('bale_robe', 'Bale Robe'),
('butajira', 'Butajira'),
('batu', 'Batu'),
('boditi', 'Boditi'),
('adwa', 'Adwa'),
('yirgalem', 'Yirgalem'),
('waliso', 'Waliso'),
('welkite', 'Welkite'),
('gode', 'Gode'),
('meki', 'Meki'),
('negele_borana', 'Negele Borana'),
('alaba_kulito', 'Alaba Kulito'),
('alamata,', 'Alamata,'),
('chiro', 'Chiro'),
('tepi', 'Tepi'),
('durame', 'Durame'),
('goba', 'Goba'),
('assosa', 'Assosa'),
('gimbi', 'Gimbi'),
('wukro', 'Wukro'),
('haramaya', 'Haramaya'),
('mizan_teferi', 'Mizan Teferi'),
('sawla', 'Sawla'),
('mojo', 'Mojo'),
('dembi_dolo', 'Dembi Dolo'),
('aleta_wendo', 'Aleta Wendo'),
('metu', 'Metu'),
('mota', 'Mota'),
('fiche', 'Fiche'),
('finote_selam', 'Finote Selam'),
('bule_hora_town', 'Bule Hora Town'),
('bonga', 'Bonga'),
('kobo', 'Kobo'),
('jinka', 'Jinka'),
('dangila', 'Dangila'),
('degehabur', 'Degehabur'),
('bedessa', 'Bedessa'),
('agaro', 'Agaro') ON CONFLICT (key) DO
UPDATE
SET value = EXCLUDED.value;
-- Settings Initial Data
INSERT INTO global_settings (key, value) INSERT INTO global_settings (key, value)
VALUES ('sms_provider', 'afro_message'), VALUES
('max_number_of_outcomes', '30'), ('platform_name', 'Yimaru LMS'),
('max_unsettled_bets', '100'), ('default_language', 'en'),
('bet_amount_limit', '10000000'), ('allow_self_signup', 'true'),
('daily_ticket_limit', '50'), ('otp_expiry_minutes', '5'),
('total_winnings_limit', '100000000'), ('certificate_enabled', 'true'),
('total_winnings_notify', '10000000'), ('max_courses_per_instructor', '50')
('amount_for_bet_referral', '1000000'), ON CONFLICT (key) DO NOTHING;
('cashback_amount_cap', '1000'),
('default_winning_limit', '5000000'), -- ======================================================
('referral_reward_amount', '10000'), -- Organizations (Tenants)
('cashback_percentage', '0.2'), -- ======================================================
('default_max_referrals', '15'), INSERT INTO organizations (
('minimum_bet_amount', '100'), id,
('bet_duplicate_limit', '5'), name,
('send_email_on_bet_finish', 'true'), slug,
('send_sms_on_bet_finish', 'false'), owner_id,
('welcome_bonus_active', 'false'), is_active,
('welcome_bonus_multiplier', '1.5'), created_at,
('welcome_bonus_cap', '100000'), updated_at
('welcome_bonus_count', '3'), )
('welcome_bonus_expiry', '10') ON CONFLICT (key) DO NOTHING; VALUES (
1,
'Yimaru Academy',
'yimaru-academy',
1,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
slug = EXCLUDED.slug,
is_active = EXCLUDED.is_active,
updated_at = CURRENT_TIMESTAMP;
-- ======================================================
-- Users -- Users
-- Roles: SUPER_ADMIN, ORG_ADMIN, INSTRUCTOR, STUDENT
-- ======================================================
INSERT INTO users ( INSERT INTO users (
id, id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
password, password,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at,
updated_at,
suspended, suspended,
company_id organization_id,
created_at,
updated_at
) )
VALUES ( VALUES
(
1, 1,
'John', 'Sarah',
'Doe', 'Connor',
'john.doe@example.com', 'SarahC',
'sarah.connor@yimaru.com',
NULL, NULL,
crypt('password@123', gen_salt('bf'))::bytea, crypt('password@123', gen_salt('bf'))::bytea,
'customer', 'SUPER_ADMIN',
35,
'Masters',
'USA',
'California',
TRUE, TRUE,
FALSE, FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE, FALSE,
1 NULL,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
), ),
( (
2, 2,
'Test', 'Test',
'Admin', 'Instructor',
'test.admin@gmail.com', 'InstructorT',
'instructor@yimaru.com',
'0988554466', '0988554466',
crypt('password@123', gen_salt('bf'))::bytea, crypt('password@123', gen_salt('bf'))::bytea,
'admin', 'INSTRUCTOR',
30,
'Bachelors',
'USA',
'New York',
TRUE, TRUE,
TRUE, TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE, FALSE,
1 1,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
), ),
( (
3, 3,
'Samuel', 'Demo',
'Tariku', 'Student',
'cybersamt@gmail.com', 'DemoS',
'0911111111', 'student@yimaru.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea, crypt('password@123', gen_salt('bf'))::bytea,
'super_admin', 'STUDENT',
22,
'High School',
'USA',
'Texas',
TRUE, TRUE,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE, FALSE,
NULL
),
(
4,
'Kirubel',
'Kibru',
'kirubel.jkl679@gmail.com',
'0911554486',
crypt('password@123', gen_salt('bf'))::bytea,
'super_admin',
TRUE,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE, FALSE,
NULL 1,
) ON CONFLICT (id) DO CURRENT_TIMESTAMP,
UPDATE CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO UPDATE
SET first_name = EXCLUDED.first_name, SET first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name, last_name = EXCLUDED.last_name,
nick_name = EXCLUDED.nick_name,
email = EXCLUDED.email, email = EXCLUDED.email,
phone_number = EXCLUDED.phone_number, phone_number = EXCLUDED.phone_number,
password = EXCLUDED.password, password = EXCLUDED.password,
role = EXCLUDED.role, role = EXCLUDED.role,
age = EXCLUDED.age,
education_level = EXCLUDED.education_level,
country = EXCLUDED.country,
region = EXCLUDED.region,
email_verified = EXCLUDED.email_verified, email_verified = EXCLUDED.email_verified,
phone_verified = EXCLUDED.phone_verified, phone_verified = EXCLUDED.phone_verified,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at,
suspended = EXCLUDED.suspended, suspended = EXCLUDED.suspended,
company_id = EXCLUDED.company_id; organization_id = EXCLUDED.organization_id,
-- Supported Operations updated_at = CURRENT_TIMESTAMP;
INSERT INTO supported_operations (id, name, description)
VALUES (1, 'SportBook', 'Sportbook operations'), -- ======================================================
(2, 'Virtual', 'Virtual operations') ON CONFLICT (id) DO -- Courses
UPDATE -- ======================================================
SET name = EXCLUDED.name, INSERT INTO courses (
description = EXCLUDED.description;
-- Wallets
INSERT INTO wallets (
id, id,
balance, organization_id,
is_withdraw, instructor_id,
is_bettable, title,
is_transferable,
user_id,
type,
currency,
is_active,
created_at,
updated_at
)
VALUES (
1,
10000,
TRUE,
TRUE,
TRUE,
1,
'regular_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
2,
5000,
FALSE,
TRUE,
TRUE,
1,
'static_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
3,
100000000,
TRUE,
TRUE,
TRUE,
2,
'company_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
4,
50000000,
TRUE,
TRUE,
TRUE,
2,
'branch_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (id) DO
UPDATE
SET balance = EXCLUDED.balance,
is_withdraw = EXCLUDED.is_withdraw,
is_bettable = EXCLUDED.is_bettable,
is_transferable = EXCLUDED.is_transferable,
user_id = EXCLUDED.user_id,
type = EXCLUDED.type,
currency = EXCLUDED.currency,
is_active = EXCLUDED.is_active,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at;
-- Customer Wallets
INSERT INTO customer_wallets (
id,
customer_id,
regular_wallet_id,
static_wallet_id
)
VALUES (1, 1, 1, 2) ON CONFLICT (id) DO
UPDATE
SET customer_id = EXCLUDED.customer_id,
regular_wallet_id = EXCLUDED.regular_wallet_id,
static_wallet_id = EXCLUDED.static_wallet_id;
-- Company
INSERT INTO companies (
id,
name,
slug,
admin_id,
wallet_id,
deducted_percentage,
is_active,
created_at,
updated_at
)
VALUES (
1,
'FortuneBets',
'fortunebets',
2,
3,
0.10,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (id) DO
UPDATE
SET name = EXCLUDED.name,
slug = EXCLUDED.slug,
admin_id = EXCLUDED.admin_id,
wallet_id = EXCLUDED.wallet_id,
deducted_percentage = EXCLUDED.deducted_percentage,
is_active = EXCLUDED.is_active,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at;
-- Branch
INSERT INTO branches (
id,
name,
location,
wallet_id,
branch_manager_id,
company_id,
is_self_owned,
profit_percent,
is_active,
created_at,
updated_at
)
VALUES (
1,
'Test Branch',
'addis_ababa',
4,
2,
1,
TRUE,
0.10,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (id) DO
UPDATE
SET name = EXCLUDED.name,
location = EXCLUDED.location,
wallet_id = EXCLUDED.wallet_id,
branch_manager_id = EXCLUDED.branch_manager_id,
company_id = EXCLUDED.company_id,
is_self_owned = EXCLUDED.is_self_owned,
profit_percent = EXCLUDED.profit_percent,
is_active = EXCLUDED.is_active,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at;
-- Bonus
INSERT INTO user_bonuses (
id,
name,
description, description,
type, level,
user_id, language,
reward_amount, is_published,
expires_at created_at,
updated_at
) )
VALUES ( VALUES (
1, 1,
'Welcome Bonus',
'Awarded for deposit number (1 / 3)',
'welcome_bonus',
1, 1,
1000, 2,
now() + INTERVAL '1 day' 'Introduction to Go Programming',
) ON CONFLICT (id) DO 'Learn the fundamentals of Go for backend development.',
UPDATE 'beginner',
SET name = EXCLUDED.name, 'en',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO UPDATE
SET title = EXCLUDED.title,
description = EXCLUDED.description, description = EXCLUDED.description,
type = EXCLUDED.type, is_published = EXCLUDED.is_published,
user_id = EXCLUDED.user_id, updated_at = CURRENT_TIMESTAMP;
reward_amount = EXCLUDED.reward_amount,
expires_at = EXCLUDED.expires_at; -- ======================================================
-- Course Modules
-- ======================================================
INSERT INTO course_modules (
id,
course_id,
title,
position,
created_at
)
VALUES (
1,
1,
'Getting Started',
1,
CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO NOTHING;
-- ======================================================
-- Lessons
-- ======================================================
INSERT INTO lessons (
id,
module_id,
title,
content_type,
content_url,
duration_minutes,
position,
created_at
)
VALUES (
1,
1,
'What is Go?',
'video',
'https://example.com/go-intro',
15,
1,
CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO NOTHING;
-- ======================================================
-- Enrollments
-- ======================================================
INSERT INTO enrollments (
id,
course_id,
student_id,
enrolled_at
)
VALUES (
1,
1,
3,
CURRENT_TIMESTAMP
)
ON CONFLICT (id) DO NOTHING;
-- ======================================================
-- Notifications (Sample)
-- ======================================================
INSERT INTO notifications (
user_id,
type,
level,
channel,
title,
message,
created_at
)
VALUES (
3,
'course_enrolled',
'info',
'in_app',
'Welcome to your course',
'You have successfully enrolled in Introduction to Go Programming.',
CURRENT_TIMESTAMP
);

View File

@ -1,148 +0,0 @@
-- Users
INSERT INTO users (
id,
first_name,
last_name,
email,
phone_number,
password,
role,
email_verified,
phone_verified,
created_at,
updated_at,
suspended,
company_id
)
VALUES (
5,
'Test',
'Veli',
'test.veli@example.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea,
'customer',
TRUE,
FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE,
1
),
(
6,
'Kirubel',
'Kibru',
'modernkibru@gmail.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea,
'customer',
TRUE,
FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE,
1
) ON CONFLICT (id) DO
UPDATE
SET first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
email = EXCLUDED.email,
phone_number = EXCLUDED.phone_number,
password = EXCLUDED.password,
role = EXCLUDED.role,
email_verified = EXCLUDED.email_verified,
phone_verified = EXCLUDED.phone_verified,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at,
suspended = EXCLUDED.suspended,
company_id = EXCLUDED.company_id;
INSERT INTO wallets (
id,
balance,
is_withdraw,
is_bettable,
is_transferable,
user_id,
type,
currency,
is_active,
created_at,
updated_at
)
VALUES (
5,
10000,
TRUE,
TRUE,
TRUE,
5,
'regular_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
6,
5000,
FALSE,
TRUE,
TRUE,
5,
'static_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
7,
1000000,
TRUE,
TRUE,
TRUE,
6,
'regular_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
),
(
8,
5000,
FALSE,
TRUE,
TRUE,
6,
'static_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (id) DO
UPDATE
SET balance = EXCLUDED.balance,
is_withdraw = EXCLUDED.is_withdraw,
is_bettable = EXCLUDED.is_bettable,
is_transferable = EXCLUDED.is_transferable,
user_id = EXCLUDED.user_id,
type = EXCLUDED.type,
currency = EXCLUDED.currency,
is_active = EXCLUDED.is_active,
created_at = EXCLUDED.created_at,
updated_at = EXCLUDED.updated_at;
-- Customer Wallets
INSERT INTO customer_wallets (
id,
customer_id,
regular_wallet_id,
static_wallet_id
)
VALUES (2, 5, 5, 6),
(3, 6, 7, 8) ON CONFLICT (id) DO
UPDATE
SET customer_id = EXCLUDED.customer_id,
regular_wallet_id = EXCLUDED.regular_wallet_id,
static_wallet_id = EXCLUDED.static_wallet_id;

View File

@ -1,31 +1,69 @@
-- For each table with an id sequence -- ======================================================
-- Reset sequences for LMS tables
-- ======================================================
SELECT setval( SELECT setval(
pg_get_serial_sequence('users', 'id'), pg_get_serial_sequence('users', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM users; FROM users;
SELECT setval( SELECT setval(
pg_get_serial_sequence('wallets', 'id'), pg_get_serial_sequence('organizations', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM wallets; FROM organizations;
SELECT setval( SELECT setval(
pg_get_serial_sequence('customer_wallets', 'id'), pg_get_serial_sequence('courses', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM customer_wallets; FROM courses;
SELECT setval( SELECT setval(
pg_get_serial_sequence('companies', 'id'), pg_get_serial_sequence('course_modules', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM companies; FROM course_modules;
SELECT setval( SELECT setval(
pg_get_serial_sequence('branches', 'id'), pg_get_serial_sequence('lessons', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM branches; FROM lessons;
SELECT setval( SELECT setval(
pg_get_serial_sequence('supported_operations', 'id'), pg_get_serial_sequence('enrollments', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM supported_operations; FROM enrollments;
SELECT setval(
pg_get_serial_sequence('assessments', 'id'),
COALESCE(MAX(id), 1)
)
FROM assessments;
SELECT setval(
pg_get_serial_sequence('assessment_submissions', 'id'),
COALESCE(MAX(id), 1)
)
FROM assessment_submissions;
SELECT setval(
pg_get_serial_sequence('notifications', 'id'),
COALESCE(MAX(id), 1)
)
FROM notifications;
SELECT setval(
pg_get_serial_sequence('referral_codes', 'id'),
COALESCE(MAX(id), 1)
)
FROM referral_codes;
SELECT setval(
pg_get_serial_sequence('user_referrals', 'id'),
COALESCE(MAX(id), 1)
)
FROM user_referrals;

View File

@ -1,217 +0,0 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
DO $$
DECLARE _admin_id bigint;
_manager_id bigint;
_company_wallet_id bigint;
_company_id bigint;
_branch_id bigint;
_branch_wallet_id bigint;
_cashier_id bigint;
BEGIN
INSERT INTO users (
first_name,
last_name,
email,
phone_number,
password,
role,
email_verified,
phone_verified,
created_at,
updated_at,
suspended
)
VALUES (
'Admin',
'BetFidel',
'admin.betfidel@gmail.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea,
'admin',
TRUE,
FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE
) ON CONFLICT (email) DO
UPDATE
SET updated_at = EXCLUDED.updated_at
RETURNING id INTO STRICT _admin_id;
INSERT INTO users (
first_name,
last_name,
email,
phone_number,
password,
role,
email_verified,
phone_verified,
created_at,
updated_at,
suspended,
company_id
)
VALUES (
'Manager',
'BetFidel',
'manager.betfidel@gmail.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea,
'branch_manager',
TRUE,
FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE,
_company_id
) ON CONFLICT (email) DO
UPDATE
SET updated_at = EXCLUDED.updated_at
RETURNING id INTO STRICT _manager_id;
INSERT INTO wallets (
balance,
is_withdraw,
is_bettable,
is_transferable,
user_id,
type,
currency,
is_active,
created_at,
updated_at
)
VALUES (
10000,
TRUE,
TRUE,
TRUE,
_admin_id,
'company_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
RETURNING id INTO STRICT _company_wallet_id;
INSERT INTO companies (
name,
slug,
admin_id,
wallet_id,
deducted_percentage,
is_active,
created_at,
updated_at
)
VALUES (
'FidelBet',
'betfidel',
_admin_id,
_company_wallet_id,
0.15,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (slug) DO
UPDATE
SET updated_at = EXCLUDED.updated_at
RETURNING id INTO STRICT _company_id;
UPDATE users
SET company_id = _company_id
WHERE id = _admin_id;
INSERT INTO wallets (
balance,
is_withdraw,
is_bettable,
is_transferable,
user_id,
type,
currency,
is_active,
created_at,
updated_at
)
VALUES (
10000,
TRUE,
TRUE,
TRUE,
_admin_id,
'branch_wallet',
'ETB',
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
RETURNING id INTO STRICT _branch_wallet_id;
INSERT INTO branches (
name,
location,
wallet_id,
branch_manager_id,
company_id,
is_self_owned,
profit_percent,
is_active,
created_at,
updated_at
)
VALUES (
'Test Branch',
'addis_ababa',
_branch_wallet_id,
_manager_id,
_company_id,
TRUE,
0.10,
TRUE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) ON CONFLICT (wallet_id) DO
UPDATE
SET updated_at = EXCLUDED.updated_at
RETURNING id INTO STRICT _branch_id;
INSERT INTO users (
first_name,
last_name,
email,
phone_number,
password,
role,
email_verified,
phone_verified,
created_at,
updated_at,
suspended,
company_id
)
VALUES (
'Cashier',
'BetFidel',
'cashier.betfidel@gmail.com',
NULL,
crypt('password@123', gen_salt('bf'))::bytea,
'cashier',
TRUE,
FALSE,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
FALSE,
_company_id
) ON CONFLICT (email) DO
UPDATE
SET updated_at = EXCLUDED.updated_at
RETURNING id INTO STRICT _cashier_id;
INSERT INTO branch_cashiers (user_id, branch_id)
VALUES (_cashier_id, _branch_id);
RAISE NOTICE 'BETFIDEL_DEV_DATA (Admin ID: %, Company Wallet ID: %, Company ID: %)',
_admin_id,
_company_wallet_id,
_company_id;
RAISE NOTICE 'BETFIDEL_DEV_DATA (Branch ID: %, Branch Wallet ID: %, Manager ID: %)',
_branch_id,
_branch_wallet_id,
_manager_id;
RAISE NOTICE 'BETFIDEL_DEV_DATA (Cashier ID: %)',
_cashier_id;
END $$;

View File

@ -1,85 +0,0 @@
DROP TABLE IF EXISTS virtual_game_providers;
-- Drop tables that depend on service_type_setting
DROP TABLE IF EXISTS service_type_setting;
-- Drop product-related tables and types
DROP TABLE IF EXISTS product;
DROP TYPE IF EXISTS tier_group;
-- Drop onboarding-related tables and types
DROP TABLE IF EXISTS verification_key;
DROP TABLE IF EXISTS onboarding_user;
DROP TYPE IF EXISTS verification_status;
DROP TYPE IF EXISTS onboarding_status;
-- Drop staff-related tables and types
DROP TABLE IF EXISTS staff_session;
DROP TABLE IF EXISTS user_agent;
DROP TABLE IF EXISTS staff;
DROP TYPE IF EXISTS password_status;
-- Drop mobile app-related tables and types
DROP TABLE IF EXISTS user_devices;
DROP TABLE IF EXISTS user_session;
DROP TABLE IF EXISTS linked_accounts;
DROP TABLE IF EXISTS users;
DROP TYPE IF EXISTS device_type;
DROP TYPE IF EXISTS registeration_type;
DROP TYPE IF EXISTS customer_group;
-- Drop linked accounts and beneficiary tables and types
DROP TABLE IF EXISTS beneficiary;
DROP TYPE IF EXISTS fund_destination;
-- Drop maker checker-related tables and types
DROP TABLE IF EXISTS workflow;
DROP TYPE IF EXISTS approval_status;
DROP TYPE IF EXISTS action_type;
DROP TYPE IF EXISTS context_type;
-- Drop authorization-related tables and types
DROP TRIGGER IF EXISTS enforce_unique_array ON policy;
DROP FUNCTION IF EXISTS check_unique_array;
DROP TABLE IF EXISTS policy;
DROP TABLE IF EXISTS roles;
DROP TYPE IF EXISTS policy_action;
DROP TYPE IF EXISTS policy_object;
-- Drop bank-related tables and types
DROP TABLE IF EXISTS bank;
DROP TABLE IF EXISTS flagged_users;
-- Drop transaction-related tables and types
DROP TABLE IF EXISTS transaction_daily;
DROP TABLE IF EXISTS system_limits;
DROP TABLE IF EXISTS transactions;
DROP TYPE IF EXISTS payment_status;
DROP TYPE IF EXISTS service_type;
DROP TYPE IF EXISTS channel;
DROP TYPE IF EXISTS transaction_category;
DROP TYPE IF EXISTS registration_type;
-- Drop branches and related tables
DROP TABLE IF EXISTS branches;
DROP TABLE IF EXISTS cities;
DROP TABLE IF EXISTS districts;
DROP TABLE IF EXISTS regions;
-- Drop activity logs
DROP TABLE IF EXISTS activity;
-- Drop ussd account and related enums
DROP TABLE IF EXISTS ussd_account;
DROP TYPE IF EXISTS ua_pin_status;
DROP TYPE IF EXISTS ua_status;
DROP TYPE IF EXISTS ua_registaration_type;
-- Drop FortuneBet
DROP TABLE IF EXISTS tickets;
DROP TABLE IF EXISTS ticket_outcomes;
DROP TABLE IF EXISTS bets;
DROP TABLE IF EXISTS bet_outcomes;
DROP TABLE IF EXISTS wallets;
DROP TABLE IF EXISTS customer_wallets;
DROP TABLE IF EXISTS wallet_transfer;
DROP TABLE IF EXISTS transactions;
DROP TABLE IF EXISTS branches;
DROP TABLE IF EXISTS companies;
DROP TABLE IF EXISTS supported_operations;
DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS otps;
DROP TABLE IF EXISTS odds;
DROP TABLE IF EXISTS events;
DROP TABLE IF EXISTS leagues;
DROP TABLE IF EXISTS teams;
DROP TABLE IF EXISTS settings;
DROP TABLE IF EXISTS bonus;
DROP TABLE IF EXISTS flags;
-- DELETE FROM wallet_transfer;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,51 @@
-- =========================================
-- Notifications
-- =========================================
DROP TABLE IF EXISTS notifications;
-- =========================================
-- Issue Reporting
-- =========================================
DROP TABLE IF EXISTS reported_issues;
-- =========================================
-- Assessments
-- =========================================
DROP TABLE IF EXISTS assessment_submissions;
DROP TABLE IF EXISTS assessments;
-- =========================================
-- Progress & Enrollment
-- =========================================
DROP TABLE IF EXISTS lesson_progress;
DROP TABLE IF EXISTS enrollments;
-- =========================================
-- Course Content Structure
-- =========================================
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS course_modules;
DROP TABLE IF EXISTS courses;
-- =========================================
-- Organization Settings
-- =========================================
DROP TABLE IF EXISTS organization_settings;
DROP TABLE IF EXISTS global_settings;
-- =========================================
-- Organizations (Tenants)
-- =========================================
DROP TABLE IF EXISTS organizations;
-- =========================================
-- Authentication & Security
-- =========================================
DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS otps;
-- =========================================
-- Users
-- =========================================
DROP TABLE IF EXISTS users;

View File

@ -0,0 +1,195 @@
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
nick_name VARCHAR(100),
email VARCHAR(255) UNIQUE,
phone_number VARCHAR(20) UNIQUE,
role VARCHAR(50) NOT NULL, -- SUPER_ADMIN, ORG_ADMIN, INSTRUCTOR, STUDENT, SUPPORT
password BYTEA NOT NULL,
age INT,
education_level VARCHAR(100),
country VARCHAR(100),
region VARCHAR(100),
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
phone_verified BOOLEAN NOT NULL DEFAULT FALSE,
suspended BOOLEAN NOT NULL DEFAULT FALSE,
suspended_at TIMESTAMPTZ,
organization_id BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
CHECK (email IS NOT NULL OR phone_number IS NOT NULL),
UNIQUE (email, organization_id),
UNIQUE (phone_number, organization_id)
);
CREATE TABLE refresh_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
revoked BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE otps (
id BIGSERIAL PRIMARY KEY,
sent_to VARCHAR(255) NOT NULL,
medium VARCHAR(50) NOT NULL, -- email, sms
otp_for VARCHAR(50) NOT NULL, -- login, reset_password, verify
otp VARCHAR(10) NOT NULL,
used BOOLEAN NOT NULL DEFAULT FALSE,
used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE organizations (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
slug TEXT UNIQUE NOT NULL,
owner_id BIGINT NOT NULL REFERENCES users(id),
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE courses (
id BIGSERIAL PRIMARY KEY,
organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
instructor_id BIGINT NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
description TEXT,
level TEXT,
language TEXT,
is_published BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE course_modules (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
title TEXT NOT NULL,
position INT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE lessons (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT NOT NULL REFERENCES course_modules(id) ON DELETE CASCADE,
title TEXT NOT NULL,
content_type TEXT NOT NULL, -- video, article, quiz
content_url TEXT,
duration_minutes INT,
position INT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE enrollments (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
student_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
enrolled_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMPTZ,
UNIQUE (course_id, student_id)
);
CREATE TABLE lesson_progress (
id BIGSERIAL PRIMARY KEY,
lesson_id BIGINT NOT NULL REFERENCES lessons(id) ON DELETE CASCADE,
student_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
completed BOOLEAN NOT NULL DEFAULT FALSE,
completed_at TIMESTAMPTZ,
UNIQUE (lesson_id, student_id)
);
CREATE TABLE assessments (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
title TEXT NOT NULL,
type TEXT NOT NULL, -- quiz, assignment
total_score INT NOT NULL,
due_date TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE assessment_submissions (
id BIGSERIAL PRIMARY KEY,
assessment_id BIGINT NOT NULL REFERENCES assessments(id) ON DELETE CASCADE,
student_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
score INT,
feedback TEXT,
submitted_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
graded_at TIMESTAMPTZ,
UNIQUE (assessment_id, student_id)
);
CREATE TABLE IF NOT EXISTS notifications (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type TEXT NOT NULL CHECK (
type IN (
'course_enrolled',
'lesson_completed',
'assessment_assigned',
'assessment_submitted',
'assessment_graded',
'course_completed',
'certificate_issued',
'announcement',
'otp_sent',
'signup_welcome',
'system_alert'
)
),
level TEXT NOT NULL CHECK (
level IN ('info', 'warning', 'success', 'error')
),
channel TEXT CHECK (
channel IN ('email', 'sms', 'push', 'in_app')
),
title TEXT NOT NULL,
message TEXT NOT NULL,
payload JSONB,
is_read BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
read_at TIMESTAMPTZ
);
CREATE TABLE global_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE organization_settings (
organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (organization_id, key)
);
CREATE TABLE IF NOT EXISTS reported_issues (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
user_role VARCHAR(255) NOT NULL,
subject TEXT NOT NULL,
description TEXT NOT NULL,
issue_type TEXT NOT NULL,
-- e.g., "deposit", "withdrawal", "bet", "technical"
status TEXT NOT NULL DEFAULT 'pending',
-- pending, in_progress, resolved, rejected
metadata JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

View File

@ -1,2 +0,0 @@
DROP TABLE notifications;
DROP TABLE wallet_threshold_notifications;

View File

@ -1,54 +0,0 @@
CREATE TABLE IF NOT EXISTS notifications (
id VARCHAR(255) NOT NULL PRIMARY KEY,
recipient_id BIGSERIAL NOT NULL,
type TEXT NOT NULL CHECK (
type IN (
'cash_out_success',
'deposit_success',
'withdraw_success',
'bet_placed',
'daily_report',
'report_request',
'high_loss_on_bet',
'bet_overload',
'signup_welcome',
'otp_sent',
'wallet_threshold',
'wallet_updated',
'transfer_failed',
'transfer_success',
'admin_alert',
'bet_result',
'transfer_rejected',
'approval_required',
'bonus_awarded'
)
),
level TEXT NOT NULL CHECK (level IN ('info', 'error', 'warning', 'success')),
error_severity TEXT CHECK (
error_severity IN ('low', 'medium', 'high', 'critical', 'fatal')
),
reciever TEXT NOT NULL CHECK (reciever IN ('admin', 'customer')),
is_read BOOLEAN NOT NULL DEFAULT FALSE,
delivery_status TEXT NOT NULL CHECK (delivery_status IN ('pending', 'sent', 'failed')),
delivery_channel TEXT CHECK (
delivery_channel IN ('email', 'sms', 'push', 'in-app')
),
payload JSONB NOT NULL,
priority INTEGER,
version INTEGER NOT NULL DEFAULT 0,
timestamp TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
img TEXT,
expires TIMESTAMPTZ NOT NULL,
metadata JSONB
);
CREATE TABLE IF NOT EXISTS wallet_threshold_notifications (
company_id BIGINT NOT NULL,
threshold FLOAT NOT NULL,
notified_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (company_id, threshold)
);
CREATE INDEX idx_wallet_threshold_notifications_company ON wallet_threshold_notifications(company_id);
CREATE INDEX idx_notifications_recipient_id ON notifications (recipient_id);
CREATE INDEX idx_notifications_timestamp ON notifications (timestamp);
CREATE INDEX idx_notifications_type ON notifications (type);

View File

@ -0,0 +1,45 @@
CREATE TABLE IF NOT EXISTS referral_codes (
id BIGSERIAL PRIMARY KEY,
code VARCHAR(12) NOT NULL UNIQUE,
referrer_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
max_uses INT,
current_uses INT NOT NULL DEFAULT 0,
incentive_type TEXT NOT NULL CHECK (
incentive_type IN (
'course_access',
'discount',
'certificate_unlock',
'feature_unlock'
)
),
incentive_value TEXT, -- e.g. course_id, percentage, feature_key
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_referral_codes_referrer_id
ON referral_codes (referrer_id);
CREATE INDEX idx_referral_codes_code
ON referral_codes (code);
CREATE TABLE IF NOT EXISTS user_referrals (
id BIGSERIAL PRIMARY KEY,
referrer_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
referred_user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
referral_code_id BIGINT NOT NULL REFERENCES referral_codes(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (referred_user_id),
UNIQUE (referrer_id, referred_user_id)
);

View File

@ -1,37 +0,0 @@
-- CREATE TYPE ReferralStatus AS ENUM ('PENDING', 'COMPLETED', 'EXPIRED', 'CANCELLED');
-- CREATE TABLE IF NOT EXISTS referral_settings (
-- id BIGSERIAL PRIMARY KEY,
-- referral_reward_amount DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
-- cashback_percentage DECIMAL(5, 2) NOT NULL DEFAULT 0.00,
-- bet_referral_bonus_percentage NUMERIC DEFAULT 5.0,
-- max_referrals INTEGER NOT NULL DEFAULT 0,
-- expires_after_days INTEGER NOT NULL DEFAULT 30,
-- updated_by VARCHAR(255) NOT NULL,
-- created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- version INTEGER NOT NULL DEFAULT 0,
-- CONSTRAINT referral_reward_amount_positive CHECK (referral_reward_amount >= 0),
-- CONSTRAINT cashback_percentage_range CHECK (
-- cashback_percentage >= 0
-- AND cashback_percentage <= 100
-- )
-- );
CREATE TABLE IF NOT EXISTS referral_codes (
id BIGSERIAL PRIMARY KEY,
referral_code VARCHAR(10) NOT NULL UNIQUE,
referrer_id BIGINT NOT NULL UNIQUE REFERENCES users (id),
company_id BIGINT NOT NULL REFERENCES companies (id),
is_active BOOLEAN NOT NULL DEFAULT true,
number_of_referrals BIGINT NOT NULL,
reward_amount BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT reward_amount_positive CHECK (reward_amount >= 0)
);
CREATE INDEX idx_referrals_referrer_id ON referral_codes (referrer_id);
CREATE TABLE IF NOT EXISTS user_referrals (
id BIGSERIAL PRIMARY KEY,
referred_id BIGINT UNIQUE NOT NULL REFERENCES users (id),
referral_code_id BIGINT NOT NULL REFERENCES referral_codes (id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

View File

@ -1,5 +0,0 @@
DROP TABLE IF EXISTS vitrual_games;
DROP TABLE IF EXISTS virtual_game_transactions;
DROP TABLE IF EXISTS virtual_game_sessions;

View File

@ -1,64 +0,0 @@
CREATE TABLE virtual_game_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
game_id VARCHAR(50) NOT NULL,
session_token VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE virtual_game_transactions (
id BIGSERIAL PRIMARY KEY,
-- session_id BIGINT NOT NULL REFERENCES virtual_game_sessions(id),
user_id BIGINT NOT NULL REFERENCES users(id),
company_id BIGINT,
provider VARCHAR(100),
game_id VARCHAR(100),
wallet_id BIGINT NOT NULL REFERENCES wallets(id),
transaction_type VARCHAR(20) NOT NULL,
amount BIGINT NOT NULL,
currency VARCHAR(3) NOT NULL,
external_transaction_id VARCHAR(100) NOT NULL UNIQUE, -- PopOK transaction ID
status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- PENDING, COMPLETED, FAILED
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE virtual_game_histories (
id BIGSERIAL PRIMARY KEY,
-- session_id VARCHAR(100), -- nullable
user_id BIGINT NOT NULL,
company_id BIGINT,
provider VARCHAR(100),
wallet_id BIGINT, -- nullable
game_id BIGINT, -- nullable
transaction_type VARCHAR(20) NOT NULL, -- e.g., BET, WIN, CANCEL
amount BIGINT NOT NULL, -- in cents or smallest currency unit
currency VARCHAR(10) NOT NULL,
external_transaction_id VARCHAR(100) NOT NULL,
reference_transaction_id VARCHAR(100), -- nullable, for cancel/refund
status VARCHAR(20) NOT NULL DEFAULT 'COMPLETED', -- transaction status
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS favorite_games (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
game_id BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Optional: Indexes for performance
CREATE INDEX idx_virtual_game_user_id ON virtual_game_histories(user_id);
CREATE INDEX idx_virtual_game_transaction_type ON virtual_game_histories(transaction_type);
CREATE INDEX idx_virtual_game_game_id ON virtual_game_histories(game_id);
CREATE INDEX idx_virtual_game_external_transaction_id ON virtual_game_histories(external_transaction_id);
CREATE INDEX idx_virtual_game_sessions_user_id ON virtual_game_sessions(user_id);
-- CREATE INDEX idx_virtual_game_transactions_session_id ON virtual_game_transactions(session_id);
CREATE INDEX idx_virtual_game_transactions_user_id ON virtual_game_transactions(user_id);
ALTER TABLE favorite_games
ADD CONSTRAINT unique_user_game_favorite UNIQUE (user_id, game_id);

View File

@ -1 +0,0 @@
DROP TABLE IF EXISTS results;

View File

@ -1,15 +0,0 @@
CREATE TABLE IF NOT EXISTS results (
id BIGSERIAL PRIMARY KEY,
bet_outcome_id BIGINT NOT NULL,
event_id BIGINT NOT NULL,
odd_id BIGINT NOT NULL,
market_id BIGINT NOT NULL,
status INT NOT NULL,
score VARCHAR(255),
full_time_score VARCHAR(255),
half_time_score VARCHAR(255),
ss VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (bet_outcome_id) REFERENCES bet_outcomes (id)
);

View File

@ -1,2 +0,0 @@
DROP TABLE IF EXISTS virtual_games;
DROP TABLE IF EXISTS user_game_interactions;

View File

@ -1,28 +0,0 @@
CREATE TABLE IF NOT EXISTS virtual_games (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
provider VARCHAR(100) NOT NULL,
category VARCHAR(100) NOT NULL,
min_bet DECIMAL(15,2) NOT NULL,
max_bet DECIMAL(15,2) NOT NULL,
volatility VARCHAR(50) NOT NULL,
rtp DECIMAL(5,2) NOT NULL,
is_featured BOOLEAN DEFAULT false,
popularity_score INTEGER DEFAULT 0,
thumbnail_url TEXT,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE user_game_interactions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
game_id BIGINT NOT NULL REFERENCES virtual_games(id),
interaction_type VARCHAR(50) NOT NULL,
-- 'view', 'play', 'bet', 'favorite'
amount DECIMAL(15, 2),
duration_seconds INTEGER,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_user_game_interactions_user ON user_game_interactions(user_id);
CREATE INDEX idx_user_game_interactions_game ON user_game_interactions(game_id);

View File

@ -1,11 +0,0 @@
DROP TABLE IF EXISTS enetpulse_sports;
DROP TABLE IF EXISTS enetpulse_tournament_templates;
DROP TABLE IF EXISTS enetpulse_tournaments;
DROP TABLE IF EXISTS enetpulse_tournament_stages;
DROP TABLE IF EXISTS enetpulse_fixtures;
DROP TABLE IF EXISTS enetpulse_results;
DROP TABLE IF EXISTS enetpulse_result_participants;
DROP TABLE IF EXISTS enetpulse_result_referees;
DROP TABLE IF EXISTS enetpulse_outcome_types;
DROP TABLE IF EXISTS enetpulse_preodds;
DROP TABLE IF EXISTS enetpulse_preodds_bettingoffers;

View File

@ -1,227 +0,0 @@
CREATE TABLE IF NOT EXISTS enetpulse_sports (
id BIGSERIAL PRIMARY KEY,
sport_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- from API "name"
updates_count INT DEFAULT 0, -- from API "n"
last_updated_at TIMESTAMPTZ, -- from API "ut"
status INT DEFAULT 1, -- optional status (active/inactive)
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS enetpulse_tournament_templates (
id BIGSERIAL PRIMARY KEY,
template_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- from API "name"
sport_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_sports(sport_id) ON DELETE CASCADE,
gender VARCHAR(20) DEFAULT 'unknown', -- from API "gender" {male, female, mixed, unknown}
updates_count INT DEFAULT 0, -- from API "n"
last_updated_at TIMESTAMPTZ, -- from API "ut"
status INT DEFAULT 1, -- optional status (active/inactive)
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS enetpulse_tournaments (
id BIGSERIAL PRIMARY KEY,
tournament_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- from API "name"
-- Link to the template it belongs to:
tournament_template_fk VARCHAR(50) NOT NULL
REFERENCES enetpulse_tournament_templates(template_id) ON DELETE CASCADE,
updates_count INT DEFAULT 0, -- from API "n"
last_updated_at TIMESTAMPTZ, -- from API "ut"
status INT DEFAULT 1, -- optional active/inactive flag
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS enetpulse_tournament_stages (
id BIGSERIAL PRIMARY KEY,
stage_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- from API "name"
tournament_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_tournaments(tournament_id) ON DELETE CASCADE,
-- from API "tournamentFK"
gender VARCHAR(20) DEFAULT 'unknown', -- from API "gender" {male, female, mixed, unknown}
country_fk VARCHAR(50), -- from API "countryFK"
country_name VARCHAR(255), -- from API "country_name"
start_date TIMESTAMPTZ, -- from API "startdate"
end_date TIMESTAMPTZ, -- from API "enddate"
updates_count INT DEFAULT 0, -- from API "n"
last_updated_at TIMESTAMPTZ, -- from API "ut"
status INT DEFAULT 1, -- optional status (active/inactive)
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_enetpulse_tournament_stages_tournament_fk
ON enetpulse_tournament_stages (tournament_fk);
CREATE TABLE IF NOT EXISTS enetpulse_fixtures (
id BIGSERIAL PRIMARY KEY,
fixture_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- fixture name (e.g. 12 de Junio-Sol de America)
sport_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_sports(sport_id) ON DELETE CASCADE,
tournament_fk VARCHAR(50), -- raw tournamentFK (optional)
tournament_template_fk VARCHAR(50) REFERENCES enetpulse_tournament_templates(template_id) ON DELETE CASCADE,
-- tournament_stage_fk VARCHAR(50) REFERENCES enetpulse_tournament_stages(stage_id) ON DELETE CASCADE,
-- tournament_stage_name VARCHAR(255),
tournament_name VARCHAR(255),
tournament_template_name VARCHAR(255),
sport_name VARCHAR(255),
gender VARCHAR(20),
start_date TIMESTAMPTZ NOT NULL, -- startdate
status_type VARCHAR(50), -- Not started, Live, Finished
status_desc_fk VARCHAR(50), -- status_descFK
round_type_fk VARCHAR(50), -- round_typeFK
updates_count INT DEFAULT 0, -- n
last_updated_at TIMESTAMPTZ, -- ut
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS enetpulse_results (
id BIGSERIAL PRIMARY KEY,
result_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(255) NOT NULL, -- event name (e.g. Brentford-Manchester City)
sport_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_sports(sport_id) ON DELETE CASCADE,
tournament_fk VARCHAR(50),
tournament_template_fk VARCHAR(50) REFERENCES enetpulse_tournament_templates(template_id) ON DELETE CASCADE,
-- tournament_stage_fk VARCHAR(50) REFERENCES enetpulse_tournament_stages(stage_id) ON DELETE CASCADE,
-- tournament_stage_name VARCHAR(255),
tournament_name VARCHAR(255),
tournament_template_name VARCHAR(255),
sport_name VARCHAR(255),
start_date TIMESTAMPTZ NOT NULL, -- startdate
status_type VARCHAR(50), -- e.g. Finished
status_desc_fk VARCHAR(50), -- status_descFK
round_type_fk VARCHAR(50), -- round_typeFK
updates_count INT DEFAULT 0, -- n
last_updated_at TIMESTAMPTZ, -- ut
-- Optional metadata (dynamic but common fields are included)
round VARCHAR(50),
live VARCHAR(10),
venue_name VARCHAR(255),
livestats_plus VARCHAR(10),
livestats_type VARCHAR(50),
commentary VARCHAR(50),
lineup_confirmed BOOLEAN,
verified BOOLEAN,
spectators INT,
-- Time-related metadata
game_started TIMESTAMPTZ,
first_half_ended TIMESTAMPTZ,
second_half_started TIMESTAMPTZ,
second_half_ended TIMESTAMPTZ,
game_ended TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
-- Event Participants (teams involved in the result)
CREATE TABLE IF NOT EXISTS enetpulse_result_participants (
id BIGSERIAL PRIMARY KEY,
participant_map_id VARCHAR(50) NOT NULL UNIQUE, -- from event_participants.*.id
result_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_results(result_id) ON DELETE CASCADE,
participant_fk VARCHAR(50) NOT NULL, -- team/player FK (from API participantFK)
number INT, -- 1 or 2 (home/away indicator)
name VARCHAR(255), -- team/player name
gender VARCHAR(20),
type VARCHAR(50),
country_fk VARCHAR(50),
country_name VARCHAR(100),
-- Result details
ordinary_time VARCHAR(10),
running_score VARCHAR(10),
halftime VARCHAR(10),
final_result VARCHAR(10),
last_updated_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Referees / Match officials
CREATE TABLE IF NOT EXISTS enetpulse_result_referees (
id BIGSERIAL PRIMARY KEY,
result_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_results(result_id) ON DELETE CASCADE,
referee_fk VARCHAR(50),
assistant1_referee_fk VARCHAR(50),
assistant2_referee_fk VARCHAR(50),
fourth_referee_fk VARCHAR(50),
var1_referee_fk VARCHAR(50),
var2_referee_fk VARCHAR(50),
last_updated_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS enetpulse_outcome_types (
id BIGSERIAL PRIMARY KEY,
outcome_type_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
name VARCHAR(100) NOT NULL, -- e.g. "1x2"
description VARCHAR(255), -- e.g. "1x2 - 3Way"
updates_count INT DEFAULT 0, -- maps to "n"
last_updated_at TIMESTAMPTZ, -- maps to "ut"
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
-- Table for pre-match odds (main outcome entries)
CREATE TABLE IF NOT EXISTS enetpulse_preodds (
id BIGSERIAL PRIMARY KEY,
preodds_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
event_fk BIGINT NOT NULL, -- maps to objectFK/event
outcome_type_fk INT, -- outcome_typeFK
outcome_scope_fk INT, -- outcome_scopeFK
outcome_subtype_fk INT, -- outcome_subtypeFK
event_participant_number INT, -- event_participant_number
iparam VARCHAR(50),
iparam2 VARCHAR(50),
dparam VARCHAR(50),
dparam2 VARCHAR(50),
sparam VARCHAR(50),
updates_count INT DEFAULT 0, -- maps to "n"
last_updated_at TIMESTAMPTZ, -- maps to "ut"
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
-- Table for nested betting offers within preodds
CREATE TABLE IF NOT EXISTS enetpulse_preodds_bettingoffers (
id BIGSERIAL PRIMARY KEY,
bettingoffer_id VARCHAR(50) NOT NULL UNIQUE, -- from API "id"
preodds_fk VARCHAR(50) NOT NULL REFERENCES enetpulse_preodds(preodds_id) ON DELETE CASCADE,
bettingoffer_status_fk INT, -- bettingoffer_statusFK
odds_provider_fk INT, -- odds_providerFK
odds NUMERIC(10,4), -- current odds
odds_old NUMERIC(10,4), -- previous odds
active BOOLEAN, -- maps "yes"/"no" to boolean
coupon_key VARCHAR(255), -- couponKey
updates_count INT DEFAULT 0, -- maps to "n"
last_updated_at TIMESTAMPTZ, -- maps to "ut"
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);

View File

@ -1,4 +0,0 @@
DROP TABLE IF EXISTS virtual_game_financial_reports;
DROP TABLE IF EXISTS virtual_game_company_reports;
DROP TABLE IF EXISTS virtual_game_player_cashflow_reports;
DROP TABLE IF EXISTS virtual_game_player_session_reports;

View File

@ -1,73 +0,0 @@
CREATE TABLE IF NOT EXISTS virtual_game_financial_reports (
id BIGSERIAL PRIMARY KEY,
game_id VARCHAR(150) NOT NULL REFERENCES virtual_games(game_id) ON DELETE CASCADE,
provider_id VARCHAR(100) NOT NULL REFERENCES virtual_game_providers(provider_id) ON DELETE CASCADE,
report_date DATE NOT NULL,
report_type VARCHAR(50) NOT NULL DEFAULT 'daily',
total_bets NUMERIC(18,2) DEFAULT 0,
total_wins NUMERIC(18,2) DEFAULT 0,
ggr NUMERIC(18,2) GENERATED ALWAYS AS (total_bets - total_wins) STORED,
rtp NUMERIC(5,2) GENERATED ALWAYS AS (
CASE WHEN total_bets > 0 THEN (total_wins / total_bets) * 100 ELSE 0 END
) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS virtual_game_company_reports (
id BIGSERIAL PRIMARY KEY,
company_id BIGINT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
provider_id VARCHAR(100) NOT NULL REFERENCES virtual_game_providers(provider_id) ON DELETE CASCADE,
report_date DATE NOT NULL,
report_type VARCHAR(50) NOT NULL DEFAULT 'daily',
total_bet_amount NUMERIC(18,2) DEFAULT 0,
total_win_amount NUMERIC(18,2) DEFAULT 0,
net_profit NUMERIC(18,2) GENERATED ALWAYS AS (total_bet_amount - total_win_amount) STORED,
profit_margin NUMERIC(6,3) GENERATED ALWAYS AS (
CASE WHEN total_bet_amount > 0 THEN (total_bet_amount - total_win_amount) / total_bet_amount ELSE 0 END
) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS virtual_game_player_activity_reports (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- Reporting scope
report_date DATE NOT NULL,
report_type VARCHAR(50) NOT NULL DEFAULT 'daily',
-- Cashflow information
total_deposits NUMERIC(18,2) DEFAULT 0,
total_withdrawals NUMERIC(18,2) DEFAULT 0,
net_contribution NUMERIC(18,2) GENERATED ALWAYS AS (
total_deposits - total_withdrawals
) STORED,
-- Betting and win/loss analytics
total_bet_amount NUMERIC(18,2) DEFAULT 0,
total_win_amount NUMERIC(18,2) DEFAULT 0,
net_result NUMERIC(18,2) GENERATED ALWAYS AS (
total_bet_amount - total_win_amount
) STORED,
rounds_played BIGINT DEFAULT 0,
avg_bet_size NUMERIC(18,4) GENERATED ALWAYS AS (
CASE WHEN rounds_played > 0 THEN total_bet_amount / rounds_played ELSE 0 END
) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);

View File

@ -6,8 +6,8 @@ WHERE (
OR phone_number = $2 OR phone_number = $2
) )
AND ( AND (
company_id = sqlc.narg('company_id') organization_id = sqlc.narg('organization_id')
OR sqlc.narg('company_id') IS NULL OR sqlc.narg('organization_id') IS NULL
); );
-- name: CreateRefreshToken :exec -- name: CreateRefreshToken :exec
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked) INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked)

View File

@ -1,240 +0,0 @@
-- name: CreateBet :one
INSERT INTO bets (
amount,
total_odds,
status,
user_id,
is_shop_bet,
outcomes_hash,
fast_code,
company_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;
-- name: CreateBetOutcome :copyfrom
INSERT INTO bet_outcomes (
bet_id,
sport_id,
event_id,
odd_id,
home_team_name,
away_team_name,
market_id,
market_name,
odd,
odd_name,
odd_header,
odd_handicap,
expires
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13
);
-- name: GetAllBets :many
SELECT *
FROM bet_with_outcomes
wHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
AND (
is_shop_bet = sqlc.narg('is_shop_bet')
OR sqlc.narg('is_shop_bet') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND (
cashed_out = sqlc.narg('cashed_out')
OR sqlc.narg('cashed_out') IS NULL
)
AND (
full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetTotalBets :one
SELECT COUNT(*)
FROM bets
wHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
AND (
is_shop_bet = sqlc.narg('is_shop_bet')
OR sqlc.narg('is_shop_bet') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND (
cashed_out = sqlc.narg('cashed_out')
OR sqlc.narg('cashed_out') IS NULL
)
AND (
full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetBetByID :one
SELECT *
FROM bet_with_outcomes
WHERE id = $1;
-- name: GetBetByUserID :many
SELECT *
FROM bet_with_outcomes
WHERE user_id = $1;
-- name: GetBetByFastCode :one
SELECT *
FROM bet_with_outcomes
WHERE fast_code = $1
LIMIT 1;
-- name: GetBetsForCashback :many
SELECT *
FROM bet_with_outcomes
WHERE status = 2
AND processed = false;
-- name: GetBetOutcomeViewByEventID :many
SELECT bet_outcomes.*,
users.first_name,
users.last_name,
bets.amount,
bets.total_odds,
companies.name as company_name
FROM bet_outcomes
JOIN bets ON bets.id = bet_outcomes.bet_id
JOIN users ON bets.user_id = users.id
JOIN companies ON bets.company_id = companies.id
WHERE bet_outcomes.event_id = $1
AND (
bets.company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
bet_outcomes.status = sqlc.narg('filter_status')
OR sqlc.narg('filter_status') IS NULL
)
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: TotalBetOutcomeViewByEventID :one
SELECT count(*)
FROM bet_outcomes
JOIN bets ON bets.id = bet_outcomes.bet_id
WHERE bet_outcomes.event_id = $1
AND (
bets.company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
bet_outcomes.status = sqlc.narg('filter_status')
OR sqlc.narg('filter_status') IS NULL
);
-- name: GetBetOutcomeByEventID :many
SELECT *
FROM bet_outcomes
WHERE (event_id = $1)
AND (
status = sqlc.narg('filter_status')
OR sqlc.narg('filter_status') IS NULL
OR status = sqlc.narg('filter_status_2')
OR sqlc.narg('filter_status_2') IS NULL
);
-- name: GetBetOutcomeByBetID :many
SELECT *
FROM bet_outcomes
WHERE bet_id = $1;
-- name: GetBetOutcomeCountByOddID :one
SELECT COUNT(*)
FROM bet_outcomes
WHERE odd_id = $1;
-- name: GetBetCountByUserID :one
SELECT COUNT(*)
FROM bets
WHERE user_id = $1
AND outcomes_hash = $2;
-- name: GetBetCountByOutcomesHash :one
SELECT COUNT(*)
FROM bets
WHERE outcomes_hash = $1;
-- name: UpdateCashOut :exec
UPDATE bets
SET cashed_out = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: UpdateBetOutcomeStatus :one
UPDATE bet_outcomes
SET status = $1
WHERE id = $2
RETURNING *;
-- name: UpdateBetOutcomeStatusByBetID :one
UPDATE bet_outcomes
SET status = $1
WHERE bet_id = $2
RETURNING *;
-- name: UpdateBetOutcomeStatusForEvent :many
UPDATE bet_outcomes
SEt status = $1
WHERE event_id = $2
RETURNING *;
-- name: UpdateBetOutcomeStatusForOddID :many
UPDATE bet_outcomes
SEt status = $1
WHERE odd_id = $2
RETURNING *;
-- name: BulkUpdateBetOutcomeStatusByOddIDs :exec
UPDATE bet_outcomes
SET status = $1
WHERE odd_id = ANY(sqlc.arg('odd_ids')::BIGINT []);
-- name: UpdateStatus :exec
UPDATE bets
SET status = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: UpdateBetWithCashback :exec
UPDATE bets
SET processed = $1
WHERE id = $2;
-- name: DeleteBet :exec
DELETE FROM bets
WHERE id = $1;
-- name: DeleteBetOutcome :exec
DELETE FROM bet_outcomes
WHERE bet_id = $1;

View File

@ -1,191 +0,0 @@
-- name: GetBetStatsByInterval :many
SELECT DATE_TRUNC(sqlc.narg('interval'), created_at)::timestamp AS date,
COUNT(*) as total_bets,
SUM(amount) AS total_stake,
SUM(
CASE
WHEN status = 0 THEN 1
ELSE 0
END
) as active_bets,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 2 THEN 1
ELSE 0
END
) as total_losses,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as win_balance,
COUNT(*) FILTER (
WHERE status = 5
) AS number_of_unsettled,
SUM(
CASE
WHEN status = 5 THEN amount
ELSE 0
END
) AS total_unsettled_amount,
COUNT(*) FILTER (
WHERE is_shop_bet = TRUE
) AS total_shop_bets
FROM bets
WHERE (
bets.company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
);
-- name: GetBetSummary :one
SELECT SUM(amount) as total_stakes,
COUNT(*) as total_bets,
SUM(
CASE
WHEN status = 0 THEN 1
ELSE 0
END
) as active_bets,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 2 THEN 1
ELSE 0
END
) as total_losses,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as win_balance
FROM bets
wHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetBetStats :many
SELECT DATE(created_at) as date,
COUNT(*) as total_bets,
SUM(amount) as total_stakes,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as total_payouts,
AVG(total_odds) as average_odds
FROM bets
wHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
is_shop_bet = sqlc.narg('is_shop_bet')
OR sqlc.narg('is_shop_bet') IS NULL
)
AND (
cashed_out = sqlc.narg('cashed_out')
OR sqlc.narg('cashed_out') IS NULL
)
AND (
full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
GROUP BY DATE(created_at)
ORDER BY DATE(created_at);
-- name: GetTotalBetsMadeInRange :one
SELECT COUNT(*) AS total_bets
FROM bets
WHERE created_at BETWEEN sqlc.arg('from') AND sqlc.arg('to');
-- name: GetTotalCashMadeInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_made
FROM bets
WHERE created_at BETWEEN sqlc.arg('from') AND sqlc.arg('to');
-- name: GetTotalCashOutInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_out
FROM bets
WHERE created_at BETWEEN sqlc.arg('from') AND sqlc.arg('to')
AND cashed_out = true;
-- name: GetTotalCashBacksInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_backs
FROM bets
WHERE created_at BETWEEN sqlc.arg('from') AND sqlc.arg('to')
AND status = 5;
-- name: GetMarketPopularity :one
WITH market_counts AS (
SELECT DATE(b.created_at) as date,
bo.market_name,
COUNT(*) as bet_count,
ROW_NUMBER() OVER (
PARTITION BY DATE(b.created_at)
ORDER BY COUNT(*) DESC
) as rank
FROM bets b
JOIN bet_outcomes bo ON b.id = bo.bet_id
WHERE bo.market_name IS NOT NULL
AND (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
GROUP BY DATE(b.created_at),
bo.market_name
)
SELECT date,
market_name
FROM market_counts
WHERE rank = 1;

View File

@ -1,61 +0,0 @@
-- name: CreateUserBonus :one
INSERT INTO user_bonuses (
name,
description,
type,
user_id,
reward_amount,
expires_at
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
-- name: GetAllUserBonuses :many
SELECT *
FROM user_bonuses
WHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetUserBonusByID :one
SELECT *
FROM user_bonuses
WHERE id = $1;
-- name: GetBonusCount :one
SELECT COUNT(*)
FROM user_bonuses
WHERE (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
);
-- name: GetBonusStats :one
SELECT COUNT(*) AS total_bonuses,
COALESCE(SUM(reward_amount), 0)::bigint AS total_reward_earned,
COUNT(
CASE
WHEN is_claimed = true THEN 1
END
) AS claimed_bonuses,
COUNT(
CASE
WHEN expires_at < now() THEN 1
END
) AS expired_bonuses
FROM user_bonuses
JOIN users ON users.id = user_bonuses.user_id
WHERE (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
);
-- name: UpdateUserBonus :exec
UPDATE user_bonuses
SET is_claimed = $2
WHERE id = $1;
-- name: DeleteUserBonus :exec
DELETE FROM user_bonuses
WHERE id = $1;

View File

@ -1,109 +1,109 @@
-- name: CreateBranch :one -- -- name: CreateBranch :one
INSERT INTO branches ( -- INSERT INTO branches (
name, -- name,
location, -- location,
wallet_id, -- wallet_id,
branch_manager_id, -- branch_manager_id,
company_id, -- company_id,
is_self_owned, -- is_self_owned,
profit_percent -- profit_percent
) -- )
VALUES ($1, $2, $3, $4, $5, $6, $7) -- VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING *; -- RETURNING *;
-- name: CreateSupportedOperation :one -- -- name: CreateSupportedOperation :one
INSERT INTO supported_operations (name, description) -- INSERT INTO supported_operations (name, description)
VALUES ($1, $2) -- VALUES ($1, $2)
RETURNING *; -- RETURNING *;
-- name: CreateBranchOperation :one -- -- name: CreateBranchOperation :one
INSERT INTO branch_operations (operation_id, branch_id) -- INSERT INTO branch_operations (operation_id, branch_id)
VALUES ($1, $2) -- VALUES ($1, $2)
RETURNING *; -- RETURNING *;
-- name: CreateBranchCashier :one -- -- name: CreateBranchCashier :one
INSERT INTO branch_cashiers (user_id, branch_id) -- INSERT INTO branch_cashiers (user_id, branch_id)
VALUES ($1, $2) -- VALUES ($1, $2)
RETURNING *; -- RETURNING *;
-- name: GetAllBranches :many -- -- name: GetAllBranches :many
SELECT * -- SELECT *
FROM branch_details -- FROM branch_details
WHERE ( -- WHERE (
company_id = sqlc.narg('company_id') -- company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL -- OR sqlc.narg('company_id') IS NULL
) -- )
AND ( -- AND (
is_active = sqlc.narg('is_active') -- is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL -- OR sqlc.narg('is_active') IS NULL
) -- )
AND ( -- AND (
branch_manager_id = sqlc.narg('branch_manager_id') -- branch_manager_id = sqlc.narg('branch_manager_id')
OR sqlc.narg('branch_manager_id') IS NULL -- OR sqlc.narg('branch_manager_id') IS NULL
) -- )
AND ( -- AND (
name ILIKE '%' || sqlc.narg('query') || '%' -- name ILIKE '%' || sqlc.narg('query') || '%'
OR location ILIKE '%' || sqlc.narg('query') || '%' -- OR location ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL -- OR sqlc.narg('query') IS NULL
) -- )
AND ( -- AND (
created_at > sqlc.narg('created_before') -- created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL -- OR sqlc.narg('created_before') IS NULL
) -- )
AND ( -- AND (
created_at < sqlc.narg('created_after') -- created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL -- OR sqlc.narg('created_after') IS NULL
); -- );
-- name: GetBranchByID :one -- -- name: GetBranchByID :one
SELECT * -- SELECT *
FROM branch_details -- FROM branch_details
WHERE id = $1; -- WHERE id = $1;
-- name: GetBranchByCompanyID :many -- -- name: GetBranchByCompanyID :many
SELECT * -- SELECT *
FROM branch_details -- FROM branch_details
WHERE company_id = $1; -- WHERE company_id = $1;
-- name: GetBranchByManagerID :many -- -- name: GetBranchByManagerID :many
SELECT * -- SELECT *
FROM branch_details -- FROM branch_details
WHERE branch_manager_id = $1; -- WHERE branch_manager_id = $1;
-- name: SearchBranchByName :many -- -- name: SearchBranchByName :many
SELECT * -- SELECT *
FROM branch_details -- FROM branch_details
WHERE name ILIKE '%' || $1 || '%' -- WHERE name ILIKE '%' || $1 || '%'
AND ( -- AND (
company_id = sqlc.narg('company_id') -- company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL -- OR sqlc.narg('company_id') IS NULL
); -- );
-- name: GetAllSupportedOperations :many -- -- name: GetAllSupportedOperations :many
SELECT * -- SELECT *
FROM supported_operations; -- FROM supported_operations;
-- name: GetBranchOperations :many -- -- name: GetBranchOperations :many
SELECT branch_operations.*, -- SELECT branch_operations.*,
supported_operations.name, -- supported_operations.name,
supported_operations.description -- supported_operations.description
FROM branch_operations -- FROM branch_operations
JOIN supported_operations ON branch_operations.operation_id = supported_operations.id -- JOIN supported_operations ON branch_operations.operation_id = supported_operations.id
WHERE branch_operations.branch_id = $1; -- WHERE branch_operations.branch_id = $1;
-- name: GetBranchByCashier :one -- -- name: GetBranchByCashier :one
SELECT branches.* -- SELECT branches.*
FROM branch_cashiers -- FROM branch_cashiers
JOIN branches ON branch_cashiers.branch_id = branches.id -- JOIN branches ON branch_cashiers.branch_id = branches.id
WHERE branch_cashiers.user_id = $1; -- WHERE branch_cashiers.user_id = $1;
-- name: UpdateBranch :one -- -- name: UpdateBranch :one
UPDATE branches -- UPDATE branches
SET name = COALESCE(sqlc.narg(name), name), -- SET name = COALESCE(sqlc.narg(name), name),
location = COALESCE(sqlc.narg(location), location), -- location = COALESCE(sqlc.narg(location), location),
branch_manager_id = COALESCE(sqlc.narg(branch_manager_id), branch_manager_id), -- branch_manager_id = COALESCE(sqlc.narg(branch_manager_id), branch_manager_id),
company_id = COALESCE(sqlc.narg(company_id), company_id), -- company_id = COALESCE(sqlc.narg(company_id), company_id),
is_self_owned = COALESCE(sqlc.narg(is_self_owned), is_self_owned), -- is_self_owned = COALESCE(sqlc.narg(is_self_owned), is_self_owned),
is_active = COALESCE(sqlc.narg(is_active), is_active), -- is_active = COALESCE(sqlc.narg(is_active), is_active),
profit_percent = COALESCE(sqlc.narg(profit_percent), profit_percent), -- profit_percent = COALESCE(sqlc.narg(profit_percent), profit_percent),
updated_at = CURRENT_TIMESTAMP -- updated_at = CURRENT_TIMESTAMP
WHERE id = $1 -- WHERE id = $1
RETURNING *; -- RETURNING *;
-- name: DeleteBranch :exec -- -- name: DeleteBranch :exec
DELETE FROM branches -- DELETE FROM branches
WHERE id = $1; -- WHERE id = $1;
-- name: DeleteBranchOperation :exec -- -- name: DeleteBranchOperation :exec
DELETE FROM branch_operations -- DELETE FROM branch_operations
WHERE operation_id = $1 -- WHERE operation_id = $1
AND branch_id = $2; -- AND branch_id = $2;
-- name: DeleteBranchCashier :exec -- -- name: DeleteBranchCashier :exec
DELETE FROM branch_cashiers -- DELETE FROM branch_cashiers
WHERE user_id = $1; -- WHERE user_id = $1;

View File

@ -1,128 +1,128 @@
-- name: UpdateBranchStats :exec -- -- name: UpdateBranchStats :exec
WITH -- Aggregate bet data per branch -- WITH -- Aggregate bet data per branch
bet_stats AS ( -- bet_stats AS (
SELECT branch_id, -- SELECT branch_id,
COUNT(*) AS total_bets, -- COUNT(*) AS total_bets,
COALESCE(SUM(amount), 0) AS total_stake, -- COALESCE(SUM(amount), 0) AS total_stake,
COALESCE( -- COALESCE(
SUM(amount) * MAX(profit_percent), -- SUM(amount) * MAX(profit_percent),
0 -- 0
) AS deducted_stake, -- ) AS deducted_stake,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN cashed_out THEN amount -- WHEN cashed_out THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_cash_out, -- ) AS total_cash_out,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN status = 3 THEN amount -- WHEN status = 3 THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_cash_backs, -- ) AS total_cash_backs,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE status = 5 -- WHERE status = 5
) AS number_of_unsettled, -- ) AS number_of_unsettled,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN status = 5 THEN amount -- WHEN status = 5 THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_unsettled_amount -- ) AS total_unsettled_amount
FROM shop_bet_detail -- FROM shop_bet_detail
LEFT JOIN branches ON branches.id = shop_bet_detail.branch_id -- LEFT JOIN branches ON branches.id = shop_bet_detail.branch_id
GROUP BY branch_id -- GROUP BY branch_id
), -- ),
cashier_stats AS ( -- cashier_stats AS (
SELECT branch_id, -- SELECT branch_id,
COUNT(*) AS total_cashiers -- COUNT(*) AS total_cashiers
FROM branch_cashiers -- FROM branch_cashiers
GROUP BY branch_id -- GROUP BY branch_id
) -- )
INSERT INTO branch_stats ( -- INSERT INTO branch_stats (
branch_id, -- branch_id,
branch_name, -- branch_name,
company_id, -- company_id,
company_name, -- company_name,
company_slug, -- company_slug,
interval_start, -- interval_start,
total_bets, -- total_bets,
total_stake, -- total_stake,
deducted_stake, -- deducted_stake,
total_cash_out, -- total_cash_out,
total_cash_backs, -- total_cash_backs,
number_of_unsettled, -- number_of_unsettled,
total_unsettled_amount, -- total_unsettled_amount,
total_cashiers, -- total_cashiers,
updated_at -- updated_at
) -- )
SELECT br.id AS branch_id, -- SELECT br.id AS branch_id,
br.name AS branch_name, -- br.name AS branch_name,
c.id AS company_id, -- c.id AS company_id,
c.name AS company_name, -- c.name AS company_name,
c.slug AS company_slug, -- c.slug AS company_slug,
DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start, -- DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start,
COALESCE(bs.total_bets, 0) AS total_bets, -- COALESCE(bs.total_bets, 0) AS total_bets,
COALESCE(bs.total_stake, 0) AS total_stake, -- COALESCE(bs.total_stake, 0) AS total_stake,
COALESCE(bs.deducted_stake, 0) AS deducted_stake, -- COALESCE(bs.deducted_stake, 0) AS deducted_stake,
COALESCE(bs.total_cash_out, 0) AS total_cash_out, -- COALESCE(bs.total_cash_out, 0) AS total_cash_out,
COALESCE(bs.total_cash_backs, 0) AS total_cash_backs, -- COALESCE(bs.total_cash_backs, 0) AS total_cash_backs,
COALESCE(bs.number_of_unsettled, 0) AS number_of_unsettled, -- COALESCE(bs.number_of_unsettled, 0) AS number_of_unsettled,
COALESCE(bs.total_unsettled_amount, 0) AS total_unsettled_amount, -- COALESCE(bs.total_unsettled_amount, 0) AS total_unsettled_amount,
COALESCE(bc.total_cashiers, 0) AS total_cashiers, -- COALESCE(bc.total_cashiers, 0) AS total_cashiers,
NOW() AS updated_at -- NOW() AS updated_at
FROM branches br -- FROM branches br
LEFT JOIN companies c ON c.id = br.company_id -- LEFT JOIN companies c ON c.id = br.company_id
LEFT JOIN bet_stats bs ON bs.branch_id = br.id -- LEFT JOIN bet_stats bs ON bs.branch_id = br.id
LEFT JOIN cashier_stats bc ON bc.branch_id = br.id ON CONFLICT (branch_id, interval_start) DO -- LEFT JOIN cashier_stats bc ON bc.branch_id = br.id ON CONFLICT (branch_id, interval_start) DO
UPDATE -- UPDATE
SET total_bets = EXCLUDED.total_bets, -- SET total_bets = EXCLUDED.total_bets,
total_stake = EXCLUDED.total_stake, -- total_stake = EXCLUDED.total_stake,
deducted_stake = EXCLUDED.deducted_stake, -- deducted_stake = EXCLUDED.deducted_stake,
total_cash_out = EXCLUDED.total_cash_out, -- total_cash_out = EXCLUDED.total_cash_out,
total_cash_backs = EXCLUDED.total_cash_backs, -- total_cash_backs = EXCLUDED.total_cash_backs,
number_of_unsettled = EXCLUDED.number_of_unsettled, -- number_of_unsettled = EXCLUDED.number_of_unsettled,
total_unsettled_amount = EXCLUDED.total_unsettled_amount, -- total_unsettled_amount = EXCLUDED.total_unsettled_amount,
total_cashiers = EXCLUDED.total_cashiers, -- total_cashiers = EXCLUDED.total_cashiers,
updated_at = EXCLUDED.updated_at; -- updated_at = EXCLUDED.updated_at;
-- name: GetBranchStatsByID :many -- -- name: GetBranchStatsByID :many
SELECt * -- SELECt *
FROM branch_stats -- FROM branch_stats
WHERE branch_id = $1 -- WHERE branch_id = $1
ORDER BY interval_start DESC; -- ORDER BY interval_start DESC;
-- name: GetBranchStats :many -- -- name: GetBranchStats :many
SELECT DATE_TRUNC(sqlc.narg('interval'), interval_start)::timestamp AS interval_start, -- SELECT DATE_TRUNC(sqlc.narg('interval'), interval_start)::timestamp AS interval_start,
branch_stats.branch_id, -- branch_stats.branch_id,
branch_stats.branch_name, -- branch_stats.branch_name,
branch_stats.company_id, -- branch_stats.company_id,
branch_stats.company_name, -- branch_stats.company_name,
branch_stats.company_slug, -- branch_stats.company_slug,
branch_stats.total_bets, -- branch_stats.total_bets,
branch_stats.total_stake, -- branch_stats.total_stake,
branch_stats.deducted_stake, -- branch_stats.deducted_stake,
branch_stats.total_cash_out, -- branch_stats.total_cash_out,
branch_stats.total_cash_backs, -- branch_stats.total_cash_backs,
branch_stats.number_of_unsettled, -- branch_stats.number_of_unsettled,
branch_stats.total_unsettled_amount, -- branch_stats.total_unsettled_amount,
branch_stats.total_cashiers, -- branch_stats.total_cashiers,
branch_stats.updated_at -- branch_stats.updated_at
FROM branch_stats -- FROM branch_stats
WHERE ( -- WHERE (
branch_stats.branch_id = sqlc.narg('branch_id') -- branch_stats.branch_id = sqlc.narg('branch_id')
OR sqlc.narg('branch_id') IS NULL -- OR sqlc.narg('branch_id') IS NULL
) -- )
AND ( -- AND (
branch_stats.company_id = sqlc.narg('company_id') -- branch_stats.company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL -- OR sqlc.narg('company_id') IS NULL
) -- )
GROUP BY interval_start -- GROUP BY interval_start
ORDER BY interval_start DESC; -- ORDER BY interval_start DESC;

View File

@ -1,39 +0,0 @@
-- name: GetCashiersByBranch :many
SELECT users.*
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE branch_cashiers.branch_id = $1;
-- name: GetAllCashiers :many
SELECT users.*,
branch_id,
branches.name AS branch_name,
branches.wallet_id AS branch_wallet,
branches.location As branch_location
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE (
first_name ILIKE '%' || sqlc.narg('query') || '%'
OR last_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
users.created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
users.created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetCashierByID :one
SELECT users.*,
branch_id,
branches.name AS branch_name,
branches.wallet_id AS branch_wallet,
branches.location As branch_location
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE users.id = $1;

View File

@ -1,56 +1,56 @@
-- name: CreateCompany :one -- -- name: CreateCompany :one
INSERT INTO companies ( -- INSERT INTO companies (
name, -- name,
slug, -- slug,
admin_id, -- admin_id,
wallet_id, -- wallet_id,
deducted_percentage, -- deducted_percentage,
is_active -- is_active
) -- )
VALUES ($1, $2, $3, $4, $5, $6) -- VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *; -- RETURNING *;
-- name: GetAllCompanies :many -- -- name: GetAllCompanies :many
SELECT * -- SELECT *
FROM companies_details -- FROM companies_details
WHERE ( -- WHERE (
name ILIKE '%' || sqlc.narg('query') || '%' -- name ILIKE '%' || sqlc.narg('query') || '%'
OR admin_first_name ILIKE '%' || sqlc.narg('query') || '%' -- OR admin_first_name ILIKE '%' || sqlc.narg('query') || '%'
OR admin_last_name ILIKE '%' || sqlc.narg('query') || '%' -- OR admin_last_name ILIKE '%' || sqlc.narg('query') || '%'
OR admin_phone_number ILIKE '%' || sqlc.narg('query') || '%' -- OR admin_phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL -- OR sqlc.narg('query') IS NULL
) -- )
AND ( -- AND (
created_at > sqlc.narg('created_before') -- created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL -- OR sqlc.narg('created_before') IS NULL
) -- )
AND ( -- AND (
created_at < sqlc.narg('created_after') -- created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL -- OR sqlc.narg('created_after') IS NULL
); -- );
-- name: GetCompanyByID :one -- -- name: GetCompanyByID :one
SELECT * -- SELECT *
FROM companies_details -- FROM companies_details
WHERE id = $1; -- WHERE id = $1;
-- name: GetCompanyUsingSlug :one -- -- name: GetCompanyUsingSlug :one
SELECT * -- SELECT *
FROM companies -- FROM companies
WHERE slug = $1; -- WHERE slug = $1;
-- name: SearchCompanyByName :many -- -- name: SearchCompanyByName :many
SELECT * -- SELECT *
FROM companies_details -- FROM companies_details
WHERE name ILIKE '%' || $1 || '%'; -- WHERE name ILIKE '%' || $1 || '%';
-- name: UpdateCompany :exec -- -- name: UpdateCompany :exec
UPDATE companies -- UPDATE companies
SET name = COALESCE(sqlc.narg(name), name), -- SET name = COALESCE(sqlc.narg(name), name),
admin_id = COALESCE(sqlc.narg(admin_id), admin_id), -- admin_id = COALESCE(sqlc.narg(admin_id), admin_id),
is_active = COALESCE(sqlc.narg(is_active), is_active), -- is_active = COALESCE(sqlc.narg(is_active), is_active),
deducted_percentage = COALESCE( -- deducted_percentage = COALESCE(
sqlc.narg(deducted_percentage), -- sqlc.narg(deducted_percentage),
deducted_percentage -- deducted_percentage
), -- ),
slug = COALESCE(sqlc.narg(slug), slug), -- slug = COALESCE(sqlc.narg(slug), slug),
updated_at = CURRENT_TIMESTAMP -- updated_at = CURRENT_TIMESTAMP
WHERE id = $1; -- WHERE id = $1;
-- name: DeleteCompany :exec -- -- name: DeleteCompany :exec
DELETE FROM companies -- DELETE FROM companies
WHERE id = $1; -- WHERE id = $1;

View File

@ -1,160 +1,160 @@
-- name: UpdateCompanyStats :exec -- -- name: UpdateCompanyStats :exec
WITH -- Aggregate bet data per company -- WITH -- Aggregate bet data per company
bet_stats AS ( -- bet_stats AS (
SELECT company_id, -- SELECT company_id,
COUNT(*) AS total_bets, -- COUNT(*) AS total_bets,
COALESCE(SUM(amount), 0) AS total_stake, -- COALESCE(SUM(amount), 0) AS total_stake,
COALESCE( -- COALESCE(
SUM(amount) * MAX(companies.deducted_percentage), -- SUM(amount) * MAX(companies.deducted_percentage),
0 -- 0
) AS deducted_stake, -- ) AS deducted_stake,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN cashed_out THEN amount -- WHEN cashed_out THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_cash_out, -- ) AS total_cash_out,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN status = 3 THEN amount -- WHEN status = 3 THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_cash_backs, -- ) AS total_cash_backs,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE status = 5 -- WHERE status = 5
) AS number_of_unsettled, -- ) AS number_of_unsettled,
COALESCE( -- COALESCE(
SUM( -- SUM(
CASE -- CASE
WHEN status = 5 THEN amount -- WHEN status = 5 THEN amount
ELSE 0 -- ELSE 0
END -- END
), -- ),
0 -- 0
) AS total_unsettled_amount -- ) AS total_unsettled_amount
FROM shop_bet_detail -- FROM shop_bet_detail
LEFT JOIN companies ON companies.id = shop_bet_detail.company_id -- LEFT JOIN companies ON companies.id = shop_bet_detail.company_id
GROUP BY company_id -- GROUP BY company_id
), -- ),
-- Aggregate user counts per company -- -- Aggregate user counts per company
user_stats AS ( -- user_stats AS (
SELECT company_id, -- SELECT company_id,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE role = 'admin' -- WHERE role = 'admin'
) AS total_admins, -- ) AS total_admins,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE role = 'branch_manager' -- WHERE role = 'branch_manager'
) AS total_managers, -- ) AS total_managers,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE role = 'cashier' -- WHERE role = 'cashier'
) AS total_cashiers, -- ) AS total_cashiers,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE role = 'customer' -- WHERE role = 'customer'
) AS total_customers, -- ) AS total_customers,
COUNT(*) FILTER ( -- COUNT(*) FILTER (
WHERE role = 'transaction_approver' -- WHERE role = 'transaction_approver'
) AS total_approvers -- ) AS total_approvers
FROM users -- FROM users
GROUP BY company_id -- GROUP BY company_id
), -- ),
-- Aggregate branch counts per company -- -- Aggregate branch counts per company
branch_stats AS ( -- branch_stats AS (
SELECT company_id, -- SELECT company_id,
COUNT(*) AS total_branches -- COUNT(*) AS total_branches
FROM branches -- FROM branches
GROUP BY company_id -- GROUP BY company_id
) -- Final combined aggregation -- ) -- Final combined aggregation
INSERT INTO company_stats ( -- INSERT INTO company_stats (
company_id, -- company_id,
company_name, -- company_name,
company_slug, -- company_slug,
interval_start, -- interval_start,
total_bets, -- total_bets,
total_stake, -- total_stake,
deducted_stake, -- deducted_stake,
total_cash_out, -- total_cash_out,
total_cash_backs, -- total_cash_backs,
number_of_unsettled, -- number_of_unsettled,
total_unsettled_amount, -- total_unsettled_amount,
total_admins, -- total_admins,
total_managers, -- total_managers,
total_cashiers, -- total_cashiers,
total_customers, -- total_customers,
total_approvers, -- total_approvers,
total_branches, -- total_branches,
updated_at -- updated_at
) -- )
SELECT c.id AS company_id, -- SELECT c.id AS company_id,
c.name AS company_name, -- c.name AS company_name,
c.slug AS company_slug, -- c.slug AS company_slug,
DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start, -- DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start,
COALESCE(b.total_bets, 0) AS total_bets, -- COALESCE(b.total_bets, 0) AS total_bets,
COALESCE(b.total_stake, 0) AS total_stake, -- COALESCE(b.total_stake, 0) AS total_stake,
COALESCE(b.deducted_stake, 0) AS deducted_stake, -- COALESCE(b.deducted_stake, 0) AS deducted_stake,
COALESCE(b.total_cash_out, 0) AS total_cash_out, -- COALESCE(b.total_cash_out, 0) AS total_cash_out,
COALESCE(b.total_cash_backs, 0) AS total_cash_backs, -- COALESCE(b.total_cash_backs, 0) AS total_cash_backs,
COALESCE(b.number_of_unsettled, 0) AS number_of_unsettled, -- COALESCE(b.number_of_unsettled, 0) AS number_of_unsettled,
COALESCE(b.total_unsettled_amount, 0) AS total_unsettled_amount, -- COALESCE(b.total_unsettled_amount, 0) AS total_unsettled_amount,
COALESCE(u.total_admins, 0) AS total_admins, -- COALESCE(u.total_admins, 0) AS total_admins,
COALESCE(u.total_managers, 0) AS total_managers, -- COALESCE(u.total_managers, 0) AS total_managers,
COALESCE(u.total_cashiers, 0) AS total_cashiers, -- COALESCE(u.total_cashiers, 0) AS total_cashiers,
COALESCE(u.total_customers, 0) AS total_customers, -- COALESCE(u.total_customers, 0) AS total_customers,
COALESCE(u.total_approvers, 0) AS total_approvers, -- COALESCE(u.total_approvers, 0) AS total_approvers,
COALESCE(br.total_branches, 0) AS total_branches, -- COALESCE(br.total_branches, 0) AS total_branches,
NOW() AS updated_at -- NOW() AS updated_at
FROM companies c -- FROM companies c
LEFT JOIN bet_stats b ON b.company_id = c.id -- LEFT JOIN bet_stats b ON b.company_id = c.id
LEFT JOIN user_stats u ON u.company_id = c.id -- LEFT JOIN user_stats u ON u.company_id = c.id
LEFT JOIN branch_stats br ON br.company_id = c.id ON CONFLICT (company_id, interval_start) DO -- LEFT JOIN branch_stats br ON br.company_id = c.id ON CONFLICT (company_id, interval_start) DO
UPDATE -- UPDATE
SET total_bets = EXCLUDED.total_bets, -- SET total_bets = EXCLUDED.total_bets,
total_stake = EXCLUDED.total_stake, -- total_stake = EXCLUDED.total_stake,
deducted_stake = EXCLUDED.deducted_stake, -- deducted_stake = EXCLUDED.deducted_stake,
total_cash_out = EXCLUDED.total_cash_out, -- total_cash_out = EXCLUDED.total_cash_out,
total_cash_backs = EXCLUDED.total_cash_backs, -- total_cash_backs = EXCLUDED.total_cash_backs,
number_of_unsettled = EXCLUDED.number_of_unsettled, -- number_of_unsettled = EXCLUDED.number_of_unsettled,
total_unsettled_amount = EXCLUDED.total_unsettled_amount, -- total_unsettled_amount = EXCLUDED.total_unsettled_amount,
total_admins = EXCLUDED.total_admins, -- total_admins = EXCLUDED.total_admins,
total_managers = EXCLUDED.total_managers, -- total_managers = EXCLUDED.total_managers,
total_cashiers = EXCLUDED.total_cashiers, -- total_cashiers = EXCLUDED.total_cashiers,
total_customers = EXCLUDED.total_customers, -- total_customers = EXCLUDED.total_customers,
total_approvers = EXCLUDED.total_approvers, -- total_approvers = EXCLUDED.total_approvers,
total_branches = EXCLUDED.total_branches, -- total_branches = EXCLUDED.total_branches,
updated_at = EXCLUDED.updated_at; -- updated_at = EXCLUDED.updated_at;
-- name: GetCompanyStatsByID :many -- -- name: GetCompanyStatsByID :many
SELECT * -- SELECT *
FROM company_stats -- FROM company_stats
WHERE company_id = $1 -- WHERE company_id = $1
ORDER BY interval_start DESC; -- ORDER BY interval_start DESC;
-- name: GetCompanyStats :many -- -- name: GetCompanyStats :many
SELECT DATE_TRUNC(sqlc.narg('interval'), interval_start)::timestamp AS interval_start, -- SELECT DATE_TRUNC(sqlc.narg('interval'), interval_start)::timestamp AS interval_start,
company_stats.company_id, -- company_stats.company_id,
company_stats.company_name, -- company_stats.company_name,
company_stats.company_slug, -- company_stats.company_slug,
company_stats.total_bets, -- company_stats.total_bets,
company_stats.total_stake, -- company_stats.total_stake,
company_stats.deducted_stake, -- company_stats.deducted_stake,
company_stats.total_cash_out, -- company_stats.total_cash_out,
company_stats.total_cash_backs, -- company_stats.total_cash_backs,
company_stats.number_of_unsettled, -- company_stats.number_of_unsettled,
company_stats.total_unsettled_amount, -- company_stats.total_unsettled_amount,
company_stats.total_admins, -- company_stats.total_admins,
company_stats.total_managers, -- company_stats.total_managers,
company_stats.total_cashiers, -- company_stats.total_cashiers,
company_stats.total_customers, -- company_stats.total_customers,
company_stats.total_approvers, -- company_stats.total_approvers,
company_stats.total_branches, -- company_stats.total_branches,
company_stats.updated_at -- company_stats.updated_at
FROM company_stats -- FROM company_stats
WHERE ( -- WHERE (
company_stats.company_id = sqlc.narg('company_id') -- company_stats.company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL -- OR sqlc.narg('company_id') IS NULL
) -- )
GROUP BY interval_start -- GROUP BY interval_start
ORDER BY interval_start DESC; -- ORDER BY interval_start DESC;

View File

@ -1,35 +0,0 @@
-- -- name: InsertCustomOddsMarket :one
-- INSERT INTO custom_odds_market (
-- odds_market_id,
-- company_id,
-- event_id,
-- raw_odds
-- )
-- VALUES ($1, $2, $3, $4)
-- RETURNING *;
-- -- name: GetAllCustomOdds :many
-- SELECT *
-- FROM custom_odds_market
-- WHERE (
-- company_id = sqlc.narg('company_id')
-- OR sqlc.narg('company_id') IS NULL
-- );
-- -- name: GetCustomOddByID :one
-- SELECT *
-- FROM custom_odds_market
-- WHERE id = $1;
-- -- name: GetCustomOddByOddID :one
-- SELECT *
-- FROM custom_odds_market
-- WHERE odds_market_id = $1
-- AND company_id = $2;
-- -- name: DeleteCustomOddsByID :exec
-- DELETE FROM custom_odds_market
-- WHERE id = $1;
-- -- name: DeleteCustomOddsByOddID :exec
-- DELETE FROM custom_odds_market
-- WHERE odds_market_id = $1
-- AND company_id = $2;
-- -- name: DeleteCustomOddByEventID :exec
-- DELETE FROM custom_odds_market
-- WHERE event_id = $1;

View File

@ -1,64 +0,0 @@
-- name: CreateDirectDeposit :one
INSERT INTO direct_deposits (
customer_id, wallet_id, bank_name, account_number,
account_holder, amount, reference_number,
transfer_screenshot, status
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'PENDING')
RETURNING *;
-- name: GetDirectDepositByID :one
SELECT *
FROM direct_deposits
WHERE id = $1;
-- name: DeleteDirectDeposit :exec
DELETE FROM direct_deposits
WHERE id = $1;
-- name: GetDirectDepositsByStatus :many
SELECT
id,
customer_id,
wallet_id,
bank_name,
account_number,
account_holder,
amount,
reference_number,
transfer_screenshot,
status,
created_at,
approved_by,
approved_at,
rejection_reason
FROM direct_deposits
WHERE status = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3;
-- name: CountDirectDepositsByStatus :one
SELECT COUNT(*)
FROM direct_deposits
WHERE status = $1;
-- name: ApproveDirectDeposit :exec
UPDATE direct_deposits
SET
status = 'APPROVED',
approved_by = $2,
approved_at = NOW()
WHERE
id = $1
AND status = 'PENDING';
-- name: RejectDirectDeposit :exec
UPDATE direct_deposits
SET
status = 'REJECTED',
approved_by = $2, -- still track the admin who took final action
approved_at = NOW(),
rejection_reason = $3
WHERE
id = $1
AND status = 'PENDING';

View File

@ -1,537 +0,0 @@
-- name: CreateEnetpulseSport :one
INSERT INTO enetpulse_sports (
sport_id,
name,
updates_count,
last_updated_at,
status,
updated_at
) VALUES (
$1, $2, $3, $4, $5, NOW()
)
ON CONFLICT (sport_id) DO UPDATE
SET
name = EXCLUDED.name,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
status = EXCLUDED.status,
updated_at = NOW()
RETURNING *;
-- name: GetAllEnetpulseSports :many
SELECT
id,
sport_id,
name,
updates_count,
last_updated_at,
status,
created_at,
updated_at
FROM enetpulse_sports
ORDER BY name;
-- name: CreateEnetpulseTournamentTemplate :one
INSERT INTO enetpulse_tournament_templates (
template_id,
name,
sport_fk,
gender,
updates_count,
last_updated_at,
status,
updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
ON CONFLICT (template_id) DO UPDATE
SET
name = EXCLUDED.name,
sport_fk = EXCLUDED.sport_fk,
gender = EXCLUDED.gender,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
status = EXCLUDED.status,
updated_at = NOW()
RETURNING *;
-- name: GetAllEnetpulseTournamentTemplates :many
SELECT
id,
template_id,
name,
sport_fk,
gender,
updates_count,
last_updated_at,
status,
created_at,
updated_at
FROM enetpulse_tournament_templates
ORDER BY name;
-- -- name: DeleteEnetpulseTournamentTemplateByID :exec
-- DELETE FROM enetpulse_tournament_templates WHERE template_id = $1;
-- name: CreateEnetpulseTournament :one
INSERT INTO enetpulse_tournaments (
tournament_id,
name,
tournament_template_fk,
updates_count,
last_updated_at,
status
) VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (tournament_id) DO UPDATE
SET
name = EXCLUDED.name,
tournament_template_fk = EXCLUDED.tournament_template_fk,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
status = EXCLUDED.status
RETURNING *;
-- name: GetAllEnetpulseTournaments :many
SELECT *
FROM enetpulse_tournaments
ORDER BY created_at DESC;
-- name: CreateEnetpulseTournamentStage :one
INSERT INTO enetpulse_tournament_stages (
stage_id,
name,
tournament_fk,
gender,
country_fk,
country_name,
start_date,
end_date,
updates_count,
last_updated_at,
status
)
VALUES (
$1, -- stage_id
$2, -- name
$3, -- tournament_fk
$4, -- gender
$5, -- country_fk
$6, -- country_name
$7, -- start_date
$8, -- end_date
$9, -- updates_count
$10, -- last_updated_at
$11 -- status
)
ON CONFLICT (stage_id) DO UPDATE
SET
name = EXCLUDED.name,
tournament_fk = EXCLUDED.tournament_fk,
gender = EXCLUDED.gender,
country_fk = EXCLUDED.country_fk,
country_name = EXCLUDED.country_name,
start_date = EXCLUDED.start_date,
end_date = EXCLUDED.end_date,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
status = EXCLUDED.status,
updated_at = NOW()
RETURNING *;
-- name: GetAllEnetpulseTournamentStages :many
SELECT *
FROM enetpulse_tournament_stages
ORDER BY created_at DESC;
-- name: GetTournamentStagesByTournamentFK :many
SELECT *
FROM enetpulse_tournament_stages
WHERE tournament_fk = $1
ORDER BY created_at DESC;
-- name: CreateEnetpulseFixture :one
INSERT INTO enetpulse_fixtures (
fixture_id,
name,
sport_fk,
tournament_fk,
tournament_template_fk,
tournament_name,
tournament_template_name,
sport_name,
gender,
start_date,
status_type,
status_desc_fk,
round_type_fk,
updates_count,
last_updated_at,
created_at,
updated_at
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP
)
ON CONFLICT (fixture_id) DO UPDATE
SET
name = EXCLUDED.name,
sport_fk = EXCLUDED.sport_fk,
tournament_fk = EXCLUDED.tournament_fk,
tournament_template_fk = EXCLUDED.tournament_template_fk,
tournament_name = EXCLUDED.tournament_name,
tournament_template_name = EXCLUDED.tournament_template_name,
sport_name = EXCLUDED.sport_name,
gender = EXCLUDED.gender,
start_date = EXCLUDED.start_date,
status_type = EXCLUDED.status_type,
status_desc_fk = EXCLUDED.status_desc_fk,
round_type_fk = EXCLUDED.round_type_fk,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetAllEnetpulseFixtures :many
SELECT *
FROM enetpulse_fixtures
ORDER BY created_at DESC;
-- name: CreateEnetpulseResult :one
INSERT INTO enetpulse_results (
result_id,
name,
sport_fk,
tournament_fk,
tournament_template_fk,
tournament_name,
tournament_template_name,
sport_name,
start_date,
status_type,
status_desc_fk,
round_type_fk,
updates_count,
last_updated_at,
round,
live,
venue_name,
livestats_plus,
livestats_type,
commentary,
lineup_confirmed,
verified,
spectators,
game_started,
first_half_ended,
second_half_started,
second_half_ended,
game_ended,
created_at,
updated_at
) VALUES (
$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,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP
)
ON CONFLICT (result_id) DO UPDATE
SET
name = EXCLUDED.name,
sport_fk = EXCLUDED.sport_fk,
tournament_fk = EXCLUDED.tournament_fk,
tournament_template_fk = EXCLUDED.tournament_template_fk,
tournament_name = EXCLUDED.tournament_name,
tournament_template_name = EXCLUDED.tournament_template_name,
sport_name = EXCLUDED.sport_name,
start_date = EXCLUDED.start_date,
status_type = EXCLUDED.status_type,
status_desc_fk = EXCLUDED.status_desc_fk,
round_type_fk = EXCLUDED.round_type_fk,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
round = EXCLUDED.round,
live = EXCLUDED.live,
venue_name = EXCLUDED.venue_name,
livestats_plus = EXCLUDED.livestats_plus,
livestats_type = EXCLUDED.livestats_type,
commentary = EXCLUDED.commentary,
lineup_confirmed = EXCLUDED.lineup_confirmed,
verified = EXCLUDED.verified,
spectators = EXCLUDED.spectators,
game_started = EXCLUDED.game_started,
first_half_ended = EXCLUDED.first_half_ended,
second_half_started = EXCLUDED.second_half_started,
second_half_ended = EXCLUDED.second_half_ended,
game_ended = EXCLUDED.game_ended,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetAllEnetpulseResults :many
SELECT *
FROM enetpulse_results
ORDER BY created_at DESC;
-- name: CreateEnetpulseResultParticipant :one
INSERT INTO enetpulse_result_participants (
participant_map_id,
result_fk,
participant_fk,
number,
name,
gender,
type,
country_fk,
country_name,
ordinary_time,
running_score,
halftime,
final_result,
last_updated_at,
created_at
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,CURRENT_TIMESTAMP
)
ON CONFLICT (participant_map_id) DO UPDATE
SET
result_fk = EXCLUDED.result_fk,
participant_fk = EXCLUDED.participant_fk,
number = EXCLUDED.number,
name = EXCLUDED.name,
gender = EXCLUDED.gender,
type = EXCLUDED.type,
country_fk = EXCLUDED.country_fk,
country_name = EXCLUDED.country_name,
ordinary_time = EXCLUDED.ordinary_time,
running_score = EXCLUDED.running_score,
halftime = EXCLUDED.halftime,
final_result = EXCLUDED.final_result,
last_updated_at = EXCLUDED.last_updated_at
RETURNING *;
-- name: GetEnetpulseResultParticipantsByResultFK :many
SELECT *
FROM enetpulse_result_participants
WHERE result_fk = $1
ORDER BY created_at DESC;
-- name: CreateEnetpulseResultReferee :one
INSERT INTO enetpulse_result_referees (
result_fk,
referee_fk,
assistant1_referee_fk,
assistant2_referee_fk,
fourth_referee_fk,
var1_referee_fk,
var2_referee_fk,
last_updated_at,
created_at
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,CURRENT_TIMESTAMP
)
ON CONFLICT (result_fk) DO UPDATE
SET
referee_fk = EXCLUDED.referee_fk,
assistant1_referee_fk = EXCLUDED.assistant1_referee_fk,
assistant2_referee_fk = EXCLUDED.assistant2_referee_fk,
fourth_referee_fk = EXCLUDED.fourth_referee_fk,
var1_referee_fk = EXCLUDED.var1_referee_fk,
var2_referee_fk = EXCLUDED.var2_referee_fk,
last_updated_at = EXCLUDED.last_updated_at
RETURNING *;
-- name: GetEnetpulseResultRefereesByResultFK :many
SELECT *
FROM enetpulse_result_referees
WHERE result_fk = $1
ORDER BY created_at DESC;
-- name: CreateEnetpulseOutcomeType :one
INSERT INTO enetpulse_outcome_types (
outcome_type_id,
name,
description,
updates_count,
last_updated_at,
created_at,
updated_at
) VALUES (
$1, $2, $3, $4, $5, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
ON CONFLICT (outcome_type_id) DO UPDATE
SET
name = EXCLUDED.name,
description = EXCLUDED.description,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetAllEnetpulseOutcomeTypes :many
SELECT *
FROM enetpulse_outcome_types
ORDER BY created_at DESC;
-- name: CreateEnetpulsePreodds :one
INSERT INTO enetpulse_preodds (
preodds_id,
event_fk,
outcome_type_fk,
outcome_scope_fk,
outcome_subtype_fk,
event_participant_number,
iparam,
iparam2,
dparam,
dparam2,
sparam,
updates_count,
last_updated_at,
created_at,
updated_at
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP
)
ON CONFLICT (preodds_id) DO UPDATE
SET
event_fk = EXCLUDED.event_fk,
outcome_type_fk = EXCLUDED.outcome_type_fk,
outcome_scope_fk = EXCLUDED.outcome_scope_fk,
outcome_subtype_fk = EXCLUDED.outcome_subtype_fk,
event_participant_number = EXCLUDED.event_participant_number,
iparam = EXCLUDED.iparam,
iparam2 = EXCLUDED.iparam2,
dparam = EXCLUDED.dparam,
dparam2 = EXCLUDED.dparam2,
sparam = EXCLUDED.sparam,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetAllEnetpulsePreodds :many
SELECT *
FROM enetpulse_preodds
ORDER BY created_at DESC;
-- name: CreateEnetpulsePreoddsBettingOffer :one
INSERT INTO enetpulse_preodds_bettingoffers (
bettingoffer_id,
preodds_fk,
bettingoffer_status_fk,
odds_provider_fk,
odds,
odds_old,
active,
coupon_key,
updates_count,
last_updated_at,
created_at,
updated_at
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP
)
ON CONFLICT (bettingoffer_id) DO UPDATE
SET
preodds_fk = EXCLUDED.preodds_fk,
bettingoffer_status_fk = EXCLUDED.bettingoffer_status_fk,
odds_provider_fk = EXCLUDED.odds_provider_fk,
odds = EXCLUDED.odds,
odds_old = EXCLUDED.odds_old,
active = EXCLUDED.active,
coupon_key = EXCLUDED.coupon_key,
updates_count = EXCLUDED.updates_count,
last_updated_at = EXCLUDED.last_updated_at,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetAllEnetpulsePreoddsBettingOffers :many
SELECT *
FROM enetpulse_preodds_bettingoffers
ORDER BY created_at DESC;
-- name: GetAllEnetpulsePreoddsWithBettingOffers :many
SELECT
p.id AS preodds_db_id,
p.preodds_id,
p.event_fk,
p.outcome_type_fk,
p.outcome_scope_fk,
p.outcome_subtype_fk,
p.event_participant_number,
p.iparam,
p.iparam2,
p.dparam,
p.dparam2,
p.sparam,
p.updates_count AS preodds_updates_count,
p.last_updated_at AS preodds_last_updated_at,
p.created_at AS preodds_created_at,
p.updated_at AS preodds_updated_at,
-- Betting offer fields
bo.id AS bettingoffer_db_id,
bo.bettingoffer_id,
bo.preodds_fk, -- ✅ ensure alias matches struct field
bo.bettingoffer_status_fk,
bo.odds_provider_fk,
bo.odds,
bo.odds_old,
bo.active,
bo.coupon_key,
bo.updates_count AS bettingoffer_updates_count,
bo.last_updated_at AS bettingoffer_last_updated_at,
bo.created_at AS bettingoffer_created_at,
bo.updated_at AS bettingoffer_updated_at
FROM enetpulse_preodds p
LEFT JOIN enetpulse_preodds_bettingoffers bo
ON bo.preodds_fk = p.preodds_id
ORDER BY p.created_at DESC, bo.created_at DESC;
-- name: GetFixturesWithPreodds :many
SELECT
f.fixture_id AS id,
f.fixture_id AS fixture_id,
f.name AS fixture_name,
f.sport_fk,
f.tournament_fk,
f.tournament_template_fk,
f.start_date,
f.status_type,
f.status_desc_fk,
f.round_type_fk,
f.updates_count AS fixture_updates_count,
f.last_updated_at AS fixture_last_updated_at,
f.created_at AS fixture_created_at,
f.updated_at AS fixture_updated_at,
-- Preodds fields
p.id AS preodds_db_id,
p.preodds_id,
p.event_fk,
p.outcome_type_fk,
p.outcome_scope_fk,
p.outcome_subtype_fk,
p.event_participant_number,
p.iparam,
p.iparam2,
p.dparam,
p.dparam2,
p.sparam,
p.updates_count AS preodds_updates_count,
p.last_updated_at AS preodds_last_updated_at,
p.created_at AS preodds_created_at,
p.updated_at AS preodds_updated_at
FROM enetpulse_fixtures f
LEFT JOIN enetpulse_preodds p
ON p.event_fk = f.id
ORDER BY f.start_date DESC;

View File

@ -1,36 +0,0 @@
-- name: InsertEventHistory :one
INSERT INTO event_history (event_id, status)
VALUES ($1, $2)
RETURNING *;
-- name: GetAllEventHistory :many
SELECT *
FROM event_history
WHERE (
event_id = sqlc.narg('event_id')
OR sqlc.narg('event_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetInitialEventPerDay :many
SELECT DISTINCT ON (DATE_TRUNC('day', created_at)) *
FROM event_history
WHERE (
event_id = sqlc.narg('event_id')
OR sqlc.narg('event_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
ORDER BY DATE_TRUNC('day', created_at),
created_at ASC;

View File

@ -1,191 +0,0 @@
-- name: InsertEvent :exec
INSERT INTO events (
source_event_id,
sport_id,
match_name,
home_team,
away_team,
home_team_id,
away_team_id,
home_kit_image,
away_kit_image,
league_id,
league_name,
start_time,
is_live,
status,
source,
default_winning_upper_limit
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16
) ON CONFLICT (source_event_id, source) DO
UPDATE
SET sport_id = EXCLUDED.sport_id,
match_name = EXCLUDED.match_name,
home_team = EXCLUDED.home_team,
away_team = EXCLUDED.away_team,
home_team_id = EXCLUDED.home_team_id,
away_team_id = EXCLUDED.away_team_id,
home_kit_image = EXCLUDED.home_kit_image,
away_kit_image = EXCLUDED.away_kit_image,
league_id = EXCLUDED.league_id,
league_name = EXCLUDED.league_name,
start_time = EXCLUDED.start_time,
score = EXCLUDED.score,
match_minute = EXCLUDED.match_minute,
timer_status = EXCLUDED.timer_status,
added_time = EXCLUDED.added_time,
match_period = EXCLUDED.match_period,
is_live = EXCLUDED.is_live,
source = EXCLUDED.source,
default_winning_upper_limit = EXCLUDED.default_winning_upper_limit,
fetched_at = now();
-- name: ListLiveEvents :many
SELECT id
FROM event_detailed
WHERE is_live = true;
-- TODO: Figure out how to make this code reusable. SQLC prohibits CTEs within multiple queries
-- name: GetAllEvents :many
SELECT *
FROM event_detailed
WHERE (
is_live = sqlc.narg('is_live')
OR sqlc.narg('is_live') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND (
league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
match_name ILIKE '%' || sqlc.narg('query') || '%'
OR league_name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
start_time < sqlc.narg('last_start_time')
OR sqlc.narg('last_start_time') IS NULL
)
AND (
start_time > sqlc.narg('first_start_time')
OR sqlc.narg('first_start_time') IS NULL
)
AND (
league_cc = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
source = sqlc.narg('source')
OR sqlc.narg('source') IS NULL
)
ORDER BY start_time ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetTotalEvents :one
SELECT COUNT(*)
FROM event_detailed
WHERE (
is_live = sqlc.narg('is_live')
OR sqlc.narg('is_live') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND (
league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
match_name ILIKE '%' || sqlc.narg('query') || '%'
OR league_name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
start_time < sqlc.narg('last_start_time')
OR sqlc.narg('last_start_time') IS NULL
)
AND (
start_time > sqlc.narg('first_start_time')
OR sqlc.narg('first_start_time') IS NULL
)
AND (
league_cc = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
source = sqlc.narg('source')
OR sqlc.narg('source') IS NULL
);
-- name: GetEventByID :one
SELECT *
FROM event_detailed
WHERE id = $1
LIMIT 1;
-- name: GetEventBySourceID :one
SELECT *
FROM event_detailed
WHERE source_event_id = $1
AND source = $2;
-- name: GetSportAndLeagueIDs :one
SELECT sport_id,
league_id
FROM events
WHERE id = $1;
-- name: UpdateMatchResult :exec
UPDATE events
SET score = $1,
status = $2
WHERE id = $3;
-- name: IsEventMonitored :one
SELECT is_monitored
FROM events
WHERE id = $1;
-- name: UpdateEventMonitored :exec
UPDATE events
SET is_monitored = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: UpdateGlobalEventSettings :exec
UPDATE events
SET default_is_active = COALESCE(sqlc.narg(default_is_active), default_is_active),
default_is_featured = COALESCE(
sqlc.narg(default_is_featured),
default_is_featured
),
default_winning_upper_limit = COALESCE(
sqlc.narg(default_winning_upper_limit),
default_winning_upper_limit
),
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: DeleteEvent :exec
DELETE FROM events
WHERE id = $1;

View File

@ -1,25 +0,0 @@
-- Aggregate bet stats per event
-- name: UpdateEventBetStats :exec
INSERT INTO event_bet_stats (
event_id,
number_of_bets,
total_amount,
avg_bet_amount,
total_potential_winnings,
updated_at
)
SELECT bo.event_id,
COUNT(DISTINCT b.id) AS number_of_bets,
COALESCE(SUM(b.amount), 0) AS total_amount,
COALESCE(AVG(b.amount), 0) AS avg_bet_amount,
COALESCE(SUM(b.potential_win), 0) AS total_potential_winnings,
NOW() AS updated_at
FROM bet_outcomes bo
JOIN bets b ON bo.bet_id = b.id
GROUP BY bo.event_id ON CONFLICT (event_id) DO
UPDATE
SET number_of_bets = EXCLUDED.number_of_bets,
total_amount = EXCLUDED.total_amount,
avg_bet_amount = EXCLUDED.avg_bet_amount,
total_potential_winnings = EXCLUDED.total_potential_winnings,
updated_at = EXCLUDED.updated_at;

View File

@ -1,123 +0,0 @@
-- name: GetTotalEventStats :one
SELECT COUNT(*) AS event_count,
COUNT(*) FILTER (
WHERE events.default_is_active = TRUE
) AS total_active_events,
COUNT(*) FILTER (
WHERE events.default_is_active = FALSE
) AS total_inactive_events,
COUNT(*) FILTER (
WHERE events.default_is_featured = TRUE
) AS total_featured_events,
COUNT(DISTINCT league_id) as total_leagues,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM events
WHERE (
events.league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
events.sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
);
-- name: GetTotalEventStatsByInterval :many
SELECT DATE_TRUNC(sqlc.narg('interval'), start_time)::timestamp AS date,
COUNT(*) AS event_count,
COUNT(*) FILTER (
WHERE events.default_is_active = TRUE
) AS total_active_events,
COUNT(*) FILTER (
WHERE events.default_is_active = FALSE
) AS total_inactive_events,
COUNT(*) FILTER (
WHERE events.default_is_featured = TRUE
) AS total_featured_events,
COUNT(DISTINCT league_id) as total_leagues,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM events
WHERE (
events.league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
events.sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
GROUP BY date
ORDER BY date;

View File

@ -1,171 +0,0 @@
-- name: SaveTenantEventSettings :exec
INSERT INTO company_event_settings (
company_id,
event_id,
is_active,
is_featured,
winning_upper_limit
)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT(company_id, event_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
is_featured = EXCLUDED.is_featured,
winning_upper_limit = EXCLUDED.winning_upper_limit;
-- name: GetTotalCompanyEvents :one
SELECT COUNT(*)
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $1
JOIN leagues l ON l.id = e.league_id
WHERE (
is_live = sqlc.narg('is_live')
OR sqlc.narg('is_live') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND(
league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
e.sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
match_name ILIKE '%' || sqlc.narg('query') || '%'
OR league_name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
start_time < sqlc.narg('last_start_time')
OR sqlc.narg('last_start_time') IS NULL
)
AND (
start_time > sqlc.narg('first_start_time')
OR sqlc.narg('first_start_time') IS NULL
)
AND (
l.country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
ces.is_featured = sqlc.narg('is_featured')
OR e.default_is_featured = sqlc.narg('is_featured')
OR sqlc.narg('is_featured') IS NULL
)
AND (
ces.is_active = sqlc.narg('is_active')
OR e.default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
)
AND (
source = sqlc.narg('source')
OR sqlc.narg('source') IS NULL
);
-- name: GetEventsWithSettings :many
SELECT e.*,
ces.company_id,
COALESCE(ces.is_active, e.default_is_active) AS is_active,
COALESCE(ces.is_featured, e.default_is_featured) AS is_featured,
COALESCE(
ces.winning_upper_limit,
e.default_winning_upper_limit
) AS winning_upper_limit,
ces.updated_at,
l.country_code as league_cc,
COALESCE(om.total_outcomes, 0) AS total_outcomes,
COALESCE(ebs.number_of_bets, 0) AS number_of_bets,
COALESCE(ebs.total_amount, 0) AS total_amount,
COALESCE(ebs.avg_bet_amount, 0) AS avg_bet_amount,
COALESCE(ebs.total_potential_winnings, 0) AS total_potential_winnings
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $1
LEFT JOIN event_bet_stats ebs ON ebs.event_id = e.id
JOIN leagues l ON l.id = e.league_id
LEFT JOIN (
SELECT event_id,
SUM(number_of_outcomes) AS total_outcomes
FROM odds_market
GROUP BY event_id
) om ON om.event_id = e.id
WHERE (
is_live = sqlc.narg('is_live')
OR sqlc.narg('is_live') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND(
league_id = sqlc.narg('league_id')
OR sqlc.narg('league_id') IS NULL
)
AND (
e.sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
match_name ILIKE '%' || sqlc.narg('query') || '%'
OR league_name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
start_time < sqlc.narg('last_start_time')
OR sqlc.narg('last_start_time') IS NULL
)
AND (
start_time > sqlc.narg('first_start_time')
OR sqlc.narg('first_start_time') IS NULL
)
AND (
l.country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
ces.is_featured = sqlc.narg('is_featured')
OR e.default_is_featured = sqlc.narg('is_featured')
OR sqlc.narg('is_featured') IS NULL
)
AND (
ces.is_active = sqlc.narg('is_active')
OR e.default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
)
AND (
source = sqlc.narg('source')
OR sqlc.narg('source') IS NULL
)
ORDER BY start_time ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetEventWithSettingByID :one
SELECT e.*,
ces.company_id,
COALESCE(ces.is_active, e.default_is_active) AS is_active,
COALESCE(ces.is_featured, e.default_is_featured) AS is_featured,
COALESCE(
ces.winning_upper_limit,
e.default_winning_upper_limit
) AS winning_upper_limit,
ces.updated_at,
l.country_code as league_cc,
COALESCE(om.total_outcomes, 0) AS total_outcomes,
COALESCE(ebs.number_of_bets, 0) AS number_of_bets,
COALESCE(ebs.total_amount, 0) AS total_amount,
COALESCE(ebs.avg_bet_amount, 0) AS avg_bet_amount,
COALESCE(ebs.total_potential_winnings, 0) AS total_potential_winnings
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $2
LEFT JOIN event_bet_stats ebs ON ebs.event_id = e.id
JOIN leagues l ON l.id = e.league_id
LEFT JOIN (
SELECT event_id,
SUM(number_of_outcomes) AS total_outcomes
FROM odds_market
GROUP BY event_id
) om ON om.event_id = e.id
WHERE e.id = $1
LIMIT 1;

View File

@ -1,8 +1,8 @@
-- name: CreateFlag :one -- -- name: CreateFlag :one
INSERT INTO flags ( -- INSERT INTO flags (
bet_id, -- bet_id,
odds_market_id, -- odds_market_id,
reason -- reason
) VALUES ( -- ) VALUES (
$1, $2, $3 -- $1, $2, $3
) RETURNING *; -- ) RETURNING *;

View File

@ -1,87 +1,87 @@
-- name: CreateBank :one -- -- name: CreateBank :one
INSERT INTO banks ( -- INSERT INTO banks (
slug, -- slug,
swift, -- swift,
name, -- name,
acct_length, -- acct_length,
country_id, -- country_id,
is_mobilemoney, -- is_mobilemoney,
is_active, -- is_active,
is_rtgs, -- is_rtgs,
active, -- active,
is_24hrs, -- is_24hrs,
created_at, -- created_at,
updated_at, -- updated_at,
currency, -- currency,
bank_logo -- bank_logo
) -- )
VALUES ( -- VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, $11, $12 -- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, $11, $12
) -- )
RETURNING *; -- RETURNING *;
-- name: GetBankByID :one -- -- name: GetBankByID :one
SELECT * -- SELECT *
FROM banks -- FROM banks
WHERE id = $1; -- WHERE id = $1;
-- name: GetAllBanks :many -- -- name: GetAllBanks :many
SELECT * -- SELECT *
FROM banks -- FROM banks
WHERE ( -- WHERE (
country_id = sqlc.narg('country_id') -- country_id = sqlc.narg('country_id')
OR sqlc.narg('country_id') IS NULL -- OR sqlc.narg('country_id') IS NULL
) -- )
AND ( -- AND (
is_active = sqlc.narg('is_active') -- is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL -- OR sqlc.narg('is_active') IS NULL
) -- )
AND ( -- AND (
name ILIKE '%' || sqlc.narg('search_term') || '%' -- name ILIKE '%' || sqlc.narg('search_term') || '%'
OR sqlc.narg('search_term') IS NULL -- OR sqlc.narg('search_term') IS NULL
) -- )
AND ( -- AND (
code ILIKE '%' || sqlc.narg('search_term') || '%' -- code ILIKE '%' || sqlc.narg('search_term') || '%'
OR sqlc.narg('search_term') IS NULL -- OR sqlc.narg('search_term') IS NULL
) -- )
ORDER BY name ASC -- ORDER BY name ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset'); -- LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: CountBanks :one -- -- name: CountBanks :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM banks -- FROM banks
WHERE ( -- WHERE (
country_id = $1 -- country_id = $1
OR $1 IS NULL -- OR $1 IS NULL
) -- )
AND ( -- AND (
is_active = $2 -- is_active = $2
OR $2 IS NULL -- OR $2 IS NULL
) -- )
AND ( -- AND (
name ILIKE '%' || $3 || '%' -- name ILIKE '%' || $3 || '%'
OR code ILIKE '%' || $3 || '%' -- OR code ILIKE '%' || $3 || '%'
OR $3 IS NULL -- OR $3 IS NULL
); -- );
-- name: UpdateBank :one -- -- name: UpdateBank :one
UPDATE banks -- UPDATE banks
SET slug = COALESCE(sqlc.narg(slug), slug), -- SET slug = COALESCE(sqlc.narg(slug), slug),
swift = COALESCE(sqlc.narg(swift), swift), -- swift = COALESCE(sqlc.narg(swift), swift),
name = COALESCE(sqlc.narg(name), name), -- name = COALESCE(sqlc.narg(name), name),
acct_length = COALESCE(sqlc.narg(acct_length), acct_length), -- acct_length = COALESCE(sqlc.narg(acct_length), acct_length),
country_id = COALESCE(sqlc.narg(country_id), country_id), -- country_id = COALESCE(sqlc.narg(country_id), country_id),
is_mobilemoney = COALESCE(sqlc.narg(is_mobilemoney), is_mobilemoney), -- is_mobilemoney = COALESCE(sqlc.narg(is_mobilemoney), is_mobilemoney),
is_active = COALESCE(sqlc.narg(is_active), is_active), -- is_active = COALESCE(sqlc.narg(is_active), is_active),
is_rtgs = COALESCE(sqlc.narg(is_rtgs), is_rtgs), -- is_rtgs = COALESCE(sqlc.narg(is_rtgs), is_rtgs),
active = COALESCE(sqlc.narg(active), active), -- active = COALESCE(sqlc.narg(active), active),
is_24hrs = COALESCE(sqlc.narg(is_24hrs), is_24hrs), -- is_24hrs = COALESCE(sqlc.narg(is_24hrs), is_24hrs),
updated_at = CURRENT_TIMESTAMP, -- updated_at = CURRENT_TIMESTAMP,
currency = COALESCE(sqlc.narg(currency), currency), -- currency = COALESCE(sqlc.narg(currency), currency),
bank_logo = COALESCE(sqlc.narg(bank_logo), bank_logo) -- bank_logo = COALESCE(sqlc.narg(bank_logo), bank_logo)
WHERE id = $1 -- WHERE id = $1
RETURNING *; -- RETURNING *;
-- name: DeleteBank :exec -- -- name: DeleteBank :exec
DELETE FROM banks -- DELETE FROM banks
WHERE id = $1; -- WHERE id = $1;

View File

@ -1,37 +1,37 @@
-- name: CreateReportedIssue :one -- -- name: CreateReportedIssue :one
INSERT INTO reported_issues ( -- INSERT INTO reported_issues (
user_id, -- user_id,
user_role, -- user_role,
subject, -- subject,
description, -- description,
issue_type, -- issue_type,
metadata -- metadata
) -- )
VALUES ($1, $2, $3, $4, $5, $6) -- VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *; -- RETURNING *;
-- name: ListReportedIssues :many -- -- name: ListReportedIssues :many
SELECT * -- SELECT *
FROM reported_issues -- FROM reported_issues
ORDER BY created_at DESC -- ORDER BY created_at DESC
LIMIT $1 OFFSET $2; -- LIMIT $1 OFFSET $2;
-- name: ListReportedIssuesByUser :many -- -- name: ListReportedIssuesByUser :many
SELECT * -- SELECT *
FROM reported_issues -- FROM reported_issues
WHERE user_id = $1 -- WHERE user_id = $1
ORDER BY created_at DESC -- ORDER BY created_at DESC
LIMIT $2 OFFSET $3; -- LIMIT $2 OFFSET $3;
-- name: CountReportedIssues :one -- -- name: CountReportedIssues :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM reported_issues; -- FROM reported_issues;
-- name: CountReportedIssuesByUser :one -- -- name: CountReportedIssuesByUser :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM reported_issues -- FROM reported_issues
WHERE user_id = $1; -- WHERE user_id = $1;
-- name: UpdateReportedIssueStatus :exec -- -- name: UpdateReportedIssueStatus :exec
UPDATE reported_issues -- UPDATE reported_issues
SET status = $2, -- SET status = $2,
updated_at = NOW() -- updated_at = NOW()
WHERE id = $1; -- WHERE id = $1;
-- name: DeleteReportedIssue :exec -- -- name: DeleteReportedIssue :exec
DELETE FROM reported_issues -- DELETE FROM reported_issues
WHERE id = $1; -- WHERE id = $1;

View File

@ -1,47 +0,0 @@
-- name: GetLeagueEventStat :many
SELECT leagues.id,
leagues.name,
COUNT(*) AS total_events,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM leagues
JOIN events ON leagues.id = events.league_id
GROUP BY leagues.id,
leagues.name;

View File

@ -1,157 +0,0 @@
-- name: InsertLeague :exec
INSERT INTO leagues (
id,
name,
country_code,
bet365_id,
sport_id,
default_is_active,
default_is_featured
)
VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO
UPDATE
SET name = EXCLUDED.name,
country_code = EXCLUDED.country_code,
bet365_id = EXCLUDED.bet365_id,
sport_id = EXCLUDED.sport_id;
-- name: SaveLeagueSettings :exec
INSERT INTO company_league_settings (
company_id,
league_id,
is_active,
is_featured
)
VALUES ($1, $2, $3, $4) ON CONFLICT(company_id, league_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
is_featured = EXCLUDED.is_featured;
-- name: GetAllLeagues :many
SELECT *
FROM leagues
WHERE (
country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
)
ORDER BY name ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetTotalLeagues :one
SELECT COUNT(*)
FROM leagues
WHERE (
country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
);
-- name: GetTotalLeaguesWithSettings :one
SELECT COUNT(*)
FROM leagues l
LEFT JOIN company_league_settings cls ON l.id = cls.league_id
AND company_id = $1
WHERE (
country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
is_active = sqlc.narg('is_active')
OR default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
)
AND (
is_featured = sqlc.narg('is_featured')
OR default_is_featured = sqlc.narg('is_featured')
OR sqlc.narg('is_featured') IS NULL
)
AND (
name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
);
-- name: GetAllLeaguesWithSettings :many
SELECT l.*,
cls.company_id,
COALESCE(cls.is_active, l.default_is_active) AS is_active,
COALESCE(cls.is_featured, l.default_is_featured) AS is_featured,
cls.updated_at
FROM leagues l
LEFT JOIN company_league_settings cls ON l.id = cls.league_id
AND company_id = $1
WHERE (
country_code = sqlc.narg('country_code')
OR sqlc.narg('country_code') IS NULL
)
AND (
sport_id = sqlc.narg('sport_id')
OR sqlc.narg('sport_id') IS NULL
)
AND (
is_active = sqlc.narg('is_active')
OR default_is_active = sqlc.narg('is_active')
OR sqlc.narg('is_active') IS NULL
)
AND (
is_featured = sqlc.narg('is_featured')
OR default_is_featured = sqlc.narg('is_featured')
OR sqlc.narg('is_featured') IS NULL
)
AND (
name ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
ORDER BY is_featured DESC,
name ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: CheckLeagueSupport :one
SELECT EXISTS(
SELECT 1
FROM company_league_settings
WHERE league_id = $1
AND company_id = $2
AND is_active = true
);
-- name: UpdateLeague :exec
UPDATE leagues
SET name = COALESCE(sqlc.narg('name'), name),
country_code = COALESCE(sqlc.narg('country_code'), country_code),
bet365_id = COALESCE(sqlc.narg('bet365_id'), bet365_id),
sport_id = COALESCE(sqlc.narg('sport_id'), sport_id)
WHERE id = $1;
-- name: UpdateCompanyLeagueSettings :exec
UPDATE company_league_settings
SET is_active = COALESCE(sqlc.narg('is_active'), is_active),
is_featured = COALESCE(
sqlc.narg('is_featured'),
is_featured
)
WHERE league_id = $1
AND company_id = $2;
-- name: UpdateGlobalLeagueSettings :exec
UPDATE leagues
SET default_is_active = COALESCE(sqlc.narg('is_active'), default_is_active),
default_is_featured = COALESCE(sqlc.narg('is_featured'), default_is_featured)
WHERE id = $1;

View File

@ -1,7 +1,7 @@
-- name: GetAllBranchLocations :many -- -- name: GetAllBranchLocations :many
SELECT * -- SELECT *
FROM branch_locations -- FROM branch_locations
WHERE ( -- WHERE (
value ILIKE '%' || sqlc.narg('query') || '%' -- value ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL -- OR sqlc.narg('query') IS NULL
); -- );

View File

@ -1,57 +0,0 @@
-- name: InsertGlobalMarketSettings :exec
INSERT INTO global_odd_market_settings (market_id, market_name, is_active)
VALUES ($1, $2, $3) ON CONFLICT (market_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
updated_at = CURRENT_TIMESTAMP;
-- name: InsertCompanyMarketSettings :exec
INSERT INTO company_odd_market_settings (company_id, market_id, market_name, is_active)
VALUES ($1, $2, $3, $4) ON CONFLICT (company_id, market_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
updated_at = CURRENT_TIMESTAMP;
-- name: GetAllGlobalMarketSettings :many
SELECT *
FROM global_odd_market_settings
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetGlobalMarketSettingsByID :one
SELECT *
FROM global_odd_market_settings
WHERE market_id = $1;
-- name: GetAllCompanyMarketSettings :many
SELECT *
FROM company_odd_market_settings
WHERE (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetCompanyMarketSettingsByID :one
SELECT *
FROM company_odd_market_settings
WHERE market_id = $1;
-- name: GetAllOverrideMarketSettings :many
SELECT gdm.market_id,
gdm.market_name,
COALESCE(cdm.is_active, gdm.is_active) AS is_active,
COALESCE(cdm.updated_at, gdm.updated_at) AS updated_at
FROM global_odd_market_settings gdm
LEFT JOIN company_odd_market_settings cdm ON cdm.market_id = gdm.market_id
AND company_id = $1
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetOverrideMarketSettingByID :one
SELECT gdm.market_id,
gdm.market_name,
COALESCE(cdm.is_active, gdm.is_active) AS is_active,
COALESCE(cdm.updated_at, gdm.updated_at) AS updated_at
FROM global_odd_market_settings gdm
LEFT JOIN company_odd_market_settings cdm ON cdm.market_id = gdm.market_id
AND company_id = $1
WHERE gdm.market_id = $2;
-- name: DeleteAllMarketSettingsForCompany :exec
DELETE FROM company_odd_market_settings
WHERE company_id = $1;
-- name: DeleteCompanyMarketSettings :exec
DELETE FROM company_odd_market_settings
WHERE market_id = $1
AND company_id = $2;

View File

@ -1,24 +0,0 @@
-- name: GetAllCompaniesBranch :many
SELECT id, name, wallet_id, admin_id
FROM companies;
-- name: GetBranchesByCompanyID :many
SELECT
id,
name,
location,
wallet_id,
branch_manager_id,
company_id,
is_self_owned
FROM branches
WHERE company_id = $1;
-- name: CountThresholdNotifications :one
SELECT COUNT(*)
FROM wallet_threshold_notifications
WHERE company_id = $1 AND threshold = $2;
-- name: CreateThresholdNotification :exec
INSERT INTO wallet_threshold_notifications (company_id, threshold)
VALUES ($1, $2);

View File

@ -1,99 +1,99 @@
-- name: CreateNotification :one -- -- name: CreateNotification :one
INSERT INTO notifications ( -- INSERT INTO notifications (
id, -- id,
recipient_id, -- recipient_id,
type, -- type,
level, -- level,
error_severity, -- error_severity,
reciever, -- reciever,
is_read, -- is_read,
delivery_status, -- delivery_status,
delivery_channel, -- delivery_channel,
payload, -- payload,
priority, -- priority,
timestamp, -- timestamp,
expires, -- expires,
img, -- img,
metadata -- metadata
) -- )
VALUES ( -- VALUES (
$1, -- $1,
$2, -- $2,
$3, -- $3,
$4, -- $4,
$5, -- $5,
$6, -- $6,
$7, -- $7,
$8, -- $8,
$9, -- $9,
$10, -- $10,
$11, -- $11,
$12, -- $12,
$13, -- $13,
$14, -- $14,
$15 -- $15
) -- )
RETURNING *; -- RETURNING *;
-- name: GetNotification :one -- -- name: GetNotification :one
SELECT * -- SELECT *
FROM notifications -- FROM notifications
WHERE id = $1 -- WHERE id = $1
LIMIT 1; -- LIMIT 1;
-- name: GetAllNotifications :many -- -- name: GetAllNotifications :many
SELECT * -- SELECT *
FROM notifications -- FROM notifications
ORDER BY timestamp DESC -- ORDER BY timestamp DESC
LIMIT $1 OFFSET $2; -- LIMIT $1 OFFSET $2;
-- name: GetTotalNotificationCount :one -- -- name: GetTotalNotificationCount :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM notifications; -- FROM notifications;
-- name: GetUserNotifications :many -- -- name: GetUserNotifications :many
SELECT * -- SELECT *
FROM notifications -- FROM notifications
WHERE recipient_id = $1 -- WHERE recipient_id = $1
ORDER BY timestamp DESC -- ORDER BY timestamp DESC
LIMIT $2 OFFSET $3; -- LIMIT $2 OFFSET $3;
-- name: GetUserNotificationCount :one -- -- name: GetUserNotificationCount :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM notifications -- FROM notifications
WHERE recipient_id = $1; -- WHERE recipient_id = $1;
-- name: CountUnreadNotifications :one -- -- name: CountUnreadNotifications :one
SELECT count(id) -- SELECT count(id)
FROM notifications -- FROM notifications
WHERE recipient_id = $1 -- WHERE recipient_id = $1
AND is_read = false; -- AND is_read = false;
-- name: UpdateNotificationStatus :one -- -- name: UpdateNotificationStatus :one
UPDATE notifications -- UPDATE notifications
SET delivery_status = $2, -- SET delivery_status = $2,
is_read = $3, -- is_read = $3,
metadata = $4 -- metadata = $4
WHERE id = $1 -- WHERE id = $1
RETURNING *; -- RETURNING *;
-- name: ListFailedNotifications :many -- -- name: ListFailedNotifications :many
SELECT * -- SELECT *
FROM notifications -- FROM notifications
WHERE delivery_status = 'failed' -- WHERE delivery_status = 'failed'
AND timestamp < NOW() - INTERVAL '1 hour' -- AND timestamp < NOW() - INTERVAL '1 hour'
ORDER BY timestamp ASC -- ORDER BY timestamp ASC
LIMIT $1; -- LIMIT $1;
-- name: ListRecipientIDsByReceiver :many -- -- name: ListRecipientIDsByReceiver :many
SELECT recipient_id -- SELECT recipient_id
FROM notifications -- FROM notifications
WHERE reciever = $1; -- WHERE reciever = $1;
-- name: GetNotificationCounts :many -- -- name: GetNotificationCounts :many
SELECT COUNT(*) as total, -- SELECT COUNT(*) as total,
COUNT( -- COUNT(
CASE -- CASE
WHEN is_read = true THEN 1 -- WHEN is_read = true THEN 1
END -- END
) as read, -- ) as read,
COUNT( -- COUNT(
CASE -- CASE
WHEN is_read = false THEN 1 -- WHEN is_read = false THEN 1
END -- END
) as unread -- ) as unread
FROM notifications; -- FROM notifications;
-- name: DeleteOldNotifications :exec -- -- name: DeleteOldNotifications :exec
DELETE FROM notifications -- DELETE FROM notifications
WHERE expires < now(); -- WHERE expires < now();

View File

@ -1,66 +0,0 @@
-- name: InsertOddHistory :one
INSERT INTO odd_history (
odds_market_id,
market_id,
raw_odd_id,
event_id,
odd_value
)
VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: GetAllOddHistory :many
SELECT *
FROM odd_history
WHERE (
odds_market_id = sqlc.narg('odd_id')
OR sqlc.narg('odd_id') IS NULL
)
AND (
market_id = sqlc.narg('market_id')
OR sqlc.narg('market_id') IS NULL
)
AND (
raw_odd_id = sqlc.narg('raw_odd_id')
OR sqlc.narg('raw_odd_id') IS NULL
)
AND (
event_id = sqlc.narg('event_id')
OR sqlc.narg('event_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetInitialOddPerDay :many
SELECT DISTINCT ON (DATE_TRUNC($1, created_at)) *
FROM odd_history
WHERE (
odds_market_id = sqlc.narg('odd_id')
OR sqlc.narg('odd_id') IS NULL
)
AND (
market_id = sqlc.narg('market_id')
OR sqlc.narg('market_id') IS NULL
)
AND (
raw_odd_id = sqlc.narg('raw_odd_id')
OR sqlc.narg('raw_odd_id') IS NULL
)
AND (
event_id = sqlc.narg('event_id')
OR sqlc.narg('event_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
ORDER BY DATE_TRUNC($1, created_at),
created_at ASC;

View File

@ -1,176 +0,0 @@
-- name: InsertOddsMarket :exec
INSERT INTO odds_market (
event_id,
market_type,
market_name,
market_category,
market_id,
number_of_outcomes,
raw_odds,
fetched_at,
expires_at
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9
) ON CONFLICT (event_id, market_id) DO
UPDATE
SET market_type = EXCLUDED.market_type,
market_name = EXCLUDED.market_name,
market_category = EXCLUDED.market_category,
raw_odds = EXCLUDED.raw_odds,
number_of_outcomes = EXCLUDED.number_of_outcomes,
fetched_at = EXCLUDED.fetched_at,
expires_at = EXCLUDED.expires_at;
-- name: SaveOddSettings :exec
INSERT INTO company_odd_settings (
company_id,
odds_market_id,
is_active,
custom_raw_odds
)
VALUES ($1, $2, $3, $4) ON CONFLICT (company_id, odds_market_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
custom_raw_odds = EXCLUDED.custom_raw_odds;
-- name: GetAllOdds :many
SELECT *
FROM odds_market_with_event
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetAllOddsWithSettings :many
SELECT o.id,
o.event_id,
o.market_type,
o.market_name,
o.market_category,
o.market_id,
o.number_of_outcomes,
o.default_is_active,
o.fetched_at,
o.expires_at,
cos.company_id,
COALESCE(cos.is_active, o.default_is_active) AS is_active,
COALESCE(cms.is_active, TRUE) AS is_market_active,
COALESCE(cos.custom_raw_odds, o.raw_odds) AS raw_odds,
cos.updated_at
FROM odds_market o
LEFT JOIN company_odd_settings cos ON o.id = cos.odds_market_id
AND cos.company_id = $1
LEFT JOIN company_odd_market_settings cms ON o.market_id = cms.market_id
AND cms.company_id = $1
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetOddByID :one
SELECT *
FROM odds_market_with_event
WHERE id = $1;
-- name: GetOddsByMarketID :one
SELECT *
FROM odds_market_with_event
WHERE market_id = $1
AND event_id = $2;
-- name: GetOddsWithSettingsByMarketID :one
SELECT o.id,
o.event_id,
o.market_type,
o.market_name,
o.market_category,
o.market_id,
o.number_of_outcomes,
o.default_is_active,
o.fetched_at,
o.expires_at,
cos.company_id,
COALESCE(cos.is_active, o.default_is_active) AS is_active,
COALESCE(cms.is_active, TRUE) AS is_market_active,
COALESCE(cos.custom_raw_odds, o.raw_odds) AS raw_odds,
cos.updated_at
FROM odds_market o
LEFT JOIN company_odd_settings cos ON o.id = cos.odds_market_id
AND cos.company_id = $3
LEFT JOIN company_odd_market_settings cms ON o.market_id = cms.market_id
AND cms.company_id = $3
WHERE o.market_id = $1
AND event_id = $2;
-- name: GetOddsWithSettingsByID :one
SELECT o.id,
o.event_id,
o.market_type,
o.market_name,
o.market_category,
o.market_id,
o.number_of_outcomes,
o.default_is_active,
o.fetched_at,
o.expires_at,
cos.company_id,
COALESCE(cos.is_active, o.default_is_active) AS is_active,
COALESCE(cms.is_active, TRUE) AS is_market_active,
COALESCE(cos.custom_raw_odds, o.raw_odds) AS raw_odds,
cos.updated_at
FROM odds_market o
LEFT JOIN company_odd_settings cos ON o.id = cos.odds_market_id
AND cos.company_id = $2
LEFT JOIN company_odd_market_settings cms ON o.market_id = cms.market_id
AND cms.company_id = $2
WHERE o.id = $1;
-- name: GetOddsByEventID :many
SELECT *
FROM odds_market_with_event
WHERE event_id = $1
AND (
is_live = sqlc.narg('is_live')
OR sqlc.narg('is_live') IS NULL
)
AND (
status = sqlc.narg('status')
OR sqlc.narg('status') IS NULL
)
AND (
source = sqlc.narg('source')
OR sqlc.narg('source') IS NULL
)
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetOddsWithSettingsByEventID :many
SELECT o.id,
o.event_id,
o.market_type,
o.market_name,
o.market_category,
o.market_id,
o.number_of_outcomes,
o.default_is_active,
o.fetched_at,
o.expires_at,
cos.company_id,
COALESCE(cos.is_active, o.default_is_active) AS is_active,
COALESCE(cms.is_active, TRUE) AS is_market_active,
COALESCE(cos.custom_raw_odds, o.raw_odds) AS raw_odds,
cos.updated_at
FROM odds_market o
LEFT JOIN company_odd_settings cos ON o.id = cos.odds_market_id
AND cos.company_id = $2
LEFT JOIN company_odd_market_settings cms ON o.market_id = cms.market_id
AND cms.company_id = $2
WHERE event_id = $1
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: DeleteOddsForEvent :exec
DELETE FROM odds_market
Where event_id = $1;
-- name: DeleteAllCompanyOddsSetting :exec
DELETE FROM company_odd_settings
WHERE company_id = $1;
-- name: DeleteCompanyOddsSettingByOddMarketID :exec
DELETE FROM company_odd_settings
WHERE company_id = $1
AND odds_market_id = $2;
-- name: UpdateGlobalOddsSetting :exec
UPDATE odds_market
SET default_is_active = COALESCE(sqlc.narg(default_is_active), default_is_active)
WHERE id = $1;

View File

@ -1,89 +0,0 @@
-- name: CreateRaffle :one
INSERT INTO raffles (company_id, name, expires_at, ticket_limit, type)
VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: GetRafflesOfCompany :many
SELECT * FROM raffles WHERE company_id = $1;
-- name: DeleteRaffle :one
DELETE FROM raffles
WHERE id = $1
RETURNING *;
-- name: UpdateRaffleTicketStatus :exec
UPDATE raffle_tickets
SET is_active = $1
WHERE id = $2;
-- name: CreateRaffleTicket :one
INSERT INTO raffle_tickets (raffle_id, user_id)
VALUES ($1, $2)
RETURNING *;
-- name: GetUserRaffleTickets :many
SELECT
rt.id AS ticket_id,
rt.user_id,
r.name,
r.type,
r.expires_at,
r.status
FROM raffle_tickets rt
JOIN raffles r ON rt.raffle_id = r.id
WHERE rt.user_id = $1;
-- name: GetRaffleStanding :many
SELECT
u.id AS user_id,
rt.raffle_id,
u.first_name,
u.last_name,
u.phone_number,
u.email,
COUNT(*) AS ticket_count
FROM raffle_tickets rt
JOIN users u ON rt.user_id = u.id
WHERE rt.is_active = true
AND rt.raffle_id = $1
GROUP BY u.id, rt.raffle_id, u.first_name, u.last_name, u.phone_number, u.email
ORDER BY ticket_count DESC
LIMIT $2;
-- name: CreateRaffleWinner :one
INSERT INTO raffle_winners (raffle_id, user_id, rank)
VALUES ($1, $2, $3)
RETURNING *;
-- name: SetRaffleComplete :exec
UPDATE raffles
SET status = 'completed'
WHERE id = $1;
-- name: AddSportRaffleFilter :one
INSERT INTO raffle_sport_filters (raffle_id, sport_id, league_id)
VALUES ($1, $2, $3)
RETURNING *;
-- name: CheckValidSportRaffleFilter :one
SELECT COUNT(*) > 0 AS exists
FROM raffle_sport_filters
WHERE raffle_id = $1
AND sport_id = $2
AND league_id = $3;
-- name: CheckSportRaffleHasFilter :one
SELECT EXISTS (
SELECT 1 FROM raffle_sport_filters WHERE raffle_id = $1
) AS has_filter;
-- name: GetRaffleTicketLimit :one
SELECT ticket_limit
FROM raffles
WHERE id = $1;
-- name: GetRaffleTicketCount :one
SELECT COUNT(*)
FROM raffle_tickets
WHERE raffle_id = $1
AND user_id = $2;

View File

@ -1,51 +1,51 @@
-- name: CreateReferralCode :one -- -- name: CreateReferralCode :one
INSERT INTO referral_codes ( -- INSERT INTO referral_codes (
referral_code, -- referral_code,
referrer_id, -- referrer_id,
company_id, -- company_id,
number_of_referrals, -- number_of_referrals,
reward_amount -- reward_amount
) -- )
VALUES ($1, $2, $3, $4, $5) -- VALUES ($1, $2, $3, $4, $5)
RETURNING *; -- RETURNING *;
-- name: CreateUserReferral :one -- -- name: CreateUserReferral :one
INSERT INTO user_referrals (referred_id, referral_code_id) -- INSERT INTO user_referrals (referred_id, referral_code_id)
VALUES ($1, $2) -- VALUES ($1, $2)
RETURNING *; -- RETURNING *;
-- name: GetReferralCodeByUser :many -- -- name: GetReferralCodeByUser :many
SELECt * -- SELECt *
FROM referral_codes -- FROM referral_codes
WHERE referrer_id = $1; -- WHERE referrer_id = $1;
-- name: GetReferralCode :one -- -- name: GetReferralCode :one
SELECT * -- SELECT *
FROM referral_codes -- FROM referral_codes
WHERE referral_code = $1; -- WHERE referral_code = $1;
-- name: UpdateReferralCode :exec -- -- name: UpdateReferralCode :exec
UPDATE referral_codes -- UPDATE referral_codes
SET is_active = $2, -- SET is_active = $2,
referral_code = $3, -- referral_code = $3,
number_of_referrals = $4, -- number_of_referrals = $4,
reward_amount = $5, -- reward_amount = $5,
updated_at = CURRENT_TIMESTAMP -- updated_at = CURRENT_TIMESTAMP
WHERE id = $1; -- WHERE id = $1;
-- name: GetReferralStats :one -- -- name: GetReferralStats :one
SELECT COUNT(*) AS total_referrals, -- SELECT COUNT(*) AS total_referrals,
COALESCE(SUM(reward_amount), 0)::bigint AS total_reward_earned -- COALESCE(SUM(reward_amount), 0)::bigint AS total_reward_earned
FROM user_referrals -- FROM user_referrals
JOIN referral_codes ON referral_codes.id = referral_code_id -- JOIN referral_codes ON referral_codes.id = referral_code_id
WHERE referrer_id = $1 -- WHERE referrer_id = $1
AND company_id = $2; -- AND company_id = $2;
-- name: GetUserReferral :one -- -- name: GetUserReferral :one
SELECT * -- SELECT *
FROM user_referrals -- FROM user_referrals
WHERE referred_id = $1; -- WHERE referred_id = $1;
-- name: GetUserReferralsByCode :many -- -- name: GetUserReferralsByCode :many
SELECT user_referrals.* -- SELECT user_referrals.*
FROM user_referrals -- FROM user_referrals
JOIN referral_codes ON referral_codes.id = referral_code_id -- JOIN referral_codes ON referral_codes.id = referral_code_id
WHERE referral_code = $1; -- WHERE referral_code = $1;
-- name: GetUserReferralsCount :one -- -- name: GetUserReferralsCount :one
SELECT COUNT(*) -- SELECT COUNT(*)
FROM user_referrals -- FROM user_referrals
JOIN referral_codes ON referral_codes.id = referral_code_id -- JOIN referral_codes ON referral_codes.id = referral_code_id
WHERE referrer_id = $1; -- WHERE referrer_id = $1;

View File

@ -1,53 +0,0 @@
-- name: CreateResult :one
INSERT INTO results (
bet_outcome_id,
event_id,
odd_id,
market_id,
status,
score,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
) RETURNING *;
-- name: InsertResult :exec
INSERT INTO results (
bet_outcome_id,
event_id,
odd_id,
market_id,
status,
score,
full_time_score,
half_time_score,
ss,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
);
-- name: GetResultByBetOutcomeID :one
SELECT * FROM results WHERE bet_outcome_id = $1;
-- name: GetPendingBetOutcomes :many
SELECT * FROM bet_outcomes WHERE status = 0 AND expires <= CURRENT_TIMESTAMP;

View File

@ -1,28 +0,0 @@
-- name: CreateResultLog :one
INSERT INTO result_log (
status_not_finished_count,
status_not_finished_bets,
status_to_be_fixed_count,
status_to_be_fixed_bets,
status_postponed_count,
status_postponed_bets,
status_ended_count,
status_ended_bets,
status_removed_count,
status_removed_bets,
removed_count
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING *;
-- name: GetAllResultLog :many
SELECT *
FROM result_log
WHERE (
created_at < sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at > sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
)
ORDER BY created_at DESC;

View File

@ -1,48 +1,48 @@
-- name: InsertGlobalSetting :exec -- -- name: InsertGlobalSetting :exec
INSERT INTO global_settings (key, value) -- INSERT INTO global_settings (key, value)
VALUES ($1, $2) ON CONFLICT (key) DO -- VALUES ($1, $2) ON CONFLICT (key) DO
UPDATE -- UPDATE
SET value = EXCLUDED.value; -- SET value = EXCLUDED.value;
-- name: GetGlobalSettings :many -- -- name: GetGlobalSettings :many
SELECT * -- SELECT *
FROM global_settings; -- FROM global_settings;
-- name: GetGlobalSetting :one -- -- name: GetGlobalSetting :one
SELECT * -- SELECT *
FROM global_settings -- FROM global_settings
WHERE key = $1; -- WHERE key = $1;
-- name: UpdateGlobalSetting :exec -- -- name: UpdateGlobalSetting :exec
UPDATE global_settings -- UPDATE global_settings
SET value = $2, -- SET value = $2,
updated_at = CURRENT_TIMESTAMP -- updated_at = CURRENT_TIMESTAMP
WHERE key = $1; -- WHERE key = $1;
-- name: InsertCompanySetting :exec -- -- name: InsertCompanySetting :exec
INSERT INTO company_settings (company_id, key, value) -- INSERT INTO company_settings (company_id, key, value)
VALUES ($1, $2, $3) ON CONFLICT (company_id, key) DO -- VALUES ($1, $2, $3) ON CONFLICT (company_id, key) DO
UPDATE -- UPDATE
SET value = EXCLUDED.value; -- SET value = EXCLUDED.value;
-- name: GetAllCompanySettings :many -- -- name: GetAllCompanySettings :many
SELECT * -- SELECT *
FROM company_settings; -- FROM company_settings;
-- name: GetCompanySetting :many -- -- name: GetCompanySetting :many
SELECT * -- SELECT *
FROM company_settings -- FROM company_settings
WHERE company_id = $1; -- WHERE company_id = $1;
-- name: GetCompanySettingsByKey :many -- -- name: GetCompanySettingsByKey :many
SELECT * -- SELECT *
FROM company_settings -- FROM company_settings
WHERE key = $1; -- WHERE key = $1;
-- name: GetOverrideSettings :many -- -- name: GetOverrideSettings :many
SELECT gs.key, -- SELECT gs.key,
gs.created_at, -- gs.created_at,
gs.updated_at, -- gs.updated_at,
COALESCE(cs.value, gs.value) AS value -- COALESCE(cs.value, gs.value) AS value
FROM global_settings gs -- FROM global_settings gs
LEFT JOIN company_settings cs ON cs.key = gs.key -- LEFT JOIN company_settings cs ON cs.key = gs.key
AND cs.company_id = $1; -- AND cs.company_id = $1;
-- name: DeleteCompanySetting :exec -- -- name: DeleteCompanySetting :exec
DELETE FROM company_settings -- DELETE FROM company_settings
WHERE company_id = $1 -- WHERE company_id = $1
AND key = $2; -- AND key = $2;
-- name: DeleteAllCompanySetting :exec -- -- name: DeleteAllCompanySetting :exec
DELETE FROM company_settings -- DELETE FROM company_settings
WHERE company_id = $1; -- WHERE company_id = $1;

View File

@ -1,178 +1,74 @@
-- name: CreateShopTransaction :one -- -- name: CreateShopTransaction :one
INSERT INTO shop_transactions ( -- INSERT INTO shop_transactions (
amount, -- amount,
branch_id, -- branch_id,
company_id, -- company_id,
user_id, -- user_id,
type, -- type,
full_name, -- full_name,
phone_number, -- phone_number,
payment_option, -- payment_option,
bank_code, -- bank_code,
beneficiary_name, -- beneficiary_name,
account_name, -- account_name,
account_number, -- account_number,
reference_number -- reference_number
) -- )
VALUES ( -- VALUES (
$1, -- $1,
$2, -- $2,
$3, -- $3,
$4, -- $4,
$5, -- $5,
$6, -- $6,
$7, -- $7,
$8, -- $8,
$9, -- $9,
$10, -- $10,
$11, -- $11,
$12, -- $12,
$13 -- $13
) -- )
RETURNING *; -- RETURNING *;
-- name: GetAllShopTransactions :many -- -- name: GetAllShopTransactions :many
SELECT * -- SELECT *
FROM shop_transaction_detail -- FROM shop_transaction_detail
wHERE ( -- wHERE (
branch_id = sqlc.narg('branch_id') -- branch_id = sqlc.narg('branch_id')
OR sqlc.narg('branch_id') IS NULL -- OR sqlc.narg('branch_id') IS NULL
) -- )
AND ( -- AND (
company_id = sqlc.narg('company_id') -- company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL -- OR sqlc.narg('company_id') IS NULL
) -- )
AND ( -- AND (
user_id = sqlc.narg('user_id') -- user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL -- OR sqlc.narg('user_id') IS NULL
) -- )
AND ( -- AND (
full_name ILIKE '%' || sqlc.narg('query') || '%' -- full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%' -- OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL -- OR sqlc.narg('query') IS NULL
) -- )
AND ( -- AND (
created_at > sqlc.narg('created_before') -- created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL -- OR sqlc.narg('created_before') IS NULL
) -- )
AND ( -- AND (
created_at < sqlc.narg('created_after') -- created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL -- OR sqlc.narg('created_after') IS NULL
); -- );
-- name: GetShopTransactionByID :one -- -- name: GetShopTransactionByID :one
SELECT * -- SELECT *
FROM shop_transaction_detail -- FROM shop_transaction_detail
WHERE id = $1; -- WHERE id = $1;
-- name: GetShopTransactionByBranch :many -- -- name: GetShopTransactionByBranch :many
SELECT * -- SELECT *
FROM shop_transaction_detail -- FROM shop_transaction_detail
WHERE branch_id = $1; -- WHERE branch_id = $1;
-- name: UpdateShopTransactionVerified :exec -- -- name: UpdateShopTransactionVerified :exec
UPDATE shop_transactions -- UPDATE shop_transactions
SET verified = $2, -- SET verified = $2,
approved_by = $3, -- approved_by = $3,
updated_at = CURRENT_TIMESTAMP -- updated_at = CURRENT_TIMESTAMP
WHERE id = $1; -- WHERE id = $1;
-- name: CreateShopBet :one
INSERT INTO shop_bets (
shop_transaction_id,
cashout_id,
bet_id,
number_of_outcomes
)
VALUES ($1, $2, $3, $4)
RETURNING *;
-- name: GetAllShopBets :many
SELECT *
FROM shop_bet_detail
WHERE (
full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
branch_id = sqlc.narg('branch_id')
OR sqlc.narg('branch_id') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetShopBetByID :one
SELECT *
FROM shop_bet_detail
WHERE id = $1;
-- name: GetShopBetByBetID :one
SELECT *
FROM shop_bet_detail
WHERE bet_id = $1;
-- name: GetShopBetByCashoutID :one
SELECT *
FROM shop_bet_detail
WHERE cashout_id = $1;
-- name: GetShopBetByShopTransactionID :one
SELECT *
FROM shop_bet_detail
WHERE shop_transaction_id = $1;
-- name: UpdateShopBetCashOut :exec
UPDATE shop_bets
SET cashed_out = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: UpdateShopBetCashoutID :exec
UPDATE shop_bets
SET cashout_id = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: CreateShopDeposit :one
INSERT INTO shop_deposits (
shop_transaction_id,
customer_id,
branch_wallet_id
)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetAllShopDeposit :many
SELECT *
FROM shop_deposit_detail
WHERE (
full_name ILIKE '%' || sqlc.narg('query') || '%'
OR phone_number ILIKE '%' || sqlc.narg('query') || '%'
OR sqlc.narg('query') IS NULL
)
AND (
branch_id = sqlc.narg('branch_id')
OR sqlc.narg('branch_id') IS NULL
)
AND (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
)
AND (
created_at > sqlc.narg('created_before')
OR sqlc.narg('created_before') IS NULL
)
AND (
created_at < sqlc.narg('created_after')
OR sqlc.narg('created_after') IS NULL
);
-- name: GetShopDepositByID :one
SELECT *
FROM shop_deposit_detail
WHERE id = $1;
-- name: GetShopDepositByShopTransactionID :one
SELECT *
FROM shop_deposit_detail
WHERE shop_transaction_id = $1;
-- name: UpdateShopDepositTransferID :exec
UPDATE shop_deposits
SET wallet_transfer_id = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;

View File

@ -1,70 +0,0 @@
-- name: CreateTicket :one
INSERT INTO tickets (amount, total_odds, ip, company_id)
VALUES ($1, $2, $3, $4)
RETURNING *;
-- name: CreateTicketOutcome :copyfrom
INSERT INTO ticket_outcomes (
ticket_id,
event_id,
odd_id,
home_team_name,
away_team_name,
market_id,
market_name,
odd,
odd_name,
odd_header,
odd_handicap,
expires
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12
);
-- name: GetAllTickets :many
SELECT *
FROM ticket_with_outcomes
WHERE (
company_id = sqlc.narg('company_id')
OR sqlc.narg('company_id') IS NULL
);
-- name: GetTicketByID :one
SELECT *
FROM ticket_with_outcomes
WHERE id = $1;
-- name: GetTicketOutcome :many
SELECT *
FROM ticket_outcomes
WHERE ticket_id = $1;
-- name: CountTicketByIP :one
SELECT count(id)
FROM tickets
WHERE IP = $1;
-- name: UpdateTicketOutcomeStatus :exec
UPDATE ticket_outcomes
SET status = $1
WHERE id = $2;
-- name: DeleteTicket :exec
DELETE FROM tickets
WHERE id = $1;
-- name: DeleteOldTickets :exec
Delete from tickets
where created_at < now() - interval '1 day';
-- name: DeleteTicketOutcome :exec
Delete from ticket_outcomes
where ticket_id = $1;
-- name: GetAllTicketsInRange :one
SELECT COUNT(*) as total_tickets,
COALESCE(SUM(amount), 0) as total_amount
FROM tickets
WHERE created_at BETWEEN $1 AND $2;

View File

@ -1,63 +0,0 @@
-- name: CreateTransfer :one
INSERT INTO wallet_transfer (
amount,
message,
type,
receiver_wallet_id,
sender_wallet_id,
cashier_id,
verified,
reference_number,
ext_reference_number,
session_id,
status,
payment_method
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING *;
-- name: GetAllTransfers :many
SELECT *
FROM wallet_transfer_details;
-- name: GetTransfersByWallet :many
SELECT *
FROM wallet_transfer_details
WHERE receiver_wallet_id = $1
OR sender_wallet_id = $1;
-- name: GetTransferByID :one
SELECT *
FROM wallet_transfer_details
WHERE id = $1;
-- name: GetTransferByReference :one
SELECT *
FROM wallet_transfer_details
WHERE reference_number = $1;
-- name: GetTransferStats :one
SELECT COUNT(*) AS total_transfers, COUNT(*) FILTER (
WHERE type = 'deposit'
) AS total_deposits,
COUNT(*) FILTER (
WHERE type = 'withdraw'
) AS total_withdraw,
COUNT(*) FILTER (
WHERE type = 'wallet'
) AS total_wallet_to_wallet
FROM wallet_transfer
WHERE sender_wallet_id = $1
OR receiver_wallet_id = $1;
-- name: UpdateTransferVerification :exec
UPDATE wallet_transfer
SET verified = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: UpdateTransferStatus :exec
UPDATE wallet_transfer
SET status = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: GetWalletTransactionsInRange :many
SELECT type,
COUNT(*) as count,
SUM(amount) as total_amount
FROM wallet_transfer
WHERE created_at BETWEEN $1 AND $2
GROUP BY type;

View File

@ -2,16 +2,22 @@
INSERT INTO users ( INSERT INTO users (
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
password, password,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at,
updated_at,
suspended, suspended,
company_id suspended_at,
organization_id,
created_at,
updated_at
) )
VALUES ( VALUES (
$1, $1,
@ -25,20 +31,32 @@ VALUES (
$9, $9,
$10, $10,
$11, $11,
$12 $12,
$13,
$14,
$15,
$16,
$17,
$18
) )
RETURNING id, RETURNING id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at, created_at,
updated_at, updated_at,
suspended, suspended,
company_id; suspended_at,
organization_id;
-- name: GetUserByID :one -- name: GetUserByID :one
SELECT * SELECT *
FROM users FROM users
@ -47,23 +65,28 @@ WHERE id = $1;
SELECT id, SELECT id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at, created_at,
updated_at, updated_at,
suspended, suspended,
suspended_at, suspended_at,
company_id organization_id
FROM users FROM users
wHERE ( wHERE (
role = $1 role = $1
OR $1 IS NULL OR $1 IS NULL
) )
AND ( AND (
company_id = $2 organization_id = $2
OR $2 IS NULL OR $2 IS NULL
) )
AND ( AND (
@ -89,27 +112,32 @@ wHERE (
OR $1 IS NULL OR $1 IS NULL
) )
AND ( AND (
company_id = $2 organization_id = $2
OR $2 IS NULL OR $2 IS NULL
); );
-- name: SearchUserByNameOrPhone :many -- name: SearchUserByNameOrPhone :many
SELECT id, SELECT id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at, created_at,
updated_at, updated_at,
suspended, suspended,
suspended_at, suspended_at,
company_id organization_id
FROM users FROM users
WHERE ( WHERE (
company_id = sqlc.narg('company_id') organization_id = sqlc.narg('organization_id')
OR sqlc.narg('company_id') IS NULL OR sqlc.narg('organization_id') IS NULL
) )
AND ( AND (
first_name ILIKE '%' || $1 || '%' first_name ILIKE '%' || $1 || '%'
@ -127,9 +155,9 @@ SET first_name = $1,
suspended = $3, suspended = $3,
updated_at = CURRENT_TIMESTAMP updated_at = CURRENT_TIMESTAMP
WHERE id = $4; WHERE id = $4;
-- name: UpdateUserCompany :exec -- name: UpdateUserOrganization :exec
UPDATE users UPDATE users
SET company_id = $1 SET organization_id = $1
WHERE id = $2; WHERE id = $2;
-- name: SuspendUser :exec -- name: SuspendUser :exec
UPDATE users UPDATE users
@ -146,60 +174,69 @@ SELECT EXISTS (
FROM users FROM users
WHERE users.phone_number = $1 WHERE users.phone_number = $1
AND users.phone_number IS NOT NULL AND users.phone_number IS NOT NULL
AND users.company_id = $2 AND users.organization_id = $2
) AS phone_exists, ) AS phone_exists,
EXISTS ( EXISTS (
SELECT 1 SELECT 1
FROM users FROM users
WHERE users.email = $3 WHERE users.email = $3
AND users.email IS NOT NULL AND users.email IS NOT NULL
AND users.company_id = $2 AND users.organization_id = $2
) AS email_exists; ) AS email_exists;
-- name: GetUserByEmail :one -- name: GetUserByEmail :one
SELECT id, SELECT id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at, created_at,
updated_at, updated_at,
suspended, suspended,
suspended_at, suspended_at,
company_id organization_id
FROM users FROM users
WHERE email = $1 WHERE email = $1
AND company_id = $2; AND organization_id = $2;
-- name: GetUserByPhone :one -- name: GetUserByPhone :one
SELECT id, SELECT id,
first_name, first_name,
last_name, last_name,
nick_name,
email, email,
phone_number, phone_number,
role, role,
age,
education_level,
country,
region,
email_verified, email_verified,
phone_verified, phone_verified,
created_at, created_at,
updated_at, updated_at,
suspended, suspended,
suspended_at, suspended_at,
company_id organization_id
FROM users FROM users
WHERE phone_number = $1 WHERE phone_number = $1
AND company_id = $2; AND organization_id = $2;
-- name: UpdatePassword :exec -- name: UpdatePassword :exec
UPDATE users UPDATE users
SET password = $1, SET password = $1,
updated_at = $4 updated_at = $4
WHERE ( WHERE (
email = $2 (email = $2 OR phone_number = $3)
OR phone_number = $3 AND organization_id = $5
AND company_id = $5
); );
-- name: GetAdminByCompanyID :one -- name: GetOwnerByOrganizationID :one
SELECT users.* SELECT users.*
FROM companies FROM organizations
JOIN users ON companies.admin_id = users.id JOIN users ON organizations.owner_id = users.id
where companies.id = $1; WHERE organizations.id = $1;

View File

@ -1,386 +0,0 @@
-- name: CreateVirtualGameProvider :one
INSERT INTO virtual_game_providers (
provider_id,
provider_name,
logo_dark,
logo_light,
enabled
)
VALUES ($1, $2, $3, $4, $5)
RETURNING id,
provider_id,
provider_name,
logo_dark,
logo_light,
enabled,
created_at,
updated_at;
-- name: DeleteVirtualGameProvider :exec
DELETE FROM virtual_game_providers
WHERE provider_id = $1;
-- name: DeleteAllVirtualGameProviders :exec
DELETE FROM virtual_game_providers;
-- name: GetVirtualGameProviderByID :one
SELECT id,
provider_id,
provider_name,
logo_dark,
logo_light,
enabled,
created_at,
updated_at
FROM virtual_game_providers
WHERE provider_id = $1;
-- name: ListVirtualGameProviders :many
SELECT id,
provider_id,
provider_name,
logo_dark,
logo_light,
enabled,
created_at,
updated_at
FROM virtual_game_providers
ORDER BY created_at DESC
LIMIT $1 OFFSET $2;
-- name: CountVirtualGameProviders :one
SELECT COUNT(*) AS total
FROM virtual_game_providers;
-- name: UpdateVirtualGameProviderEnabled :one
UPDATE virtual_game_providers
SET enabled = $2,
updated_at = CURRENT_TIMESTAMP
WHERE provider_id = $1
RETURNING id,
provider_id,
provider_name,
logo_dark,
logo_light,
enabled,
created_at,
updated_at;
-- name: CreateVirtualGameSession :one
INSERT INTO virtual_game_sessions (
user_id,
game_id,
session_token
)
VALUES ($1, $2, $3)
RETURNING
id,
user_id,
game_id,
session_token,
created_at,
updated_at;
-- name: GetVirtualGameSessionByUserID :one
SELECT
id,
user_id,
game_id,
session_token,
created_at,
updated_at
FROM virtual_game_sessions
WHERE user_id = $1;
-- name: GetVirtualGameSessionByToken :one
SELECT id,
user_id,
game_id,
session_token,
created_at,
updated_at
FROM virtual_game_sessions
WHERE session_token = $1;
-- name: CreateVirtualGameTransaction :one
INSERT INTO virtual_game_transactions (
-- session_id,
user_id,
company_id,
provider,
wallet_id,
transaction_type,
amount,
currency,
external_transaction_id,
status
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id,
-- session_id,
user_id,
company_id,
provider,
wallet_id,
transaction_type,
amount,
currency,
external_transaction_id,
status,
created_at,
updated_at;
-- name: CreateVirtualGameHistory :one
INSERT INTO virtual_game_histories (
-- session_id,
user_id,
company_id,
provider,
wallet_id,
game_id,
transaction_type,
amount,
currency,
external_transaction_id,
reference_transaction_id,
status
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11
-- $12
)
RETURNING id,
-- session_id,
user_id,
company_id,
provider,
wallet_id,
game_id,
transaction_type,
amount,
currency,
external_transaction_id,
reference_transaction_id,
status,
created_at,
updated_at;
-- name: GetVirtualGameTransactionByExternalID :one
SELECT id,
-- session_id,
user_id,
wallet_id,
transaction_type,
amount,
currency,
external_transaction_id,
status,
created_at,
updated_at
FROM virtual_game_transactions
WHERE external_transaction_id = $1;
-- name: UpdateVirtualGameTransactionStatus :exec
UPDATE virtual_game_transactions
SET status = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: GetVirtualGameSummaryInRange :many
SELECT c.name AS company_name,
vg.name AS game_name,
COUNT(vgt.id) AS number_of_bets,
COALESCE(SUM(vgt.amount), 0) AS total_transaction_sum
FROM virtual_game_transactions vgt
-- JOIN virtual_game_sessions vgs ON vgt.session_id = vgs.id
JOIN virtual_games vg ON vgs.game_id = vg.id
JOIN companies c ON vgt.company_id = c.id
WHERE vgt.transaction_type = 'BET'
AND vgt.created_at BETWEEN $1 AND $2
GROUP BY c.name,
vg.name;
-- name: AddFavoriteGame :exec
INSERT INTO virtual_game_favourites (user_id, game_id, provider_id, created_at)
VALUES ($1, $2, $3, NOW())
ON CONFLICT (game_id, user_id) DO NOTHING;
-- name: RemoveFavoriteGame :exec
DELETE FROM virtual_game_favourites
WHERE user_id = $1 AND game_id = $2 AND provider_id = $3;
-- name: GetUserFavoriteGamesPaginated :many
SELECT
vg.*
FROM virtual_games vg
JOIN virtual_game_favourites vf
ON vf.game_id = vg.id
WHERE
vf.user_id = $1
AND ($2::varchar IS NULL OR vf.provider_id = $2)
ORDER BY vf.created_at DESC
LIMIT $3 OFFSET $4;
-- name: CreateVirtualGame :one
INSERT INTO virtual_games (
game_id,
provider_id,
name,
category,
device_type,
volatility,
rtp,
has_demo,
has_free_bets,
bets,
thumbnail,
status
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12
)
RETURNING id,
game_id,
provider_id,
name,
category,
device_type,
volatility,
rtp,
has_demo,
has_free_bets,
bets,
thumbnail,
status,
created_at,
updated_at;
-- name: GetAllVirtualGames :many
SELECT vg.id,
vg.game_id,
vg.provider_id,
vp.provider_name,
vg.name,
vg.category,
vg.device_type,
vg.volatility,
vg.rtp,
vg.has_demo,
vg.has_free_bets,
vg.bets,
vg.thumbnail,
vg.status,
vg.created_at,
vg.updated_at
FROM virtual_games vg
JOIN virtual_game_providers vp ON vg.provider_id = vp.provider_id
WHERE (
vg.category = sqlc.narg('category')
OR sqlc.narg('category') IS NULL
)
AND (
name ILIKE '%' || sqlc.narg('name') || '%'
OR sqlc.narg('name') IS NULL
)
AND (
vg.provider_id = sqlc.narg('provider_id')
OR sqlc.narg('provider_id') IS NULL
)
ORDER BY vg.created_at DESC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: DeleteAllVirtualGames :exec
DELETE FROM virtual_games;
-- name: CreateVirtualGameProviderReport :one
INSERT INTO virtual_game_provider_reports (
provider_id,
report_date,
total_games_played,
total_bets,
total_payouts,
total_players,
report_type,
created_at,
updated_at
) VALUES (
$1, $2, $3, $4, $5, $6, COALESCE($7, 'daily'), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
ON CONFLICT (provider_id, report_date, report_type) DO UPDATE
SET
total_games_played = EXCLUDED.total_games_played,
total_bets = EXCLUDED.total_bets,
total_payouts = EXCLUDED.total_payouts,
total_players = EXCLUDED.total_players,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: CreateVirtualGameReport :one
INSERT INTO virtual_game_reports (
game_id,
provider_id,
report_date,
total_rounds,
total_bets,
total_payouts,
total_players,
report_type,
created_at,
updated_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, COALESCE($8, 'daily'), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)
ON CONFLICT (game_id, report_date, report_type) DO UPDATE
SET
total_rounds = EXCLUDED.total_rounds,
total_bets = EXCLUDED.total_bets,
total_payouts = EXCLUDED.total_payouts,
total_players = EXCLUDED.total_players,
updated_at = CURRENT_TIMESTAMP
RETURNING *;
-- name: GetVirtualGameProviderReportByProviderAndDate :one
SELECT *
FROM virtual_game_provider_reports
WHERE provider_id = $1
AND report_date = $2
AND report_type = $3;
-- name: UpdateVirtualGameProviderReportByDate :exec
UPDATE virtual_game_provider_reports
SET
total_games_played = total_games_played + $4,
total_bets = total_bets + $5,
total_payouts = total_payouts + $6,
total_players = total_players + $7,
updated_at = CURRENT_TIMESTAMP
WHERE
provider_id = $1
AND report_date = $2
AND report_type = $3;
-- name: ListVirtualGameProviderReportsByGamesPlayedAsc :many
SELECT *
FROM virtual_game_provider_reports
ORDER BY total_games_played ASC;
-- name: ListVirtualGameProviderReportsByGamesPlayedDesc :many
SELECT *
FROM virtual_game_provider_reports
ORDER BY total_games_played DESC;

View File

@ -1,139 +0,0 @@
-- name: CreateFinancialReport :one
INSERT INTO virtual_game_financial_reports (
game_id, provider_id, report_date, report_type,
total_bets, total_wins, created_at
) VALUES ($1, $2, $3, $4, $5, $6, NOW())
RETURNING *;
-- name: UpsertFinancialReport :one
INSERT INTO virtual_game_financial_reports (
game_id, provider_id, report_date, report_type,
total_bets, total_wins, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
ON CONFLICT (game_id, provider_id, report_date, report_type)
DO UPDATE SET
total_bets = EXCLUDED.total_bets,
total_wins = EXCLUDED.total_wins,
updated_at = NOW()
RETURNING *;
-- name: GetFinancialReportByID :one
SELECT * FROM virtual_game_financial_reports
WHERE id = $1;
-- name: GetFinancialReportsForGame :many
SELECT * FROM virtual_game_financial_reports
WHERE game_id = $1
AND provider_id = $2
AND report_date BETWEEN $3 AND $4
ORDER BY report_date;
-- name: GetDailyFinancialReports :many
SELECT * FROM virtual_game_financial_reports
WHERE report_date = $1
AND report_type = 'daily';
-- name: DeleteFinancialReport :exec
DELETE FROM virtual_game_financial_reports
WHERE id = $1;
-- name: CreateCompanyReport :one
INSERT INTO virtual_game_company_reports (
company_id, provider_id,
report_date, report_type,
total_bet_amount, total_win_amount, created_at
)
VALUES ($1, $2, $3, $4, $5, $6, NOW())
RETURNING *;
-- name: UpsertCompanyReport :one
INSERT INTO virtual_game_company_reports (
company_id, provider_id,
report_date, report_type,
total_bet_amount, total_win_amount,
created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
ON CONFLICT (company_id, provider_id, report_date, report_type)
DO UPDATE SET
total_bet_amount = EXCLUDED.total_bet_amount,
total_win_amount = EXCLUDED.total_win_amount,
updated_at = NOW()
RETURNING *;
-- name: GetCompanyReportByID :one
SELECT * FROM virtual_game_company_reports
WHERE id = $1;
-- name: GetCompanyReportsInRange :many
SELECT * FROM virtual_game_company_reports
WHERE company_id = $1
AND provider_id = $2
AND report_date BETWEEN $3 AND $4
ORDER BY report_date;
-- name: GetCompanyProfitTrend :many
SELECT report_date, SUM(net_profit) AS total_profit
FROM virtual_game_company_reports
WHERE company_id = $1
AND provider_id = $2
AND report_date BETWEEN $3 AND $4
GROUP BY report_date
ORDER BY report_date;
-- name: CreatePlayerActivityReport :one
INSERT INTO virtual_game_player_activity_reports (
user_id, report_date, report_type,
total_deposits, total_withdrawals,
total_bet_amount, total_win_amount,
rounds_played, created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())
RETURNING *;
-- name: UpsertPlayerActivityReport :one
INSERT INTO virtual_game_player_activity_reports (
user_id, report_date, report_type,
total_deposits, total_withdrawals,
total_bet_amount, total_win_amount,
rounds_played, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
ON CONFLICT (user_id, report_date, report_type)
DO UPDATE SET
total_deposits = EXCLUDED.total_deposits,
total_withdrawals = EXCLUDED.total_withdrawals,
total_bet_amount = EXCLUDED.total_bet_amount,
total_win_amount = EXCLUDED.total_win_amount,
rounds_played = EXCLUDED.rounds_played,
updated_at = NOW()
RETURNING *;
-- name: GetPlayerActivityByID :one
SELECT * FROM virtual_game_player_activity_reports
WHERE id = $1;
-- name: GetPlayerActivityByDate :one
SELECT * FROM virtual_game_player_activity_reports
WHERE user_id = $1
AND report_date = $2
AND report_type = $3;
-- name: GetPlayerActivityRange :many
SELECT * FROM virtual_game_player_activity_reports
WHERE user_id = $1
AND report_date BETWEEN $2 AND $3
ORDER BY report_date;
-- name: GetTopPlayersByNetResult :many
SELECT user_id, SUM(net_result) AS total_net
FROM virtual_game_player_activity_reports
WHERE report_date BETWEEN $1 AND $2
GROUP BY user_id
ORDER BY total_net DESC
LIMIT $3;
-- name: DeletePlayerActivityReport :exec
DELETE FROM virtual_game_player_activity_reports
WHERE id = $1;

View File

@ -1,75 +0,0 @@
-- name: CreateWallet :one
INSERT INTO wallets (
is_withdraw,
is_bettable,
is_transferable,
user_id,
type
)
VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: CreateCustomerWallet :one
INSERT INTO customer_wallets (
customer_id,
regular_wallet_id,
static_wallet_id
)
VALUES ($1, $2, $3)
RETURNING *;
-- name: GetAllWallets :many
SELECT *
FROM wallets;
-- name: GetWalletByID :one
SELECT *
FROM wallets
WHERE id = $1;
-- name: GetWalletByUserID :many
SELECT *
FROM wallets
WHERE user_id = $1;
-- name: GetAllCustomerWallet :many
SELECT *
FROM customer_wallet_details;
-- name: GetCustomerWallet :one
SELECT *
FROM customer_wallet_details
WHERE customer_id = $1;
-- name: GetAllBranchWallets :many
SELECT wallets.id,
wallets.balance,
wallets.is_active,
wallets.updated_at,
wallets.created_at,
branches.name,
branches.location,
branches.branch_manager_id,
branches.company_id,
branches.is_self_owned
FROM branches
JOIN wallets ON branches.wallet_id = wallets.id;
-- name: UpdateBalance :exec
UPDATE wallets
SET balance = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: UpdateWalletActive :exec
UPDATE wallets
SET is_active = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2;
-- name: GetCompanyByWalletID :one
SELECT id, name, admin_id, wallet_id
FROM companies
WHERE wallet_id = $1
LIMIT 1;
-- name: GetBranchByWalletID :one
SELECT id, name, location, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at
FROM branches
WHERE wallet_id = $1
LIMIT 1;
-- -- name: GetCustomerByWalletID :one
-- SELECT id, first_name, last_name, email, phone_number,email_verified,phone_verified,company_id,suspended
-- FROM users
-- WHERE wallet_id = $1
-- LIMIT 1;

View File

@ -1,130 +0,0 @@
-- name: UpdateWalletStats :exec
WITH all_transfers AS (
SELECT sender_wallet_id AS wallet_id,
amount,
type
FROM wallet_transfer
WHERE sender_wallet_id IS NOT NULL
UNION ALL
SELECT receiver_wallet_id AS wallet_id,
amount,
type
FROM wallet_transfer
WHERE receiver_wallet_id IS NOT NULL
),
transfer_stats AS (
SELECT wallet_id,
COUNT(*) AS number_of_transactions,
COALESCE(SUM(amount), 0) AS total_transactions,
COUNT(*) FILTER (
WHERE type = 'deposit'
) AS number_of_deposits,
COALESCE(
SUM(
CASE
WHEN type = 'deposit' THEN amount
ELSE 0
END
),
0
) AS total_deposits_amount,
COUNT(*) FILTER (
WHERE type = 'withdraw'
) AS number_of_withdraws,
COALESCE(
SUM(
CASE
WHEN type = 'withdraw' THEN amount
ELSE 0
END
),
0
) AS total_withdraws_amount,
COUNT(*) FILTER (
WHERE type = 'wallet'
) AS number_of_transfers,
COALESCE(
SUM(
CASE
WHEN type = 'wallet' THEN amount
ELSE 0
END
),
0
) AS total_transfers_amount
FROM all_transfers
GROUP BY wallet_id
)
INSERT INTO wallet_stats(
wallet_id,
wallet_user_id,
wallet_user_first_name,
wallet_user_last_name,
wallet_type,
interval_start,
number_of_transactions,
total_transactions,
number_of_deposits,
total_deposits_amount,
number_of_withdraws,
total_withdraws_amount,
number_of_transfers,
total_transfers_amount,
updated_at
)
SELECT w.id AS wallet_id,
w.user_id AS wallet_user_id,
u.first_name AS wallet_user_first_name,
u.last_name AS wallet_user_last_name,
w.type AS wallet_type,
DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start,
COALESCE(ts.number_of_transactions, 0) AS number_of_transactions,
COALESCE(ts.total_transactions, 0) AS total_transactions,
COALESCE(ts.number_of_deposits, 0) AS number_of_deposits,
COALESCE(ts.total_deposits_amount, 0) AS total_deposits_amount,
COALESCE(ts.number_of_withdraws, 0) AS number_of_withdraws,
COALESCE(ts.total_withdraws_amount, 0) AS total_withdraws_amount,
COALESCE(ts.number_of_transfers, 0) AS number_of_transfers,
COALESCE(ts.total_transfers_amount, 0) AS total_transfers_amount,
NOW() AS updated_at
FROM wallets w
LEFT JOIN users u ON u.id = w.user_id
LEFT JOIN transfer_stats ts ON ts.wallet_id = w.id ON CONFLICT (wallet_id, interval_start) DO
UPDATE
SET number_of_transactions = EXCLUDED.number_of_transactions,
total_transactions = EXCLUDED.total_transactions,
number_of_deposits = EXCLUDED.number_of_deposits,
total_deposits_amount = EXCLUDED.total_deposits_amount,
number_of_withdraws = EXCLUDED.number_of_withdraws,
total_withdraws_amount = EXCLUDED.total_withdraws_amount,
number_of_transfers = EXCLUDED.number_of_transfers,
total_transfers_amount = EXCLUDED.total_transfers_amount,
updated_at = EXCLUDED.updated_at;
-- name: GetWalletStatsByID :many
SELECT *
FROM wallet_stats
WHERE wallet_id = $1
ORDER BY interval_start DESC;
-- name: GetWalletStats :many
SELECT DATE_TRUNC(sqlc.narg('interval'), interval_start)::timestamp AS interval_start,
wallet_stats.wallet_id,
wallet_stats.wallet_user_id,
wallet_stats.wallet_user_first_name,
wallet_stats.wallet_user_last_name,
wallet_stats.wallet_type,
wallet_stats.number_of_transactions,
wallet_stats.total_transactions,
wallet_stats.number_of_deposits,
wallet_stats.total_deposits_amount,
wallet_stats.number_of_withdraws,
wallet_stats.total_withdraws_amount,
wallet_stats.number_of_transfers,
wallet_stats.total_transfers_amount,
wallet_stats.updated_at
FROM wallet_stats
WHERE (
wallet_stats.wallet_user_id = sqlc.narg('user_id')
OR sqlc.narg('user_id') IS NULL
)
GROUP BY interval_start
ORDER BY interval_start DESC;

View File

@ -1,31 +1,45 @@
-- For each table with an id sequence -- ======================================================
-- Reset sequences for LMS tables
-- ======================================================
SELECT setval( SELECT setval(
pg_get_serial_sequence('users', 'id'), pg_get_serial_sequence('users', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM users; FROM users;
SELECT setval( SELECT setval(
pg_get_serial_sequence('wallets', 'id'), pg_get_serial_sequence('refresh_tokens', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM wallets; FROM refresh_tokens;
SELECT setval( SELECT setval(
pg_get_serial_sequence('customer_wallets', 'id'), pg_get_serial_sequence('otps', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM customer_wallets; FROM otps;
SELECT setval( SELECT setval(
pg_get_serial_sequence('companies', 'id'), pg_get_serial_sequence('notifications', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM companies; FROM notifications;
SELECT setval( SELECT setval(
pg_get_serial_sequence('branches', 'id'), pg_get_serial_sequence('referral_codes', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM branches; FROM referral_codes;
SELECT setval( SELECT setval(
pg_get_serial_sequence('supported_operations', 'id'), pg_get_serial_sequence('user_referrals', 'id'),
COALESCE(MAX(id), 1) COALESCE(MAX(id), 1)
) )
FROM supported_operations; FROM user_referrals;
SELECT setval(
pg_get_serial_sequence('report_requests', 'id'),
COALESCE(MAX(id), 1)
)
FROM report_requests;

View File

@ -2,7 +2,7 @@ version: "3.8"
services: services:
postgres: postgres:
container_name: fortunebet-backend-postgres-1 container_name: yimaru-backend-postgres-1
image: postgres:16-alpine image: postgres:16-alpine
ports: ports:
- "5422:5432" - "5422:5432"
@ -22,7 +22,7 @@ services:
- ./exports:/exports - ./exports:/exports
mongo: mongo:
container_name: fortunebet-mongo container_name: yimaru-mongo
image: mongo:7.0.11 image: mongo:7.0.11
restart: always restart: always
ports: ports:

10535
docs/docs.go

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -36,7 +36,7 @@ func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshToken
} }
const GetRefreshToken = `-- name: GetRefreshToken :one const GetRefreshToken = `-- name: GetRefreshToken :one
SELECT id, user_id, token, expires_at, created_at, revoked SELECT id, user_id, token, expires_at, revoked, created_at
FROM refresh_tokens FROM refresh_tokens
WHERE token = $1 WHERE token = $1
` `
@ -49,14 +49,14 @@ func (q *Queries) GetRefreshToken(ctx context.Context, token string) (RefreshTok
&i.UserID, &i.UserID,
&i.Token, &i.Token,
&i.ExpiresAt, &i.ExpiresAt,
&i.CreatedAt,
&i.Revoked, &i.Revoked,
&i.CreatedAt,
) )
return i, err return i, err
} }
const GetRefreshTokenByUserID = `-- name: GetRefreshTokenByUserID :one const GetRefreshTokenByUserID = `-- name: GetRefreshTokenByUserID :one
SELECT id, user_id, token, expires_at, created_at, revoked SELECT id, user_id, token, expires_at, revoked, created_at
FROM refresh_tokens FROM refresh_tokens
WHERE user_id = $1 WHERE user_id = $1
` `
@ -69,21 +69,21 @@ func (q *Queries) GetRefreshTokenByUserID(ctx context.Context, userID int64) (Re
&i.UserID, &i.UserID,
&i.Token, &i.Token,
&i.ExpiresAt, &i.ExpiresAt,
&i.CreatedAt,
&i.Revoked, &i.Revoked,
&i.CreatedAt,
) )
return i, err return i, err
} }
const GetUserByEmailPhone = `-- name: GetUserByEmailPhone :one const GetUserByEmailPhone = `-- name: GetUserByEmailPhone :one
SELECT id, first_name, last_name, email, phone_number, role, password, email_verified, phone_verified, created_at, updated_at, company_id, suspended_at, suspended SELECT id, first_name, last_name, nick_name, email, phone_number, role, password, age, education_level, country, region, email_verified, phone_verified, suspended, suspended_at, organization_id, created_at, updated_at
FROM users FROM users
WHERE ( WHERE (
email = $1 email = $1
OR phone_number = $2 OR phone_number = $2
) )
AND ( AND (
company_id = $3 organization_id = $3
OR $3 IS NULL OR $3 IS NULL
) )
` `
@ -91,27 +91,32 @@ WHERE (
type GetUserByEmailPhoneParams struct { type GetUserByEmailPhoneParams struct {
Email pgtype.Text `json:"email"` Email pgtype.Text `json:"email"`
PhoneNumber pgtype.Text `json:"phone_number"` PhoneNumber pgtype.Text `json:"phone_number"`
CompanyID pgtype.Int8 `json:"company_id"` OrganizationID pgtype.Int8 `json:"organization_id"`
} }
func (q *Queries) GetUserByEmailPhone(ctx context.Context, arg GetUserByEmailPhoneParams) (User, error) { func (q *Queries) GetUserByEmailPhone(ctx context.Context, arg GetUserByEmailPhoneParams) (User, error) {
row := q.db.QueryRow(ctx, GetUserByEmailPhone, arg.Email, arg.PhoneNumber, arg.CompanyID) row := q.db.QueryRow(ctx, GetUserByEmailPhone, arg.Email, arg.PhoneNumber, arg.OrganizationID)
var i User var i User
err := row.Scan( err := row.Scan(
&i.ID, &i.ID,
&i.FirstName, &i.FirstName,
&i.LastName, &i.LastName,
&i.NickName,
&i.Email, &i.Email,
&i.PhoneNumber, &i.PhoneNumber,
&i.Role, &i.Role,
&i.Password, &i.Password,
&i.Age,
&i.EducationLevel,
&i.Country,
&i.Region,
&i.EmailVerified, &i.EmailVerified,
&i.PhoneVerified, &i.PhoneVerified,
&i.Suspended,
&i.SuspendedAt,
&i.OrganizationID,
&i.CreatedAt, &i.CreatedAt,
&i.UpdatedAt, &i.UpdatedAt,
&i.CompanyID,
&i.SuspendedAt,
&i.Suspended,
) )
return i, err return i, err
} }

View File

@ -1,930 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: bet.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const BulkUpdateBetOutcomeStatusByOddIDs = `-- name: BulkUpdateBetOutcomeStatusByOddIDs :exec
UPDATE bet_outcomes
SET status = $1
WHERE odd_id = ANY($2::BIGINT [])
`
type BulkUpdateBetOutcomeStatusByOddIDsParams struct {
Status int32 `json:"status"`
OddIds []int64 `json:"odd_ids"`
}
func (q *Queries) BulkUpdateBetOutcomeStatusByOddIDs(ctx context.Context, arg BulkUpdateBetOutcomeStatusByOddIDsParams) error {
_, err := q.db.Exec(ctx, BulkUpdateBetOutcomeStatusByOddIDs, arg.Status, arg.OddIds)
return err
}
const CreateBet = `-- name: CreateBet :one
INSERT INTO bets (
amount,
total_odds,
status,
user_id,
is_shop_bet,
outcomes_hash,
fast_code,
company_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at
`
type CreateBetParams struct {
Amount int64 `json:"amount"`
TotalOdds float32 `json:"total_odds"`
Status int32 `json:"status"`
UserID int64 `json:"user_id"`
IsShopBet bool `json:"is_shop_bet"`
OutcomesHash string `json:"outcomes_hash"`
FastCode string `json:"fast_code"`
CompanyID int64 `json:"company_id"`
}
func (q *Queries) CreateBet(ctx context.Context, arg CreateBetParams) (Bet, error) {
row := q.db.QueryRow(ctx, CreateBet,
arg.Amount,
arg.TotalOdds,
arg.Status,
arg.UserID,
arg.IsShopBet,
arg.OutcomesHash,
arg.FastCode,
arg.CompanyID,
)
var i Bet
err := row.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
type CreateBetOutcomeParams struct {
BetID int64 `json:"bet_id"`
SportID int64 `json:"sport_id"`
EventID int64 `json:"event_id"`
OddID int64 `json:"odd_id"`
HomeTeamName string `json:"home_team_name"`
AwayTeamName string `json:"away_team_name"`
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
Odd float32 `json:"odd"`
OddName string `json:"odd_name"`
OddHeader string `json:"odd_header"`
OddHandicap string `json:"odd_handicap"`
Expires pgtype.Timestamp `json:"expires"`
}
const DeleteBet = `-- name: DeleteBet :exec
DELETE FROM bets
WHERE id = $1
`
func (q *Queries) DeleteBet(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteBet, id)
return err
}
const DeleteBetOutcome = `-- name: DeleteBetOutcome :exec
DELETE FROM bet_outcomes
WHERE bet_id = $1
`
func (q *Queries) DeleteBetOutcome(ctx context.Context, betID int64) error {
_, err := q.db.Exec(ctx, DeleteBetOutcome, betID)
return err
}
const GetAllBets = `-- name: GetAllBets :many
SELECT id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at, full_name, phone_number, outcomes, company_slug
FROM bet_with_outcomes
wHERE (
user_id = $1
OR $1 IS NULL
)
AND (
is_shop_bet = $2
OR $2 IS NULL
)
AND (
company_id = $3
OR $3 IS NULL
)
AND (
status = $4
OR $4 IS NULL
)
AND (
cashed_out = $5
OR $5 IS NULL
)
AND (
full_name ILIKE '%' || $6 || '%'
OR phone_number ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
AND (
created_at > $7
OR $7 IS NULL
)
AND (
created_at < $8
OR $8 IS NULL
)
LIMIT $10 OFFSET $9
`
type GetAllBetsParams struct {
UserID pgtype.Int8 `json:"user_id"`
IsShopBet pgtype.Bool `json:"is_shop_bet"`
CompanyID pgtype.Int8 `json:"company_id"`
Status pgtype.Int4 `json:"status"`
CashedOut pgtype.Bool `json:"cashed_out"`
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllBets(ctx context.Context, arg GetAllBetsParams) ([]BetWithOutcome, error) {
rows, err := q.db.Query(ctx, GetAllBets,
arg.UserID,
arg.IsShopBet,
arg.CompanyID,
arg.Status,
arg.CashedOut,
arg.Query,
arg.CreatedBefore,
arg.CreatedAfter,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetWithOutcome
for rows.Next() {
var i BetWithOutcome
if err := rows.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
&i.FullName,
&i.PhoneNumber,
&i.Outcomes,
&i.CompanySlug,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetByFastCode = `-- name: GetBetByFastCode :one
SELECT id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at, full_name, phone_number, outcomes, company_slug
FROM bet_with_outcomes
WHERE fast_code = $1
LIMIT 1
`
func (q *Queries) GetBetByFastCode(ctx context.Context, fastCode string) (BetWithOutcome, error) {
row := q.db.QueryRow(ctx, GetBetByFastCode, fastCode)
var i BetWithOutcome
err := row.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
&i.FullName,
&i.PhoneNumber,
&i.Outcomes,
&i.CompanySlug,
)
return i, err
}
const GetBetByID = `-- name: GetBetByID :one
SELECT id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at, full_name, phone_number, outcomes, company_slug
FROM bet_with_outcomes
WHERE id = $1
`
func (q *Queries) GetBetByID(ctx context.Context, id int64) (BetWithOutcome, error) {
row := q.db.QueryRow(ctx, GetBetByID, id)
var i BetWithOutcome
err := row.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
&i.FullName,
&i.PhoneNumber,
&i.Outcomes,
&i.CompanySlug,
)
return i, err
}
const GetBetByUserID = `-- name: GetBetByUserID :many
SELECT id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at, full_name, phone_number, outcomes, company_slug
FROM bet_with_outcomes
WHERE user_id = $1
`
func (q *Queries) GetBetByUserID(ctx context.Context, userID int64) ([]BetWithOutcome, error) {
rows, err := q.db.Query(ctx, GetBetByUserID, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetWithOutcome
for rows.Next() {
var i BetWithOutcome
if err := rows.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
&i.FullName,
&i.PhoneNumber,
&i.Outcomes,
&i.CompanySlug,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetCountByOutcomesHash = `-- name: GetBetCountByOutcomesHash :one
SELECT COUNT(*)
FROM bets
WHERE outcomes_hash = $1
`
func (q *Queries) GetBetCountByOutcomesHash(ctx context.Context, outcomesHash string) (int64, error) {
row := q.db.QueryRow(ctx, GetBetCountByOutcomesHash, outcomesHash)
var count int64
err := row.Scan(&count)
return count, err
}
const GetBetCountByUserID = `-- name: GetBetCountByUserID :one
SELECT COUNT(*)
FROM bets
WHERE user_id = $1
AND outcomes_hash = $2
`
type GetBetCountByUserIDParams struct {
UserID int64 `json:"user_id"`
OutcomesHash string `json:"outcomes_hash"`
}
func (q *Queries) GetBetCountByUserID(ctx context.Context, arg GetBetCountByUserIDParams) (int64, error) {
row := q.db.QueryRow(ctx, GetBetCountByUserID, arg.UserID, arg.OutcomesHash)
var count int64
err := row.Scan(&count)
return count, err
}
const GetBetOutcomeByBetID = `-- name: GetBetOutcomeByBetID :many
SELECT id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
FROM bet_outcomes
WHERE bet_id = $1
`
func (q *Queries) GetBetOutcomeByBetID(ctx context.Context, betID int64) ([]BetOutcome, error) {
rows, err := q.db.Query(ctx, GetBetOutcomeByBetID, betID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetOutcome
for rows.Next() {
var i BetOutcome
if err := rows.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetOutcomeByEventID = `-- name: GetBetOutcomeByEventID :many
SELECT id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
FROM bet_outcomes
WHERE (event_id = $1)
AND (
status = $2
OR $2 IS NULL
OR status = $3
OR $3 IS NULL
)
`
type GetBetOutcomeByEventIDParams struct {
EventID int64 `json:"event_id"`
FilterStatus pgtype.Int4 `json:"filter_status"`
FilterStatus2 pgtype.Int4 `json:"filter_status_2"`
}
func (q *Queries) GetBetOutcomeByEventID(ctx context.Context, arg GetBetOutcomeByEventIDParams) ([]BetOutcome, error) {
rows, err := q.db.Query(ctx, GetBetOutcomeByEventID, arg.EventID, arg.FilterStatus, arg.FilterStatus2)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetOutcome
for rows.Next() {
var i BetOutcome
if err := rows.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetOutcomeCountByOddID = `-- name: GetBetOutcomeCountByOddID :one
SELECT COUNT(*)
FROM bet_outcomes
WHERE odd_id = $1
`
func (q *Queries) GetBetOutcomeCountByOddID(ctx context.Context, oddID int64) (int64, error) {
row := q.db.QueryRow(ctx, GetBetOutcomeCountByOddID, oddID)
var count int64
err := row.Scan(&count)
return count, err
}
const GetBetOutcomeViewByEventID = `-- name: GetBetOutcomeViewByEventID :many
SELECT bet_outcomes.id, bet_outcomes.bet_id, bet_outcomes.sport_id, bet_outcomes.event_id, bet_outcomes.odd_id, bet_outcomes.home_team_name, bet_outcomes.away_team_name, bet_outcomes.market_id, bet_outcomes.market_name, bet_outcomes.odd, bet_outcomes.odd_name, bet_outcomes.odd_header, bet_outcomes.odd_handicap, bet_outcomes.status, bet_outcomes.expires,
users.first_name,
users.last_name,
bets.amount,
bets.total_odds,
companies.name as company_name
FROM bet_outcomes
JOIN bets ON bets.id = bet_outcomes.bet_id
JOIN users ON bets.user_id = users.id
JOIN companies ON bets.company_id = companies.id
WHERE bet_outcomes.event_id = $1
AND (
bets.company_id = $2
OR $2 IS NULL
)
AND (
bet_outcomes.status = $3
OR $3 IS NULL
)
LIMIT $5 OFFSET $4
`
type GetBetOutcomeViewByEventIDParams struct {
EventID int64 `json:"event_id"`
CompanyID pgtype.Int8 `json:"company_id"`
FilterStatus pgtype.Int4 `json:"filter_status"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
type GetBetOutcomeViewByEventIDRow struct {
ID int64 `json:"id"`
BetID int64 `json:"bet_id"`
SportID int64 `json:"sport_id"`
EventID int64 `json:"event_id"`
OddID int64 `json:"odd_id"`
HomeTeamName string `json:"home_team_name"`
AwayTeamName string `json:"away_team_name"`
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
Odd float32 `json:"odd"`
OddName string `json:"odd_name"`
OddHeader string `json:"odd_header"`
OddHandicap string `json:"odd_handicap"`
Status int32 `json:"status"`
Expires pgtype.Timestamp `json:"expires"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Amount int64 `json:"amount"`
TotalOdds float32 `json:"total_odds"`
CompanyName string `json:"company_name"`
}
func (q *Queries) GetBetOutcomeViewByEventID(ctx context.Context, arg GetBetOutcomeViewByEventIDParams) ([]GetBetOutcomeViewByEventIDRow, error) {
rows, err := q.db.Query(ctx, GetBetOutcomeViewByEventID,
arg.EventID,
arg.CompanyID,
arg.FilterStatus,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBetOutcomeViewByEventIDRow
for rows.Next() {
var i GetBetOutcomeViewByEventIDRow
if err := rows.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
&i.FirstName,
&i.LastName,
&i.Amount,
&i.TotalOdds,
&i.CompanyName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetsForCashback = `-- name: GetBetsForCashback :many
SELECT id, company_id, amount, total_odds, potential_win, status, user_id, is_shop_bet, cashed_out, outcomes_hash, fast_code, processed, created_at, updated_at, full_name, phone_number, outcomes, company_slug
FROM bet_with_outcomes
WHERE status = 2
AND processed = false
`
func (q *Queries) GetBetsForCashback(ctx context.Context) ([]BetWithOutcome, error) {
rows, err := q.db.Query(ctx, GetBetsForCashback)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetWithOutcome
for rows.Next() {
var i BetWithOutcome
if err := rows.Scan(
&i.ID,
&i.CompanyID,
&i.Amount,
&i.TotalOdds,
&i.PotentialWin,
&i.Status,
&i.UserID,
&i.IsShopBet,
&i.CashedOut,
&i.OutcomesHash,
&i.FastCode,
&i.Processed,
&i.CreatedAt,
&i.UpdatedAt,
&i.FullName,
&i.PhoneNumber,
&i.Outcomes,
&i.CompanySlug,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetTotalBets = `-- name: GetTotalBets :one
SELECT COUNT(*)
FROM bets
wHERE (
user_id = $1
OR $1 IS NULL
)
AND (
is_shop_bet = $2
OR $2 IS NULL
)
AND (
company_id = $3
OR $3 IS NULL
)
AND (
status = $4
OR $4 IS NULL
)
AND (
cashed_out = $5
OR $5 IS NULL
)
AND (
full_name ILIKE '%' || $6 || '%'
OR phone_number ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
AND (
created_at > $7
OR $7 IS NULL
)
AND (
created_at < $8
OR $8 IS NULL
)
`
type GetTotalBetsParams struct {
UserID pgtype.Int8 `json:"user_id"`
IsShopBet pgtype.Bool `json:"is_shop_bet"`
CompanyID pgtype.Int8 `json:"company_id"`
Status pgtype.Int4 `json:"status"`
CashedOut pgtype.Bool `json:"cashed_out"`
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
func (q *Queries) GetTotalBets(ctx context.Context, arg GetTotalBetsParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalBets,
arg.UserID,
arg.IsShopBet,
arg.CompanyID,
arg.Status,
arg.CashedOut,
arg.Query,
arg.CreatedBefore,
arg.CreatedAfter,
)
var count int64
err := row.Scan(&count)
return count, err
}
const TotalBetOutcomeViewByEventID = `-- name: TotalBetOutcomeViewByEventID :one
SELECT count(*)
FROM bet_outcomes
JOIN bets ON bets.id = bet_outcomes.bet_id
WHERE bet_outcomes.event_id = $1
AND (
bets.company_id = $2
OR $2 IS NULL
)
AND (
bet_outcomes.status = $3
OR $3 IS NULL
)
`
type TotalBetOutcomeViewByEventIDParams struct {
EventID int64 `json:"event_id"`
CompanyID pgtype.Int8 `json:"company_id"`
FilterStatus pgtype.Int4 `json:"filter_status"`
}
func (q *Queries) TotalBetOutcomeViewByEventID(ctx context.Context, arg TotalBetOutcomeViewByEventIDParams) (int64, error) {
row := q.db.QueryRow(ctx, TotalBetOutcomeViewByEventID, arg.EventID, arg.CompanyID, arg.FilterStatus)
var count int64
err := row.Scan(&count)
return count, err
}
const UpdateBetOutcomeStatus = `-- name: UpdateBetOutcomeStatus :one
UPDATE bet_outcomes
SET status = $1
WHERE id = $2
RETURNING id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
`
type UpdateBetOutcomeStatusParams struct {
Status int32 `json:"status"`
ID int64 `json:"id"`
}
func (q *Queries) UpdateBetOutcomeStatus(ctx context.Context, arg UpdateBetOutcomeStatusParams) (BetOutcome, error) {
row := q.db.QueryRow(ctx, UpdateBetOutcomeStatus, arg.Status, arg.ID)
var i BetOutcome
err := row.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
)
return i, err
}
const UpdateBetOutcomeStatusByBetID = `-- name: UpdateBetOutcomeStatusByBetID :one
UPDATE bet_outcomes
SET status = $1
WHERE bet_id = $2
RETURNING id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
`
type UpdateBetOutcomeStatusByBetIDParams struct {
Status int32 `json:"status"`
BetID int64 `json:"bet_id"`
}
func (q *Queries) UpdateBetOutcomeStatusByBetID(ctx context.Context, arg UpdateBetOutcomeStatusByBetIDParams) (BetOutcome, error) {
row := q.db.QueryRow(ctx, UpdateBetOutcomeStatusByBetID, arg.Status, arg.BetID)
var i BetOutcome
err := row.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
)
return i, err
}
const UpdateBetOutcomeStatusForEvent = `-- name: UpdateBetOutcomeStatusForEvent :many
UPDATE bet_outcomes
SEt status = $1
WHERE event_id = $2
RETURNING id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
`
type UpdateBetOutcomeStatusForEventParams struct {
Status int32 `json:"status"`
EventID int64 `json:"event_id"`
}
func (q *Queries) UpdateBetOutcomeStatusForEvent(ctx context.Context, arg UpdateBetOutcomeStatusForEventParams) ([]BetOutcome, error) {
rows, err := q.db.Query(ctx, UpdateBetOutcomeStatusForEvent, arg.Status, arg.EventID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetOutcome
for rows.Next() {
var i BetOutcome
if err := rows.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateBetOutcomeStatusForOddID = `-- name: UpdateBetOutcomeStatusForOddID :many
UPDATE bet_outcomes
SEt status = $1
WHERE odd_id = $2
RETURNING id, bet_id, sport_id, event_id, odd_id, home_team_name, away_team_name, market_id, market_name, odd, odd_name, odd_header, odd_handicap, status, expires
`
type UpdateBetOutcomeStatusForOddIDParams struct {
Status int32 `json:"status"`
OddID int64 `json:"odd_id"`
}
func (q *Queries) UpdateBetOutcomeStatusForOddID(ctx context.Context, arg UpdateBetOutcomeStatusForOddIDParams) ([]BetOutcome, error) {
rows, err := q.db.Query(ctx, UpdateBetOutcomeStatusForOddID, arg.Status, arg.OddID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BetOutcome
for rows.Next() {
var i BetOutcome
if err := rows.Scan(
&i.ID,
&i.BetID,
&i.SportID,
&i.EventID,
&i.OddID,
&i.HomeTeamName,
&i.AwayTeamName,
&i.MarketID,
&i.MarketName,
&i.Odd,
&i.OddName,
&i.OddHeader,
&i.OddHandicap,
&i.Status,
&i.Expires,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateBetWithCashback = `-- name: UpdateBetWithCashback :exec
UPDATE bets
SET processed = $1
WHERE id = $2
`
type UpdateBetWithCashbackParams struct {
Processed bool `json:"processed"`
ID int64 `json:"id"`
}
func (q *Queries) UpdateBetWithCashback(ctx context.Context, arg UpdateBetWithCashbackParams) error {
_, err := q.db.Exec(ctx, UpdateBetWithCashback, arg.Processed, arg.ID)
return err
}
const UpdateCashOut = `-- name: UpdateCashOut :exec
UPDATE bets
SET cashed_out = $2,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
`
type UpdateCashOutParams struct {
ID int64 `json:"id"`
CashedOut bool `json:"cashed_out"`
}
func (q *Queries) UpdateCashOut(ctx context.Context, arg UpdateCashOutParams) error {
_, err := q.db.Exec(ctx, UpdateCashOut, arg.ID, arg.CashedOut)
return err
}
const UpdateStatus = `-- name: UpdateStatus :exec
UPDATE bets
SET status = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2
`
type UpdateStatusParams struct {
Status int32 `json:"status"`
ID int64 `json:"id"`
}
func (q *Queries) UpdateStatus(ctx context.Context, arg UpdateStatusParams) error {
_, err := q.db.Exec(ctx, UpdateStatus, arg.Status, arg.ID)
return err
}

View File

@ -1,429 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: bet_stat.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetBetStats = `-- name: GetBetStats :many
SELECT DATE(created_at) as date,
COUNT(*) as total_bets,
SUM(amount) as total_stakes,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as total_payouts,
AVG(total_odds) as average_odds
FROM bets
wHERE (
user_id = $1
OR $1 IS NULL
)
AND (
company_id = $2
OR $2 IS NULL
)
AND (
is_shop_bet = $3
OR $3 IS NULL
)
AND (
cashed_out = $4
OR $4 IS NULL
)
AND (
full_name ILIKE '%' || $5 || '%'
OR phone_number ILIKE '%' || $5 || '%'
OR $5 IS NULL
)
AND (
created_at > $6
OR $6 IS NULL
)
AND (
created_at < $7
OR $7 IS NULL
)
GROUP BY DATE(created_at)
ORDER BY DATE(created_at)
`
type GetBetStatsParams struct {
UserID pgtype.Int8 `json:"user_id"`
CompanyID pgtype.Int8 `json:"company_id"`
IsShopBet pgtype.Bool `json:"is_shop_bet"`
CashedOut pgtype.Bool `json:"cashed_out"`
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
type GetBetStatsRow struct {
Date pgtype.Date `json:"date"`
TotalBets int64 `json:"total_bets"`
TotalStakes int64 `json:"total_stakes"`
TotalWins int64 `json:"total_wins"`
TotalPayouts int64 `json:"total_payouts"`
AverageOdds float64 `json:"average_odds"`
}
func (q *Queries) GetBetStats(ctx context.Context, arg GetBetStatsParams) ([]GetBetStatsRow, error) {
rows, err := q.db.Query(ctx, GetBetStats,
arg.UserID,
arg.CompanyID,
arg.IsShopBet,
arg.CashedOut,
arg.Query,
arg.CreatedBefore,
arg.CreatedAfter,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBetStatsRow
for rows.Next() {
var i GetBetStatsRow
if err := rows.Scan(
&i.Date,
&i.TotalBets,
&i.TotalStakes,
&i.TotalWins,
&i.TotalPayouts,
&i.AverageOdds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetStatsByInterval = `-- name: GetBetStatsByInterval :many
SELECT DATE_TRUNC($1, created_at)::timestamp AS date,
COUNT(*) as total_bets,
SUM(amount) AS total_stake,
SUM(
CASE
WHEN status = 0 THEN 1
ELSE 0
END
) as active_bets,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 2 THEN 1
ELSE 0
END
) as total_losses,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as win_balance,
COUNT(*) FILTER (
WHERE status = 5
) AS number_of_unsettled,
SUM(
CASE
WHEN status = 5 THEN amount
ELSE 0
END
) AS total_unsettled_amount,
COUNT(*) FILTER (
WHERE is_shop_bet = TRUE
) AS total_shop_bets
FROM bets
WHERE (
bets.company_id = $2
OR $2 IS NULL
)
`
type GetBetStatsByIntervalParams struct {
Interval pgtype.Text `json:"interval"`
CompanyID pgtype.Int8 `json:"company_id"`
}
type GetBetStatsByIntervalRow struct {
Date pgtype.Timestamp `json:"date"`
TotalBets int64 `json:"total_bets"`
TotalStake int64 `json:"total_stake"`
ActiveBets int64 `json:"active_bets"`
TotalWins int64 `json:"total_wins"`
TotalLosses int64 `json:"total_losses"`
WinBalance int64 `json:"win_balance"`
NumberOfUnsettled int64 `json:"number_of_unsettled"`
TotalUnsettledAmount int64 `json:"total_unsettled_amount"`
TotalShopBets int64 `json:"total_shop_bets"`
}
func (q *Queries) GetBetStatsByInterval(ctx context.Context, arg GetBetStatsByIntervalParams) ([]GetBetStatsByIntervalRow, error) {
rows, err := q.db.Query(ctx, GetBetStatsByInterval, arg.Interval, arg.CompanyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBetStatsByIntervalRow
for rows.Next() {
var i GetBetStatsByIntervalRow
if err := rows.Scan(
&i.Date,
&i.TotalBets,
&i.TotalStake,
&i.ActiveBets,
&i.TotalWins,
&i.TotalLosses,
&i.WinBalance,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalShopBets,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBetSummary = `-- name: GetBetSummary :one
SELECT SUM(amount) as total_stakes,
COUNT(*) as total_bets,
SUM(
CASE
WHEN status = 0 THEN 1
ELSE 0
END
) as active_bets,
SUM(
CASE
WHEN status = 1 THEN 1
ELSE 0
END
) as total_wins,
SUM(
CASE
WHEN status = 2 THEN 1
ELSE 0
END
) as total_losses,
SUM(
CASE
WHEN status = 1 THEN amount * total_odds
ELSE 0
END
) as win_balance
FROM bets
wHERE (
user_id = $1
OR $1 IS NULL
)
AND (
company_id = $2
OR $2 IS NULL
)
AND (
created_at > $3
OR $3 IS NULL
)
AND (
created_at < $4
OR $4 IS NULL
)
`
type GetBetSummaryParams struct {
UserID pgtype.Int8 `json:"user_id"`
CompanyID pgtype.Int8 `json:"company_id"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
type GetBetSummaryRow struct {
TotalStakes int64 `json:"total_stakes"`
TotalBets int64 `json:"total_bets"`
ActiveBets int64 `json:"active_bets"`
TotalWins int64 `json:"total_wins"`
TotalLosses int64 `json:"total_losses"`
WinBalance int64 `json:"win_balance"`
}
func (q *Queries) GetBetSummary(ctx context.Context, arg GetBetSummaryParams) (GetBetSummaryRow, error) {
row := q.db.QueryRow(ctx, GetBetSummary,
arg.UserID,
arg.CompanyID,
arg.CreatedBefore,
arg.CreatedAfter,
)
var i GetBetSummaryRow
err := row.Scan(
&i.TotalStakes,
&i.TotalBets,
&i.ActiveBets,
&i.TotalWins,
&i.TotalLosses,
&i.WinBalance,
)
return i, err
}
const GetMarketPopularity = `-- name: GetMarketPopularity :one
WITH market_counts AS (
SELECT DATE(b.created_at) as date,
bo.market_name,
COUNT(*) as bet_count,
ROW_NUMBER() OVER (
PARTITION BY DATE(b.created_at)
ORDER BY COUNT(*) DESC
) as rank
FROM bets b
JOIN bet_outcomes bo ON b.id = bo.bet_id
WHERE bo.market_name IS NOT NULL
AND (
user_id = $1
OR $1 IS NULL
)
AND (
company_id = $2
OR $2 IS NULL
)
AND (
created_at > $3
OR $3 IS NULL
)
AND (
created_at < $4
OR $4 IS NULL
)
GROUP BY DATE(b.created_at),
bo.market_name
)
SELECT date,
market_name
FROM market_counts
WHERE rank = 1
`
type GetMarketPopularityParams struct {
UserID pgtype.Int8 `json:"user_id"`
CompanyID pgtype.Int8 `json:"company_id"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
type GetMarketPopularityRow struct {
Date pgtype.Date `json:"date"`
MarketName string `json:"market_name"`
}
func (q *Queries) GetMarketPopularity(ctx context.Context, arg GetMarketPopularityParams) (GetMarketPopularityRow, error) {
row := q.db.QueryRow(ctx, GetMarketPopularity,
arg.UserID,
arg.CompanyID,
arg.CreatedBefore,
arg.CreatedAfter,
)
var i GetMarketPopularityRow
err := row.Scan(&i.Date, &i.MarketName)
return i, err
}
const GetTotalBetsMadeInRange = `-- name: GetTotalBetsMadeInRange :one
SELECT COUNT(*) AS total_bets
FROM bets
WHERE created_at BETWEEN $1 AND $2
`
type GetTotalBetsMadeInRangeParams struct {
From pgtype.Timestamp `json:"from"`
To pgtype.Timestamp `json:"to"`
}
func (q *Queries) GetTotalBetsMadeInRange(ctx context.Context, arg GetTotalBetsMadeInRangeParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalBetsMadeInRange, arg.From, arg.To)
var total_bets int64
err := row.Scan(&total_bets)
return total_bets, err
}
const GetTotalCashBacksInRange = `-- name: GetTotalCashBacksInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_backs
FROM bets
WHERE created_at BETWEEN $1 AND $2
AND status = 5
`
type GetTotalCashBacksInRangeParams struct {
From pgtype.Timestamp `json:"from"`
To pgtype.Timestamp `json:"to"`
}
func (q *Queries) GetTotalCashBacksInRange(ctx context.Context, arg GetTotalCashBacksInRangeParams) (interface{}, error) {
row := q.db.QueryRow(ctx, GetTotalCashBacksInRange, arg.From, arg.To)
var total_cash_backs interface{}
err := row.Scan(&total_cash_backs)
return total_cash_backs, err
}
const GetTotalCashMadeInRange = `-- name: GetTotalCashMadeInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_made
FROM bets
WHERE created_at BETWEEN $1 AND $2
`
type GetTotalCashMadeInRangeParams struct {
From pgtype.Timestamp `json:"from"`
To pgtype.Timestamp `json:"to"`
}
func (q *Queries) GetTotalCashMadeInRange(ctx context.Context, arg GetTotalCashMadeInRangeParams) (interface{}, error) {
row := q.db.QueryRow(ctx, GetTotalCashMadeInRange, arg.From, arg.To)
var total_cash_made interface{}
err := row.Scan(&total_cash_made)
return total_cash_made, err
}
const GetTotalCashOutInRange = `-- name: GetTotalCashOutInRange :one
SELECT COALESCE(SUM(amount), 0) AS total_cash_out
FROM bets
WHERE created_at BETWEEN $1 AND $2
AND cashed_out = true
`
type GetTotalCashOutInRangeParams struct {
From pgtype.Timestamp `json:"from"`
To pgtype.Timestamp `json:"to"`
}
func (q *Queries) GetTotalCashOutInRange(ctx context.Context, arg GetTotalCashOutInRangeParams) (interface{}, error) {
row := q.db.QueryRow(ctx, GetTotalCashOutInRange, arg.From, arg.To)
var total_cash_out interface{}
err := row.Scan(&total_cash_out)
return total_cash_out, err
}

View File

@ -1,224 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: bonus.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CreateUserBonus = `-- name: CreateUserBonus :one
INSERT INTO user_bonuses (
name,
description,
type,
user_id,
reward_amount,
expires_at
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, description, type, user_id, reward_amount, is_claimed, expires_at, claimed_at, created_at, updated_at
`
type CreateUserBonusParams struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
UserID int64 `json:"user_id"`
RewardAmount int64 `json:"reward_amount"`
ExpiresAt pgtype.Timestamp `json:"expires_at"`
}
func (q *Queries) CreateUserBonus(ctx context.Context, arg CreateUserBonusParams) (UserBonuse, error) {
row := q.db.QueryRow(ctx, CreateUserBonus,
arg.Name,
arg.Description,
arg.Type,
arg.UserID,
arg.RewardAmount,
arg.ExpiresAt,
)
var i UserBonuse
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Type,
&i.UserID,
&i.RewardAmount,
&i.IsClaimed,
&i.ExpiresAt,
&i.ClaimedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const DeleteUserBonus = `-- name: DeleteUserBonus :exec
DELETE FROM user_bonuses
WHERE id = $1
`
func (q *Queries) DeleteUserBonus(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteUserBonus, id)
return err
}
const GetAllUserBonuses = `-- name: GetAllUserBonuses :many
SELECT id, name, description, type, user_id, reward_amount, is_claimed, expires_at, claimed_at, created_at, updated_at
FROM user_bonuses
WHERE (
user_id = $1
OR $1 IS NULL
)
LIMIT $3 OFFSET $2
`
type GetAllUserBonusesParams struct {
UserID pgtype.Int8 `json:"user_id"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllUserBonuses(ctx context.Context, arg GetAllUserBonusesParams) ([]UserBonuse, error) {
rows, err := q.db.Query(ctx, GetAllUserBonuses, arg.UserID, arg.Offset, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []UserBonuse
for rows.Next() {
var i UserBonuse
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Type,
&i.UserID,
&i.RewardAmount,
&i.IsClaimed,
&i.ExpiresAt,
&i.ClaimedAt,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBonusCount = `-- name: GetBonusCount :one
SELECT COUNT(*)
FROM user_bonuses
WHERE (
user_id = $1
OR $1 IS NULL
)
`
func (q *Queries) GetBonusCount(ctx context.Context, userID pgtype.Int8) (int64, error) {
row := q.db.QueryRow(ctx, GetBonusCount, userID)
var count int64
err := row.Scan(&count)
return count, err
}
const GetBonusStats = `-- name: GetBonusStats :one
SELECT COUNT(*) AS total_bonuses,
COALESCE(SUM(reward_amount), 0)::bigint AS total_reward_earned,
COUNT(
CASE
WHEN is_claimed = true THEN 1
END
) AS claimed_bonuses,
COUNT(
CASE
WHEN expires_at < now() THEN 1
END
) AS expired_bonuses
FROM user_bonuses
JOIN users ON users.id = user_bonuses.user_id
WHERE (
company_id = $1
OR $1 IS NULL
)
AND (
user_id = $2
OR $2 IS NULL
)
`
type GetBonusStatsParams struct {
CompanyID pgtype.Int8 `json:"company_id"`
UserID pgtype.Int8 `json:"user_id"`
}
type GetBonusStatsRow struct {
TotalBonuses int64 `json:"total_bonuses"`
TotalRewardEarned int64 `json:"total_reward_earned"`
ClaimedBonuses int64 `json:"claimed_bonuses"`
ExpiredBonuses int64 `json:"expired_bonuses"`
}
func (q *Queries) GetBonusStats(ctx context.Context, arg GetBonusStatsParams) (GetBonusStatsRow, error) {
row := q.db.QueryRow(ctx, GetBonusStats, arg.CompanyID, arg.UserID)
var i GetBonusStatsRow
err := row.Scan(
&i.TotalBonuses,
&i.TotalRewardEarned,
&i.ClaimedBonuses,
&i.ExpiredBonuses,
)
return i, err
}
const GetUserBonusByID = `-- name: GetUserBonusByID :one
SELECT id, name, description, type, user_id, reward_amount, is_claimed, expires_at, claimed_at, created_at, updated_at
FROM user_bonuses
WHERE id = $1
`
func (q *Queries) GetUserBonusByID(ctx context.Context, id int64) (UserBonuse, error) {
row := q.db.QueryRow(ctx, GetUserBonusByID, id)
var i UserBonuse
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Type,
&i.UserID,
&i.RewardAmount,
&i.IsClaimed,
&i.ExpiresAt,
&i.ClaimedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const UpdateUserBonus = `-- name: UpdateUserBonus :exec
UPDATE user_bonuses
SET is_claimed = $2
WHERE id = $1
`
type UpdateUserBonusParams struct {
ID int64 `json:"id"`
IsClaimed bool `json:"is_claimed"`
}
func (q *Queries) UpdateUserBonus(ctx context.Context, arg UpdateUserBonusParams) error {
_, err := q.db.Exec(ctx, UpdateUserBonus, arg.ID, arg.IsClaimed)
return err
}

View File

@ -1,606 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: branch.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CreateBranch = `-- name: CreateBranch :one
INSERT INTO branches (
name,
location,
wallet_id,
branch_manager_id,
company_id,
is_self_owned,
profit_percent
)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at
`
type CreateBranchParams struct {
Name string `json:"name"`
Location string `json:"location"`
WalletID int64 `json:"wallet_id"`
BranchManagerID int64 `json:"branch_manager_id"`
CompanyID int64 `json:"company_id"`
IsSelfOwned bool `json:"is_self_owned"`
ProfitPercent float32 `json:"profit_percent"`
}
func (q *Queries) CreateBranch(ctx context.Context, arg CreateBranchParams) (Branch, error) {
row := q.db.QueryRow(ctx, CreateBranch,
arg.Name,
arg.Location,
arg.WalletID,
arg.BranchManagerID,
arg.CompanyID,
arg.IsSelfOwned,
arg.ProfitPercent,
)
var i Branch
err := row.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const CreateBranchCashier = `-- name: CreateBranchCashier :one
INSERT INTO branch_cashiers (user_id, branch_id)
VALUES ($1, $2)
RETURNING id, user_id, branch_id
`
type CreateBranchCashierParams struct {
UserID int64 `json:"user_id"`
BranchID int64 `json:"branch_id"`
}
func (q *Queries) CreateBranchCashier(ctx context.Context, arg CreateBranchCashierParams) (BranchCashier, error) {
row := q.db.QueryRow(ctx, CreateBranchCashier, arg.UserID, arg.BranchID)
var i BranchCashier
err := row.Scan(&i.ID, &i.UserID, &i.BranchID)
return i, err
}
const CreateBranchOperation = `-- name: CreateBranchOperation :one
INSERT INTO branch_operations (operation_id, branch_id)
VALUES ($1, $2)
RETURNING id, operation_id, branch_id, created_at, updated_at
`
type CreateBranchOperationParams struct {
OperationID int64 `json:"operation_id"`
BranchID int64 `json:"branch_id"`
}
func (q *Queries) CreateBranchOperation(ctx context.Context, arg CreateBranchOperationParams) (BranchOperation, error) {
row := q.db.QueryRow(ctx, CreateBranchOperation, arg.OperationID, arg.BranchID)
var i BranchOperation
err := row.Scan(
&i.ID,
&i.OperationID,
&i.BranchID,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const CreateSupportedOperation = `-- name: CreateSupportedOperation :one
INSERT INTO supported_operations (name, description)
VALUES ($1, $2)
RETURNING id, name, description
`
type CreateSupportedOperationParams struct {
Name string `json:"name"`
Description string `json:"description"`
}
func (q *Queries) CreateSupportedOperation(ctx context.Context, arg CreateSupportedOperationParams) (SupportedOperation, error) {
row := q.db.QueryRow(ctx, CreateSupportedOperation, arg.Name, arg.Description)
var i SupportedOperation
err := row.Scan(&i.ID, &i.Name, &i.Description)
return i, err
}
const DeleteBranch = `-- name: DeleteBranch :exec
DELETE FROM branches
WHERE id = $1
`
func (q *Queries) DeleteBranch(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteBranch, id)
return err
}
const DeleteBranchCashier = `-- name: DeleteBranchCashier :exec
DELETE FROM branch_cashiers
WHERE user_id = $1
`
func (q *Queries) DeleteBranchCashier(ctx context.Context, userID int64) error {
_, err := q.db.Exec(ctx, DeleteBranchCashier, userID)
return err
}
const DeleteBranchOperation = `-- name: DeleteBranchOperation :exec
DELETE FROM branch_operations
WHERE operation_id = $1
AND branch_id = $2
`
type DeleteBranchOperationParams struct {
OperationID int64 `json:"operation_id"`
BranchID int64 `json:"branch_id"`
}
func (q *Queries) DeleteBranchOperation(ctx context.Context, arg DeleteBranchOperationParams) error {
_, err := q.db.Exec(ctx, DeleteBranchOperation, arg.OperationID, arg.BranchID)
return err
}
const GetAllBranches = `-- name: GetAllBranches :many
SELECT id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at, manager_name, manager_phone_number, balance, wallet_is_active, company_name, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, stats_updated_at
FROM branch_details
WHERE (
company_id = $1
OR $1 IS NULL
)
AND (
is_active = $2
OR $2 IS NULL
)
AND (
branch_manager_id = $3
OR $3 IS NULL
)
AND (
name ILIKE '%' || $4 || '%'
OR location ILIKE '%' || $4 || '%'
OR $4 IS NULL
)
AND (
created_at > $5
OR $5 IS NULL
)
AND (
created_at < $6
OR $6 IS NULL
)
`
type GetAllBranchesParams struct {
CompanyID pgtype.Int8 `json:"company_id"`
IsActive pgtype.Bool `json:"is_active"`
BranchManagerID pgtype.Int8 `json:"branch_manager_id"`
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
func (q *Queries) GetAllBranches(ctx context.Context, arg GetAllBranchesParams) ([]BranchDetail, error) {
rows, err := q.db.Query(ctx, GetAllBranches,
arg.CompanyID,
arg.IsActive,
arg.BranchManagerID,
arg.Query,
arg.CreatedBefore,
arg.CreatedAfter,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchDetail
for rows.Next() {
var i BranchDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
&i.ManagerName,
&i.ManagerPhoneNumber,
&i.Balance,
&i.WalletIsActive,
&i.CompanyName,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetAllSupportedOperations = `-- name: GetAllSupportedOperations :many
SELECT id, name, description
FROM supported_operations
`
func (q *Queries) GetAllSupportedOperations(ctx context.Context) ([]SupportedOperation, error) {
rows, err := q.db.Query(ctx, GetAllSupportedOperations)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SupportedOperation
for rows.Next() {
var i SupportedOperation
if err := rows.Scan(&i.ID, &i.Name, &i.Description); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBranchByCashier = `-- name: GetBranchByCashier :one
SELECT branches.id, branches.name, branches.location, branches.profit_percent, branches.is_active, branches.wallet_id, branches.branch_manager_id, branches.company_id, branches.is_self_owned, branches.created_at, branches.updated_at
FROM branch_cashiers
JOIN branches ON branch_cashiers.branch_id = branches.id
WHERE branch_cashiers.user_id = $1
`
func (q *Queries) GetBranchByCashier(ctx context.Context, userID int64) (Branch, error) {
row := q.db.QueryRow(ctx, GetBranchByCashier, userID)
var i Branch
err := row.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const GetBranchByCompanyID = `-- name: GetBranchByCompanyID :many
SELECT id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at, manager_name, manager_phone_number, balance, wallet_is_active, company_name, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, stats_updated_at
FROM branch_details
WHERE company_id = $1
`
func (q *Queries) GetBranchByCompanyID(ctx context.Context, companyID int64) ([]BranchDetail, error) {
rows, err := q.db.Query(ctx, GetBranchByCompanyID, companyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchDetail
for rows.Next() {
var i BranchDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
&i.ManagerName,
&i.ManagerPhoneNumber,
&i.Balance,
&i.WalletIsActive,
&i.CompanyName,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBranchByID = `-- name: GetBranchByID :one
SELECT id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at, manager_name, manager_phone_number, balance, wallet_is_active, company_name, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, stats_updated_at
FROM branch_details
WHERE id = $1
`
func (q *Queries) GetBranchByID(ctx context.Context, id int64) (BranchDetail, error) {
row := q.db.QueryRow(ctx, GetBranchByID, id)
var i BranchDetail
err := row.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
&i.ManagerName,
&i.ManagerPhoneNumber,
&i.Balance,
&i.WalletIsActive,
&i.CompanyName,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.StatsUpdatedAt,
)
return i, err
}
const GetBranchByManagerID = `-- name: GetBranchByManagerID :many
SELECT id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at, manager_name, manager_phone_number, balance, wallet_is_active, company_name, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, stats_updated_at
FROM branch_details
WHERE branch_manager_id = $1
`
func (q *Queries) GetBranchByManagerID(ctx context.Context, branchManagerID int64) ([]BranchDetail, error) {
rows, err := q.db.Query(ctx, GetBranchByManagerID, branchManagerID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchDetail
for rows.Next() {
var i BranchDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
&i.ManagerName,
&i.ManagerPhoneNumber,
&i.Balance,
&i.WalletIsActive,
&i.CompanyName,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBranchOperations = `-- name: GetBranchOperations :many
SELECT branch_operations.id, branch_operations.operation_id, branch_operations.branch_id, branch_operations.created_at, branch_operations.updated_at,
supported_operations.name,
supported_operations.description
FROM branch_operations
JOIN supported_operations ON branch_operations.operation_id = supported_operations.id
WHERE branch_operations.branch_id = $1
`
type GetBranchOperationsRow struct {
ID int64 `json:"id"`
OperationID int64 `json:"operation_id"`
BranchID int64 `json:"branch_id"`
CreatedAt pgtype.Timestamp `json:"created_at"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
Name string `json:"name"`
Description string `json:"description"`
}
func (q *Queries) GetBranchOperations(ctx context.Context, branchID int64) ([]GetBranchOperationsRow, error) {
rows, err := q.db.Query(ctx, GetBranchOperations, branchID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBranchOperationsRow
for rows.Next() {
var i GetBranchOperationsRow
if err := rows.Scan(
&i.ID,
&i.OperationID,
&i.BranchID,
&i.CreatedAt,
&i.UpdatedAt,
&i.Name,
&i.Description,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const SearchBranchByName = `-- name: SearchBranchByName :many
SELECT id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at, manager_name, manager_phone_number, balance, wallet_is_active, company_name, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, stats_updated_at
FROM branch_details
WHERE name ILIKE '%' || $1 || '%'
AND (
company_id = $2
OR $2 IS NULL
)
`
type SearchBranchByNameParams struct {
Column1 pgtype.Text `json:"column_1"`
CompanyID pgtype.Int8 `json:"company_id"`
}
func (q *Queries) SearchBranchByName(ctx context.Context, arg SearchBranchByNameParams) ([]BranchDetail, error) {
rows, err := q.db.Query(ctx, SearchBranchByName, arg.Column1, arg.CompanyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchDetail
for rows.Next() {
var i BranchDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
&i.ManagerName,
&i.ManagerPhoneNumber,
&i.Balance,
&i.WalletIsActive,
&i.CompanyName,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateBranch = `-- name: UpdateBranch :one
UPDATE branches
SET name = COALESCE($2, name),
location = COALESCE($3, location),
branch_manager_id = COALESCE($4, branch_manager_id),
company_id = COALESCE($5, company_id),
is_self_owned = COALESCE($6, is_self_owned),
is_active = COALESCE($7, is_active),
profit_percent = COALESCE($8, profit_percent),
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING id, name, location, profit_percent, is_active, wallet_id, branch_manager_id, company_id, is_self_owned, created_at, updated_at
`
type UpdateBranchParams struct {
ID int64 `json:"id"`
Name pgtype.Text `json:"name"`
Location pgtype.Text `json:"location"`
BranchManagerID pgtype.Int8 `json:"branch_manager_id"`
CompanyID pgtype.Int8 `json:"company_id"`
IsSelfOwned pgtype.Bool `json:"is_self_owned"`
IsActive pgtype.Bool `json:"is_active"`
ProfitPercent pgtype.Float4 `json:"profit_percent"`
}
func (q *Queries) UpdateBranch(ctx context.Context, arg UpdateBranchParams) (Branch, error) {
row := q.db.QueryRow(ctx, UpdateBranch,
arg.ID,
arg.Name,
arg.Location,
arg.BranchManagerID,
arg.CompanyID,
arg.IsSelfOwned,
arg.IsActive,
arg.ProfitPercent,
)
var i Branch
err := row.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.ProfitPercent,
&i.IsActive,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}

View File

@ -1,247 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: branch_stats.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetBranchStats = `-- name: GetBranchStats :many
SELECT DATE_TRUNC($1, interval_start)::timestamp AS interval_start,
branch_stats.branch_id,
branch_stats.branch_name,
branch_stats.company_id,
branch_stats.company_name,
branch_stats.company_slug,
branch_stats.total_bets,
branch_stats.total_stake,
branch_stats.deducted_stake,
branch_stats.total_cash_out,
branch_stats.total_cash_backs,
branch_stats.number_of_unsettled,
branch_stats.total_unsettled_amount,
branch_stats.total_cashiers,
branch_stats.updated_at
FROM branch_stats
WHERE (
branch_stats.branch_id = $2
OR $2 IS NULL
)
AND (
branch_stats.company_id = $3
OR $3 IS NULL
)
GROUP BY interval_start
ORDER BY interval_start DESC
`
type GetBranchStatsParams struct {
Interval pgtype.Text `json:"interval"`
BranchID pgtype.Int8 `json:"branch_id"`
CompanyID pgtype.Int8 `json:"company_id"`
}
type GetBranchStatsRow struct {
IntervalStart pgtype.Timestamp `json:"interval_start"`
BranchID int64 `json:"branch_id"`
BranchName string `json:"branch_name"`
CompanyID int64 `json:"company_id"`
CompanyName string `json:"company_name"`
CompanySlug string `json:"company_slug"`
TotalBets int64 `json:"total_bets"`
TotalStake int64 `json:"total_stake"`
DeductedStake int64 `json:"deducted_stake"`
TotalCashOut int64 `json:"total_cash_out"`
TotalCashBacks int64 `json:"total_cash_backs"`
NumberOfUnsettled int64 `json:"number_of_unsettled"`
TotalUnsettledAmount int64 `json:"total_unsettled_amount"`
TotalCashiers int64 `json:"total_cashiers"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
}
func (q *Queries) GetBranchStats(ctx context.Context, arg GetBranchStatsParams) ([]GetBranchStatsRow, error) {
rows, err := q.db.Query(ctx, GetBranchStats, arg.Interval, arg.BranchID, arg.CompanyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBranchStatsRow
for rows.Next() {
var i GetBranchStatsRow
if err := rows.Scan(
&i.IntervalStart,
&i.BranchID,
&i.BranchName,
&i.CompanyID,
&i.CompanyName,
&i.CompanySlug,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBranchStatsByID = `-- name: GetBranchStatsByID :many
SELECt branch_id, branch_name, company_id, company_name, company_slug, interval_start, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_cashiers, updated_at
FROM branch_stats
WHERE branch_id = $1
ORDER BY interval_start DESC
`
func (q *Queries) GetBranchStatsByID(ctx context.Context, branchID int64) ([]BranchStat, error) {
rows, err := q.db.Query(ctx, GetBranchStatsByID, branchID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchStat
for rows.Next() {
var i BranchStat
if err := rows.Scan(
&i.BranchID,
&i.BranchName,
&i.CompanyID,
&i.CompanyName,
&i.CompanySlug,
&i.IntervalStart,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalCashiers,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateBranchStats = `-- name: UpdateBranchStats :exec
WITH -- Aggregate bet data per branch
bet_stats AS (
SELECT branch_id,
COUNT(*) AS total_bets,
COALESCE(SUM(amount), 0) AS total_stake,
COALESCE(
SUM(amount) * MAX(profit_percent),
0
) AS deducted_stake,
COALESCE(
SUM(
CASE
WHEN cashed_out THEN amount
ELSE 0
END
),
0
) AS total_cash_out,
COALESCE(
SUM(
CASE
WHEN status = 3 THEN amount
ELSE 0
END
),
0
) AS total_cash_backs,
COUNT(*) FILTER (
WHERE status = 5
) AS number_of_unsettled,
COALESCE(
SUM(
CASE
WHEN status = 5 THEN amount
ELSE 0
END
),
0
) AS total_unsettled_amount
FROM shop_bet_detail
LEFT JOIN branches ON branches.id = shop_bet_detail.branch_id
GROUP BY branch_id
),
cashier_stats AS (
SELECT branch_id,
COUNT(*) AS total_cashiers
FROM branch_cashiers
GROUP BY branch_id
)
INSERT INTO branch_stats (
branch_id,
branch_name,
company_id,
company_name,
company_slug,
interval_start,
total_bets,
total_stake,
deducted_stake,
total_cash_out,
total_cash_backs,
number_of_unsettled,
total_unsettled_amount,
total_cashiers,
updated_at
)
SELECT br.id AS branch_id,
br.name AS branch_name,
c.id AS company_id,
c.name AS company_name,
c.slug AS company_slug,
DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start,
COALESCE(bs.total_bets, 0) AS total_bets,
COALESCE(bs.total_stake, 0) AS total_stake,
COALESCE(bs.deducted_stake, 0) AS deducted_stake,
COALESCE(bs.total_cash_out, 0) AS total_cash_out,
COALESCE(bs.total_cash_backs, 0) AS total_cash_backs,
COALESCE(bs.number_of_unsettled, 0) AS number_of_unsettled,
COALESCE(bs.total_unsettled_amount, 0) AS total_unsettled_amount,
COALESCE(bc.total_cashiers, 0) AS total_cashiers,
NOW() AS updated_at
FROM branches br
LEFT JOIN companies c ON c.id = br.company_id
LEFT JOIN bet_stats bs ON bs.branch_id = br.id
LEFT JOIN cashier_stats bc ON bc.branch_id = br.id ON CONFLICT (branch_id, interval_start) DO
UPDATE
SET total_bets = EXCLUDED.total_bets,
total_stake = EXCLUDED.total_stake,
deducted_stake = EXCLUDED.deducted_stake,
total_cash_out = EXCLUDED.total_cash_out,
total_cash_backs = EXCLUDED.total_cash_backs,
number_of_unsettled = EXCLUDED.number_of_unsettled,
total_unsettled_amount = EXCLUDED.total_unsettled_amount,
total_cashiers = EXCLUDED.total_cashiers,
updated_at = EXCLUDED.updated_at
`
func (q *Queries) UpdateBranchStats(ctx context.Context) error {
_, err := q.db.Exec(ctx, UpdateBranchStats)
return err
}

View File

@ -1,205 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: cashier.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetAllCashiers = `-- name: GetAllCashiers :many
SELECT users.id, users.first_name, users.last_name, users.email, users.phone_number, users.role, users.password, users.email_verified, users.phone_verified, users.created_at, users.updated_at, users.company_id, users.suspended_at, users.suspended,
branch_id,
branches.name AS branch_name,
branches.wallet_id AS branch_wallet,
branches.location As branch_location
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE (
first_name ILIKE '%' || $1 || '%'
OR last_name ILIKE '%' || $1 || '%'
OR phone_number ILIKE '%' || $1 || '%'
OR $1 IS NULL
)
AND (
users.created_at > $2
OR $2 IS NULL
)
AND (
users.created_at < $3
OR $3 IS NULL
)
`
type GetAllCashiersParams struct {
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamptz `json:"created_before"`
CreatedAfter pgtype.Timestamptz `json:"created_after"`
}
type GetAllCashiersRow struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email pgtype.Text `json:"email"`
PhoneNumber pgtype.Text `json:"phone_number"`
Role string `json:"role"`
Password []byte `json:"password"`
EmailVerified bool `json:"email_verified"`
PhoneVerified bool `json:"phone_verified"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
CompanyID pgtype.Int8 `json:"company_id"`
SuspendedAt pgtype.Timestamptz `json:"suspended_at"`
Suspended bool `json:"suspended"`
BranchID int64 `json:"branch_id"`
BranchName string `json:"branch_name"`
BranchWallet int64 `json:"branch_wallet"`
BranchLocation string `json:"branch_location"`
}
func (q *Queries) GetAllCashiers(ctx context.Context, arg GetAllCashiersParams) ([]GetAllCashiersRow, error) {
rows, err := q.db.Query(ctx, GetAllCashiers, arg.Query, arg.CreatedBefore, arg.CreatedAfter)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllCashiersRow
for rows.Next() {
var i GetAllCashiersRow
if err := rows.Scan(
&i.ID,
&i.FirstName,
&i.LastName,
&i.Email,
&i.PhoneNumber,
&i.Role,
&i.Password,
&i.EmailVerified,
&i.PhoneVerified,
&i.CreatedAt,
&i.UpdatedAt,
&i.CompanyID,
&i.SuspendedAt,
&i.Suspended,
&i.BranchID,
&i.BranchName,
&i.BranchWallet,
&i.BranchLocation,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetCashierByID = `-- name: GetCashierByID :one
SELECT users.id, users.first_name, users.last_name, users.email, users.phone_number, users.role, users.password, users.email_verified, users.phone_verified, users.created_at, users.updated_at, users.company_id, users.suspended_at, users.suspended,
branch_id,
branches.name AS branch_name,
branches.wallet_id AS branch_wallet,
branches.location As branch_location
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE users.id = $1
`
type GetCashierByIDRow struct {
ID int64 `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email pgtype.Text `json:"email"`
PhoneNumber pgtype.Text `json:"phone_number"`
Role string `json:"role"`
Password []byte `json:"password"`
EmailVerified bool `json:"email_verified"`
PhoneVerified bool `json:"phone_verified"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
CompanyID pgtype.Int8 `json:"company_id"`
SuspendedAt pgtype.Timestamptz `json:"suspended_at"`
Suspended bool `json:"suspended"`
BranchID int64 `json:"branch_id"`
BranchName string `json:"branch_name"`
BranchWallet int64 `json:"branch_wallet"`
BranchLocation string `json:"branch_location"`
}
func (q *Queries) GetCashierByID(ctx context.Context, id int64) (GetCashierByIDRow, error) {
row := q.db.QueryRow(ctx, GetCashierByID, id)
var i GetCashierByIDRow
err := row.Scan(
&i.ID,
&i.FirstName,
&i.LastName,
&i.Email,
&i.PhoneNumber,
&i.Role,
&i.Password,
&i.EmailVerified,
&i.PhoneVerified,
&i.CreatedAt,
&i.UpdatedAt,
&i.CompanyID,
&i.SuspendedAt,
&i.Suspended,
&i.BranchID,
&i.BranchName,
&i.BranchWallet,
&i.BranchLocation,
)
return i, err
}
const GetCashiersByBranch = `-- name: GetCashiersByBranch :many
SELECT users.id, users.first_name, users.last_name, users.email, users.phone_number, users.role, users.password, users.email_verified, users.phone_verified, users.created_at, users.updated_at, users.company_id, users.suspended_at, users.suspended
FROM branch_cashiers
JOIN users ON branch_cashiers.user_id = users.id
JOIN branches ON branches.id = branch_id
WHERE branch_cashiers.branch_id = $1
`
func (q *Queries) GetCashiersByBranch(ctx context.Context, branchID int64) ([]User, error) {
rows, err := q.db.Query(ctx, GetCashiersByBranch, branchID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []User
for rows.Next() {
var i User
if err := rows.Scan(
&i.ID,
&i.FirstName,
&i.LastName,
&i.Email,
&i.PhoneNumber,
&i.Role,
&i.Password,
&i.EmailVerified,
&i.PhoneVerified,
&i.CreatedAt,
&i.UpdatedAt,
&i.CompanyID,
&i.SuspendedAt,
&i.Suspended,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -1,298 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: company.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CreateCompany = `-- name: CreateCompany :one
INSERT INTO companies (
name,
slug,
admin_id,
wallet_id,
deducted_percentage,
is_active
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, slug, admin_id, wallet_id, deducted_percentage, is_active, created_at, updated_at
`
type CreateCompanyParams struct {
Name string `json:"name"`
Slug string `json:"slug"`
AdminID int64 `json:"admin_id"`
WalletID int64 `json:"wallet_id"`
DeductedPercentage float32 `json:"deducted_percentage"`
IsActive bool `json:"is_active"`
}
func (q *Queries) CreateCompany(ctx context.Context, arg CreateCompanyParams) (Company, error) {
row := q.db.QueryRow(ctx, CreateCompany,
arg.Name,
arg.Slug,
arg.AdminID,
arg.WalletID,
arg.DeductedPercentage,
arg.IsActive,
)
var i Company
err := row.Scan(
&i.ID,
&i.Name,
&i.Slug,
&i.AdminID,
&i.WalletID,
&i.DeductedPercentage,
&i.IsActive,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const DeleteCompany = `-- name: DeleteCompany :exec
DELETE FROM companies
WHERE id = $1
`
func (q *Queries) DeleteCompany(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteCompany, id)
return err
}
const GetAllCompanies = `-- name: GetAllCompanies :many
SELECT id, name, slug, admin_id, wallet_id, deducted_percentage, is_active, created_at, updated_at, balance, wallet_is_active, admin_first_name, admin_last_name, admin_phone_number, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_admins, total_managers, total_cashiers, total_customers, total_approvers, total_branches, stats_updated_at
FROM companies_details
WHERE (
name ILIKE '%' || $1 || '%'
OR admin_first_name ILIKE '%' || $1 || '%'
OR admin_last_name ILIKE '%' || $1 || '%'
OR admin_phone_number ILIKE '%' || $1 || '%'
OR $1 IS NULL
)
AND (
created_at > $2
OR $2 IS NULL
)
AND (
created_at < $3
OR $3 IS NULL
)
`
type GetAllCompaniesParams struct {
Query pgtype.Text `json:"query"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
func (q *Queries) GetAllCompanies(ctx context.Context, arg GetAllCompaniesParams) ([]CompaniesDetail, error) {
rows, err := q.db.Query(ctx, GetAllCompanies, arg.Query, arg.CreatedBefore, arg.CreatedAfter)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CompaniesDetail
for rows.Next() {
var i CompaniesDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Slug,
&i.AdminID,
&i.WalletID,
&i.DeductedPercentage,
&i.IsActive,
&i.CreatedAt,
&i.UpdatedAt,
&i.Balance,
&i.WalletIsActive,
&i.AdminFirstName,
&i.AdminLastName,
&i.AdminPhoneNumber,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalAdmins,
&i.TotalManagers,
&i.TotalCashiers,
&i.TotalCustomers,
&i.TotalApprovers,
&i.TotalBranches,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetCompanyByID = `-- name: GetCompanyByID :one
SELECT id, name, slug, admin_id, wallet_id, deducted_percentage, is_active, created_at, updated_at, balance, wallet_is_active, admin_first_name, admin_last_name, admin_phone_number, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_admins, total_managers, total_cashiers, total_customers, total_approvers, total_branches, stats_updated_at
FROM companies_details
WHERE id = $1
`
func (q *Queries) GetCompanyByID(ctx context.Context, id int64) (CompaniesDetail, error) {
row := q.db.QueryRow(ctx, GetCompanyByID, id)
var i CompaniesDetail
err := row.Scan(
&i.ID,
&i.Name,
&i.Slug,
&i.AdminID,
&i.WalletID,
&i.DeductedPercentage,
&i.IsActive,
&i.CreatedAt,
&i.UpdatedAt,
&i.Balance,
&i.WalletIsActive,
&i.AdminFirstName,
&i.AdminLastName,
&i.AdminPhoneNumber,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalAdmins,
&i.TotalManagers,
&i.TotalCashiers,
&i.TotalCustomers,
&i.TotalApprovers,
&i.TotalBranches,
&i.StatsUpdatedAt,
)
return i, err
}
const GetCompanyUsingSlug = `-- name: GetCompanyUsingSlug :one
SELECT id, name, slug, admin_id, wallet_id, deducted_percentage, is_active, created_at, updated_at
FROM companies
WHERE slug = $1
`
func (q *Queries) GetCompanyUsingSlug(ctx context.Context, slug string) (Company, error) {
row := q.db.QueryRow(ctx, GetCompanyUsingSlug, slug)
var i Company
err := row.Scan(
&i.ID,
&i.Name,
&i.Slug,
&i.AdminID,
&i.WalletID,
&i.DeductedPercentage,
&i.IsActive,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const SearchCompanyByName = `-- name: SearchCompanyByName :many
SELECT id, name, slug, admin_id, wallet_id, deducted_percentage, is_active, created_at, updated_at, balance, wallet_is_active, admin_first_name, admin_last_name, admin_phone_number, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_admins, total_managers, total_cashiers, total_customers, total_approvers, total_branches, stats_updated_at
FROM companies_details
WHERE name ILIKE '%' || $1 || '%'
`
func (q *Queries) SearchCompanyByName(ctx context.Context, dollar_1 pgtype.Text) ([]CompaniesDetail, error) {
rows, err := q.db.Query(ctx, SearchCompanyByName, dollar_1)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CompaniesDetail
for rows.Next() {
var i CompaniesDetail
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Slug,
&i.AdminID,
&i.WalletID,
&i.DeductedPercentage,
&i.IsActive,
&i.CreatedAt,
&i.UpdatedAt,
&i.Balance,
&i.WalletIsActive,
&i.AdminFirstName,
&i.AdminLastName,
&i.AdminPhoneNumber,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalAdmins,
&i.TotalManagers,
&i.TotalCashiers,
&i.TotalCustomers,
&i.TotalApprovers,
&i.TotalBranches,
&i.StatsUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateCompany = `-- name: UpdateCompany :exec
UPDATE companies
SET name = COALESCE($2, name),
admin_id = COALESCE($3, admin_id),
is_active = COALESCE($4, is_active),
deducted_percentage = COALESCE(
$5,
deducted_percentage
),
slug = COALESCE($6, slug),
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
`
type UpdateCompanyParams struct {
ID int64 `json:"id"`
Name pgtype.Text `json:"name"`
AdminID pgtype.Int8 `json:"admin_id"`
IsActive pgtype.Bool `json:"is_active"`
DeductedPercentage pgtype.Float4 `json:"deducted_percentage"`
Slug pgtype.Text `json:"slug"`
}
func (q *Queries) UpdateCompany(ctx context.Context, arg UpdateCompanyParams) error {
_, err := q.db.Exec(ctx, UpdateCompany,
arg.ID,
arg.Name,
arg.AdminID,
arg.IsActive,
arg.DeductedPercentage,
arg.Slug,
)
return err
}

View File

@ -1,287 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: company_stats.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetCompanyStats = `-- name: GetCompanyStats :many
SELECT DATE_TRUNC($1, interval_start)::timestamp AS interval_start,
company_stats.company_id,
company_stats.company_name,
company_stats.company_slug,
company_stats.total_bets,
company_stats.total_stake,
company_stats.deducted_stake,
company_stats.total_cash_out,
company_stats.total_cash_backs,
company_stats.number_of_unsettled,
company_stats.total_unsettled_amount,
company_stats.total_admins,
company_stats.total_managers,
company_stats.total_cashiers,
company_stats.total_customers,
company_stats.total_approvers,
company_stats.total_branches,
company_stats.updated_at
FROM company_stats
WHERE (
company_stats.company_id = $2
OR $2 IS NULL
)
GROUP BY interval_start
ORDER BY interval_start DESC
`
type GetCompanyStatsParams struct {
Interval pgtype.Text `json:"interval"`
CompanyID pgtype.Int8 `json:"company_id"`
}
type GetCompanyStatsRow struct {
IntervalStart pgtype.Timestamp `json:"interval_start"`
CompanyID int64 `json:"company_id"`
CompanyName string `json:"company_name"`
CompanySlug string `json:"company_slug"`
TotalBets int64 `json:"total_bets"`
TotalStake int64 `json:"total_stake"`
DeductedStake int64 `json:"deducted_stake"`
TotalCashOut int64 `json:"total_cash_out"`
TotalCashBacks int64 `json:"total_cash_backs"`
NumberOfUnsettled int64 `json:"number_of_unsettled"`
TotalUnsettledAmount int64 `json:"total_unsettled_amount"`
TotalAdmins int64 `json:"total_admins"`
TotalManagers int64 `json:"total_managers"`
TotalCashiers int64 `json:"total_cashiers"`
TotalCustomers int64 `json:"total_customers"`
TotalApprovers int64 `json:"total_approvers"`
TotalBranches int64 `json:"total_branches"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
}
func (q *Queries) GetCompanyStats(ctx context.Context, arg GetCompanyStatsParams) ([]GetCompanyStatsRow, error) {
rows, err := q.db.Query(ctx, GetCompanyStats, arg.Interval, arg.CompanyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetCompanyStatsRow
for rows.Next() {
var i GetCompanyStatsRow
if err := rows.Scan(
&i.IntervalStart,
&i.CompanyID,
&i.CompanyName,
&i.CompanySlug,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalAdmins,
&i.TotalManagers,
&i.TotalCashiers,
&i.TotalCustomers,
&i.TotalApprovers,
&i.TotalBranches,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetCompanyStatsByID = `-- name: GetCompanyStatsByID :many
SELECT company_id, company_name, company_slug, interval_start, total_bets, total_stake, deducted_stake, total_cash_out, total_cash_backs, number_of_unsettled, total_unsettled_amount, total_admins, total_managers, total_cashiers, total_customers, total_approvers, total_branches, updated_at
FROM company_stats
WHERE company_id = $1
ORDER BY interval_start DESC
`
func (q *Queries) GetCompanyStatsByID(ctx context.Context, companyID int64) ([]CompanyStat, error) {
rows, err := q.db.Query(ctx, GetCompanyStatsByID, companyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CompanyStat
for rows.Next() {
var i CompanyStat
if err := rows.Scan(
&i.CompanyID,
&i.CompanyName,
&i.CompanySlug,
&i.IntervalStart,
&i.TotalBets,
&i.TotalStake,
&i.DeductedStake,
&i.TotalCashOut,
&i.TotalCashBacks,
&i.NumberOfUnsettled,
&i.TotalUnsettledAmount,
&i.TotalAdmins,
&i.TotalManagers,
&i.TotalCashiers,
&i.TotalCustomers,
&i.TotalApprovers,
&i.TotalBranches,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateCompanyStats = `-- name: UpdateCompanyStats :exec
WITH -- Aggregate bet data per company
bet_stats AS (
SELECT company_id,
COUNT(*) AS total_bets,
COALESCE(SUM(amount), 0) AS total_stake,
COALESCE(
SUM(amount) * MAX(companies.deducted_percentage),
0
) AS deducted_stake,
COALESCE(
SUM(
CASE
WHEN cashed_out THEN amount
ELSE 0
END
),
0
) AS total_cash_out,
COALESCE(
SUM(
CASE
WHEN status = 3 THEN amount
ELSE 0
END
),
0
) AS total_cash_backs,
COUNT(*) FILTER (
WHERE status = 5
) AS number_of_unsettled,
COALESCE(
SUM(
CASE
WHEN status = 5 THEN amount
ELSE 0
END
),
0
) AS total_unsettled_amount
FROM shop_bet_detail
LEFT JOIN companies ON companies.id = shop_bet_detail.company_id
GROUP BY company_id
),
user_stats AS (
SELECT company_id,
COUNT(*) FILTER (
WHERE role = 'admin'
) AS total_admins,
COUNT(*) FILTER (
WHERE role = 'branch_manager'
) AS total_managers,
COUNT(*) FILTER (
WHERE role = 'cashier'
) AS total_cashiers,
COUNT(*) FILTER (
WHERE role = 'customer'
) AS total_customers,
COUNT(*) FILTER (
WHERE role = 'transaction_approver'
) AS total_approvers
FROM users
GROUP BY company_id
),
branch_stats AS (
SELECT company_id,
COUNT(*) AS total_branches
FROM branches
GROUP BY company_id
) -- Final combined aggregation
INSERT INTO company_stats (
company_id,
company_name,
company_slug,
interval_start,
total_bets,
total_stake,
deducted_stake,
total_cash_out,
total_cash_backs,
number_of_unsettled,
total_unsettled_amount,
total_admins,
total_managers,
total_cashiers,
total_customers,
total_approvers,
total_branches,
updated_at
)
SELECT c.id AS company_id,
c.name AS company_name,
c.slug AS company_slug,
DATE_TRUNC('day', NOW() AT TIME ZONE 'UTC') AS interval_start,
COALESCE(b.total_bets, 0) AS total_bets,
COALESCE(b.total_stake, 0) AS total_stake,
COALESCE(b.deducted_stake, 0) AS deducted_stake,
COALESCE(b.total_cash_out, 0) AS total_cash_out,
COALESCE(b.total_cash_backs, 0) AS total_cash_backs,
COALESCE(b.number_of_unsettled, 0) AS number_of_unsettled,
COALESCE(b.total_unsettled_amount, 0) AS total_unsettled_amount,
COALESCE(u.total_admins, 0) AS total_admins,
COALESCE(u.total_managers, 0) AS total_managers,
COALESCE(u.total_cashiers, 0) AS total_cashiers,
COALESCE(u.total_customers, 0) AS total_customers,
COALESCE(u.total_approvers, 0) AS total_approvers,
COALESCE(br.total_branches, 0) AS total_branches,
NOW() AS updated_at
FROM companies c
LEFT JOIN bet_stats b ON b.company_id = c.id
LEFT JOIN user_stats u ON u.company_id = c.id
LEFT JOIN branch_stats br ON br.company_id = c.id ON CONFLICT (company_id, interval_start) DO
UPDATE
SET total_bets = EXCLUDED.total_bets,
total_stake = EXCLUDED.total_stake,
deducted_stake = EXCLUDED.deducted_stake,
total_cash_out = EXCLUDED.total_cash_out,
total_cash_backs = EXCLUDED.total_cash_backs,
number_of_unsettled = EXCLUDED.number_of_unsettled,
total_unsettled_amount = EXCLUDED.total_unsettled_amount,
total_admins = EXCLUDED.total_admins,
total_managers = EXCLUDED.total_managers,
total_cashiers = EXCLUDED.total_cashiers,
total_customers = EXCLUDED.total_customers,
total_approvers = EXCLUDED.total_approvers,
total_branches = EXCLUDED.total_branches,
updated_at = EXCLUDED.updated_at
`
// Aggregate user counts per company
// Aggregate branch counts per company
func (q *Queries) UpdateCompanyStats(ctx context.Context) error {
_, err := q.db.Exec(ctx, UpdateCompanyStats)
return err
}

View File

@ -1,97 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: copyfrom.go
package dbgen
import (
"context"
)
// iteratorForCreateBetOutcome implements pgx.CopyFromSource.
type iteratorForCreateBetOutcome struct {
rows []CreateBetOutcomeParams
skippedFirstNextCall bool
}
func (r *iteratorForCreateBetOutcome) Next() bool {
if len(r.rows) == 0 {
return false
}
if !r.skippedFirstNextCall {
r.skippedFirstNextCall = true
return true
}
r.rows = r.rows[1:]
return len(r.rows) > 0
}
func (r iteratorForCreateBetOutcome) Values() ([]interface{}, error) {
return []interface{}{
r.rows[0].BetID,
r.rows[0].SportID,
r.rows[0].EventID,
r.rows[0].OddID,
r.rows[0].HomeTeamName,
r.rows[0].AwayTeamName,
r.rows[0].MarketID,
r.rows[0].MarketName,
r.rows[0].Odd,
r.rows[0].OddName,
r.rows[0].OddHeader,
r.rows[0].OddHandicap,
r.rows[0].Expires,
}, nil
}
func (r iteratorForCreateBetOutcome) Err() error {
return nil
}
func (q *Queries) CreateBetOutcome(ctx context.Context, arg []CreateBetOutcomeParams) (int64, error) {
return q.db.CopyFrom(ctx, []string{"bet_outcomes"}, []string{"bet_id", "sport_id", "event_id", "odd_id", "home_team_name", "away_team_name", "market_id", "market_name", "odd", "odd_name", "odd_header", "odd_handicap", "expires"}, &iteratorForCreateBetOutcome{rows: arg})
}
// iteratorForCreateTicketOutcome implements pgx.CopyFromSource.
type iteratorForCreateTicketOutcome struct {
rows []CreateTicketOutcomeParams
skippedFirstNextCall bool
}
func (r *iteratorForCreateTicketOutcome) Next() bool {
if len(r.rows) == 0 {
return false
}
if !r.skippedFirstNextCall {
r.skippedFirstNextCall = true
return true
}
r.rows = r.rows[1:]
return len(r.rows) > 0
}
func (r iteratorForCreateTicketOutcome) Values() ([]interface{}, error) {
return []interface{}{
r.rows[0].TicketID,
r.rows[0].EventID,
r.rows[0].OddID,
r.rows[0].HomeTeamName,
r.rows[0].AwayTeamName,
r.rows[0].MarketID,
r.rows[0].MarketName,
r.rows[0].Odd,
r.rows[0].OddName,
r.rows[0].OddHeader,
r.rows[0].OddHandicap,
r.rows[0].Expires,
}, nil
}
func (r iteratorForCreateTicketOutcome) Err() error {
return nil
}
func (q *Queries) CreateTicketOutcome(ctx context.Context, arg []CreateTicketOutcomeParams) (int64, error) {
return q.db.CopyFrom(ctx, []string{"ticket_outcomes"}, []string{"ticket_id", "event_id", "odd_id", "home_team_name", "away_team_name", "market_id", "market_name", "odd", "odd_name", "odd_header", "odd_handicap", "expires"}, &iteratorForCreateTicketOutcome{rows: arg})
}

View File

@ -15,7 +15,6 @@ type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error) Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row QueryRow(context.Context, string, ...interface{}) pgx.Row
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
} }
func New(db DBTX) *Queries { func New(db DBTX) *Queries {

View File

@ -1,221 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: direct_deposit.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const ApproveDirectDeposit = `-- name: ApproveDirectDeposit :exec
UPDATE direct_deposits
SET
status = 'APPROVED',
approved_by = $2,
approved_at = NOW()
WHERE
id = $1
AND status = 'PENDING'
`
type ApproveDirectDepositParams struct {
ID int64 `json:"id"`
ApprovedBy pgtype.Int8 `json:"approved_by"`
}
func (q *Queries) ApproveDirectDeposit(ctx context.Context, arg ApproveDirectDepositParams) error {
_, err := q.db.Exec(ctx, ApproveDirectDeposit, arg.ID, arg.ApprovedBy)
return err
}
const CountDirectDepositsByStatus = `-- name: CountDirectDepositsByStatus :one
SELECT COUNT(*)
FROM direct_deposits
WHERE status = $1
`
func (q *Queries) CountDirectDepositsByStatus(ctx context.Context, status pgtype.Text) (int64, error) {
row := q.db.QueryRow(ctx, CountDirectDepositsByStatus, status)
var count int64
err := row.Scan(&count)
return count, err
}
const CreateDirectDeposit = `-- name: CreateDirectDeposit :one
INSERT INTO direct_deposits (
customer_id, wallet_id, bank_name, account_number,
account_holder, amount, reference_number,
transfer_screenshot, status
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'PENDING')
RETURNING id, customer_id, wallet_id, bank_name, account_number, account_holder, amount, reference_number, transfer_screenshot, status, created_at, approved_by, approved_at, rejection_reason
`
type CreateDirectDepositParams struct {
CustomerID pgtype.Int8 `json:"customer_id"`
WalletID pgtype.Int8 `json:"wallet_id"`
BankName pgtype.Text `json:"bank_name"`
AccountNumber pgtype.Text `json:"account_number"`
AccountHolder pgtype.Text `json:"account_holder"`
Amount pgtype.Numeric `json:"amount"`
ReferenceNumber pgtype.Text `json:"reference_number"`
TransferScreenshot pgtype.Text `json:"transfer_screenshot"`
}
func (q *Queries) CreateDirectDeposit(ctx context.Context, arg CreateDirectDepositParams) (DirectDeposit, error) {
row := q.db.QueryRow(ctx, CreateDirectDeposit,
arg.CustomerID,
arg.WalletID,
arg.BankName,
arg.AccountNumber,
arg.AccountHolder,
arg.Amount,
arg.ReferenceNumber,
arg.TransferScreenshot,
)
var i DirectDeposit
err := row.Scan(
&i.ID,
&i.CustomerID,
&i.WalletID,
&i.BankName,
&i.AccountNumber,
&i.AccountHolder,
&i.Amount,
&i.ReferenceNumber,
&i.TransferScreenshot,
&i.Status,
&i.CreatedAt,
&i.ApprovedBy,
&i.ApprovedAt,
&i.RejectionReason,
)
return i, err
}
const DeleteDirectDeposit = `-- name: DeleteDirectDeposit :exec
DELETE FROM direct_deposits
WHERE id = $1
`
func (q *Queries) DeleteDirectDeposit(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteDirectDeposit, id)
return err
}
const GetDirectDepositByID = `-- name: GetDirectDepositByID :one
SELECT id, customer_id, wallet_id, bank_name, account_number, account_holder, amount, reference_number, transfer_screenshot, status, created_at, approved_by, approved_at, rejection_reason
FROM direct_deposits
WHERE id = $1
`
func (q *Queries) GetDirectDepositByID(ctx context.Context, id int64) (DirectDeposit, error) {
row := q.db.QueryRow(ctx, GetDirectDepositByID, id)
var i DirectDeposit
err := row.Scan(
&i.ID,
&i.CustomerID,
&i.WalletID,
&i.BankName,
&i.AccountNumber,
&i.AccountHolder,
&i.Amount,
&i.ReferenceNumber,
&i.TransferScreenshot,
&i.Status,
&i.CreatedAt,
&i.ApprovedBy,
&i.ApprovedAt,
&i.RejectionReason,
)
return i, err
}
const GetDirectDepositsByStatus = `-- name: GetDirectDepositsByStatus :many
SELECT
id,
customer_id,
wallet_id,
bank_name,
account_number,
account_holder,
amount,
reference_number,
transfer_screenshot,
status,
created_at,
approved_by,
approved_at,
rejection_reason
FROM direct_deposits
WHERE status = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
`
type GetDirectDepositsByStatusParams struct {
Status pgtype.Text `json:"status"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
func (q *Queries) GetDirectDepositsByStatus(ctx context.Context, arg GetDirectDepositsByStatusParams) ([]DirectDeposit, error) {
rows, err := q.db.Query(ctx, GetDirectDepositsByStatus, arg.Status, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []DirectDeposit
for rows.Next() {
var i DirectDeposit
if err := rows.Scan(
&i.ID,
&i.CustomerID,
&i.WalletID,
&i.BankName,
&i.AccountNumber,
&i.AccountHolder,
&i.Amount,
&i.ReferenceNumber,
&i.TransferScreenshot,
&i.Status,
&i.CreatedAt,
&i.ApprovedBy,
&i.ApprovedAt,
&i.RejectionReason,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const RejectDirectDeposit = `-- name: RejectDirectDeposit :exec
UPDATE direct_deposits
SET
status = 'REJECTED',
approved_by = $2, -- still track the admin who took final action
approved_at = NOW(),
rejection_reason = $3
WHERE
id = $1
AND status = 'PENDING'
`
type RejectDirectDepositParams struct {
ID int64 `json:"id"`
ApprovedBy pgtype.Int8 `json:"approved_by"`
RejectionReason pgtype.Text `json:"rejection_reason"`
}
func (q *Queries) RejectDirectDeposit(ctx context.Context, arg RejectDirectDepositParams) error {
_, err := q.db.Exec(ctx, RejectDirectDeposit, arg.ID, arg.ApprovedBy, arg.RejectionReason)
return err
}

File diff suppressed because it is too large Load Diff

View File

@ -1,133 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: event_history.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetAllEventHistory = `-- name: GetAllEventHistory :many
SELECT id, event_id, status, created_at
FROM event_history
WHERE (
event_id = $1
OR $1 IS NULL
)
AND (
created_at > $2
OR $2 IS NULL
)
AND (
created_at < $3
OR $3 IS NULL
)
`
type GetAllEventHistoryParams struct {
EventID pgtype.Int8 `json:"event_id"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
func (q *Queries) GetAllEventHistory(ctx context.Context, arg GetAllEventHistoryParams) ([]EventHistory, error) {
rows, err := q.db.Query(ctx, GetAllEventHistory, arg.EventID, arg.CreatedBefore, arg.CreatedAfter)
if err != nil {
return nil, err
}
defer rows.Close()
var items []EventHistory
for rows.Next() {
var i EventHistory
if err := rows.Scan(
&i.ID,
&i.EventID,
&i.Status,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetInitialEventPerDay = `-- name: GetInitialEventPerDay :many
SELECT DISTINCT ON (DATE_TRUNC('day', created_at)) id, event_id, status, created_at
FROM event_history
WHERE (
event_id = $1
OR $1 IS NULL
)
AND (
created_at > $2
OR $2 IS NULL
)
AND (
created_at < $3
OR $3 IS NULL
)
ORDER BY DATE_TRUNC('day', created_at),
created_at ASC
`
type GetInitialEventPerDayParams struct {
EventID pgtype.Int8 `json:"event_id"`
CreatedBefore pgtype.Timestamp `json:"created_before"`
CreatedAfter pgtype.Timestamp `json:"created_after"`
}
func (q *Queries) GetInitialEventPerDay(ctx context.Context, arg GetInitialEventPerDayParams) ([]EventHistory, error) {
rows, err := q.db.Query(ctx, GetInitialEventPerDay, arg.EventID, arg.CreatedBefore, arg.CreatedAfter)
if err != nil {
return nil, err
}
defer rows.Close()
var items []EventHistory
for rows.Next() {
var i EventHistory
if err := rows.Scan(
&i.ID,
&i.EventID,
&i.Status,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const InsertEventHistory = `-- name: InsertEventHistory :one
INSERT INTO event_history (event_id, status)
VALUES ($1, $2)
RETURNING id, event_id, status, created_at
`
type InsertEventHistoryParams struct {
EventID int64 `json:"event_id"`
Status string `json:"status"`
}
func (q *Queries) InsertEventHistory(ctx context.Context, arg InsertEventHistoryParams) (EventHistory, error) {
row := q.db.QueryRow(ctx, InsertEventHistory, arg.EventID, arg.Status)
var i EventHistory
err := row.Scan(
&i.ID,
&i.EventID,
&i.Status,
&i.CreatedAt,
)
return i, err
}

View File

@ -1,545 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: events.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const DeleteEvent = `-- name: DeleteEvent :exec
DELETE FROM events
WHERE id = $1
`
func (q *Queries) DeleteEvent(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteEvent, id)
return err
}
const GetAllEvents = `-- name: GetAllEvents :many
SELECT id, source_event_id, sport_id, match_name, home_team, away_team, home_team_id, away_team_id, home_kit_image, away_kit_image, league_id, league_name, start_time, score, match_minute, timer_status, added_time, match_period, is_live, status, fetched_at, updated_at, source, default_is_active, default_is_featured, default_winning_upper_limit, is_monitored, league_cc, total_outcomes, number_of_bets, total_amount, avg_bet_amount, total_potential_winnings
FROM event_detailed
WHERE (
is_live = $1
OR $1 IS NULL
)
AND (
status = $2
OR $2 IS NULL
)
AND (
league_id = $3
OR $3 IS NULL
)
AND (
sport_id = $4
OR $4 IS NULL
)
AND (
match_name ILIKE '%' || $5 || '%'
OR league_name ILIKE '%' || $5 || '%'
OR $5 IS NULL
)
AND (
start_time < $6
OR $6 IS NULL
)
AND (
start_time > $7
OR $7 IS NULL
)
AND (
league_cc = $8
OR $8 IS NULL
)
AND (
source = $9
OR $9 IS NULL
)
ORDER BY start_time ASC
LIMIT $11 OFFSET $10
`
type GetAllEventsParams struct {
IsLive pgtype.Bool `json:"is_live"`
Status pgtype.Text `json:"status"`
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
LastStartTime pgtype.Timestamp `json:"last_start_time"`
FirstStartTime pgtype.Timestamp `json:"first_start_time"`
CountryCode pgtype.Text `json:"country_code"`
Source pgtype.Text `json:"source"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
// TODO: Figure out how to make this code reusable. SQLC prohibits CTEs within multiple queries
func (q *Queries) GetAllEvents(ctx context.Context, arg GetAllEventsParams) ([]EventDetailed, error) {
rows, err := q.db.Query(ctx, GetAllEvents,
arg.IsLive,
arg.Status,
arg.LeagueID,
arg.SportID,
arg.Query,
arg.LastStartTime,
arg.FirstStartTime,
arg.CountryCode,
arg.Source,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []EventDetailed
for rows.Next() {
var i EventDetailed
if err := rows.Scan(
&i.ID,
&i.SourceEventID,
&i.SportID,
&i.MatchName,
&i.HomeTeam,
&i.AwayTeam,
&i.HomeTeamID,
&i.AwayTeamID,
&i.HomeKitImage,
&i.AwayKitImage,
&i.LeagueID,
&i.LeagueName,
&i.StartTime,
&i.Score,
&i.MatchMinute,
&i.TimerStatus,
&i.AddedTime,
&i.MatchPeriod,
&i.IsLive,
&i.Status,
&i.FetchedAt,
&i.UpdatedAt,
&i.Source,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.DefaultWinningUpperLimit,
&i.IsMonitored,
&i.LeagueCc,
&i.TotalOutcomes,
&i.NumberOfBets,
&i.TotalAmount,
&i.AvgBetAmount,
&i.TotalPotentialWinnings,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetEventByID = `-- name: GetEventByID :one
SELECT id, source_event_id, sport_id, match_name, home_team, away_team, home_team_id, away_team_id, home_kit_image, away_kit_image, league_id, league_name, start_time, score, match_minute, timer_status, added_time, match_period, is_live, status, fetched_at, updated_at, source, default_is_active, default_is_featured, default_winning_upper_limit, is_monitored, league_cc, total_outcomes, number_of_bets, total_amount, avg_bet_amount, total_potential_winnings
FROM event_detailed
WHERE id = $1
LIMIT 1
`
func (q *Queries) GetEventByID(ctx context.Context, id int64) (EventDetailed, error) {
row := q.db.QueryRow(ctx, GetEventByID, id)
var i EventDetailed
err := row.Scan(
&i.ID,
&i.SourceEventID,
&i.SportID,
&i.MatchName,
&i.HomeTeam,
&i.AwayTeam,
&i.HomeTeamID,
&i.AwayTeamID,
&i.HomeKitImage,
&i.AwayKitImage,
&i.LeagueID,
&i.LeagueName,
&i.StartTime,
&i.Score,
&i.MatchMinute,
&i.TimerStatus,
&i.AddedTime,
&i.MatchPeriod,
&i.IsLive,
&i.Status,
&i.FetchedAt,
&i.UpdatedAt,
&i.Source,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.DefaultWinningUpperLimit,
&i.IsMonitored,
&i.LeagueCc,
&i.TotalOutcomes,
&i.NumberOfBets,
&i.TotalAmount,
&i.AvgBetAmount,
&i.TotalPotentialWinnings,
)
return i, err
}
const GetEventBySourceID = `-- name: GetEventBySourceID :one
SELECT id, source_event_id, sport_id, match_name, home_team, away_team, home_team_id, away_team_id, home_kit_image, away_kit_image, league_id, league_name, start_time, score, match_minute, timer_status, added_time, match_period, is_live, status, fetched_at, updated_at, source, default_is_active, default_is_featured, default_winning_upper_limit, is_monitored, league_cc, total_outcomes, number_of_bets, total_amount, avg_bet_amount, total_potential_winnings
FROM event_detailed
WHERE source_event_id = $1
AND source = $2
`
type GetEventBySourceIDParams struct {
SourceEventID string `json:"source_event_id"`
Source string `json:"source"`
}
func (q *Queries) GetEventBySourceID(ctx context.Context, arg GetEventBySourceIDParams) (EventDetailed, error) {
row := q.db.QueryRow(ctx, GetEventBySourceID, arg.SourceEventID, arg.Source)
var i EventDetailed
err := row.Scan(
&i.ID,
&i.SourceEventID,
&i.SportID,
&i.MatchName,
&i.HomeTeam,
&i.AwayTeam,
&i.HomeTeamID,
&i.AwayTeamID,
&i.HomeKitImage,
&i.AwayKitImage,
&i.LeagueID,
&i.LeagueName,
&i.StartTime,
&i.Score,
&i.MatchMinute,
&i.TimerStatus,
&i.AddedTime,
&i.MatchPeriod,
&i.IsLive,
&i.Status,
&i.FetchedAt,
&i.UpdatedAt,
&i.Source,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.DefaultWinningUpperLimit,
&i.IsMonitored,
&i.LeagueCc,
&i.TotalOutcomes,
&i.NumberOfBets,
&i.TotalAmount,
&i.AvgBetAmount,
&i.TotalPotentialWinnings,
)
return i, err
}
const GetSportAndLeagueIDs = `-- name: GetSportAndLeagueIDs :one
SELECT sport_id,
league_id
FROM events
WHERE id = $1
`
type GetSportAndLeagueIDsRow struct {
SportID int32 `json:"sport_id"`
LeagueID int64 `json:"league_id"`
}
func (q *Queries) GetSportAndLeagueIDs(ctx context.Context, id int64) (GetSportAndLeagueIDsRow, error) {
row := q.db.QueryRow(ctx, GetSportAndLeagueIDs, id)
var i GetSportAndLeagueIDsRow
err := row.Scan(&i.SportID, &i.LeagueID)
return i, err
}
const GetTotalEvents = `-- name: GetTotalEvents :one
SELECT COUNT(*)
FROM event_detailed
WHERE (
is_live = $1
OR $1 IS NULL
)
AND (
status = $2
OR $2 IS NULL
)
AND (
league_id = $3
OR $3 IS NULL
)
AND (
sport_id = $4
OR $4 IS NULL
)
AND (
match_name ILIKE '%' || $5 || '%'
OR league_name ILIKE '%' || $5 || '%'
OR $5 IS NULL
)
AND (
start_time < $6
OR $6 IS NULL
)
AND (
start_time > $7
OR $7 IS NULL
)
AND (
league_cc = $8
OR $8 IS NULL
)
AND (
source = $9
OR $9 IS NULL
)
`
type GetTotalEventsParams struct {
IsLive pgtype.Bool `json:"is_live"`
Status pgtype.Text `json:"status"`
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
LastStartTime pgtype.Timestamp `json:"last_start_time"`
FirstStartTime pgtype.Timestamp `json:"first_start_time"`
CountryCode pgtype.Text `json:"country_code"`
Source pgtype.Text `json:"source"`
}
func (q *Queries) GetTotalEvents(ctx context.Context, arg GetTotalEventsParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalEvents,
arg.IsLive,
arg.Status,
arg.LeagueID,
arg.SportID,
arg.Query,
arg.LastStartTime,
arg.FirstStartTime,
arg.CountryCode,
arg.Source,
)
var count int64
err := row.Scan(&count)
return count, err
}
const InsertEvent = `-- name: InsertEvent :exec
INSERT INTO events (
source_event_id,
sport_id,
match_name,
home_team,
away_team,
home_team_id,
away_team_id,
home_kit_image,
away_kit_image,
league_id,
league_name,
start_time,
is_live,
status,
source,
default_winning_upper_limit
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16
) ON CONFLICT (source_event_id, source) DO
UPDATE
SET sport_id = EXCLUDED.sport_id,
match_name = EXCLUDED.match_name,
home_team = EXCLUDED.home_team,
away_team = EXCLUDED.away_team,
home_team_id = EXCLUDED.home_team_id,
away_team_id = EXCLUDED.away_team_id,
home_kit_image = EXCLUDED.home_kit_image,
away_kit_image = EXCLUDED.away_kit_image,
league_id = EXCLUDED.league_id,
league_name = EXCLUDED.league_name,
start_time = EXCLUDED.start_time,
score = EXCLUDED.score,
match_minute = EXCLUDED.match_minute,
timer_status = EXCLUDED.timer_status,
added_time = EXCLUDED.added_time,
match_period = EXCLUDED.match_period,
is_live = EXCLUDED.is_live,
source = EXCLUDED.source,
default_winning_upper_limit = EXCLUDED.default_winning_upper_limit,
fetched_at = now()
`
type InsertEventParams struct {
SourceEventID string `json:"source_event_id"`
SportID int32 `json:"sport_id"`
MatchName string `json:"match_name"`
HomeTeam string `json:"home_team"`
AwayTeam string `json:"away_team"`
HomeTeamID int64 `json:"home_team_id"`
AwayTeamID int64 `json:"away_team_id"`
HomeKitImage string `json:"home_kit_image"`
AwayKitImage string `json:"away_kit_image"`
LeagueID int64 `json:"league_id"`
LeagueName string `json:"league_name"`
StartTime pgtype.Timestamp `json:"start_time"`
IsLive bool `json:"is_live"`
Status string `json:"status"`
Source string `json:"source"`
DefaultWinningUpperLimit int64 `json:"default_winning_upper_limit"`
}
func (q *Queries) InsertEvent(ctx context.Context, arg InsertEventParams) error {
_, err := q.db.Exec(ctx, InsertEvent,
arg.SourceEventID,
arg.SportID,
arg.MatchName,
arg.HomeTeam,
arg.AwayTeam,
arg.HomeTeamID,
arg.AwayTeamID,
arg.HomeKitImage,
arg.AwayKitImage,
arg.LeagueID,
arg.LeagueName,
arg.StartTime,
arg.IsLive,
arg.Status,
arg.Source,
arg.DefaultWinningUpperLimit,
)
return err
}
const IsEventMonitored = `-- name: IsEventMonitored :one
SELECT is_monitored
FROM events
WHERE id = $1
`
func (q *Queries) IsEventMonitored(ctx context.Context, id int64) (bool, error) {
row := q.db.QueryRow(ctx, IsEventMonitored, id)
var is_monitored bool
err := row.Scan(&is_monitored)
return is_monitored, err
}
const ListLiveEvents = `-- name: ListLiveEvents :many
SELECT id
FROM event_detailed
WHERE is_live = true
`
func (q *Queries) ListLiveEvents(ctx context.Context) ([]int64, error) {
rows, err := q.db.Query(ctx, ListLiveEvents)
if err != nil {
return nil, err
}
defer rows.Close()
var items []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateEventMonitored = `-- name: UpdateEventMonitored :exec
UPDATE events
SET is_monitored = $1,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2
`
type UpdateEventMonitoredParams struct {
IsMonitored bool `json:"is_monitored"`
ID int64 `json:"id"`
}
func (q *Queries) UpdateEventMonitored(ctx context.Context, arg UpdateEventMonitoredParams) error {
_, err := q.db.Exec(ctx, UpdateEventMonitored, arg.IsMonitored, arg.ID)
return err
}
const UpdateGlobalEventSettings = `-- name: UpdateGlobalEventSettings :exec
UPDATE events
SET default_is_active = COALESCE($2, default_is_active),
default_is_featured = COALESCE(
$3,
default_is_featured
),
default_winning_upper_limit = COALESCE(
$4,
default_winning_upper_limit
),
updated_at = CURRENT_TIMESTAMP
WHERE id = $1
`
type UpdateGlobalEventSettingsParams struct {
ID int64 `json:"id"`
DefaultIsActive pgtype.Bool `json:"default_is_active"`
DefaultIsFeatured pgtype.Bool `json:"default_is_featured"`
DefaultWinningUpperLimit pgtype.Int8 `json:"default_winning_upper_limit"`
}
func (q *Queries) UpdateGlobalEventSettings(ctx context.Context, arg UpdateGlobalEventSettingsParams) error {
_, err := q.db.Exec(ctx, UpdateGlobalEventSettings,
arg.ID,
arg.DefaultIsActive,
arg.DefaultIsFeatured,
arg.DefaultWinningUpperLimit,
)
return err
}
const UpdateMatchResult = `-- name: UpdateMatchResult :exec
UPDATE events
SET score = $1,
status = $2
WHERE id = $3
`
type UpdateMatchResultParams struct {
Score pgtype.Text `json:"score"`
Status string `json:"status"`
ID int64 `json:"id"`
}
func (q *Queries) UpdateMatchResult(ctx context.Context, arg UpdateMatchResultParams) error {
_, err := q.db.Exec(ctx, UpdateMatchResult, arg.Score, arg.Status, arg.ID)
return err
}

View File

@ -1,42 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: events_bet_stats.sql
package dbgen
import (
"context"
)
const UpdateEventBetStats = `-- name: UpdateEventBetStats :exec
INSERT INTO event_bet_stats (
event_id,
number_of_bets,
total_amount,
avg_bet_amount,
total_potential_winnings,
updated_at
)
SELECT bo.event_id,
COUNT(DISTINCT b.id) AS number_of_bets,
COALESCE(SUM(b.amount), 0) AS total_amount,
COALESCE(AVG(b.amount), 0) AS avg_bet_amount,
COALESCE(SUM(b.potential_win), 0) AS total_potential_winnings,
NOW() AS updated_at
FROM bet_outcomes bo
JOIN bets b ON bo.bet_id = b.id
GROUP BY bo.event_id ON CONFLICT (event_id) DO
UPDATE
SET number_of_bets = EXCLUDED.number_of_bets,
total_amount = EXCLUDED.total_amount,
avg_bet_amount = EXCLUDED.avg_bet_amount,
total_potential_winnings = EXCLUDED.total_potential_winnings,
updated_at = EXCLUDED.updated_at
`
// Aggregate bet stats per event
func (q *Queries) UpdateEventBetStats(ctx context.Context) error {
_, err := q.db.Exec(ctx, UpdateEventBetStats)
return err
}

View File

@ -1,259 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: events_stat.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetTotalEventStats = `-- name: GetTotalEventStats :one
SELECT COUNT(*) AS event_count,
COUNT(*) FILTER (
WHERE events.default_is_active = TRUE
) AS total_active_events,
COUNT(*) FILTER (
WHERE events.default_is_active = FALSE
) AS total_inactive_events,
COUNT(*) FILTER (
WHERE events.default_is_featured = TRUE
) AS total_featured_events,
COUNT(DISTINCT league_id) as total_leagues,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM events
WHERE (
events.league_id = $1
OR $1 IS NULL
)
AND (
events.sport_id = $2
OR $2 IS NULL
)
`
type GetTotalEventStatsParams struct {
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
}
type GetTotalEventStatsRow struct {
EventCount int64 `json:"event_count"`
TotalActiveEvents int64 `json:"total_active_events"`
TotalInactiveEvents int64 `json:"total_inactive_events"`
TotalFeaturedEvents int64 `json:"total_featured_events"`
TotalLeagues int64 `json:"total_leagues"`
Pending int64 `json:"pending"`
InPlay int64 `json:"in_play"`
ToBeFixed int64 `json:"to_be_fixed"`
Ended int64 `json:"ended"`
Postponed int64 `json:"postponed"`
Cancelled int64 `json:"cancelled"`
Walkover int64 `json:"walkover"`
Interrupted int64 `json:"interrupted"`
Abandoned int64 `json:"abandoned"`
Retired int64 `json:"retired"`
Suspended int64 `json:"suspended"`
DecidedByFa int64 `json:"decided_by_fa"`
Removed int64 `json:"removed"`
}
func (q *Queries) GetTotalEventStats(ctx context.Context, arg GetTotalEventStatsParams) (GetTotalEventStatsRow, error) {
row := q.db.QueryRow(ctx, GetTotalEventStats, arg.LeagueID, arg.SportID)
var i GetTotalEventStatsRow
err := row.Scan(
&i.EventCount,
&i.TotalActiveEvents,
&i.TotalInactiveEvents,
&i.TotalFeaturedEvents,
&i.TotalLeagues,
&i.Pending,
&i.InPlay,
&i.ToBeFixed,
&i.Ended,
&i.Postponed,
&i.Cancelled,
&i.Walkover,
&i.Interrupted,
&i.Abandoned,
&i.Retired,
&i.Suspended,
&i.DecidedByFa,
&i.Removed,
)
return i, err
}
const GetTotalEventStatsByInterval = `-- name: GetTotalEventStatsByInterval :many
SELECT DATE_TRUNC($1, start_time)::timestamp AS date,
COUNT(*) AS event_count,
COUNT(*) FILTER (
WHERE events.default_is_active = TRUE
) AS total_active_events,
COUNT(*) FILTER (
WHERE events.default_is_active = FALSE
) AS total_inactive_events,
COUNT(*) FILTER (
WHERE events.default_is_featured = TRUE
) AS total_featured_events,
COUNT(DISTINCT league_id) as total_leagues,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM events
WHERE (
events.league_id = $2
OR $2 IS NULL
)
AND (
events.sport_id = $3
OR $3 IS NULL
)
GROUP BY date
ORDER BY date
`
type GetTotalEventStatsByIntervalParams struct {
Interval pgtype.Text `json:"interval"`
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
}
type GetTotalEventStatsByIntervalRow struct {
Date pgtype.Timestamp `json:"date"`
EventCount int64 `json:"event_count"`
TotalActiveEvents int64 `json:"total_active_events"`
TotalInactiveEvents int64 `json:"total_inactive_events"`
TotalFeaturedEvents int64 `json:"total_featured_events"`
TotalLeagues int64 `json:"total_leagues"`
Pending int64 `json:"pending"`
InPlay int64 `json:"in_play"`
ToBeFixed int64 `json:"to_be_fixed"`
Ended int64 `json:"ended"`
Postponed int64 `json:"postponed"`
Cancelled int64 `json:"cancelled"`
Walkover int64 `json:"walkover"`
Interrupted int64 `json:"interrupted"`
Abandoned int64 `json:"abandoned"`
Retired int64 `json:"retired"`
Suspended int64 `json:"suspended"`
DecidedByFa int64 `json:"decided_by_fa"`
Removed int64 `json:"removed"`
}
func (q *Queries) GetTotalEventStatsByInterval(ctx context.Context, arg GetTotalEventStatsByIntervalParams) ([]GetTotalEventStatsByIntervalRow, error) {
rows, err := q.db.Query(ctx, GetTotalEventStatsByInterval, arg.Interval, arg.LeagueID, arg.SportID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetTotalEventStatsByIntervalRow
for rows.Next() {
var i GetTotalEventStatsByIntervalRow
if err := rows.Scan(
&i.Date,
&i.EventCount,
&i.TotalActiveEvents,
&i.TotalInactiveEvents,
&i.TotalFeaturedEvents,
&i.TotalLeagues,
&i.Pending,
&i.InPlay,
&i.ToBeFixed,
&i.Ended,
&i.Postponed,
&i.Cancelled,
&i.Walkover,
&i.Interrupted,
&i.Abandoned,
&i.Retired,
&i.Suspended,
&i.DecidedByFa,
&i.Removed,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -1,469 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: events_with_settings.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetEventWithSettingByID = `-- name: GetEventWithSettingByID :one
SELECT e.id, e.source_event_id, e.sport_id, e.match_name, e.home_team, e.away_team, e.home_team_id, e.away_team_id, e.home_kit_image, e.away_kit_image, e.league_id, e.league_name, e.start_time, e.score, e.match_minute, e.timer_status, e.added_time, e.match_period, e.is_live, e.status, e.fetched_at, e.updated_at, e.source, e.default_is_active, e.default_is_featured, e.default_winning_upper_limit, e.is_monitored,
ces.company_id,
COALESCE(ces.is_active, e.default_is_active) AS is_active,
COALESCE(ces.is_featured, e.default_is_featured) AS is_featured,
COALESCE(
ces.winning_upper_limit,
e.default_winning_upper_limit
) AS winning_upper_limit,
ces.updated_at,
l.country_code as league_cc,
COALESCE(om.total_outcomes, 0) AS total_outcomes,
COALESCE(ebs.number_of_bets, 0) AS number_of_bets,
COALESCE(ebs.total_amount, 0) AS total_amount,
COALESCE(ebs.avg_bet_amount, 0) AS avg_bet_amount,
COALESCE(ebs.total_potential_winnings, 0) AS total_potential_winnings
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $2
LEFT JOIN event_bet_stats ebs ON ebs.event_id = e.id
JOIN leagues l ON l.id = e.league_id
LEFT JOIN (
SELECT event_id,
SUM(number_of_outcomes) AS total_outcomes
FROM odds_market
GROUP BY event_id
) om ON om.event_id = e.id
WHERE e.id = $1
LIMIT 1
`
type GetEventWithSettingByIDParams struct {
ID int64 `json:"id"`
CompanyID int64 `json:"company_id"`
}
type GetEventWithSettingByIDRow struct {
ID int64 `json:"id"`
SourceEventID string `json:"source_event_id"`
SportID int32 `json:"sport_id"`
MatchName string `json:"match_name"`
HomeTeam string `json:"home_team"`
AwayTeam string `json:"away_team"`
HomeTeamID int64 `json:"home_team_id"`
AwayTeamID int64 `json:"away_team_id"`
HomeKitImage string `json:"home_kit_image"`
AwayKitImage string `json:"away_kit_image"`
LeagueID int64 `json:"league_id"`
LeagueName string `json:"league_name"`
StartTime pgtype.Timestamp `json:"start_time"`
Score pgtype.Text `json:"score"`
MatchMinute pgtype.Int4 `json:"match_minute"`
TimerStatus pgtype.Text `json:"timer_status"`
AddedTime pgtype.Int4 `json:"added_time"`
MatchPeriod pgtype.Int4 `json:"match_period"`
IsLive bool `json:"is_live"`
Status string `json:"status"`
FetchedAt pgtype.Timestamp `json:"fetched_at"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
Source string `json:"source"`
DefaultIsActive bool `json:"default_is_active"`
DefaultIsFeatured bool `json:"default_is_featured"`
DefaultWinningUpperLimit int64 `json:"default_winning_upper_limit"`
IsMonitored bool `json:"is_monitored"`
CompanyID pgtype.Int8 `json:"company_id"`
IsActive bool `json:"is_active"`
IsFeatured bool `json:"is_featured"`
WinningUpperLimit int64 `json:"winning_upper_limit"`
UpdatedAt_2 pgtype.Timestamp `json:"updated_at_2"`
LeagueCc pgtype.Text `json:"league_cc"`
TotalOutcomes int64 `json:"total_outcomes"`
NumberOfBets int64 `json:"number_of_bets"`
TotalAmount int64 `json:"total_amount"`
AvgBetAmount float64 `json:"avg_bet_amount"`
TotalPotentialWinnings int64 `json:"total_potential_winnings"`
}
func (q *Queries) GetEventWithSettingByID(ctx context.Context, arg GetEventWithSettingByIDParams) (GetEventWithSettingByIDRow, error) {
row := q.db.QueryRow(ctx, GetEventWithSettingByID, arg.ID, arg.CompanyID)
var i GetEventWithSettingByIDRow
err := row.Scan(
&i.ID,
&i.SourceEventID,
&i.SportID,
&i.MatchName,
&i.HomeTeam,
&i.AwayTeam,
&i.HomeTeamID,
&i.AwayTeamID,
&i.HomeKitImage,
&i.AwayKitImage,
&i.LeagueID,
&i.LeagueName,
&i.StartTime,
&i.Score,
&i.MatchMinute,
&i.TimerStatus,
&i.AddedTime,
&i.MatchPeriod,
&i.IsLive,
&i.Status,
&i.FetchedAt,
&i.UpdatedAt,
&i.Source,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.DefaultWinningUpperLimit,
&i.IsMonitored,
&i.CompanyID,
&i.IsActive,
&i.IsFeatured,
&i.WinningUpperLimit,
&i.UpdatedAt_2,
&i.LeagueCc,
&i.TotalOutcomes,
&i.NumberOfBets,
&i.TotalAmount,
&i.AvgBetAmount,
&i.TotalPotentialWinnings,
)
return i, err
}
const GetEventsWithSettings = `-- name: GetEventsWithSettings :many
SELECT e.id, e.source_event_id, e.sport_id, e.match_name, e.home_team, e.away_team, e.home_team_id, e.away_team_id, e.home_kit_image, e.away_kit_image, e.league_id, e.league_name, e.start_time, e.score, e.match_minute, e.timer_status, e.added_time, e.match_period, e.is_live, e.status, e.fetched_at, e.updated_at, e.source, e.default_is_active, e.default_is_featured, e.default_winning_upper_limit, e.is_monitored,
ces.company_id,
COALESCE(ces.is_active, e.default_is_active) AS is_active,
COALESCE(ces.is_featured, e.default_is_featured) AS is_featured,
COALESCE(
ces.winning_upper_limit,
e.default_winning_upper_limit
) AS winning_upper_limit,
ces.updated_at,
l.country_code as league_cc,
COALESCE(om.total_outcomes, 0) AS total_outcomes,
COALESCE(ebs.number_of_bets, 0) AS number_of_bets,
COALESCE(ebs.total_amount, 0) AS total_amount,
COALESCE(ebs.avg_bet_amount, 0) AS avg_bet_amount,
COALESCE(ebs.total_potential_winnings, 0) AS total_potential_winnings
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $1
LEFT JOIN event_bet_stats ebs ON ebs.event_id = e.id
JOIN leagues l ON l.id = e.league_id
LEFT JOIN (
SELECT event_id,
SUM(number_of_outcomes) AS total_outcomes
FROM odds_market
GROUP BY event_id
) om ON om.event_id = e.id
WHERE (
is_live = $2
OR $2 IS NULL
)
AND (
status = $3
OR $3 IS NULL
)
AND(
league_id = $4
OR $4 IS NULL
)
AND (
e.sport_id = $5
OR $5 IS NULL
)
AND (
match_name ILIKE '%' || $6 || '%'
OR league_name ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
AND (
start_time < $7
OR $7 IS NULL
)
AND (
start_time > $8
OR $8 IS NULL
)
AND (
l.country_code = $9
OR $9 IS NULL
)
AND (
ces.is_featured = $10
OR e.default_is_featured = $10
OR $10 IS NULL
)
AND (
ces.is_active = $11
OR e.default_is_active = $11
OR $11 IS NULL
)
AND (
source = $12
OR $12 IS NULL
)
ORDER BY start_time ASC
LIMIT $14 OFFSET $13
`
type GetEventsWithSettingsParams struct {
CompanyID int64 `json:"company_id"`
IsLive pgtype.Bool `json:"is_live"`
Status pgtype.Text `json:"status"`
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
LastStartTime pgtype.Timestamp `json:"last_start_time"`
FirstStartTime pgtype.Timestamp `json:"first_start_time"`
CountryCode pgtype.Text `json:"country_code"`
IsFeatured pgtype.Bool `json:"is_featured"`
IsActive pgtype.Bool `json:"is_active"`
Source pgtype.Text `json:"source"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
type GetEventsWithSettingsRow struct {
ID int64 `json:"id"`
SourceEventID string `json:"source_event_id"`
SportID int32 `json:"sport_id"`
MatchName string `json:"match_name"`
HomeTeam string `json:"home_team"`
AwayTeam string `json:"away_team"`
HomeTeamID int64 `json:"home_team_id"`
AwayTeamID int64 `json:"away_team_id"`
HomeKitImage string `json:"home_kit_image"`
AwayKitImage string `json:"away_kit_image"`
LeagueID int64 `json:"league_id"`
LeagueName string `json:"league_name"`
StartTime pgtype.Timestamp `json:"start_time"`
Score pgtype.Text `json:"score"`
MatchMinute pgtype.Int4 `json:"match_minute"`
TimerStatus pgtype.Text `json:"timer_status"`
AddedTime pgtype.Int4 `json:"added_time"`
MatchPeriod pgtype.Int4 `json:"match_period"`
IsLive bool `json:"is_live"`
Status string `json:"status"`
FetchedAt pgtype.Timestamp `json:"fetched_at"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
Source string `json:"source"`
DefaultIsActive bool `json:"default_is_active"`
DefaultIsFeatured bool `json:"default_is_featured"`
DefaultWinningUpperLimit int64 `json:"default_winning_upper_limit"`
IsMonitored bool `json:"is_monitored"`
CompanyID pgtype.Int8 `json:"company_id"`
IsActive bool `json:"is_active"`
IsFeatured bool `json:"is_featured"`
WinningUpperLimit int64 `json:"winning_upper_limit"`
UpdatedAt_2 pgtype.Timestamp `json:"updated_at_2"`
LeagueCc pgtype.Text `json:"league_cc"`
TotalOutcomes int64 `json:"total_outcomes"`
NumberOfBets int64 `json:"number_of_bets"`
TotalAmount int64 `json:"total_amount"`
AvgBetAmount float64 `json:"avg_bet_amount"`
TotalPotentialWinnings int64 `json:"total_potential_winnings"`
}
func (q *Queries) GetEventsWithSettings(ctx context.Context, arg GetEventsWithSettingsParams) ([]GetEventsWithSettingsRow, error) {
rows, err := q.db.Query(ctx, GetEventsWithSettings,
arg.CompanyID,
arg.IsLive,
arg.Status,
arg.LeagueID,
arg.SportID,
arg.Query,
arg.LastStartTime,
arg.FirstStartTime,
arg.CountryCode,
arg.IsFeatured,
arg.IsActive,
arg.Source,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetEventsWithSettingsRow
for rows.Next() {
var i GetEventsWithSettingsRow
if err := rows.Scan(
&i.ID,
&i.SourceEventID,
&i.SportID,
&i.MatchName,
&i.HomeTeam,
&i.AwayTeam,
&i.HomeTeamID,
&i.AwayTeamID,
&i.HomeKitImage,
&i.AwayKitImage,
&i.LeagueID,
&i.LeagueName,
&i.StartTime,
&i.Score,
&i.MatchMinute,
&i.TimerStatus,
&i.AddedTime,
&i.MatchPeriod,
&i.IsLive,
&i.Status,
&i.FetchedAt,
&i.UpdatedAt,
&i.Source,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.DefaultWinningUpperLimit,
&i.IsMonitored,
&i.CompanyID,
&i.IsActive,
&i.IsFeatured,
&i.WinningUpperLimit,
&i.UpdatedAt_2,
&i.LeagueCc,
&i.TotalOutcomes,
&i.NumberOfBets,
&i.TotalAmount,
&i.AvgBetAmount,
&i.TotalPotentialWinnings,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetTotalCompanyEvents = `-- name: GetTotalCompanyEvents :one
SELECT COUNT(*)
FROM events e
LEFT JOIN company_event_settings ces ON e.id = ces.event_id
AND ces.company_id = $1
JOIN leagues l ON l.id = e.league_id
WHERE (
is_live = $2
OR $2 IS NULL
)
AND (
status = $3
OR $3 IS NULL
)
AND(
league_id = $4
OR $4 IS NULL
)
AND (
e.sport_id = $5
OR $5 IS NULL
)
AND (
match_name ILIKE '%' || $6 || '%'
OR league_name ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
AND (
start_time < $7
OR $7 IS NULL
)
AND (
start_time > $8
OR $8 IS NULL
)
AND (
l.country_code = $9
OR $9 IS NULL
)
AND (
ces.is_featured = $10
OR e.default_is_featured = $10
OR $10 IS NULL
)
AND (
ces.is_active = $11
OR e.default_is_active = $11
OR $11 IS NULL
)
AND (
source = $12
OR $12 IS NULL
)
`
type GetTotalCompanyEventsParams struct {
CompanyID int64 `json:"company_id"`
IsLive pgtype.Bool `json:"is_live"`
Status pgtype.Text `json:"status"`
LeagueID pgtype.Int8 `json:"league_id"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
LastStartTime pgtype.Timestamp `json:"last_start_time"`
FirstStartTime pgtype.Timestamp `json:"first_start_time"`
CountryCode pgtype.Text `json:"country_code"`
IsFeatured pgtype.Bool `json:"is_featured"`
IsActive pgtype.Bool `json:"is_active"`
Source pgtype.Text `json:"source"`
}
func (q *Queries) GetTotalCompanyEvents(ctx context.Context, arg GetTotalCompanyEventsParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalCompanyEvents,
arg.CompanyID,
arg.IsLive,
arg.Status,
arg.LeagueID,
arg.SportID,
arg.Query,
arg.LastStartTime,
arg.FirstStartTime,
arg.CountryCode,
arg.IsFeatured,
arg.IsActive,
arg.Source,
)
var count int64
err := row.Scan(&count)
return count, err
}
const SaveTenantEventSettings = `-- name: SaveTenantEventSettings :exec
INSERT INTO company_event_settings (
company_id,
event_id,
is_active,
is_featured,
winning_upper_limit
)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT(company_id, event_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
is_featured = EXCLUDED.is_featured,
winning_upper_limit = EXCLUDED.winning_upper_limit
`
type SaveTenantEventSettingsParams struct {
CompanyID int64 `json:"company_id"`
EventID int64 `json:"event_id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
WinningUpperLimit pgtype.Int8 `json:"winning_upper_limit"`
}
func (q *Queries) SaveTenantEventSettings(ctx context.Context, arg SaveTenantEventSettingsParams) error {
_, err := q.db.Exec(ctx, SaveTenantEventSettings,
arg.CompanyID,
arg.EventID,
arg.IsActive,
arg.IsFeatured,
arg.WinningUpperLimit,
)
return err
}

View File

@ -1,42 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: flags.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CreateFlag = `-- name: CreateFlag :one
INSERT INTO flags (
bet_id,
odds_market_id,
reason
) VALUES (
$1, $2, $3
) RETURNING id, bet_id, odds_market_id, reason, flagged_at, resolved
`
type CreateFlagParams struct {
BetID pgtype.Int8 `json:"bet_id"`
OddsMarketID pgtype.Int8 `json:"odds_market_id"`
Reason pgtype.Text `json:"reason"`
}
func (q *Queries) CreateFlag(ctx context.Context, arg CreateFlagParams) (Flag, error) {
row := q.db.QueryRow(ctx, CreateFlag, arg.BetID, arg.OddsMarketID, arg.Reason)
var i Flag
err := row.Scan(
&i.ID,
&i.BetID,
&i.OddsMarketID,
&i.Reason,
&i.FlaggedAt,
&i.Resolved,
)
return i, err
}

View File

@ -1,301 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: institutions.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CountBanks = `-- name: CountBanks :one
SELECT COUNT(*)
FROM banks
WHERE (
country_id = $1
OR $1 IS NULL
)
AND (
is_active = $2
OR $2 IS NULL
)
AND (
name ILIKE '%' || $3 || '%'
OR code ILIKE '%' || $3 || '%'
OR $3 IS NULL
)
`
type CountBanksParams struct {
CountryID int32 `json:"country_id"`
IsActive int32 `json:"is_active"`
Column3 pgtype.Text `json:"column_3"`
}
func (q *Queries) CountBanks(ctx context.Context, arg CountBanksParams) (int64, error) {
row := q.db.QueryRow(ctx, CountBanks, arg.CountryID, arg.IsActive, arg.Column3)
var count int64
err := row.Scan(&count)
return count, err
}
const CreateBank = `-- name: CreateBank :one
INSERT INTO banks (
slug,
swift,
name,
acct_length,
country_id,
is_mobilemoney,
is_active,
is_rtgs,
active,
is_24hrs,
created_at,
updated_at,
currency,
bank_logo
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, $11, $12
)
RETURNING id, slug, swift, name, acct_length, country_id, is_mobilemoney, is_active, is_rtgs, active, is_24hrs, created_at, updated_at, currency, bank_logo
`
type CreateBankParams struct {
Slug string `json:"slug"`
Swift string `json:"swift"`
Name string `json:"name"`
AcctLength int32 `json:"acct_length"`
CountryID int32 `json:"country_id"`
IsMobilemoney pgtype.Int4 `json:"is_mobilemoney"`
IsActive int32 `json:"is_active"`
IsRtgs int32 `json:"is_rtgs"`
Active int32 `json:"active"`
Is24hrs pgtype.Int4 `json:"is_24hrs"`
Currency string `json:"currency"`
BankLogo pgtype.Text `json:"bank_logo"`
}
func (q *Queries) CreateBank(ctx context.Context, arg CreateBankParams) (Bank, error) {
row := q.db.QueryRow(ctx, CreateBank,
arg.Slug,
arg.Swift,
arg.Name,
arg.AcctLength,
arg.CountryID,
arg.IsMobilemoney,
arg.IsActive,
arg.IsRtgs,
arg.Active,
arg.Is24hrs,
arg.Currency,
arg.BankLogo,
)
var i Bank
err := row.Scan(
&i.ID,
&i.Slug,
&i.Swift,
&i.Name,
&i.AcctLength,
&i.CountryID,
&i.IsMobilemoney,
&i.IsActive,
&i.IsRtgs,
&i.Active,
&i.Is24hrs,
&i.CreatedAt,
&i.UpdatedAt,
&i.Currency,
&i.BankLogo,
)
return i, err
}
const DeleteBank = `-- name: DeleteBank :exec
DELETE FROM banks
WHERE id = $1
`
func (q *Queries) DeleteBank(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteBank, id)
return err
}
const GetAllBanks = `-- name: GetAllBanks :many
SELECT id, slug, swift, name, acct_length, country_id, is_mobilemoney, is_active, is_rtgs, active, is_24hrs, created_at, updated_at, currency, bank_logo
FROM banks
WHERE (
country_id = $1
OR $1 IS NULL
)
AND (
is_active = $2
OR $2 IS NULL
)
AND (
name ILIKE '%' || $3 || '%'
OR $3 IS NULL
)
AND (
code ILIKE '%' || $3 || '%'
OR $3 IS NULL
)
ORDER BY name ASC
LIMIT $5 OFFSET $4
`
type GetAllBanksParams struct {
CountryID pgtype.Int4 `json:"country_id"`
IsActive pgtype.Int4 `json:"is_active"`
SearchTerm pgtype.Text `json:"search_term"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllBanks(ctx context.Context, arg GetAllBanksParams) ([]Bank, error) {
rows, err := q.db.Query(ctx, GetAllBanks,
arg.CountryID,
arg.IsActive,
arg.SearchTerm,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Bank
for rows.Next() {
var i Bank
if err := rows.Scan(
&i.ID,
&i.Slug,
&i.Swift,
&i.Name,
&i.AcctLength,
&i.CountryID,
&i.IsMobilemoney,
&i.IsActive,
&i.IsRtgs,
&i.Active,
&i.Is24hrs,
&i.CreatedAt,
&i.UpdatedAt,
&i.Currency,
&i.BankLogo,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBankByID = `-- name: GetBankByID :one
SELECT id, slug, swift, name, acct_length, country_id, is_mobilemoney, is_active, is_rtgs, active, is_24hrs, created_at, updated_at, currency, bank_logo
FROM banks
WHERE id = $1
`
func (q *Queries) GetBankByID(ctx context.Context, id int64) (Bank, error) {
row := q.db.QueryRow(ctx, GetBankByID, id)
var i Bank
err := row.Scan(
&i.ID,
&i.Slug,
&i.Swift,
&i.Name,
&i.AcctLength,
&i.CountryID,
&i.IsMobilemoney,
&i.IsActive,
&i.IsRtgs,
&i.Active,
&i.Is24hrs,
&i.CreatedAt,
&i.UpdatedAt,
&i.Currency,
&i.BankLogo,
)
return i, err
}
const UpdateBank = `-- name: UpdateBank :one
UPDATE banks
SET slug = COALESCE($2, slug),
swift = COALESCE($3, swift),
name = COALESCE($4, name),
acct_length = COALESCE($5, acct_length),
country_id = COALESCE($6, country_id),
is_mobilemoney = COALESCE($7, is_mobilemoney),
is_active = COALESCE($8, is_active),
is_rtgs = COALESCE($9, is_rtgs),
active = COALESCE($10, active),
is_24hrs = COALESCE($11, is_24hrs),
updated_at = CURRENT_TIMESTAMP,
currency = COALESCE($12, currency),
bank_logo = COALESCE($13, bank_logo)
WHERE id = $1
RETURNING id, slug, swift, name, acct_length, country_id, is_mobilemoney, is_active, is_rtgs, active, is_24hrs, created_at, updated_at, currency, bank_logo
`
type UpdateBankParams struct {
ID int64 `json:"id"`
Slug pgtype.Text `json:"slug"`
Swift pgtype.Text `json:"swift"`
Name pgtype.Text `json:"name"`
AcctLength pgtype.Int4 `json:"acct_length"`
CountryID pgtype.Int4 `json:"country_id"`
IsMobilemoney pgtype.Int4 `json:"is_mobilemoney"`
IsActive pgtype.Int4 `json:"is_active"`
IsRtgs pgtype.Int4 `json:"is_rtgs"`
Active pgtype.Int4 `json:"active"`
Is24hrs pgtype.Int4 `json:"is_24hrs"`
Currency pgtype.Text `json:"currency"`
BankLogo pgtype.Text `json:"bank_logo"`
}
func (q *Queries) UpdateBank(ctx context.Context, arg UpdateBankParams) (Bank, error) {
row := q.db.QueryRow(ctx, UpdateBank,
arg.ID,
arg.Slug,
arg.Swift,
arg.Name,
arg.AcctLength,
arg.CountryID,
arg.IsMobilemoney,
arg.IsActive,
arg.IsRtgs,
arg.Active,
arg.Is24hrs,
arg.Currency,
arg.BankLogo,
)
var i Bank
err := row.Scan(
&i.ID,
&i.Slug,
&i.Swift,
&i.Name,
&i.AcctLength,
&i.CountryID,
&i.IsMobilemoney,
&i.IsActive,
&i.IsRtgs,
&i.Active,
&i.Is24hrs,
&i.CreatedAt,
&i.UpdatedAt,
&i.Currency,
&i.BankLogo,
)
return i, err
}

View File

@ -1,197 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: issue_reporting.sql
package dbgen
import (
"context"
)
const CountReportedIssues = `-- name: CountReportedIssues :one
SELECT COUNT(*)
FROM reported_issues
`
func (q *Queries) CountReportedIssues(ctx context.Context) (int64, error) {
row := q.db.QueryRow(ctx, CountReportedIssues)
var count int64
err := row.Scan(&count)
return count, err
}
const CountReportedIssuesByUser = `-- name: CountReportedIssuesByUser :one
SELECT COUNT(*)
FROM reported_issues
WHERE user_id = $1
`
func (q *Queries) CountReportedIssuesByUser(ctx context.Context, userID int64) (int64, error) {
row := q.db.QueryRow(ctx, CountReportedIssuesByUser, userID)
var count int64
err := row.Scan(&count)
return count, err
}
const CreateReportedIssue = `-- name: CreateReportedIssue :one
INSERT INTO reported_issues (
user_id,
user_role,
subject,
description,
issue_type,
metadata
)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, user_id, user_role, subject, description, issue_type, status, metadata, created_at, updated_at
`
type CreateReportedIssueParams struct {
UserID int64 `json:"user_id"`
UserRole string `json:"user_role"`
Subject string `json:"subject"`
Description string `json:"description"`
IssueType string `json:"issue_type"`
Metadata []byte `json:"metadata"`
}
func (q *Queries) CreateReportedIssue(ctx context.Context, arg CreateReportedIssueParams) (ReportedIssue, error) {
row := q.db.QueryRow(ctx, CreateReportedIssue,
arg.UserID,
arg.UserRole,
arg.Subject,
arg.Description,
arg.IssueType,
arg.Metadata,
)
var i ReportedIssue
err := row.Scan(
&i.ID,
&i.UserID,
&i.UserRole,
&i.Subject,
&i.Description,
&i.IssueType,
&i.Status,
&i.Metadata,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const DeleteReportedIssue = `-- name: DeleteReportedIssue :exec
DELETE FROM reported_issues
WHERE id = $1
`
func (q *Queries) DeleteReportedIssue(ctx context.Context, id int64) error {
_, err := q.db.Exec(ctx, DeleteReportedIssue, id)
return err
}
const ListReportedIssues = `-- name: ListReportedIssues :many
SELECT id, user_id, user_role, subject, description, issue_type, status, metadata, created_at, updated_at
FROM reported_issues
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
`
type ListReportedIssuesParams struct {
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
func (q *Queries) ListReportedIssues(ctx context.Context, arg ListReportedIssuesParams) ([]ReportedIssue, error) {
rows, err := q.db.Query(ctx, ListReportedIssues, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReportedIssue
for rows.Next() {
var i ReportedIssue
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.UserRole,
&i.Subject,
&i.Description,
&i.IssueType,
&i.Status,
&i.Metadata,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const ListReportedIssuesByUser = `-- name: ListReportedIssuesByUser :many
SELECT id, user_id, user_role, subject, description, issue_type, status, metadata, created_at, updated_at
FROM reported_issues
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
`
type ListReportedIssuesByUserParams struct {
UserID int64 `json:"user_id"`
Limit int32 `json:"limit"`
Offset int32 `json:"offset"`
}
func (q *Queries) ListReportedIssuesByUser(ctx context.Context, arg ListReportedIssuesByUserParams) ([]ReportedIssue, error) {
rows, err := q.db.Query(ctx, ListReportedIssuesByUser, arg.UserID, arg.Limit, arg.Offset)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReportedIssue
for rows.Next() {
var i ReportedIssue
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.UserRole,
&i.Subject,
&i.Description,
&i.IssueType,
&i.Status,
&i.Metadata,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const UpdateReportedIssueStatus = `-- name: UpdateReportedIssueStatus :exec
UPDATE reported_issues
SET status = $2,
updated_at = NOW()
WHERE id = $1
`
type UpdateReportedIssueStatusParams struct {
ID int64 `json:"id"`
Status string `json:"status"`
}
func (q *Queries) UpdateReportedIssueStatus(ctx context.Context, arg UpdateReportedIssueStatusParams) error {
_, err := q.db.Exec(ctx, UpdateReportedIssueStatus, arg.ID, arg.Status)
return err
}

View File

@ -1,115 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: league_stats.sql
package dbgen
import (
"context"
)
const GetLeagueEventStat = `-- name: GetLeagueEventStat :many
SELECT leagues.id,
leagues.name,
COUNT(*) AS total_events,
COUNT(*) FILTER (
WHERE events.status = 'upcoming'
) AS pending,
COUNT(*) FILTER (
WHERE events.status = 'in_play'
) AS in_play,
COUNT(*) FILTER (
WHERE events.status = 'to_be_fixed'
) AS to_be_fixed,
COUNT(*) FILTER (
WHERE events.status = 'ended'
) AS ended,
COUNT(*) FILTER (
WHERE events.status = 'postponed'
) AS postponed,
COUNT(*) FILTER (
WHERE events.status = 'cancelled'
) AS cancelled,
COUNT(*) FILTER (
WHERE events.status = 'walkover'
) AS walkover,
COUNT(*) FILTER (
WHERE events.status = 'interrupted'
) AS interrupted,
COUNT(*) FILTER (
WHERE events.status = 'abandoned'
) AS abandoned,
COUNT(*) FILTER (
WHERE events.status = 'retired'
) AS retired,
COUNT(*) FILTER (
WHERE events.status = 'suspended'
) AS suspended,
COUNT(*) FILTER (
WHERE events.status = 'decided_by_fa'
) AS decided_by_fa,
COUNT(*) FILTER (
WHERE events.status = 'removed'
) AS removed
FROM leagues
JOIN events ON leagues.id = events.league_id
GROUP BY leagues.id,
leagues.name
`
type GetLeagueEventStatRow struct {
ID int64 `json:"id"`
Name string `json:"name"`
TotalEvents int64 `json:"total_events"`
Pending int64 `json:"pending"`
InPlay int64 `json:"in_play"`
ToBeFixed int64 `json:"to_be_fixed"`
Ended int64 `json:"ended"`
Postponed int64 `json:"postponed"`
Cancelled int64 `json:"cancelled"`
Walkover int64 `json:"walkover"`
Interrupted int64 `json:"interrupted"`
Abandoned int64 `json:"abandoned"`
Retired int64 `json:"retired"`
Suspended int64 `json:"suspended"`
DecidedByFa int64 `json:"decided_by_fa"`
Removed int64 `json:"removed"`
}
func (q *Queries) GetLeagueEventStat(ctx context.Context) ([]GetLeagueEventStatRow, error) {
rows, err := q.db.Query(ctx, GetLeagueEventStat)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetLeagueEventStatRow
for rows.Next() {
var i GetLeagueEventStatRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.TotalEvents,
&i.Pending,
&i.InPlay,
&i.ToBeFixed,
&i.Ended,
&i.Postponed,
&i.Cancelled,
&i.Walkover,
&i.Interrupted,
&i.Abandoned,
&i.Retired,
&i.Suspended,
&i.DecidedByFa,
&i.Removed,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -1,443 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: leagues.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const CheckLeagueSupport = `-- name: CheckLeagueSupport :one
SELECT EXISTS(
SELECT 1
FROM company_league_settings
WHERE league_id = $1
AND company_id = $2
AND is_active = true
)
`
type CheckLeagueSupportParams struct {
LeagueID int64 `json:"league_id"`
CompanyID int64 `json:"company_id"`
}
func (q *Queries) CheckLeagueSupport(ctx context.Context, arg CheckLeagueSupportParams) (bool, error) {
row := q.db.QueryRow(ctx, CheckLeagueSupport, arg.LeagueID, arg.CompanyID)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const GetAllLeagues = `-- name: GetAllLeagues :many
SELECT id, name, img_url, country_code, bet365_id, sport_id, default_is_active, default_is_featured
FROM leagues
WHERE (
country_code = $1
OR $1 IS NULL
)
AND (
sport_id = $2
OR $2 IS NULL
)
AND (
name ILIKE '%' || $3 || '%'
OR $3 IS NULL
)
AND (
default_is_active = $4
OR $4 IS NULL
)
ORDER BY name ASC
LIMIT $6 OFFSET $5
`
type GetAllLeaguesParams struct {
CountryCode pgtype.Text `json:"country_code"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
IsActive pgtype.Bool `json:"is_active"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllLeagues(ctx context.Context, arg GetAllLeaguesParams) ([]League, error) {
rows, err := q.db.Query(ctx, GetAllLeagues,
arg.CountryCode,
arg.SportID,
arg.Query,
arg.IsActive,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []League
for rows.Next() {
var i League
if err := rows.Scan(
&i.ID,
&i.Name,
&i.ImgUrl,
&i.CountryCode,
&i.Bet365ID,
&i.SportID,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetAllLeaguesWithSettings = `-- name: GetAllLeaguesWithSettings :many
SELECT l.id, l.name, l.img_url, l.country_code, l.bet365_id, l.sport_id, l.default_is_active, l.default_is_featured,
cls.company_id,
COALESCE(cls.is_active, l.default_is_active) AS is_active,
COALESCE(cls.is_featured, l.default_is_featured) AS is_featured,
cls.updated_at
FROM leagues l
LEFT JOIN company_league_settings cls ON l.id = cls.league_id
AND company_id = $1
WHERE (
country_code = $2
OR $2 IS NULL
)
AND (
sport_id = $3
OR $3 IS NULL
)
AND (
is_active = $4
OR default_is_active = $4
OR $4 IS NULL
)
AND (
is_featured = $5
OR default_is_featured = $5
OR $5 IS NULL
)
AND (
name ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
ORDER BY is_featured DESC,
name ASC
LIMIT $8 OFFSET $7
`
type GetAllLeaguesWithSettingsParams struct {
CompanyID int64 `json:"company_id"`
CountryCode pgtype.Text `json:"country_code"`
SportID pgtype.Int4 `json:"sport_id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
Query pgtype.Text `json:"query"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
type GetAllLeaguesWithSettingsRow struct {
ID int64 `json:"id"`
Name string `json:"name"`
ImgUrl pgtype.Text `json:"img_url"`
CountryCode pgtype.Text `json:"country_code"`
Bet365ID pgtype.Int4 `json:"bet365_id"`
SportID int32 `json:"sport_id"`
DefaultIsActive bool `json:"default_is_active"`
DefaultIsFeatured bool `json:"default_is_featured"`
CompanyID pgtype.Int8 `json:"company_id"`
IsActive bool `json:"is_active"`
IsFeatured bool `json:"is_featured"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
}
func (q *Queries) GetAllLeaguesWithSettings(ctx context.Context, arg GetAllLeaguesWithSettingsParams) ([]GetAllLeaguesWithSettingsRow, error) {
rows, err := q.db.Query(ctx, GetAllLeaguesWithSettings,
arg.CompanyID,
arg.CountryCode,
arg.SportID,
arg.IsActive,
arg.IsFeatured,
arg.Query,
arg.Offset,
arg.Limit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllLeaguesWithSettingsRow
for rows.Next() {
var i GetAllLeaguesWithSettingsRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.ImgUrl,
&i.CountryCode,
&i.Bet365ID,
&i.SportID,
&i.DefaultIsActive,
&i.DefaultIsFeatured,
&i.CompanyID,
&i.IsActive,
&i.IsFeatured,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetTotalLeagues = `-- name: GetTotalLeagues :one
SELECT COUNT(*)
FROM leagues
WHERE (
country_code = $1
OR $1 IS NULL
)
AND (
sport_id = $2
OR $2 IS NULL
)
AND (
name ILIKE '%' || $3 || '%'
OR $3 IS NULL
)
AND (
default_is_active = $4
OR $4 IS NULL
)
`
type GetTotalLeaguesParams struct {
CountryCode pgtype.Text `json:"country_code"`
SportID pgtype.Int4 `json:"sport_id"`
Query pgtype.Text `json:"query"`
IsActive pgtype.Bool `json:"is_active"`
}
func (q *Queries) GetTotalLeagues(ctx context.Context, arg GetTotalLeaguesParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalLeagues,
arg.CountryCode,
arg.SportID,
arg.Query,
arg.IsActive,
)
var count int64
err := row.Scan(&count)
return count, err
}
const GetTotalLeaguesWithSettings = `-- name: GetTotalLeaguesWithSettings :one
SELECT COUNT(*)
FROM leagues l
LEFT JOIN company_league_settings cls ON l.id = cls.league_id
AND company_id = $1
WHERE (
country_code = $2
OR $2 IS NULL
)
AND (
sport_id = $3
OR $3 IS NULL
)
AND (
is_active = $4
OR default_is_active = $4
OR $4 IS NULL
)
AND (
is_featured = $5
OR default_is_featured = $5
OR $5 IS NULL
)
AND (
name ILIKE '%' || $6 || '%'
OR $6 IS NULL
)
`
type GetTotalLeaguesWithSettingsParams struct {
CompanyID int64 `json:"company_id"`
CountryCode pgtype.Text `json:"country_code"`
SportID pgtype.Int4 `json:"sport_id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
Query pgtype.Text `json:"query"`
}
func (q *Queries) GetTotalLeaguesWithSettings(ctx context.Context, arg GetTotalLeaguesWithSettingsParams) (int64, error) {
row := q.db.QueryRow(ctx, GetTotalLeaguesWithSettings,
arg.CompanyID,
arg.CountryCode,
arg.SportID,
arg.IsActive,
arg.IsFeatured,
arg.Query,
)
var count int64
err := row.Scan(&count)
return count, err
}
const InsertLeague = `-- name: InsertLeague :exec
INSERT INTO leagues (
id,
name,
country_code,
bet365_id,
sport_id,
default_is_active,
default_is_featured
)
VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO
UPDATE
SET name = EXCLUDED.name,
country_code = EXCLUDED.country_code,
bet365_id = EXCLUDED.bet365_id,
sport_id = EXCLUDED.sport_id
`
type InsertLeagueParams struct {
ID int64 `json:"id"`
Name string `json:"name"`
CountryCode pgtype.Text `json:"country_code"`
Bet365ID pgtype.Int4 `json:"bet365_id"`
SportID int32 `json:"sport_id"`
DefaultIsActive bool `json:"default_is_active"`
DefaultIsFeatured bool `json:"default_is_featured"`
}
func (q *Queries) InsertLeague(ctx context.Context, arg InsertLeagueParams) error {
_, err := q.db.Exec(ctx, InsertLeague,
arg.ID,
arg.Name,
arg.CountryCode,
arg.Bet365ID,
arg.SportID,
arg.DefaultIsActive,
arg.DefaultIsFeatured,
)
return err
}
const SaveLeagueSettings = `-- name: SaveLeagueSettings :exec
INSERT INTO company_league_settings (
company_id,
league_id,
is_active,
is_featured
)
VALUES ($1, $2, $3, $4) ON CONFLICT(company_id, league_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
is_featured = EXCLUDED.is_featured
`
type SaveLeagueSettingsParams struct {
CompanyID int64 `json:"company_id"`
LeagueID int64 `json:"league_id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
}
func (q *Queries) SaveLeagueSettings(ctx context.Context, arg SaveLeagueSettingsParams) error {
_, err := q.db.Exec(ctx, SaveLeagueSettings,
arg.CompanyID,
arg.LeagueID,
arg.IsActive,
arg.IsFeatured,
)
return err
}
const UpdateCompanyLeagueSettings = `-- name: UpdateCompanyLeagueSettings :exec
UPDATE company_league_settings
SET is_active = COALESCE($3, is_active),
is_featured = COALESCE(
$4,
is_featured
)
WHERE league_id = $1
AND company_id = $2
`
type UpdateCompanyLeagueSettingsParams struct {
LeagueID int64 `json:"league_id"`
CompanyID int64 `json:"company_id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
}
func (q *Queries) UpdateCompanyLeagueSettings(ctx context.Context, arg UpdateCompanyLeagueSettingsParams) error {
_, err := q.db.Exec(ctx, UpdateCompanyLeagueSettings,
arg.LeagueID,
arg.CompanyID,
arg.IsActive,
arg.IsFeatured,
)
return err
}
const UpdateGlobalLeagueSettings = `-- name: UpdateGlobalLeagueSettings :exec
UPDATE leagues
SET default_is_active = COALESCE($2, default_is_active),
default_is_featured = COALESCE($3, default_is_featured)
WHERE id = $1
`
type UpdateGlobalLeagueSettingsParams struct {
ID int64 `json:"id"`
IsActive pgtype.Bool `json:"is_active"`
IsFeatured pgtype.Bool `json:"is_featured"`
}
func (q *Queries) UpdateGlobalLeagueSettings(ctx context.Context, arg UpdateGlobalLeagueSettingsParams) error {
_, err := q.db.Exec(ctx, UpdateGlobalLeagueSettings, arg.ID, arg.IsActive, arg.IsFeatured)
return err
}
const UpdateLeague = `-- name: UpdateLeague :exec
UPDATE leagues
SET name = COALESCE($2, name),
country_code = COALESCE($3, country_code),
bet365_id = COALESCE($4, bet365_id),
sport_id = COALESCE($5, sport_id)
WHERE id = $1
`
type UpdateLeagueParams struct {
ID int64 `json:"id"`
Name pgtype.Text `json:"name"`
CountryCode pgtype.Text `json:"country_code"`
Bet365ID pgtype.Int4 `json:"bet365_id"`
SportID pgtype.Int4 `json:"sport_id"`
}
func (q *Queries) UpdateLeague(ctx context.Context, arg UpdateLeagueParams) error {
_, err := q.db.Exec(ctx, UpdateLeague,
arg.ID,
arg.Name,
arg.CountryCode,
arg.Bet365ID,
arg.SportID,
)
return err
}

View File

@ -1,41 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: location.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const GetAllBranchLocations = `-- name: GetAllBranchLocations :many
SELECT key, value
FROM branch_locations
WHERE (
value ILIKE '%' || $1 || '%'
OR $1 IS NULL
)
`
func (q *Queries) GetAllBranchLocations(ctx context.Context, query pgtype.Text) ([]BranchLocation, error) {
rows, err := q.db.Query(ctx, GetAllBranchLocations, query)
if err != nil {
return nil, err
}
defer rows.Close()
var items []BranchLocation
for rows.Next() {
var i BranchLocation
if err := rows.Scan(&i.Key, &i.Value); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

View File

@ -1,281 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: market_settings.sql
package dbgen
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const DeleteAllMarketSettingsForCompany = `-- name: DeleteAllMarketSettingsForCompany :exec
DELETE FROM company_odd_market_settings
WHERE company_id = $1
`
func (q *Queries) DeleteAllMarketSettingsForCompany(ctx context.Context, companyID int64) error {
_, err := q.db.Exec(ctx, DeleteAllMarketSettingsForCompany, companyID)
return err
}
const DeleteCompanyMarketSettings = `-- name: DeleteCompanyMarketSettings :exec
DELETE FROM company_odd_market_settings
WHERE market_id = $1
AND company_id = $2
`
type DeleteCompanyMarketSettingsParams struct {
MarketID int64 `json:"market_id"`
CompanyID int64 `json:"company_id"`
}
func (q *Queries) DeleteCompanyMarketSettings(ctx context.Context, arg DeleteCompanyMarketSettingsParams) error {
_, err := q.db.Exec(ctx, DeleteCompanyMarketSettings, arg.MarketID, arg.CompanyID)
return err
}
const GetAllCompanyMarketSettings = `-- name: GetAllCompanyMarketSettings :many
SELECT market_id, market_name, company_id, is_active, updated_at
FROM company_odd_market_settings
WHERE (
company_id = $1
OR $1 IS NULL
)
LIMIT $3 OFFSET $2
`
type GetAllCompanyMarketSettingsParams struct {
CompanyID pgtype.Int8 `json:"company_id"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllCompanyMarketSettings(ctx context.Context, arg GetAllCompanyMarketSettingsParams) ([]CompanyOddMarketSetting, error) {
rows, err := q.db.Query(ctx, GetAllCompanyMarketSettings, arg.CompanyID, arg.Offset, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CompanyOddMarketSetting
for rows.Next() {
var i CompanyOddMarketSetting
if err := rows.Scan(
&i.MarketID,
&i.MarketName,
&i.CompanyID,
&i.IsActive,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetAllGlobalMarketSettings = `-- name: GetAllGlobalMarketSettings :many
SELECT market_id, market_name, is_active, updated_at
FROM global_odd_market_settings
LIMIT $2 OFFSET $1
`
type GetAllGlobalMarketSettingsParams struct {
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
func (q *Queries) GetAllGlobalMarketSettings(ctx context.Context, arg GetAllGlobalMarketSettingsParams) ([]GlobalOddMarketSetting, error) {
rows, err := q.db.Query(ctx, GetAllGlobalMarketSettings, arg.Offset, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GlobalOddMarketSetting
for rows.Next() {
var i GlobalOddMarketSetting
if err := rows.Scan(
&i.MarketID,
&i.MarketName,
&i.IsActive,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetAllOverrideMarketSettings = `-- name: GetAllOverrideMarketSettings :many
SELECT gdm.market_id,
gdm.market_name,
COALESCE(cdm.is_active, gdm.is_active) AS is_active,
COALESCE(cdm.updated_at, gdm.updated_at) AS updated_at
FROM global_odd_market_settings gdm
LEFT JOIN company_odd_market_settings cdm ON cdm.market_id = gdm.market_id
AND company_id = $1
LIMIT $3 OFFSET $2
`
type GetAllOverrideMarketSettingsParams struct {
CompanyID int64 `json:"company_id"`
Offset pgtype.Int4 `json:"offset"`
Limit pgtype.Int4 `json:"limit"`
}
type GetAllOverrideMarketSettingsRow struct {
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
IsActive bool `json:"is_active"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
}
func (q *Queries) GetAllOverrideMarketSettings(ctx context.Context, arg GetAllOverrideMarketSettingsParams) ([]GetAllOverrideMarketSettingsRow, error) {
rows, err := q.db.Query(ctx, GetAllOverrideMarketSettings, arg.CompanyID, arg.Offset, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllOverrideMarketSettingsRow
for rows.Next() {
var i GetAllOverrideMarketSettingsRow
if err := rows.Scan(
&i.MarketID,
&i.MarketName,
&i.IsActive,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetCompanyMarketSettingsByID = `-- name: GetCompanyMarketSettingsByID :one
SELECT market_id, market_name, company_id, is_active, updated_at
FROM company_odd_market_settings
WHERE market_id = $1
`
func (q *Queries) GetCompanyMarketSettingsByID(ctx context.Context, marketID int64) (CompanyOddMarketSetting, error) {
row := q.db.QueryRow(ctx, GetCompanyMarketSettingsByID, marketID)
var i CompanyOddMarketSetting
err := row.Scan(
&i.MarketID,
&i.MarketName,
&i.CompanyID,
&i.IsActive,
&i.UpdatedAt,
)
return i, err
}
const GetGlobalMarketSettingsByID = `-- name: GetGlobalMarketSettingsByID :one
SELECT market_id, market_name, is_active, updated_at
FROM global_odd_market_settings
WHERE market_id = $1
`
func (q *Queries) GetGlobalMarketSettingsByID(ctx context.Context, marketID int64) (GlobalOddMarketSetting, error) {
row := q.db.QueryRow(ctx, GetGlobalMarketSettingsByID, marketID)
var i GlobalOddMarketSetting
err := row.Scan(
&i.MarketID,
&i.MarketName,
&i.IsActive,
&i.UpdatedAt,
)
return i, err
}
const GetOverrideMarketSettingByID = `-- name: GetOverrideMarketSettingByID :one
SELECT gdm.market_id,
gdm.market_name,
COALESCE(cdm.is_active, gdm.is_active) AS is_active,
COALESCE(cdm.updated_at, gdm.updated_at) AS updated_at
FROM global_odd_market_settings gdm
LEFT JOIN company_odd_market_settings cdm ON cdm.market_id = gdm.market_id
AND company_id = $1
WHERE gdm.market_id = $2
`
type GetOverrideMarketSettingByIDParams struct {
CompanyID int64 `json:"company_id"`
MarketID int64 `json:"market_id"`
}
type GetOverrideMarketSettingByIDRow struct {
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
IsActive bool `json:"is_active"`
UpdatedAt pgtype.Timestamp `json:"updated_at"`
}
func (q *Queries) GetOverrideMarketSettingByID(ctx context.Context, arg GetOverrideMarketSettingByIDParams) (GetOverrideMarketSettingByIDRow, error) {
row := q.db.QueryRow(ctx, GetOverrideMarketSettingByID, arg.CompanyID, arg.MarketID)
var i GetOverrideMarketSettingByIDRow
err := row.Scan(
&i.MarketID,
&i.MarketName,
&i.IsActive,
&i.UpdatedAt,
)
return i, err
}
const InsertCompanyMarketSettings = `-- name: InsertCompanyMarketSettings :exec
INSERT INTO company_odd_market_settings (company_id, market_id, market_name, is_active)
VALUES ($1, $2, $3, $4) ON CONFLICT (company_id, market_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
updated_at = CURRENT_TIMESTAMP
`
type InsertCompanyMarketSettingsParams struct {
CompanyID int64 `json:"company_id"`
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
IsActive pgtype.Bool `json:"is_active"`
}
func (q *Queries) InsertCompanyMarketSettings(ctx context.Context, arg InsertCompanyMarketSettingsParams) error {
_, err := q.db.Exec(ctx, InsertCompanyMarketSettings,
arg.CompanyID,
arg.MarketID,
arg.MarketName,
arg.IsActive,
)
return err
}
const InsertGlobalMarketSettings = `-- name: InsertGlobalMarketSettings :exec
INSERT INTO global_odd_market_settings (market_id, market_name, is_active)
VALUES ($1, $2, $3) ON CONFLICT (market_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
updated_at = CURRENT_TIMESTAMP
`
type InsertGlobalMarketSettingsParams struct {
MarketID int64 `json:"market_id"`
MarketName string `json:"market_name"`
IsActive bool `json:"is_active"`
}
func (q *Queries) InsertGlobalMarketSettings(ctx context.Context, arg InsertGlobalMarketSettingsParams) error {
_, err := q.db.Exec(ctx, InsertGlobalMarketSettings, arg.MarketID, arg.MarketName, arg.IsActive)
return err
}

File diff suppressed because it is too large Load Diff

View File

@ -1,131 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.29.0
// source: monitor.sql
package dbgen
import (
"context"
)
const CountThresholdNotifications = `-- name: CountThresholdNotifications :one
SELECT COUNT(*)
FROM wallet_threshold_notifications
WHERE company_id = $1 AND threshold = $2
`
type CountThresholdNotificationsParams struct {
CompanyID int64 `json:"company_id"`
Threshold float64 `json:"threshold"`
}
func (q *Queries) CountThresholdNotifications(ctx context.Context, arg CountThresholdNotificationsParams) (int64, error) {
row := q.db.QueryRow(ctx, CountThresholdNotifications, arg.CompanyID, arg.Threshold)
var count int64
err := row.Scan(&count)
return count, err
}
const CreateThresholdNotification = `-- name: CreateThresholdNotification :exec
INSERT INTO wallet_threshold_notifications (company_id, threshold)
VALUES ($1, $2)
`
type CreateThresholdNotificationParams struct {
CompanyID int64 `json:"company_id"`
Threshold float64 `json:"threshold"`
}
func (q *Queries) CreateThresholdNotification(ctx context.Context, arg CreateThresholdNotificationParams) error {
_, err := q.db.Exec(ctx, CreateThresholdNotification, arg.CompanyID, arg.Threshold)
return err
}
const GetAllCompaniesBranch = `-- name: GetAllCompaniesBranch :many
SELECT id, name, wallet_id, admin_id
FROM companies
`
type GetAllCompaniesBranchRow struct {
ID int64 `json:"id"`
Name string `json:"name"`
WalletID int64 `json:"wallet_id"`
AdminID int64 `json:"admin_id"`
}
func (q *Queries) GetAllCompaniesBranch(ctx context.Context) ([]GetAllCompaniesBranchRow, error) {
rows, err := q.db.Query(ctx, GetAllCompaniesBranch)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAllCompaniesBranchRow
for rows.Next() {
var i GetAllCompaniesBranchRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.WalletID,
&i.AdminID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const GetBranchesByCompanyID = `-- name: GetBranchesByCompanyID :many
SELECT
id,
name,
location,
wallet_id,
branch_manager_id,
company_id,
is_self_owned
FROM branches
WHERE company_id = $1
`
type GetBranchesByCompanyIDRow struct {
ID int64 `json:"id"`
Name string `json:"name"`
Location string `json:"location"`
WalletID int64 `json:"wallet_id"`
BranchManagerID int64 `json:"branch_manager_id"`
CompanyID int64 `json:"company_id"`
IsSelfOwned bool `json:"is_self_owned"`
}
func (q *Queries) GetBranchesByCompanyID(ctx context.Context, companyID int64) ([]GetBranchesByCompanyIDRow, error) {
rows, err := q.db.Query(ctx, GetBranchesByCompanyID, companyID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetBranchesByCompanyIDRow
for rows.Next() {
var i GetBranchesByCompanyIDRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Location,
&i.WalletID,
&i.BranchManagerID,
&i.CompanyID,
&i.IsSelfOwned,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}

Some files were not shown because too many files have changed in this diff Show More