implemented

This commit is contained in:
병준 박 2022-08-16 17:00:26 +00:00
parent ee705fe250
commit 88fc45b7c8
74 changed files with 1822 additions and 192 deletions

2
.vscode/launch.json vendored
View File

@ -20,6 +20,7 @@
} }
}, },
"env": { "env": {
"URL_DATABASE": "postgresql://beteran:qwer5795QWER@192.168.50.200:25432/beteran",
"URL_BROKER": "nats://192.168.50.200:4222", "URL_BROKER": "nats://192.168.50.200:4222",
"QUEUE_BROKER": "bet.beteran", "QUEUE_BROKER": "bet.beteran",
"K_SECRET": "c23d770b873b2ce95747abc57052beb0", "K_SECRET": "c23d770b873b2ce95747abc57052beb0",
@ -45,6 +46,7 @@
} }
}, },
"env": { "env": {
"URL_DATABASE": "postgresql://beteran:qwer5795QWER@192.168.50.200:25432/beteran",
"URL_BROKER": "nats://192.168.50.200:4222", "URL_BROKER": "nats://192.168.50.200:4222",
"QUEUE_BROKER": "bet.beteran", "QUEUE_BROKER": "bet.beteran",
"K_SECRET": "c23d770b873b2ce95747abc57052beb0", "K_SECRET": "c23d770b873b2ce95747abc57052beb0",

View File

@ -11,6 +11,10 @@ path = "./src/main.rs"
[dependencies] [dependencies]
chrono = { version = "0" }
diesel = { version = "1", features = ["chrono", "r2d2", "uuidv07", "postgres"] }
diesel_migrations = { version = "1" }
diesel-derive-enum = { version = "1", features = ["postgres"] }
futures = { version = "0", default-features = false, features = [ futures = { version = "0", default-features = false, features = [
"async-await", "async-await",
] } ] }
@ -21,9 +25,11 @@ reqwest = { version = "0", features = ["json"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" } serde_json = { version = "1" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tokio-cron-scheduler = { version = "*" }
uuid = { version = "0", features = ["serde", "v4", "v5"] }
beteran-protobuf-rust = { git = "https://gitlab.loafle.net/bet/beteran-protobuf-rust.git", tag = "v0.1.22-snapshot" } beteran-protobuf-rust = { git = "https://gitlab.loafle.net/bet/beteran-protobuf-rust.git", tag = "v0.1.61-snapshot" }
beteran-common-rust = { git = "https://gitlab.loafle.net/bet/beteran-common-rust.git", tag = "v0.1.2-snapshot" } beteran-common-rust = { git = "https://gitlab.loafle.net/bet/beteran-common-rust.git", tag = "v0.1.45-snapshot" }
[build-dependencies] [build-dependencies]

View File

@ -0,0 +1,3 @@
DROP INDEX idx_api_kgon_members_member_id;
DROP TRIGGER tg_api_kgon_members_updated_at;
DROP TABLE api_kgon_members;

View File

@ -0,0 +1,27 @@
CREATE TABLE IF NOT EXISTS api_kgon_members (
id BIGINT NOT NULL,
balance BIGINT NOT NULL DEFAULT 0,
balance_bota BIGINT NOT NULL DEFAULT 0,
balance_sum BIGINT NOT NULL DEFAULT 0,
companies BIGINT NOT NULL DEFAULT 0,
oriental_play BOOLEAN NOT NULL DEFAULT FALSE,
member_id UUID NOT NULL,
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
updated_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
PRIMARY KEY (id),
CONSTRAINT fk_api_kgon_members_member_id
FOREIGN KEY(member_id)
REFERENCES members(id)
);
CREATE INDEX idx_api_kgon_members_member_id ON api_kgon_members (member_id);
-- trigger (updated_at)
CREATE TRIGGER tg_api_kgon_members_updated_at
BEFORE UPDATE
ON api_kgon_members
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at_column();

View File

@ -0,0 +1 @@
DROP TABLE api_kgon_synchronization_members;

View File

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS api_kgon_synchronization_members (
id BIGSERIAL PRIMARY KEY;
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000)
);

View File

@ -0,0 +1,2 @@
DROP TRIGGER tg_api_kgon_balances_updated_at;
DROP TABLE api_kgon_balances;

View File

@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS api_kgon_balances (
id SERIAL PRIMARY KEY;
balance BIGINT NOT NULL DEFAULT 0,
balance_bota BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
updated_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000)
);
-- trigger (updated_at)
CREATE TRIGGER tg_api_kgon_balances_updated_at
BEFORE UPDATE
ON api_kgon_balances
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at_column();

View File

@ -0,0 +1,2 @@
DROP TRIGGER tg_api_kgon_balances_updated_at;
DROP TABLE api_kgon_balances;

View File

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS api_kgon_synchronization_balances (
id BIGSERIAL PRIMARY KEY;
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000)
);

View File

@ -0,0 +1,25 @@
CREATE TABLE IF NOT EXISTS api_kgon_vendors (
id BIGINT NOT NULL,
company_id BIGINT NOT NULL,
vendor_id BIGINT NOT NULL,
max_bet_casino BIGINT NOT NULL,
max_bet_slot BIGINT NOT NULL,
is_enable BOOLEAN NOT NULL,
bet_count BIGINT NOT NULL,
key TEXT NOT NULL,
name TEXT NOT NULL,
category TEXT NOT NULL,
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
updated_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
PRIMARY KEY (id),
CONSTRAINT fk_api_kgon_vendors_parent_id
FOREIGN KEY(parent_id)
REFERENCES roles(id)
);
-- trigger (updated_at)
CREATE TRIGGER tg_api_kgon_vendors_updated_at
BEFORE UPDATE
ON api_kgon_vendors
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at_column();

View File

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS api_kgon_synchronization_vendors (
id BIGSERIAL PRIMARY KEY;
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000)
);

View File

@ -0,0 +1,23 @@
CREATE TABLE IF NOT EXISTS api_kgon_games (
id BIGINT NOT NULL,
vendor_id BIGINT NOT NULL,
key TEXT NOT NULL,
names TEXT NOT NULL,
platform TEXT NOT NULL,
category TEXT NOT NULL,
game_type TEXT NOT NULL,
image TEXT,
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
updated_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000),
PRIMARY KEY (id),
CONSTRAINT fk_api_kgon_games_vendor_id
FOREIGN KEY(vendor_id)
REFERENCES api_kgon_vendors(id)
);
-- trigger (updated_at)
CREATE TRIGGER tg_api_kgon_games_updated_at
BEFORE UPDATE
ON api_kgon_games
FOR EACH ROW
EXECUTE PROCEDURE update_updated_at_column();

View File

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS api_kgon_synchronization_games (
id BIGSERIAL PRIMARY KEY;
created_at BIGINT NOT NULL DEFAULT (extract(epoch from now()) * 1000)
);

View File

@ -2,22 +2,22 @@ use super::models;
use std::{collections::HashMap, time::Duration}; use std::{collections::HashMap, time::Duration};
/// ///
pub struct Repository { pub struct Api {
client: reqwest::Client, client: reqwest::Client,
k_secret: String, k_secret: String,
k_username: String, k_username: String,
} }
impl std::fmt::Debug for Repository { impl std::fmt::Debug for Api {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api.kgon.identity").finish() f.debug_struct("Api of api.kgon.identity").finish()
} }
} }
impl Repository { impl Api {
/// ///
pub fn new(k_secret: &str, k_username: &str) -> Repository { pub fn new(k_secret: &str, k_username: &str) -> Api {
Repository { Api {
client: reqwest::Client::new(), client: reqwest::Client::new(),
k_secret: k_secret.to_string(), k_secret: k_secret.to_string(),
k_username: k_username.to_string(), k_username: k_username.to_string(),

7
src/api/betting/mod.rs Normal file
View File

@ -0,0 +1,7 @@
//!
//!
///
pub mod api;
///
pub mod models;

150
src/api/game/api.rs Normal file
View File

@ -0,0 +1,150 @@
use super::models;
use std::{collections::HashMap, time::Duration};
///
pub struct Api {
client: reqwest::Client,
k_secret: String,
k_username: String,
}
impl std::fmt::Debug for Api {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Api of api.kgon.identity").finish()
}
}
impl Api {
///
pub fn new(k_secret: &str, k_username: &str) -> Api {
Api {
client: reqwest::Client::new(),
k_secret: k_secret.to_string(),
k_username: k_username.to_string(),
}
}
///
pub async fn find_vendors(
&self,
data: models::FindVendorsRequest,
) -> Result<models::FindVendorsResponse, models::Error> {
let res = match self
.client
.post("https://dev-mw.kgonapi.com/vendors")
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header("k-secret", self.k_secret.as_str())
.header("k-username", self.k_username.as_str())
.send()
.await
{
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
}
};
match res.status() {
reqwest::StatusCode::OK => match res.json::<models::FindVendorsResponse>().await {
Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }),
},
_ => Err(models::Error { code: 0, msg: None }),
}
}
///
pub async fn find_games(
&self,
data: models::FindGamesRequest,
) -> Result<models::FindGamesResponse, models::Error> {
let mut params = HashMap::new();
params.insert("vendorKey", data.vendor_key);
let res = match self
.client
.post("https://dev-mw.kgonapi.com/games")
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header("k-secret", self.k_secret.as_str())
.header("k-username", self.k_username.as_str())
.form(&params)
.send()
.await
{
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
}
};
match res.status() {
reqwest::StatusCode::OK => match res.json::<models::FindGamesResponse>().await {
Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }),
},
_ => Err(models::Error { code: 0, msg: None }),
}
}
///
pub async fn play(
&self,
data: models::PlayRequest,
) -> Result<models::PlayResponse, models::Error> {
let mut params = HashMap::new();
params.insert("vendorKey", data.vendor_key);
params.insert("gameKey", data.game_key);
params.insert("username", data.username);
params.insert("nickname", data.nickname);
params.insert("siteUsername", data.site_username);
if let Some(group_key) = data.group_key {
params.insert("groupKey", group_key);
}
params.insert("amount", data.amount.to_string());
if let Some(request_key) = data.request_key {
params.insert("requestKey", request_key);
}
let res = match self
.client
.post("https://dev-mw.kgonapi.com/play")
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header("k-secret", self.k_secret.as_str())
.header("k-username", self.k_username.as_str())
.form(&params)
.timeout(Duration::from_secs(10))
.send()
.await
{
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
}
};
match res.status() {
reqwest::StatusCode::OK => match res.json::<models::PlayResponse>().await {
Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }),
},
_ => Err(models::Error { code: 0, msg: None }),
}
}
}

7
src/api/game/mod.rs Normal file
View File

@ -0,0 +1,7 @@
//!
//!
///
pub mod api;
///
pub mod models;

47
src/api/game/models.rs Normal file
View File

@ -0,0 +1,47 @@
use serde::{Deserialize, Serialize};
pub struct Error {
pub code: i64,
pub msg: Option<String>,
}
pub struct FindVendorsRequest {}
#[derive(Serialize, Deserialize, Debug)]
pub struct FindVendorsResponse {
pub code: i64,
pub msg: Option<String>,
pub vendors: Vec<String>,
}
pub struct FindGamesRequest {
pub vendor_key: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct FindGamesResponse {
pub code: i64,
pub msg: Option<String>,
pub games: Vec<String>,
}
pub struct PlayRequest {
pub vendor_key: String,
pub game_key: String,
pub username: String,
pub nickname: String,
pub site_username: String,
pub group_key: Option<String>,
pub amount: i64,
pub request_key: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PlayResponse {
pub code: i64,
pub msg: Option<String>,
#[serde(rename = "userId")]
pub user_id: String,
pub url: String,
pub balance: i64,
}

View File

@ -2,33 +2,35 @@ use super::models;
use std::collections::HashMap; use std::collections::HashMap;
/// ///
pub struct Repository { pub struct Api {
client: reqwest::Client, client: reqwest::Client,
url: String,
k_secret: String, k_secret: String,
k_username: String, k_username: String,
} }
impl std::fmt::Debug for Repository { impl std::fmt::Debug for Api {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api.kgon.identity").finish() f.debug_struct("Api of api.kgon.identity").finish()
} }
} }
impl Repository { impl Api {
/// ///
pub fn new(k_secret: &str, k_username: &str) -> Repository { pub fn new(url: &str, k_secret: &str, k_username: &str) -> Api {
Repository { Api {
client: reqwest::Client::new(), client: reqwest::Client::new(),
url: url.to_string(),
k_secret: k_secret.to_string(), k_secret: k_secret.to_string(),
k_username: k_username.to_string(), k_username: k_username.to_string(),
} }
} }
/// ///
pub async fn find_members( pub async fn list_members(
&self, &self,
data: models::FindMembersRequest, data: models::ListMembersRequest,
) -> Result<models::FindMembersResponse, models::Error> { ) -> Result<models::ListMembersResponse, models::Error> {
let mut params = HashMap::new(); let mut params = HashMap::new();
if let Some(group_key) = data.group_key { if let Some(group_key) = data.group_key {
@ -37,7 +39,7 @@ impl Repository {
let res = match self let res = match self
.client .client
.post("https://dev-mw.kgonapi.com/users") .post(format!("{}/users", self.url))
.header(reqwest::header::ACCEPT, "application/json") .header(reqwest::header::ACCEPT, "application/json")
.header( .header(
reqwest::header::CONTENT_TYPE, reqwest::header::CONTENT_TYPE,
@ -56,7 +58,7 @@ impl Repository {
}; };
match res.status() { match res.status() {
reqwest::StatusCode::OK => match res.json::<models::FindMembersResponse>().await { reqwest::StatusCode::OK => match res.json::<models::ListMembersResponse>().await {
Ok(r) => Ok(r), Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }), Err(e) => Err(models::Error { code: 0, msg: None }),
}, },
@ -116,7 +118,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn find_members() { async fn find_members() {
let repository = Repository::new("c23d770b873b2ce95747abc57052beb0", "Turbo77"); let repository = Api::new("c23d770b873b2ce95747abc57052beb0", "Turbo77");
let r = repository let r = repository
.find_members(models::FindMembersRequest { group_key: None }) .find_members(models::FindMembersRequest { group_key: None })
@ -128,7 +130,7 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn save_member() { async fn save_member() {
let repository = Repository::new("c23d770b873b2ce95747abc57052beb0", "Turbo77"); let repository = Api::new("c23d770b873b2ce95747abc57052beb0", "Turbo77");
let r = repository let r = repository
.save_member(models::SaveMemberRequest { .save_member(models::SaveMemberRequest {

7
src/api/member/mod.rs Normal file
View File

@ -0,0 +1,7 @@
//!
//!
///
pub mod api;
///
pub mod models;

View File

@ -7,7 +7,7 @@ pub struct Error {
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct FindMembersRequest { pub struct ListMembersRequest {
pub group_key: Option<String>, pub group_key: Option<String>,
} }
@ -24,7 +24,7 @@ pub struct FindMember {
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct FindMembersResponse { pub struct ListMembersResponse {
pub code: i64, pub code: i64,
pub msg: Option<String>, pub msg: Option<String>,
pub users: Vec<FindMember>, pub users: Vec<FindMember>,

View File

@ -2,22 +2,22 @@ use super::models;
use std::collections::HashMap; use std::collections::HashMap;
/// ///
pub struct Repository { pub struct Api {
client: reqwest::Client, client: reqwest::Client,
k_secret: String, k_secret: String,
k_username: String, k_username: String,
} }
impl std::fmt::Debug for Repository { impl std::fmt::Debug for Api {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api.kgon.identity").finish() f.debug_struct("Api of api.kgon.member_account").finish()
} }
} }
impl Repository { impl Api {
/// ///
pub fn new(k_secret: &str, k_username: &str) -> Repository { pub fn new(k_secret: &str, k_username: &str) -> Api {
Repository { Api {
client: reqwest::Client::new(), client: reqwest::Client::new(),
k_secret: k_secret.to_string(), k_secret: k_secret.to_string(),
k_username: k_username.to_string(), k_username: k_username.to_string(),

View File

@ -0,0 +1,7 @@
//!
//!
///
pub mod api;
///
pub mod models;

4
src/api/mod.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod betting;
pub mod game;
pub mod member;
pub mod member_account;

View File

View File

View File

View File

View File

@ -0,0 +1,4 @@
pub mod betting;
pub mod game;
pub mod member;
pub mod member_account;

View File

@ -1,14 +1,31 @@
//! //!
//! //!
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use std::env; use std::env;
mod api;
mod compositions; mod compositions;
mod repositories; mod repositories;
mod schedulers;
mod services; mod services;
diesel_migrations::embed_migrations!();
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url_db = match env::var_os("URL_DATABASE") {
Some(v) => v.into_string().unwrap(),
None => "".to_string(),
};
let url_server_broker = match env::var_os("URL_BROKER") { let url_server_broker = match env::var_os("URL_BROKER") {
Some(v) => v.into_string().unwrap(), Some(v) => v.into_string().unwrap(),
None => "".to_string(), None => "".to_string(),
@ -27,19 +44,63 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
None => "".to_string(), None => "".to_string(),
}; };
let mut sched = tokio_cron_scheduler::JobScheduler::new().await?;
let manager = ConnectionManager::<PgConnection>::new(url_db);
let pool = Pool::builder()
.max_size(4)
.test_on_check_out(true)
.build(manager)?;
let conn = pool.get()?;
embedded_migrations::run(&conn)?;
let server_broker_opts = nats::asynk::Options::new(); let server_broker_opts = nats::asynk::Options::new();
let connection_server_broker = server_broker_opts.connect(url_server_broker).await?; let connection_server_broker = server_broker_opts.connect(url_server_broker).await?;
let identity_service = services::identity::service::Service::new( let member_service = services::member::service::Service::new(
connection_server_broker.clone(),
queue_server_broker.clone(),
k_secret.clone(),
k_username.clone(),
);
let member_account_service = services::member_account::service::Service::new(
connection_server_broker.clone(),
queue_server_broker.clone(),
k_secret.clone(),
k_username.clone(),
);
let game_service = services::game::service::Service::new(
connection_server_broker.clone(),
queue_server_broker.clone(),
k_secret.clone(),
k_username.clone(),
);
let betting_service = services::betting::service::Service::new(
connection_server_broker.clone(), connection_server_broker.clone(),
queue_server_broker.clone(), queue_server_broker.clone(),
k_secret.clone(), k_secret.clone(),
k_username.clone(), k_username.clone(),
); );
let vendor_scheduler = schedulers::vendor::scheduler::Scheduler::new(pool.clone(), sched.clone());
vendor_scheduler.queue().await;
let start = sched.start().await;
if start.is_err() {
panic!("Error starting scheduler");
}
println!("Server service [beteran-api-kgon-server-service] is started"); println!("Server service [beteran-api-kgon-server-service] is started");
futures::try_join!(identity_service.subscribe(),)?; futures::try_join!(
member_service.subscribe(),
member_account_service.subscribe(),
game_service.subscribe(),
betting_service.subscribe(),
)?;
sched.shutdown().await?;
Ok(()) Ok(())
} }

View File

@ -5,3 +5,5 @@
pub mod models; pub mod models;
/// ///
pub mod repository; pub mod repository;
///
pub mod schema;

View File

@ -0,0 +1,37 @@
use super::schema::api_kgon_balances;
///
#[derive(Eq, Hash, Identifiable, Queryable, PartialEq, Debug, Clone)]
#[table_name = "api_kgon_balances"]
pub struct Balance {
///
pub id: i32,
///
pub balance: i64,
///
pub balance_bota: i64,
///
pub created_at: i64,
///
pub updated_at: i64,
}
///
#[derive(Insertable, Debug, Clone)]
#[table_name = "api_kgon_balances"]
pub struct NewBalance {
///
pub balance: i64,
///
pub balance_bota: i64,
}
///
#[derive(AsChangeset, Debug, Clone)]
#[table_name = "api_kgon_balances"]
pub struct ModifyBalance {
///
pub balance: i64,
///
pub balance_bota: i64,
}

View File

@ -0,0 +1,75 @@
//!
//!
use super::{models, schema::api_kgon_balances};
use diesel::prelude::*;
use diesel::result::Error;
///
pub struct Repository {}
impl std::fmt::Debug for Repository {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api_kgon_balances").finish()
}
}
impl Default for Repository {
fn default() -> Self {
Self::new()
}
}
impl Repository {
///
pub fn new() -> Repository {
Repository {}
}
///
pub fn insert(
&self,
conn: &diesel::PgConnection,
new_member: &models::NewBalance,
) -> Result<models::Balance, Error> {
let inserted = diesel::insert_into(api_kgon_balances::table)
.values(new_member)
.get_result::<models::Balance>(conn)?;
Ok(inserted)
}
///
pub fn select(&self, conn: &diesel::PgConnection) -> Result<Option<models::Balance>, Error> {
match api_kgon_balances::table.first::<models::Balance>(conn) {
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
}
}
///
pub fn update(
&self,
conn: &diesel::PgConnection,
id: i32,
modify: &models::ModifyBalance,
) -> Result<u64, Error> {
use api_kgon_balances::dsl;
diesel::update(dsl::api_kgon_balances.filter(dsl::id.eq(id)))
.set(modify)
.execute(conn)
.map(|c| c as u64)
}
///
pub fn delete(&self, conn: &diesel::PgConnection, id: i32) -> Result<u64, Error> {
use api_kgon_balances::dsl;
diesel::delete(api_kgon_balances::table.filter(dsl::id.eq(id)))
.execute(conn)
.map(|c| c as u64)
}
}

View File

@ -0,0 +1,18 @@
//!
//!
table! {
///
api_kgon_balances(id) {
///
id -> Integer,
///
balance -> BigInt,
///
balance_bota -> BigInt,
///
created_at -> BigInt,
///
updated_at -> BigInt,
}
}

View File

@ -5,3 +5,5 @@
pub mod models; pub mod models;
/// ///
pub mod repository; pub mod repository;
///
pub mod schema;

View File

@ -1,47 +1,92 @@
use serde::{Deserialize, Serialize}; use super::schema::api_kgon_games;
use beteran_common_rust as bcr;
pub struct Error { ///
pub code: i64, #[derive(Eq, Hash, Identifiable, Queryable, PartialEq, Debug, Clone)]
pub msg: Option<String>, #[table_name = "api_kgon_games"]
pub struct Game {
///
pub id: i64,
///
pub vendor_id: i64,
///
pub key: String,
///
pub names: String,
///
pub platform: String,
///
pub category: String,
///
pub game_type: String,
///
pub image: Option<String>,
///
pub created_at: i64,
///
pub updated_at: i64,
} }
pub struct FindVendorsRequest {} ///
#[derive(Insertable, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug)] #[table_name = "api_kgon_games"]
pub struct FindVendorsResponse { pub struct NewGame {
pub code: i64, ///
pub msg: Option<String>, pub id: i64,
pub vendors: Vec<String>, ///
pub vendor_id: i64,
///
pub key: String,
///
pub names: String,
///
pub platform: String,
///
pub category: String,
///
pub game_type: String,
///
pub image: Option<String>,
} }
pub struct FindGamesRequest { ///
pub vendor_key: String, #[derive(AsChangeset, Debug, Clone)]
#[table_name = "api_kgon_games"]
pub struct ModifyGame {
///
pub key: String,
///
pub names: String,
///
pub platform: String,
///
pub category: String,
///
pub game_type: String,
///
pub image: Option<String>,
} }
#[derive(Serialize, Deserialize, Debug)] ///
pub struct FindGamesResponse { #[derive(Debug, Clone)]
pub code: i64, pub struct FindAllSearch {
pub msg: Option<String>, ///
pub games: Vec<String>, pub vendor_id: Option<i64>,
///
pub key_like: Option<String>,
///
pub platform_like: Option<String>,
///
pub category_like: Option<String>,
///
pub game_type_like: Option<String>,
} }
///
pub struct PlayRequest { #[derive(Debug, Clone)]
pub vendor_key: String, pub struct FindAll {
pub game_key: String, pub search: Option<FindAllSearch>,
pub username: String, ///
pub nickname: String, pub pagination: Option<bcr::models::pagination::Pagination>,
pub site_username: String, ///
pub group_key: Option<String>, pub sorts: Option<Vec<bcr::models::pagination::Sort>>,
pub amount: i64,
pub request_key: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct PlayResponse {
pub code: i64,
pub msg: Option<String>,
#[serde(rename = "userId")]
pub user_id: String,
pub url: String,
pub balance: i64,
} }

View File

@ -1,150 +1,201 @@
use super::models; //!
use std::{collections::HashMap, time::Duration}; //!
use super::{models, schema::api_kgon_games};
use beteran_common_rust as bcr;
use diesel::prelude::*;
use diesel::result::Error;
/// ///
pub struct Repository { pub struct Repository {}
client: reqwest::Client,
k_secret: String,
k_username: String,
}
impl std::fmt::Debug for Repository { impl std::fmt::Debug for Repository {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api.kgon.identity").finish() f.debug_struct("Repository of api_kgon_games").finish()
}
}
impl Default for Repository {
fn default() -> Self {
Self::new()
} }
} }
impl Repository { impl Repository {
/// ///
pub fn new(k_secret: &str, k_username: &str) -> Repository { pub fn new() -> Repository {
Repository { Repository {}
client: reqwest::Client::new(), }
k_secret: k_secret.to_string(),
k_username: k_username.to_string(), ///
pub fn insert(
&self,
conn: &diesel::PgConnection,
new_member: &models::NewGame,
) -> Result<models::Game, Error> {
let inserted = diesel::insert_into(api_kgon_games::table)
.values(new_member)
.get_result::<models::Game>(conn)?;
Ok(inserted)
}
///
pub fn select(
&self,
conn: &diesel::PgConnection,
id: i64,
) -> Result<Option<models::Game>, Error> {
match api_kgon_games::table.find(id).first::<models::Game>(conn) {
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
} }
} }
/// ///
pub async fn find_vendors( pub fn select_all_count(
&self, &self,
data: models::FindVendorsRequest, conn: &diesel::PgConnection,
) -> Result<models::FindVendorsResponse, models::Error> { find_all: &models::FindAll,
let res = match self ) -> Result<i64, Error> {
.client let mut q = api_kgon_games::table.into_boxed();
.post("https://dev-mw.kgonapi.com/vendors")
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header("k-secret", self.k_secret.as_str())
.header("k-username", self.k_username.as_str())
.send()
.await
{
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
}
};
match res.status() { if let Some(s) = &find_all.search {
reqwest::StatusCode::OK => match res.json::<models::FindVendorsResponse>().await { if let Some(sp) = s.vendor_id {
Ok(r) => Ok(r), q = q.filter(api_kgon_games::dsl::vendor_id.eq(sp));
Err(e) => Err(models::Error { code: 0, msg: None }),
},
_ => Err(models::Error { code: 0, msg: None }),
} }
if let Some(sp) = s.key_like {
q = q.filter(api_kgon_games::dsl::key.like(sp));
}
if let Some(sp) = s.platform_like {
q = q.filter(api_kgon_games::dsl::platform.like(sp));
}
if let Some(sp) = s.category_like {
q = q.filter(api_kgon_games::dsl::category.like(sp));
}
if let Some(sp) = s.game_type_like {
q = q.filter(api_kgon_games::dsl::game_type.like(sp));
}
}
q.count().get_result(conn)
} }
/// ///
pub async fn find_games( pub fn select_all(
&self, &self,
data: models::FindGamesRequest, conn: &diesel::PgConnection,
) -> Result<models::FindGamesResponse, models::Error> { find_all: &models::FindAll,
let mut params = HashMap::new(); ) -> Result<Vec<models::Game>, Error> {
let mut q = api_kgon_games::table.into_boxed();
params.insert("vendorKey", data.vendor_key); if let Some(s) = &find_all.search {
if let Some(sp) = s.vendor_id {
let res = match self q = q.filter(api_kgon_games::dsl::vendor_id.eq(sp));
.client }
.post("https://dev-mw.kgonapi.com/games") if let Some(sp) = s.key_like {
.header(reqwest::header::ACCEPT, "application/json") q = q.filter(api_kgon_games::dsl::key.like(sp));
.header( }
reqwest::header::CONTENT_TYPE, if let Some(sp) = s.platform_like {
"application/x-www-form-urlencoded", q = q.filter(api_kgon_games::dsl::platform.like(sp));
) }
.header("k-secret", self.k_secret.as_str()) if let Some(sp) = s.category_like {
.header("k-username", self.k_username.as_str()) q = q.filter(api_kgon_games::dsl::category.like(sp));
.form(&params) }
.send() if let Some(sp) = s.game_type_like {
.await q = q.filter(api_kgon_games::dsl::game_type.like(sp));
{ }
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
} }
};
match res.status() { if let Some(p) = &find_all.pagination {
reqwest::StatusCode::OK => match res.json::<models::FindGamesResponse>().await { let page = p.page.unwrap_or(1);
Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }), if let Some(page_size) = p.page_size {
q = q.offset(((page - 1) * page_size) as i64);
q = q.limit(page_size as i64);
}
}
if let Some(orderbys) = &find_all.sorts {
for s in orderbys {
match s {
bcr::models::pagination::Sort::ASC(property) => match property.as_str() {
"vendor_id" => {
q = q.order_by(api_kgon_games::vendor_id.asc());
}
"key" => {
q = q.order_by(api_kgon_games::key.asc());
}
"platform" => {
q = q.order_by(api_kgon_games::platform.asc());
}
"category" => {
q = q.order_by(api_kgon_games::category.asc());
}
"game_type" => {
q = q.order_by(api_kgon_games::game_type.asc());
}
"created_at" => {
q = q.order_by(api_kgon_games::created_at.asc());
}
"updated_at" => {
q = q.order_by(api_kgon_games::updated_at.asc());
}
_ => {}
}, },
_ => Err(models::Error { code: 0, msg: None }), bcr::models::pagination::Sort::DESC(property) => match property.as_str() {
"vendor_id" => {
q = q.order_by(api_kgon_games::vendor_id.desc());
} }
"key" => {
q = q.order_by(api_kgon_games::key.desc());
}
"platform" => {
q = q.order_by(api_kgon_games::platform.desc());
}
"category" => {
q = q.order_by(api_kgon_games::category.desc());
}
"game_type" => {
q = q.order_by(api_kgon_games::game_type.desc());
}
"created_at" => {
q = q.order_by(api_kgon_games::created_at.desc());
}
"updated_at" => {
q = q.order_by(api_kgon_games::updated_at.desc());
}
_ => {}
},
};
}
}
q.load::<models::Game>(conn)
} }
/// ///
pub async fn play( pub fn update(
&self, &self,
data: models::PlayRequest, conn: &diesel::PgConnection,
) -> Result<models::PlayResponse, models::Error> { id: i64,
let mut params = HashMap::new(); modify: &models::ModifyGame,
) -> Result<u64, Error> {
use api_kgon_games::dsl;
params.insert("vendorKey", data.vendor_key); diesel::update(dsl::api_kgon_games.filter(dsl::id.eq(id)))
params.insert("gameKey", data.game_key); .set(modify)
params.insert("username", data.username); .execute(conn)
params.insert("nickname", data.nickname); .map(|c| c as u64)
params.insert("siteUsername", data.site_username);
if let Some(group_key) = data.group_key {
params.insert("groupKey", group_key);
} }
params.insert("amount", data.amount.to_string()); ///
pub fn delete(&self, conn: &diesel::PgConnection, id: i64) -> Result<u64, Error> {
use api_kgon_games::dsl;
if let Some(request_key) = data.request_key { diesel::delete(api_kgon_games::table.filter(dsl::id.eq(id)))
params.insert("requestKey", request_key); .execute(conn)
} .map(|c| c as u64)
let res = match self
.client
.post("https://dev-mw.kgonapi.com/play")
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header("k-secret", self.k_secret.as_str())
.header("k-username", self.k_username.as_str())
.form(&params)
.timeout(Duration::from_secs(10))
.send()
.await
{
Ok(res) => res,
Err(err) => {
return Err(models::Error { code: 0, msg: None });
}
};
match res.status() {
reqwest::StatusCode::OK => match res.json::<models::PlayResponse>().await {
Ok(r) => Ok(r),
Err(e) => Err(models::Error { code: 0, msg: None }),
},
_ => Err(models::Error { code: 0, msg: None }),
}
} }
} }

View File

@ -0,0 +1,28 @@
//!
//!
table! {
///
api_kgon_games(id) {
///
id -> BigInt,
///
vendor_id -> BigInt,
///
key -> Text,
///
names -> Text,
///
platform -> Text,
///
category -> Text,
///
game_type -> Text,
///
image -> Nullable<Text>,
///
created_at -> BigInt,
///
updated_at -> BigInt,
}
}

View File

@ -5,3 +5,5 @@
pub mod models; pub mod models;
/// ///
pub mod repository; pub mod repository;
///
pub mod schema;

View File

@ -0,0 +1,78 @@
use super::schema::api_kgon_members;
use beteran_common_rust as bcr;
///
#[derive(Eq, Hash, Identifiable, Queryable, PartialEq, Debug, Clone)]
#[table_name = "api_kgon_members"]
pub struct Member {
///
pub id: i64,
///
pub balance: i64,
///
pub balance_bota: i64,
///
pub balance_sum: i64,
///
pub companies: i64,
///
pub oriental_play: bool,
///
pub member_id: uuid::Uuid,
///
pub created_at: i64,
///
pub updated_at: i64,
}
///
#[derive(Insertable, Debug, Clone)]
#[table_name = "api_kgon_members"]
pub struct NewMember {
///
pub id: i64,
///
pub balance: i64,
///
pub balance_bota: i64,
///
pub balance_sum: i64,
///
pub companies: i64,
///
pub oriental_play: bool,
///
pub member_id: uuid::Uuid,
}
///
#[derive(AsChangeset, Debug, Clone)]
#[table_name = "api_kgon_members"]
pub struct ModifyMember {
///
pub balance: i64,
///
pub balance_bota: i64,
///
pub balance_sum: i64,
///
pub companies: i64,
///
pub oriental_play: bool,
}
///
#[derive(Debug, Clone)]
pub struct FindAllSearch {
///
pub oriental_play: Option<bool>,
}
///
#[derive(Debug, Clone)]
pub struct FindAll {
pub search: Option<FindAllSearch>,
///
pub pagination: Option<bcr::models::pagination::Pagination>,
///
pub sorts: Option<Vec<bcr::models::pagination::Sort>>,
}

View File

@ -0,0 +1,200 @@
//!
//!
use super::{models, schema::api_kgon_members};
use beteran_common_rust as bcr;
use diesel::prelude::*;
use diesel::result::Error;
///
pub struct Repository {}
impl std::fmt::Debug for Repository {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api_kgon_members").finish()
}
}
impl Default for Repository {
fn default() -> Self {
Self::new()
}
}
impl Repository {
///
pub fn new() -> Repository {
Repository {}
}
///
pub fn insert(
&self,
conn: &diesel::PgConnection,
new_member: &models::NewMember,
) -> Result<models::Member, Error> {
let inserted = diesel::insert_into(api_kgon_members::table)
.values(new_member)
.get_result::<models::Member>(conn)?;
Ok(inserted)
}
///
pub fn select(
&self,
conn: &diesel::PgConnection,
id: i64,
) -> Result<Option<models::Member>, Error> {
match api_kgon_members::table
.find(id)
.first::<models::Member>(conn)
{
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
}
}
///
pub fn select_by_member_id(
&self,
conn: &diesel::PgConnection,
member_id: uuid::Uuid,
) -> Result<Option<models::Member>, Error> {
use api_kgon_members::dsl;
match api_kgon_members::table
.filter(dsl::member_id.eq(member_id))
.first::<models::Member>(conn)
{
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
}
}
///
pub fn select_all_count(
&self,
conn: &diesel::PgConnection,
find_all: &models::FindAll,
) -> Result<i64, Error> {
let mut q = api_kgon_members::table.into_boxed();
if let Some(s) = &find_all.search {
if let Some(sp) = s.oriental_play {
q = q.filter(api_kgon_members::dsl::oriental_play.eq(sp));
}
}
q.count().get_result(conn)
}
///
pub fn select_all(
&self,
conn: &diesel::PgConnection,
find_all: &models::FindAll,
) -> Result<Vec<models::Member>, Error> {
let mut q = api_kgon_members::table.into_boxed();
if let Some(s) = &find_all.search {
if let Some(sp) = s.oriental_play {
q = q.filter(api_kgon_members::dsl::oriental_play.eq(sp));
}
}
if let Some(p) = &find_all.pagination {
let page = p.page.unwrap_or(1);
if let Some(page_size) = p.page_size {
q = q.offset(((page - 1) * page_size) as i64);
q = q.limit(page_size as i64);
}
}
if let Some(orderbys) = &find_all.sorts {
for s in orderbys {
match s {
bcr::models::pagination::Sort::ASC(property) => match property.as_str() {
"balance" => {
q = q.order_by(api_kgon_members::balance.asc());
}
"balance_bota" => {
q = q.order_by(api_kgon_members::balance_bota.asc());
}
"balance_sum" => {
q = q.order_by(api_kgon_members::balance_sum.asc());
}
"companies" => {
q = q.order_by(api_kgon_members::companies.asc());
}
"oriental_play" => {
q = q.order_by(api_kgon_members::oriental_play.asc());
}
"created_at" => {
q = q.order_by(api_kgon_members::created_at.asc());
}
"updated_at" => {
q = q.order_by(api_kgon_members::updated_at.asc());
}
_ => {}
},
bcr::models::pagination::Sort::DESC(property) => match property.as_str() {
"balance" => {
q = q.order_by(api_kgon_members::balance.desc());
}
"balance_bota" => {
q = q.order_by(api_kgon_members::balance_bota.desc());
}
"balance_sum" => {
q = q.order_by(api_kgon_members::balance_sum.desc());
}
"companies" => {
q = q.order_by(api_kgon_members::companies.desc());
}
"oriental_play" => {
q = q.order_by(api_kgon_members::oriental_play.desc());
}
"created_at" => {
q = q.order_by(api_kgon_members::created_at.desc());
}
"updated_at" => {
q = q.order_by(api_kgon_members::updated_at.desc());
}
_ => {}
},
};
}
}
q.load::<models::Member>(conn)
}
///
pub fn update(
&self,
conn: &diesel::PgConnection,
id: i64,
modify: &models::ModifyMember,
) -> Result<u64, Error> {
use api_kgon_members::dsl;
diesel::update(dsl::api_kgon_members.filter(dsl::id.eq(id)))
.set(modify)
.execute(conn)
.map(|c| c as u64)
}
///
pub fn delete(&self, conn: &diesel::PgConnection, id: i64) -> Result<u64, Error> {
use api_kgon_members::dsl;
diesel::delete(api_kgon_members::table.filter(dsl::id.eq(id)))
.execute(conn)
.map(|c| c as u64)
}
}

View File

@ -0,0 +1,26 @@
//!
//!
table! {
///
api_kgon_members(id) {
///
id -> BigInt,
///
balance -> BigInt,
///
balance_bota -> BigInt,
///
balance_sum -> BigInt,
///
companies -> BigInt,
///
oriental_play -> Bool,
///
member_id -> Uuid,
///
created_at -> BigInt,
///
updated_at -> BigInt,
}
}

View File

@ -1,4 +1,4 @@
pub mod account; pub mod balance;
pub mod betting;
pub mod game; pub mod game;
pub mod identity; pub mod member;
pub mod vendor;

View File

@ -5,3 +5,5 @@
pub mod models; pub mod models;
/// ///
pub mod repository; pub mod repository;
///
pub mod schema;

108
src/repositories/vendor/models.rs vendored Normal file
View File

@ -0,0 +1,108 @@
use super::schema::api_kgon_vendors;
use beteran_common_rust as bcr;
///
#[derive(Eq, Hash, Identifiable, Queryable, PartialEq, Debug, Clone)]
#[table_name = "api_kgon_vendors"]
pub struct Vendor {
///
pub id: i64,
///
pub company_id: i64,
///
pub vendor_id: i64,
///
pub key: String,
///
pub name: String,
///
pub category: String,
///
pub max_bet_casino: i64,
///
pub max_bet_slot: i64,
///
pub is_enable: bool,
///
pub bet_count: i64,
///
pub created_at: i64,
///
pub updated_at: i64,
}
///
#[derive(Insertable, Debug, Clone)]
#[table_name = "api_kgon_vendors"]
pub struct NewVendor {
///
pub id: i64,
///
pub company_id: i64,
///
pub vendor_id: i64,
///
pub key: String,
///
pub name: String,
///
pub category: String,
///
pub max_bet_casino: i64,
///
pub max_bet_slot: i64,
///
pub is_enable: bool,
///
pub bet_count: i64,
}
///
#[derive(AsChangeset, Debug, Clone)]
#[table_name = "api_kgon_vendors"]
pub struct ModifyVendor {
///
pub company_id: i64,
///
pub vendor_id: i64,
///
pub key: String,
///
pub name: String,
///
pub category: String,
///
pub max_bet_casino: i64,
///
pub max_bet_slot: i64,
///
pub is_enable: bool,
///
pub bet_count: i64,
}
///
#[derive(Debug, Clone)]
pub struct FindAllSearch {
///
pub company_id: Option<i64>,
///
pub vendor_id: Option<i64>,
///
pub key_like: Option<String>,
///
pub name_like: Option<String>,
///
pub category_like: Option<String>,
///
pub is_enable: Option<bool>,
}
///
#[derive(Debug, Clone)]
pub struct FindAll {
pub search: Option<FindAllSearch>,
///
pub pagination: Option<bcr::models::pagination::Pagination>,
///
pub sorts: Option<Vec<bcr::models::pagination::Sort>>,
}

234
src/repositories/vendor/repository.rs vendored Normal file
View File

@ -0,0 +1,234 @@
//!
//!
use super::{models, schema::api_kgon_vendors};
use beteran_common_rust as bcr;
use diesel::prelude::*;
use diesel::result::Error;
///
pub struct Repository {}
impl std::fmt::Debug for Repository {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of api_kgon_vendors").finish()
}
}
impl Default for Repository {
fn default() -> Self {
Self::new()
}
}
impl Repository {
///
pub fn new() -> Repository {
Repository {}
}
///
pub fn insert(
&self,
conn: &diesel::PgConnection,
new_member: &models::NewVendor,
) -> Result<models::Vendor, Error> {
let inserted = diesel::insert_into(api_kgon_vendors::table)
.values(new_member)
.get_result::<models::Vendor>(conn)?;
Ok(inserted)
}
///
pub fn select(
&self,
conn: &diesel::PgConnection,
id: i64,
) -> Result<Option<models::Vendor>, Error> {
match api_kgon_vendors::table
.find(id)
.first::<models::Vendor>(conn)
{
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
}
}
///
pub fn select_all_count(
&self,
conn: &diesel::PgConnection,
find_all: &models::FindAll,
) -> Result<i64, Error> {
let mut q = api_kgon_vendors::table.into_boxed();
if let Some(s) = &find_all.search {
if let Some(sp) = s.company_id {
q = q.filter(api_kgon_vendors::dsl::company_id.eq(sp));
}
if let Some(sp) = s.vendor_id {
q = q.filter(api_kgon_vendors::dsl::vendor_id.eq(sp));
}
if let Some(sp) = s.key_like {
q = q.filter(api_kgon_vendors::dsl::key.like(sp));
}
if let Some(sp) = s.name_like {
q = q.filter(api_kgon_vendors::dsl::name.like(sp));
}
if let Some(sp) = s.category_like {
q = q.filter(api_kgon_vendors::dsl::category.like(sp));
}
if let Some(sp) = s.is_enable {
q = q.filter(api_kgon_vendors::dsl::is_enable.eq(sp));
}
}
q.count().get_result(conn)
}
///
pub fn select_all(
&self,
conn: &diesel::PgConnection,
find_all: &models::FindAll,
) -> Result<Vec<models::Vendor>, Error> {
let mut q = api_kgon_vendors::table.into_boxed();
if let Some(s) = &find_all.search {
if let Some(sp) = s.company_id {
q = q.filter(api_kgon_vendors::dsl::company_id.eq(sp));
}
if let Some(sp) = s.vendor_id {
q = q.filter(api_kgon_vendors::dsl::vendor_id.eq(sp));
}
if let Some(sp) = s.key_like {
q = q.filter(api_kgon_vendors::dsl::key.like(sp));
}
if let Some(sp) = s.name_like {
q = q.filter(api_kgon_vendors::dsl::name.like(sp));
}
if let Some(sp) = s.category_like {
q = q.filter(api_kgon_vendors::dsl::category.like(sp));
}
if let Some(sp) = s.is_enable {
q = q.filter(api_kgon_vendors::dsl::is_enable.eq(sp));
}
}
if let Some(p) = &find_all.pagination {
let page = p.page.unwrap_or(1);
if let Some(page_size) = p.page_size {
q = q.offset(((page - 1) * page_size) as i64);
q = q.limit(page_size as i64);
}
}
if let Some(orderbys) = &find_all.sorts {
for s in orderbys {
match s {
bcr::models::pagination::Sort::ASC(property) => match property.as_str() {
"company_id" => {
q = q.order_by(api_kgon_vendors::company_id.asc());
}
"vendor_id" => {
q = q.order_by(api_kgon_vendors::vendor_id.asc());
}
"key" => {
q = q.order_by(api_kgon_vendors::key.asc());
}
"name" => {
q = q.order_by(api_kgon_vendors::name.asc());
}
"category" => {
q = q.order_by(api_kgon_vendors::category.asc());
}
"max_bet_casino" => {
q = q.order_by(api_kgon_vendors::max_bet_casino.asc());
}
"max_bet_slot" => {
q = q.order_by(api_kgon_vendors::max_bet_slot.asc());
}
"is_enable" => {
q = q.order_by(api_kgon_vendors::is_enable.asc());
}
"bet_count" => {
q = q.order_by(api_kgon_vendors::bet_count.asc());
}
"created_at" => {
q = q.order_by(api_kgon_vendors::created_at.asc());
}
"updated_at" => {
q = q.order_by(api_kgon_vendors::updated_at.asc());
}
_ => {}
},
bcr::models::pagination::Sort::DESC(property) => match property.as_str() {
"company_id" => {
q = q.order_by(api_kgon_vendors::company_id.desc());
}
"vendor_id" => {
q = q.order_by(api_kgon_vendors::vendor_id.desc());
}
"key" => {
q = q.order_by(api_kgon_vendors::key.desc());
}
"name" => {
q = q.order_by(api_kgon_vendors::name.desc());
}
"category" => {
q = q.order_by(api_kgon_vendors::category.desc());
}
"max_bet_casino" => {
q = q.order_by(api_kgon_vendors::max_bet_casino.desc());
}
"max_bet_slot" => {
q = q.order_by(api_kgon_vendors::max_bet_slot.desc());
}
"is_enable" => {
q = q.order_by(api_kgon_vendors::is_enable.desc());
}
"bet_count" => {
q = q.order_by(api_kgon_vendors::bet_count.desc());
}
"created_at" => {
q = q.order_by(api_kgon_vendors::created_at.desc());
}
"updated_at" => {
q = q.order_by(api_kgon_vendors::updated_at.desc());
}
_ => {}
},
};
}
}
q.load::<models::Vendor>(conn)
}
///
pub fn update(
&self,
conn: &diesel::PgConnection,
id: i64,
modify: &models::ModifyVendor,
) -> Result<u64, Error> {
use api_kgon_vendors::dsl;
diesel::update(dsl::api_kgon_vendors.filter(dsl::id.eq(id)))
.set(modify)
.execute(conn)
.map(|c| c as u64)
}
///
pub fn delete(&self, conn: &diesel::PgConnection, id: i64) -> Result<u64, Error> {
use api_kgon_vendors::dsl;
diesel::delete(api_kgon_vendors::table.filter(dsl::id.eq(id)))
.execute(conn)
.map(|c| c as u64)
}
}

32
src/repositories/vendor/schema.rs vendored Normal file
View File

@ -0,0 +1,32 @@
//!
//!
table! {
///
api_kgon_vendors(id) {
///
id -> BigInt,
///
company_id -> BigInt,
///
vendor_id -> BigInt,
///
key -> Text,
///
name -> Text,
///
category -> Text,
///
max_bet_casino -> BigInt,
///
max_bet_slot -> BigInt,
///
is_enable -> Bool,
///
bet_count -> BigInt,
///
created_at -> BigInt,
///
updated_at -> BigInt,
}
}

View File

@ -0,0 +1 @@
pub mod scheduler;

View File

@ -0,0 +1,15 @@
///
pub struct Scheduler {}
impl std::fmt::Debug for Scheduler {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Scheduler of api.kgon.identity").finish()
}
}
impl Scheduler {
///
pub fn new() -> Scheduler {
Scheduler {}
}
}

View File

@ -0,0 +1 @@
pub mod scheduler;

View File

@ -0,0 +1,15 @@
///
pub struct Scheduler {}
impl std::fmt::Debug for Scheduler {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Scheduler of api.kgon.identity").finish()
}
}
impl Scheduler {
///
pub fn new() -> Scheduler {
Scheduler {}
}
}

View File

@ -0,0 +1 @@
pub mod scheduler;

View File

@ -0,0 +1,19 @@
use tokio_cron_scheduler::{Job, JobScheduler, JobToRun};
///
pub struct Scheduler {}
impl std::fmt::Debug for Scheduler {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Scheduler of api.kgon.identity").finish()
}
}
impl Scheduler {
///
pub fn new() -> Scheduler {
let mut sched = JobScheduler::new();
Scheduler {}
}
}

4
src/schedulers/mod.rs Normal file
View File

@ -0,0 +1,4 @@
pub mod balance;
pub mod game;
pub mod member;
pub mod vendor;

1
src/schedulers/vendor/mod.rs vendored Normal file
View File

@ -0,0 +1 @@
pub mod scheduler;

87
src/schedulers/vendor/scheduler.rs vendored Normal file
View File

@ -0,0 +1,87 @@
use std::time::Duration;
use crate::repositories;
use diesel::{
r2d2::{ConnectionManager, Pool},
PgConnection,
};
use tokio_cron_scheduler::{Job, JobScheduler};
///
pub struct Scheduler {
pool: Pool<ConnectionManager<PgConnection>>,
sched: JobScheduler,
vendor_repository: repositories::vendor::repository::Repository,
}
impl std::fmt::Debug for Scheduler {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Scheduler of api.kgon.identity").finish()
}
}
impl Scheduler {
///
pub fn new(pool: Pool<ConnectionManager<PgConnection>>, sched: JobScheduler) -> Scheduler {
Scheduler {
pool,
sched,
vendor_repository: repositories::vendor::repository::Repository::new(),
}
}
pub async fn queue(&self) -> Result<(), std::boxed::Box<dyn std::error::Error>> {
self.list_members().await?;
Ok(())
}
async fn list_members(&self) -> Result<(), Box<dyn std::error::Error>> {
let mut jj = Job::new_repeated(Duration::from_secs(60), |_uuid, _l| {
println!("{:?} I'm repeated every 60 seconds", chrono::Utc::now());
})
.unwrap();
jj.on_start_notification_add(
&self.sched,
Box::new(|job_id, notification_id, type_of_notification| {
Box::pin(async move {
println!(
"Job {:?} was started, notification {:?} ran ({:?})",
job_id, notification_id, type_of_notification
);
})
}),
)
.await;
jj.on_stop_notification_add(
&self.sched,
Box::new(|job_id, notification_id, type_of_notification| {
Box::pin(async move {
println!(
"Job {:?} was completed, notification {:?} ran ({:?})",
job_id, notification_id, type_of_notification
);
})
}),
)
.await;
jj.on_removed_notification_add(
&self.sched,
Box::new(|job_id, notification_id, type_of_notification| {
Box::pin(async move {
println!(
"Job {:?} was removed, notification {:?} ran ({:?})",
job_id, notification_id, type_of_notification
);
})
}),
)
.await;
self.sched.add(jj).await;
Ok(())
}
}

View File

@ -0,0 +1 @@
pub mod service;

View File

@ -0,0 +1,40 @@
///
pub struct Service {
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
}
impl std::fmt::Debug for Service {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Service of api.kgon.identity").finish()
}
}
impl Service {
///
pub fn new(
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
) -> Service {
Service {
connection_broker,
queue_broker,
k_secret,
k_username,
}
}
pub async fn subscribe(&self) -> std::result::Result<(), std::boxed::Box<dyn std::error::Error>> {
futures::try_join!(self.create_member(), self.list_members(), self.get_member(),).map(|_| ())
}
async fn list_history(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_history_for_pragmatic(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_history_for_evolution(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn statistics(&self) -> Result<(), Box<dyn std::error::Error>> {}
}

View File

@ -0,0 +1 @@
pub mod service;

View File

@ -29,6 +29,11 @@ impl Service {
} }
pub async fn subscribe(&self) -> std::result::Result<(), std::boxed::Box<dyn std::error::Error>> { pub async fn subscribe(&self) -> std::result::Result<(), std::boxed::Box<dyn std::error::Error>> {
futures::try_join!().map(|_| ()) futures::try_join!(self.create_member(), self.list_members(), self.get_member(),).map(|_| ())
} }
async fn list_vendors(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_games(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn execute_game(&self) -> Result<(), Box<dyn std::error::Error>> {}
} }

View File

@ -0,0 +1,40 @@
///
pub struct Service {
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
}
impl std::fmt::Debug for Service {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Service of api.kgon.identity").finish()
}
}
impl Service {
///
pub fn new(
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
) -> Service {
Service {
connection_broker,
queue_broker,
k_secret,
k_username,
}
}
pub async fn subscribe(&self) -> std::result::Result<(), std::boxed::Box<dyn std::error::Error>> {
futures::try_join!(self.create_member(), self.list_members(), self.get_member(),).map(|_| ())
}
async fn create_member(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_members(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn get_member(&self) -> Result<(), Box<dyn std::error::Error>> {}
}

View File

@ -0,0 +1 @@
pub mod service;

View File

@ -0,0 +1,41 @@
///
pub struct Service {
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
}
impl std::fmt::Debug for Service {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Service of api.kgon.identity").finish()
}
}
impl Service {
///
pub fn new(
connection_broker: nats::asynk::Connection,
queue_broker: String,
k_secret: String,
k_username: String,
) -> Service {
Service {
connection_broker,
queue_broker,
k_secret,
k_username,
}
}
pub async fn subscribe(&self) -> std::result::Result<(), std::boxed::Box<dyn std::error::Error>> {
futures::try_join!(self.create_member(), self.list_members(), self.get_member(),).map(|_| ())
}
async fn create_deposit(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn create_withdraw(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_partner_balnace(&self) -> Result<(), Box<dyn std::error::Error>> {}
async fn list_user_balnace(&self) -> Result<(), Box<dyn std::error::Error>> {}
}

View File

@ -1,4 +1,4 @@
pub mod account;
pub mod betting; pub mod betting;
pub mod game; pub mod game;
pub mod identity; pub mod member;
pub mod member_account;