Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change amc plugin interface to take item_ids list instead of filter #5929

Open
wants to merge 2 commits into
base: 5826-Plugin-base
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 3 additions & 14 deletions server/graphql/core/src/loader/item_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ use crate::standard_graphql_error::StandardGraphqlError;
use super::IdPair;
use actix_web::web::Data;
use async_graphql::dataloader::*;
use repository::EqualFilter;
use service::{
item_stats::{ItemStats, ItemStatsFilter},
service_provider::ServiceProvider,
};
use service::{item_stats::ItemStats, service_provider::ServiceProvider};
use std::collections::HashMap;

pub struct ItemsStatsForItemLoader {
Expand Down Expand Up @@ -42,19 +38,12 @@ impl Loader<ItemStatsLoaderInput> for ItemsStatsForItemLoader {
return Ok(HashMap::new());
};

let filter = ItemStatsFilter::new().item_id(EqualFilter::equal_any(
IdPair::get_all_secondary_ids(loader_inputs),
));
let item_ids = IdPair::get_all_secondary_ids(loader_inputs);

let item_stats = self
.service_provider
.item_stats_service
.get_item_stats(
&service_context,
&store_id,
amc_lookback_months,
Some(filter),
)
.get_item_stats(&service_context, &store_id, amc_lookback_months, item_ids)
.map_err(|e| StandardGraphqlError::from_error(&e))?;

Ok(item_stats
Expand Down
9 changes: 4 additions & 5 deletions server/service/src/backend_plugin/examples/amc/amc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ const DAY_LOOKBACK = 800;
const DAYS_IN_MONTH = 30;

let plugins = {
average_monthly_consumption: ({ store_id, filter }) => {
const item_ids = filter.item_id.equal_any;

average_monthly_consumption: ({ store_id, item_ids }) => {
const now = new Date();
now.setDate(now.getDate() - DAY_LOOKBACK);

const sql_date = now.toJSON().split('T')[0];
const sql_date = now.toJSON().split("T")[0];
const sql_item_ids = '"' + item_ids.join('","') + '"';

// Sqlite only
Expand All @@ -34,7 +32,8 @@ let plugins = {

sql_result.forEach(({ item_id, consumption }) => {
response[item_id] = {
average_monthly_consumption: consumption / (DAY_LOOKBACK / DAYS_IN_MONTH),
average_monthly_consumption:
consumption / (DAY_LOOKBACK / DAYS_IN_MONTH),
};
});

Expand Down
7 changes: 2 additions & 5 deletions server/service/src/backend_plugin/types/amc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
backend_plugin::{plugin_provider::PluginInstance, *},
item_stats::ItemStatsFilter,
};
use crate::backend_plugin::{plugin_provider::PluginInstance, *};
use plugin_provider::{call_plugin, PluginResult};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand All @@ -16,7 +13,7 @@ pub struct Input {
pub store_id: String,
pub amc_lookback_months: f64,
pub consumption_map: HashMap<String /* item_id */, f64 /* consumption */>,
pub filter: Option<ItemStatsFilter>,
pub item_ids: Vec<String>,
}

pub type Output = HashMap<String /* item_id */, AverageMonthlyConsumptionItem>;
Expand Down
12 changes: 4 additions & 8 deletions server/service/src/dashboard/item_count.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use repository::{EqualFilter, ItemFilter, ItemRepository};
use repository::{ItemFilter, ItemRepository};

use crate::{
item_stats::{get_item_stats, ItemStatsFilter},
service_provider::ServiceContext,
PluginOrRepositoryError,
item_stats::get_item_stats, service_provider::ServiceContext, PluginOrRepositoryError,
};

pub struct ItemCounts {
Expand Down Expand Up @@ -43,11 +41,9 @@ impl ItemCountServiceTrait for ItemServiceCount {

let visible_items_count = visible_items.len() as i64;

let item_id_filter =
EqualFilter::equal_any(visible_items.into_iter().map(|i| i.item_row.id).collect());
let item_id_filter = Some(ItemStatsFilter::new().item_id(item_id_filter));
let item_ids = visible_items.into_iter().map(|i| i.item_row.id).collect();

let item_stats = get_item_stats(ctx, store_id, None, item_id_filter)?;
let item_stats = get_item_stats(ctx, store_id, None, item_ids)?;

let no_stock = item_stats
.iter()
Expand Down
25 changes: 4 additions & 21 deletions server/service/src/invoice_line/stock_out_line/update/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ mod test {
mock_store_a, mock_store_b, mock_store_c, MockDataInserts,
},
test_db::setup_all,
EqualFilter, InvoiceLineRow, InvoiceLineRowRepository, InvoiceLineType, InvoiceRow,
InvoiceStatus, InvoiceType, StockLineRow, StockLineRowRepository, Upsert,
InvoiceLineRow, InvoiceLineRowRepository, InvoiceLineType, InvoiceRow, InvoiceStatus,
InvoiceType, StockLineRow, StockLineRowRepository, Upsert,
};
use util::{inline_edit, inline_init};

Expand All @@ -146,7 +146,6 @@ mod test {
},
InsertStockOutLine,
},
item_stats::ItemStatsFilter,
service_provider::ServiceProvider,
};

Expand Down Expand Up @@ -651,15 +650,7 @@ mod test {

let item_stats_service = service_provider.item_stats_service;
let stats = item_stats_service
.get_item_stats(
&context,
&context.store_id,
None,
Some(
ItemStatsFilter::new()
.item_id(EqualFilter::equal_to(mock_item_a().id.as_str())),
),
)
.get_item_stats(&context, &context.store_id, None, vec![mock_item_a().id])
.unwrap();
let stats = stats.first().unwrap();
assert_eq!(
Expand All @@ -681,15 +672,7 @@ mod test {
.unwrap();

let stats = item_stats_service
.get_item_stats(
&context,
&context.store_id,
None,
Some(
ItemStatsFilter::new()
.item_id(EqualFilter::equal_to(mock_item_a().id.as_str())),
),
)
.get_item_stats(&context, &context.store_id, None, vec![mock_item_a().id])
.unwrap();
let stats = stats.first().unwrap();
assert_eq!(
Expand Down
53 changes: 16 additions & 37 deletions server/service/src/item_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,11 @@ use repository::{
RequisitionLine, StockOnHandFilter, StockOnHandRepository, StockOnHandRow, StorageConnection,
StorePreferenceRowRepository,
};
use serde::{Deserialize, Serialize};
use util::{
constants::{DEFAULT_AMC_LOOKBACK_MONTHS, NUMBER_OF_DAYS_IN_A_MONTH},
date_now_with_offset,
};

#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct ItemStatsFilter {
pub item_id: Option<EqualFilter<String>>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ItemStats {
pub total_consumption: f64,
Expand All @@ -40,9 +34,9 @@ pub trait ItemStatsServiceTrait: Sync + Send {
ctx: &ServiceContext,
store_id: &str,
amc_lookback_months: Option<f64>,
filter: Option<ItemStatsFilter>,
item_ids: Vec<String>,
) -> Result<Vec<ItemStats>, PluginOrRepositoryError> {
get_item_stats(ctx, store_id, amc_lookback_months, filter)
get_item_stats(ctx, store_id, amc_lookback_months, item_ids)
}
}

Expand All @@ -53,12 +47,8 @@ pub fn get_item_stats(
ctx: &ServiceContext,
store_id: &str,
amc_lookback_months: Option<f64>,
filter: Option<ItemStatsFilter>,
item_ids: Vec<String>,
) -> Result<Vec<ItemStats>, PluginOrRepositoryError> {
let ItemStatsFilter {
item_id: item_id_filter,
} = filter.clone().unwrap_or_default();

let default_amc_lookback_months = StorePreferenceRowRepository::new(&ctx.connection)
.find_one_by_id(store_id)?
.map_or(DEFAULT_AMC_LOOKBACK_MONTHS.into(), |row| {
Expand All @@ -77,7 +67,7 @@ pub fn get_item_stats(
let consumption_map = get_consumption_map(
&ctx.connection,
store_id,
item_id_filter.clone(),
item_ids.clone(),
amc_lookback_months,
)?;

Expand All @@ -86,7 +76,7 @@ pub fn get_item_stats(
amc_lookback_months,
// Really don't like cloning this
consumption_map: consumption_map.clone(),
filter,
item_ids: item_ids.clone(),
};

let amc_by_item = match PluginInstance::get_one(PluginType::Amc) {
Expand All @@ -97,7 +87,7 @@ pub fn get_item_stats(
Ok(ItemStats::new_vec(
amc_by_item,
consumption_map,
get_stock_on_hand_rows(&ctx.connection, store_id, item_id_filter)?,
get_stock_on_hand_rows(&ctx.connection, store_id, Some(item_ids))?,
))
}

Expand Down Expand Up @@ -128,15 +118,15 @@ impl amc::Trait for DefaultAmc {
fn get_consumption_map(
connection: &StorageConnection,
store_id: &str,
item_id_filter: Option<EqualFilter<String>>,
item_ids: Vec<String>,
amc_lookback_months: f64,
) -> Result<HashMap<String /* item_id */, f64 /* total consumption */>, RepositoryError> {
let start_date = date_now_with_offset(Duration::days(
(amc_lookback_months * NUMBER_OF_DAYS_IN_A_MONTH).neg() as i64,
));

let filter = ConsumptionFilter {
item_id: item_id_filter,
item_id: Some(EqualFilter::equal_any(item_ids)),
store_id: Some(EqualFilter::equal_to(store_id)),
date: Some(DateFilter::after_or_equal_to(start_date)),
};
Expand All @@ -156,10 +146,10 @@ fn get_consumption_map(
pub fn get_stock_on_hand_rows(
connection: &StorageConnection,
store_id: &str,
item_id_filter: Option<EqualFilter<String>>,
item_ids: Option<Vec<String>>,
) -> Result<Vec<StockOnHandRow>, RepositoryError> {
let filter = StockOnHandFilter {
item_id: item_id_filter,
item_id: item_ids.map(|ids| EqualFilter::equal_any(ids)),
store_id: Some(EqualFilter::equal_to(store_id)),
};

Expand Down Expand Up @@ -204,24 +194,14 @@ impl ItemStats {
}
}

impl ItemStatsFilter {
pub fn new() -> ItemStatsFilter {
ItemStatsFilter { item_id: None }
}

pub fn item_id(mut self, filter: EqualFilter<String>) -> Self {
self.item_id = Some(filter);
self
}
}
#[cfg(test)]
mod test {
use repository::{
mock::{mock_store_a, mock_store_b, test_item_stats, MockDataInserts},
test_db, EqualFilter, StorePreferenceRow, StorePreferenceRowRepository,
test_db, StorePreferenceRow, StorePreferenceRowRepository,
};

use crate::{item_stats::ItemStatsFilter, service_provider::ServiceProvider};
use crate::service_provider::ServiceProvider;

#[actix_rt::test]
async fn test_item_stats_service() {
Expand All @@ -237,10 +217,9 @@ mod test {
let service = service_provider.item_stats_service;

let item_ids = vec![test_item_stats::item().id, test_item_stats::item2().id];
let filter = Some(ItemStatsFilter::new().item_id(EqualFilter::equal_any(item_ids)));

let mut item_stats = service
.get_item_stats(&context, &mock_store_a().id, None, filter.clone())
.get_item_stats(&context, &mock_store_a().id, None, item_ids.clone())
.unwrap();
item_stats.sort_by(|a, b| a.item_id.cmp(&b.item_id));

Expand All @@ -265,7 +244,7 @@ mod test {

// Reduce to looking back 1 month
let mut item_stats = service
.get_item_stats(&context, &mock_store_a().id, Some(1.0), filter.clone())
.get_item_stats(&context, &mock_store_a().id, Some(1.0), item_ids.clone())
.unwrap();
item_stats.sort_by(|a, b| a.item_id.cmp(&b.item_id));

Expand Down Expand Up @@ -293,7 +272,7 @@ mod test {
})
.unwrap();
let mut item_stats = service
.get_item_stats(&context, &mock_store_a().id, None, filter.clone())
.get_item_stats(&context, &mock_store_a().id, None, item_ids.clone())
.unwrap();
item_stats.sort_by(|a, b| a.item_id.cmp(&b.item_id));

Expand All @@ -315,7 +294,7 @@ mod test {
assert_eq!(item_stats[1].average_monthly_consumption, 0.0);

let mut item_stats = service
.get_item_stats(&context, &mock_store_b().id, None, filter.clone())
.get_item_stats(&context, &mock_store_b().id, None, item_ids.clone())
.unwrap();
item_stats.sort_by(|a, b| a.item_id.cmp(&b.item_id));

Expand Down
11 changes: 3 additions & 8 deletions server/service/src/requisition/request_requisition/generate.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use chrono::Utc;
use repository::{EqualFilter, RequisitionLineRow, RequisitionRow};
use repository::{RequisitionLineRow, RequisitionRow};
use util::uuid::uuid;

use crate::item_stats::{get_item_stats, ItemStatsFilter};
use crate::item_stats::get_item_stats;
use crate::service_provider::ServiceContext;
use crate::PluginOrRepositoryError;

Expand Down Expand Up @@ -45,12 +45,7 @@ pub fn generate_requisition_lines(
requisition_row: &RequisitionRow,
item_ids: Vec<String>,
) -> Result<Vec<RequisitionLineRow>, PluginOrRepositoryError> {
let item_stats_rows = get_item_stats(
ctx,
store_id,
None,
Some(ItemStatsFilter::new().item_id(EqualFilter::equal_any(item_ids))),
)?;
let item_stats_rows = get_item_stats(ctx, store_id, None, item_ids)?;

let result = item_stats_rows
.into_iter()
Expand Down
Loading