Skip to content
This repository has been archived by the owner on Aug 3, 2024. It is now read-only.

Commit

Permalink
added simulation date to database for persistance. removed date singl…
Browse files Browse the repository at this point in the history
…eton and once_cell dependency
  • Loading branch information
dvalnn committed May 25, 2024
1 parent c8a884b commit a624b6e
Show file tree
Hide file tree
Showing 14 changed files with 117 additions and 255 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ name = "infi-erp"
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
anyhow = "1.0"
once_cell = "1.19.0"

uuid = { version = "1.7.0", features = ["v4", "serde"] }
sqlx = { version = "0.7", default-features = false, features = [
Expand Down
7 changes: 7 additions & 0 deletions migrations/015_metada.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS epoch_table(
simulation_date INT
NOT NULL
DEFAULT 1
CHECK(simulation_date >= 0)
PRIMARY KEY
);
36 changes: 16 additions & 20 deletions src/db_api/clients.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,41 @@
use serde::{Deserialize, Serialize};
use sqlx::{
postgres::types::PgMoney, query, query_as, types::uuid::Uuid, Executor,
PgConnection, PgPool, Postgres,
};
use sqlx::{types::uuid::Uuid, PgConnection, PgPool};

use crate::db_api::NotificationChannel as Ntc;

use super::{orders::Order, pieces::FinalPiece};

#[derive(Debug)]
#[allow(dead_code)]
pub struct Client {
id: Uuid,
name: String,
}

impl Client {
fn new(name: String) -> Self {
Self {
id: Uuid::new_v4(),
name,
}
}

pub async fn query_by_name(
name: &str,
con: &mut PgConnection,
) -> sqlx::Result<Option<Self>> {
query_as!(Client, r#"SELECT * FROM clients WHERE name = $1"#, name)
.fetch_optional(con)
.await
sqlx::query_as!(
Client,
r#"SELECT * FROM clients WHERE name = $1"#,
name
)
.fetch_optional(con)
.await
}

pub async fn insert_to_db(
name: &str,
con: &mut PgConnection,
) -> sqlx::Result<Uuid> {
Ok(
query!("INSERT INTO clients (name) VALUES ($1) RETURNING id", name)
.fetch_one(con)
.await?
.id,
Ok(sqlx::query!(
"INSERT INTO clients (name) VALUES ($1) RETURNING id",
name
)
.fetch_one(con)
.await?
.id)
}
}

Expand All @@ -56,6 +51,7 @@ pub struct ClientOrder {
}

impl ClientOrder {
#[allow(dead_code)]
pub fn new(
client_name: String,
order_number: i32,
Expand Down
28 changes: 24 additions & 4 deletions src/db_api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#![allow(dead_code, unused_imports)]

// Modules
mod clients;
mod items;
Expand All @@ -20,6 +18,30 @@ pub use shipments::*;
pub use suppliers::*;
pub use transformations::*;

use sqlx::PgConnection;

pub async fn get_date(con: &mut PgConnection) -> sqlx::Result<u32> {
Ok(
sqlx::query_scalar!("SELECT simulation_date FROM epoch_table LIMIT 1")
.fetch_one(con)
.await? as u32,
)
}

pub async fn update_date(
new_date: u32,
con: &mut PgConnection,
) -> sqlx::Result<()> {
sqlx::query!(
"UPDATE epoch_table SET simulation_date = $1",
new_date as i32
)
.execute(con)
.await?;

Ok(())
}

pub enum NotificationChannel {
NewOrder,
MaterialsNeeded,
Expand All @@ -28,8 +50,6 @@ pub enum NotificationChannel {
impl NotificationChannel {
const NEW_ORDER_CHANNEL: &'static str = "new_order";
const MATERIALS_NEEDED_CHANNEL: &'static str = "materials_needed";
const ALL_STR: [&'static str; 2] =
[Self::NEW_ORDER_CHANNEL, Self::MATERIALS_NEEDED_CHANNEL];

pub async fn notify(
channel: NotificationChannel,
Expand Down
28 changes: 6 additions & 22 deletions src/db_api/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use sqlx::{
PgConnection,
};

use crate::scheduler::{self, Scheduler};

use super::{pieces::FinalPiece, ItemStatus, PieceKind};
use super::{pieces::FinalPiece, PieceKind};

#[derive(Debug, Clone, Copy, PartialEq, sqlx::Type)]
#[sqlx(type_name = "order_status", rename_all = "lowercase")]
Expand Down Expand Up @@ -45,8 +43,8 @@ pub struct Order {
late_penalty: PgMoney,

status: OrderStatus,
placement_day: i32,
delivery_day: Option<i32>,
_placement_day: i32,
_delivery_day: Option<i32>,
}

#[derive(Debug, serde::Serialize)]
Expand Down Expand Up @@ -76,16 +74,16 @@ impl Order {
early_penalty: PgMoney(early_penalty),
late_penalty: PgMoney(late_penalty),
status: OrderStatus::Pending,
placement_day: 0,
delivery_day: None,
_placement_day: 0,
_delivery_day: None,
}
}

pub async fn insert_to_db(
order: &Order,
con: &mut PgConnection,
) -> sqlx::Result<PgQueryResult> {
let placement_day = Scheduler::get_date();
let placement_day = super::get_date(con).await?;

query!(
r#"INSERT INTO orders (
Expand Down Expand Up @@ -129,20 +127,6 @@ impl Order {
.await
}

pub async fn get_id_by_due_date(
day: i32,
con: &mut PgConnection,
) -> sqlx::Result<Vec<Uuid>> {
Ok(
sqlx::query!(r#"SELECT id FROM orders WHERE due_date = $1"#, day)
.fetch_all(con)
.await?
.iter()
.map(|row| row.id)
.collect::<Vec<Uuid>>(),
)
}

pub async fn get_by_item_id(
product_id: Uuid,
con: &mut PgConnection,
Expand Down
28 changes: 2 additions & 26 deletions src/db_api/pieces.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
use std::{
collections::{BTreeMap, HashMap},
num::NonZeroU64,
};
use std::collections::BTreeMap;

use enum_iterator::Sequence;
use serde::{Deserialize, Serialize};
use sqlx::PgConnection;
use subenum::subenum;
use uuid::Uuid;

use crate::db_api::Supplier;

use super::{Item, ItemStatus};
use super::ItemStatus;

#[subenum(FinalPiece, InterPiece, RawMaterial(derive(Sequence)))]
#[derive(
Expand Down Expand Up @@ -102,25 +97,6 @@ impl RawMaterial {
}))
}

pub async fn get_stock(&self, con: &mut PgConnection) -> sqlx::Result<i64> {
sqlx::query!(
r#"
SELECT
COUNT(*) as quantity
FROM items
WHERE
items.status = $1 AND
items.piece_kind = $2 AND
items.order_id IS NULL
"#,
ItemStatus::InStock as ItemStatus,
*self as RawMaterial,
)
.fetch_one(con)
.await
.map(|row| row.quantity.expect("Count is some"))
}

pub async fn get_pending_purchase(
&self,
con: &mut PgConnection,
Expand Down
2 changes: 1 addition & 1 deletion src/db_api/recipes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use serde::{Deserialize, Serialize};
use serde::Serialize;
use sqlx::PgPool;

use super::PieceKind;
Expand Down
1 change: 1 addition & 0 deletions src/db_api/shipments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use uuid::Uuid;
use super::RawMaterial;

#[derive(Debug)]
#[allow(dead_code)]
pub struct Shipment {
id: Option<i64>,
supplier_id: i64,
Expand Down
66 changes: 1 addition & 65 deletions src/db_api/suppliers.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::collections::HashMap;

use sqlx::postgres::types::PgMoney;
use sqlx::PgConnection;
use uuid::Uuid;

use super::{RawMaterial, Shipment};

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Supplier {
id: i64,
raw_material_kind: RawMaterial,
Expand All @@ -31,28 +29,6 @@ impl Supplier {
)
}

pub async fn get_by_id(
id: i64,
con: &mut PgConnection,
) -> sqlx::Result<Supplier> {
sqlx::query_as!(
Supplier,
r#"
SELECT
id,
raw_material_kind as "raw_material_kind: RawMaterial",
min_order_quantity,
unit_price,
delivery_time
FROM suppliers
WHERE id = $1
"#,
id
)
.fetch_one(con)
.await
}

pub async fn get_by_item_kind(
kind: RawMaterial,
con: &mut PgConnection,
Expand All @@ -74,44 +50,4 @@ impl Supplier {
.fetch_all(con)
.await
}

pub async fn get_compatible(
kind: RawMaterial,
time: i32,
con: &mut PgConnection,
) -> sqlx::Result<Vec<Supplier>> {
sqlx::query_as!(
Supplier,
r#"
SELECT
id,
raw_material_kind as "raw_material_kind: RawMaterial",
min_order_quantity,
unit_price,
delivery_time
FROM suppliers
WHERE raw_material_kind = $1 AND delivery_time <= $2
"#,
kind as RawMaterial,
time
)
.fetch_all(con)
.await
}

pub fn delivery_time(&self) -> i32 {
self.delivery_time
}

pub fn unit_price(&self) -> PgMoney {
self.unit_price
}

pub fn min_order_quantity(&self) -> i32 {
self.min_order_quantity
}

pub fn id(&self) -> i64 {
self.id
}
}
8 changes: 0 additions & 8 deletions src/db_api/transformations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,6 @@ impl Transformation {
pub fn product_id(&self) -> Uuid {
self.product_id
}

pub fn date(&self) -> Option<i32> {
self.date
}

pub fn id(&self) -> Option<i64> {
self.id
}
}

#[derive(Debug, Serialize)]
Expand Down
Loading

0 comments on commit a624b6e

Please sign in to comment.