Compare commits
13 Commits
7121137145
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| e5b16ae955 | |||
| f69d94d758 | |||
| 619542357b | |||
| 4e5aab323e | |||
| 4bc04bd7e3 | |||
| 4b21fd873b | |||
| 04e8c554cc | |||
| bb965413a8 | |||
| 3e477945ea | |||
| 3ee9533faf | |||
| 8c89b9c059 | |||
| e29d664f0e | |||
| c522c23dfe |
@@ -38,6 +38,14 @@ pub mod recipes {
|
|||||||
.execute(conn)
|
.execute(conn)
|
||||||
.is_ok()
|
.is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get(conn: &SqliteConnection, recipe_id: i32) -> Option<Recipe> {
|
||||||
|
use self::schema::recipes::dsl::*;
|
||||||
|
|
||||||
|
recipes.filter(id.eq(recipe_id))
|
||||||
|
.first(conn)
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod ingredients {
|
pub mod ingredients {
|
||||||
@@ -49,6 +57,7 @@ pub mod ingredients {
|
|||||||
use super::{SqliteConnection, schema};
|
use super::{SqliteConnection, schema};
|
||||||
use super::diesel::prelude::*;
|
use super::diesel::prelude::*;
|
||||||
|
|
||||||
|
/// A wrapper of [`IngredientList`] with DB connection capacity.
|
||||||
pub struct IngredientListManager<'a>(&'a SqliteConnection, IngredientList);
|
pub struct IngredientListManager<'a>(&'a SqliteConnection, IngredientList);
|
||||||
|
|
||||||
impl<'a> IngredientListManager<'a> {
|
impl<'a> IngredientListManager<'a> {
|
||||||
@@ -90,12 +99,9 @@ pub mod ingredients {
|
|||||||
fn find(conn: &SqliteConnection, name: &str) -> Option<Ingredient> {
|
fn find(conn: &SqliteConnection, name: &str) -> Option<Ingredient> {
|
||||||
use self::schema::ingredients::dsl::*;
|
use self::schema::ingredients::dsl::*;
|
||||||
|
|
||||||
match ingredients.filter(alias.like(name))
|
ingredients.filter(alias.like(name))
|
||||||
.first(conn)
|
.first(conn)
|
||||||
{
|
.ok()
|
||||||
Ok(ingdt) => Some(ingdt),
|
|
||||||
Err(_) => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create(conn: &SqliteConnection, name: &str) -> Result<i32,String> {
|
fn create(conn: &SqliteConnection, name: &str) -> Result<i32,String> {
|
||||||
|
|||||||
@@ -144,6 +144,12 @@ pub struct Recipe {
|
|||||||
pub preparation: String,
|
pub preparation: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Recipe {
|
||||||
|
fn eq(&self, other: &Recipe) -> bool {
|
||||||
|
self.id == other.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Insertable, Debug)]
|
#[derive(Insertable, Debug)]
|
||||||
#[table_name="recipes"]
|
#[table_name="recipes"]
|
||||||
pub struct NewRecipe<'a> {
|
pub struct NewRecipe<'a> {
|
||||||
|
|||||||
@@ -5,20 +5,19 @@ extern crate cookbook;
|
|||||||
|
|
||||||
use std::time;
|
use std::time;
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::fmt::Display;
|
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use cookbook::*;
|
use cookbook::*;
|
||||||
use planner::{
|
use planner::{
|
||||||
*, Value,
|
*, Value,
|
||||||
solver::{
|
solver::{
|
||||||
Variables,
|
Solution,
|
||||||
Domain,
|
Domain,
|
||||||
Problem
|
Problem
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
fn pretty_output<K: Eq + Hash + Debug>(res: &Variables<Value, K>) -> String {
|
fn pretty_output<K: Eq + Hash + Debug>(res: &Solution<Value, K>) -> String {
|
||||||
let mut repr = String::new();
|
let mut repr = String::new();
|
||||||
for (var,value) in res {
|
for (var,value) in res {
|
||||||
let value = match value {
|
let value = match value {
|
||||||
|
|||||||
135
planner/src/constraint.rs
Normal file
135
planner/src/constraint.rs
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
//! Constraints building
|
||||||
|
//!
|
||||||
|
//! # Ideas
|
||||||
|
//!
|
||||||
|
//! Each constraints will be updated on every assignment,
|
||||||
|
//! thus their status is always inspectable.
|
||||||
|
//! A constraint applies to a set of variables, identified
|
||||||
|
//! by a key of type `K`.
|
||||||
|
//! A constraint owns references to actual values assigned,
|
||||||
|
//! used to perform checks.
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! The problem is to clarify the way Constraints operate.
|
||||||
|
//! Do they compute their status from some data on demand ?
|
||||||
|
//! Do they keep their status updated by watching the Variables
|
||||||
|
//! they act on ?
|
||||||
|
//! Worse, do they have superpowers ?
|
||||||
|
//! Could they filter on a variable domain, according to some other variable
|
||||||
|
//! state ? This would mean that constraints won't judge a result, but guide
|
||||||
|
//! the solving process to avoid erroring paths, like a constraint-driven
|
||||||
|
//! solving. This would be powerfull but maybe far too complex...
|
||||||
|
//!
|
||||||
|
//! On the other hand, we can implement a simple Observer pattern, with strong
|
||||||
|
//! coupling to [`Problem`](crate::solver::Problem).
|
||||||
|
//! Because of this, we can safely play with private fields of Problem, and in
|
||||||
|
//! return, provide a public api to build specific constraints.
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Status {
|
||||||
|
Validated,// Solution is valid
|
||||||
|
Unknown, // Constraint cannot resolve yet (unbound variables)
|
||||||
|
Violated, // Solution is invalid
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
// *Like this
|
||||||
|
enum ValueChecker {
|
||||||
|
AllDifferent,
|
||||||
|
AllSame,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Constraint<'c, V, K> {
|
||||||
|
status: Status,
|
||||||
|
variables: HashMap<&'c K, Option<&'c V>>,
|
||||||
|
// TODO: add a ValueChecker Trait object,
|
||||||
|
// or just a simple Enum.*
|
||||||
|
// to provide the check_status procedure, given
|
||||||
|
// a vector to variables values.
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'c, V, K> Constraint<'c, V, K>
|
||||||
|
where K: Eq + std::hash::Hash,
|
||||||
|
V: PartialEq,
|
||||||
|
{
|
||||||
|
|
||||||
|
pub fn new(vars: Vec<&'c K>) -> Self {
|
||||||
|
let len = vars.len();
|
||||||
|
Self {
|
||||||
|
status: Status::Unknown,
|
||||||
|
variables: vars.into_iter()
|
||||||
|
.zip(vec![None; len])
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(&self) -> &Status {
|
||||||
|
&self.status
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_status(vars: Vec<&Option<&V>>) -> Status {
|
||||||
|
/// LEts do an hacky NotEqualConstraint
|
||||||
|
let vars_len = vars.len();
|
||||||
|
let set_vars: Vec<&Option<&V>> = vars.into_iter().filter(|v| v.is_some()).collect();
|
||||||
|
let is_complete = vars_len == set_vars.len();
|
||||||
|
for (idx, value) in set_vars.iter().enumerate() {
|
||||||
|
let violated = set_vars.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(i,_)| *i != idx)
|
||||||
|
.fold(false, |res, (_,v)| {
|
||||||
|
res || v == value
|
||||||
|
});
|
||||||
|
if violated { return Status::Violated; }
|
||||||
|
}
|
||||||
|
match is_complete {
|
||||||
|
true => Status::Validated,
|
||||||
|
false => Status::Unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_status(&mut self) {
|
||||||
|
self.status = Self::check_status(self.variables.values().collect());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, key: &K, new_value: Option<&'c V>) {
|
||||||
|
if let Some(value) = self.variables.get_mut(key) {
|
||||||
|
// Actually update values
|
||||||
|
dbg!(*value = new_value);
|
||||||
|
self.update_status();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn test_all_different_problem() {
|
||||||
|
use crate::solver::{Domain, Problem};
|
||||||
|
use super::Constraint;
|
||||||
|
|
||||||
|
let domain = Domain::new(vec![1, 2, 3]);
|
||||||
|
let problem = Problem::build()
|
||||||
|
.add_variable("Left", domain.all(), None)
|
||||||
|
.add_variable("Right", domain.all(), None)
|
||||||
|
.add_constraint(Constraint::new(vec![&"Left", &"Right"]))
|
||||||
|
.finish();
|
||||||
|
|
||||||
|
let solutions = vec![
|
||||||
|
(("Left", Some(&1)), ("Right", Some(&2))),
|
||||||
|
(("Left", Some(&1)), ("Right", Some(&3))),
|
||||||
|
(("Left", Some(&2)), ("Right", Some(&1))),
|
||||||
|
(("Left", Some(&2)), ("Right", Some(&3))),
|
||||||
|
(("Left", Some(&3)), ("Right", Some(&1))),
|
||||||
|
(("Left", Some(&3)), ("Right", Some(&2))),
|
||||||
|
];
|
||||||
|
let results = problem.solve_all();
|
||||||
|
println!("{:#?}", results);
|
||||||
|
assert!(results.len() == solutions.len());
|
||||||
|
results.into_iter().for_each(|res| {
|
||||||
|
let res = (("Left", *res.get("Left").unwrap()),
|
||||||
|
("Right", *res.get("Right").unwrap())) ;
|
||||||
|
assert!(solutions.contains(&res));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ use cookbook::recipes::Recipe;
|
|||||||
|
|
||||||
pub mod solver;
|
pub mod solver;
|
||||||
pub mod template;
|
pub mod template;
|
||||||
|
pub mod constraint;
|
||||||
|
|
||||||
pub use solver::{Domain, DomainValues};
|
pub use solver::{Domain, DomainValues};
|
||||||
/// We mainly use Recipe as the domain value type
|
/// We mainly use Recipe as the domain value type
|
||||||
|
|||||||
@@ -1,16 +1,56 @@
|
|||||||
//! Rules used by the `planner`
|
//! Rules used by the `planner`
|
||||||
//! A rule is a constraint on valid solutions, but also provides insights
|
//! A rule is a constraint on valid solutions, but also provides insights
|
||||||
//! and eventually inferences to optimize the solving process.
|
//! and eventually inferences to optimize the solving process.
|
||||||
|
//!
|
||||||
|
//! * Basic repartition
|
||||||
|
//! * All different meals
|
||||||
|
//! * Map recipes categories to each meals
|
||||||
|
//! * (Eating a dish over two days (leftovers))
|
||||||
|
//! * Nutritional values
|
||||||
|
//! * Per day : according to user profile (man: 2000kcal, woman: 1800kcal)
|
||||||
|
//! * Per meal : some meals should have higher nutrional values than others
|
||||||
|
//!
|
||||||
|
//! * Ingredients
|
||||||
|
//! * Per week : should use most of a limited set of ingredients (excluding
|
||||||
|
//! condiments, ...)
|
||||||
|
//! * To consume : must use a small set of ingredients (leftovers)
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! Price
|
||||||
|
//! - Per week : should restrict ingredients cost to a given amount
|
||||||
|
|
||||||
// Nutritional values
|
enum Status {
|
||||||
// - Per day : according to user profile (man: 2000kcal, woman: 1800kcal)
|
Ok,
|
||||||
// - Per meal : some meals should have higher nutrional values than others
|
Violated,
|
||||||
|
}
|
||||||
|
|
||||||
// Ingredients
|
trait Rule {
|
||||||
// - Per week : should use most of a limited set of ingredients (excluding
|
type Key;
|
||||||
// condiments, ...)
|
type Value;
|
||||||
// - To consume : must use a small set of ingredients (leftovers)
|
|
||||||
//
|
|
||||||
|
|
||||||
// Price
|
fn status(&self, state: (Vec<&Self::Key>, Vec<&Self::Value>));
|
||||||
// - Per week : should restrict ingredients cost to a given amount
|
fn update(&self, idx: usize, value: Option<Self::Value>) -> Option<Filter>;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AllDifferentMeals;
|
||||||
|
|
||||||
|
impl Rule for AllDifferentMeals {
|
||||||
|
type State = Vec<Recipe>;
|
||||||
|
|
||||||
|
fn status(&self, _: Self::State) -> Status {
|
||||||
|
Status::Ok // Always enforced by update rule
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(&self, _: Self::State) -> Option<Filter> {
|
||||||
|
// Returns a filter excluding this value from domain.
|
||||||
|
// so that it is impossible to select the same meal twice.
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct FilterRecipeByMeals; // Essentially work on domain
|
||||||
|
|
||||||
|
struct NutritionalByDayAverageReq;
|
||||||
|
struct NutritionalByMealAverageValues;
|
||||||
|
|
||||||
|
struct IngredientsInFridge;
|
||||||
|
struct IngredientsMustUse;
|
||||||
|
|||||||
@@ -6,17 +6,26 @@ use std::hash::Hash;
|
|||||||
use std::clone::Clone;
|
use std::clone::Clone;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
/// An assignments map of variables
|
use crate::constraint::{Status, Constraint};
|
||||||
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
|
|
||||||
|
|
||||||
enum Assignment<'a, V, K> {
|
/// A solution returned by [`Solver`]
|
||||||
Update(K, &'a V),
|
pub type Solution<'a, V, K> = HashMap<K, Option<&'a V>>;
|
||||||
Clear(K)
|
|
||||||
|
|
||||||
|
/// An assignments map of variables
|
||||||
|
type Variables<'a, V> = Vec<Option<&'a V>>;
|
||||||
|
|
||||||
|
/// Orders used by solver to update variables
|
||||||
|
enum Assignment<'a, V> {
|
||||||
|
Update(usize, &'a V),
|
||||||
|
Clear(usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Collection of references to values owned by a domain.
|
||||||
pub type DomainValues<'a, V> = Vec<&'a V>;
|
pub type DomainValues<'a, V> = Vec<&'a V>;
|
||||||
/// The domain of values that can be assigned to variables
|
|
||||||
|
/// The domain of values that can be assigned to a variable.
|
||||||
|
/// The values are owned by the instance.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Domain<V> {
|
pub struct Domain<V> {
|
||||||
values: Vec<V>
|
values: Vec<V>
|
||||||
@@ -27,11 +36,21 @@ impl<V> Domain<V> {
|
|||||||
Domain { values }
|
Domain { values }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns all values of a Domain instance
|
/// Returns references to all values of this instance
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # extern crate planner;
|
||||||
|
/// # use planner::solver::Domain;
|
||||||
|
/// let domain = Domain::new(vec!["a", "b", "c"]);
|
||||||
|
/// assert_eq!(domain.all(), vec![&"a", &"b", &"c"]);
|
||||||
|
/// ```
|
||||||
pub fn all(&self) -> DomainValues<V> {
|
pub fn all(&self) -> DomainValues<V> {
|
||||||
self.values.iter().collect()
|
self.values.iter().collect()
|
||||||
}
|
}
|
||||||
/// Returns a Filter filter applied to inner values
|
/// Returns a collection of references to a filtered
|
||||||
|
/// subset of this domain.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
@@ -45,12 +64,39 @@ impl<V> Domain<V> {
|
|||||||
/// assert_eq!(domain.filter(even), vec![&2]);
|
/// assert_eq!(domain.filter(even), vec![&2]);
|
||||||
/// assert_eq!(domain.filter(|i: &i32| i % 2 == 1), vec![&1,&3]);
|
/// assert_eq!(domain.filter(|i: &i32| i % 2 == 1), vec![&1,&3]);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn filter(&self, filter_func: fn(&V) -> bool) -> DomainValues<V> {
|
pub fn filter<F>(&self, filter_func: F) -> DomainValues<V>
|
||||||
|
where F: Fn(&V) -> bool
|
||||||
|
{
|
||||||
self.values
|
self.values
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|v: &&V| filter_func(*v))
|
.filter(|v: &&V| filter_func(*v))
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Wrapper for `find`, returns a optionnal reference
|
||||||
|
/// to the first found value of this domain.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # extern crate planner;
|
||||||
|
/// # use planner::solver::Domain;
|
||||||
|
/// let domain = Domain::new(vec![1,2,3]);
|
||||||
|
/// fn even(i: &i32) -> bool {
|
||||||
|
/// *i == 2
|
||||||
|
/// };
|
||||||
|
/// assert_eq!(domain.find(even), Some(&2));
|
||||||
|
/// assert_eq!(domain.find(|i: &i32| i % 2 == 1), Some(&1));
|
||||||
|
/// assert_eq!(domain.find(|i| *i == 4), None);
|
||||||
|
/// ```
|
||||||
|
pub fn find<F>(&self, getter_func: F) -> Option<&V>
|
||||||
|
where F: Fn(&V) -> bool
|
||||||
|
{
|
||||||
|
self.values
|
||||||
|
.iter()
|
||||||
|
.find(|v: &&V| getter_func(*v))
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
||||||
@@ -59,151 +105,231 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Or we can have a much more complex version of Domain.
|
||||||
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
|
/// We want to retrieve a filtered domain for each variable.
|
||||||
|
/// Filters will be static (filter by category,...) or dynamic
|
||||||
pub struct Problem<'a, V, K> {
|
/// (inserted by rules updates).
|
||||||
/// The initial assignements map
|
///
|
||||||
variables: Variables<'a, V, K>,
|
/// For every variable, we can retrieve its filtered values (values,
|
||||||
/// Each variable has its associated domain
|
/// filtered by all globals, filtered by one local).
|
||||||
domains: HashMap<K, DomainValues<'a,V>>,
|
/// Plus, set a dynamic filter that will apply to all other variables.
|
||||||
/// Set of constraints to validate
|
/// Of course, it also affects this variable, but considering that dynamic
|
||||||
constraints: Vec<Constraint<'a,V,K>>,
|
/// filters are cleared and repopulated on every assign, this side-effect
|
||||||
|
/// can never occur.
|
||||||
|
struct SDomain<V, Filter> {
|
||||||
|
values: Vec<V>,
|
||||||
|
global_filters: Vec<Filter>, // Globals are dynamic Filters
|
||||||
|
local_filters: Vec<Filter>, // Locals are static Filters
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
impl<V, F> SDomain<V, F> {
|
||||||
|
fn new(values: Vec<V>) -> Self {
|
||||||
|
Self {
|
||||||
|
values,
|
||||||
|
global_filters: Vec::new(),
|
||||||
|
local_filters: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn build() -> ProblemBuilder<'a,V, K> {
|
/// Returns the current domain values for a variable by index
|
||||||
|
fn get(&self, idx: usize) -> DomainValues<V> {
|
||||||
|
self.values
|
||||||
|
.iter()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a dynamic filter to globals, identified by its setter's id
|
||||||
|
/// /!\ Previously set filters are overriden, hence dynamic
|
||||||
|
fn set_global(&mut self, setter: usize, filter: F) {
|
||||||
|
self.global_filters[setter] = filter;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
|
||||||
|
|
||||||
|
|
||||||
|
/// Could be more efficient to just use fixed array of options as variables,
|
||||||
|
/// using a helper to bind Keys to Index in this array.
|
||||||
|
/// Domains could be a similar array of DomainValues.
|
||||||
|
/// It makes sense with an array where indexing is O(1)
|
||||||
|
|
||||||
|
pub struct Problem<'p, V, K> {
|
||||||
|
keys: Vec<K>,
|
||||||
|
/// The initial assignements
|
||||||
|
variables: Variables<'p, V>,
|
||||||
|
/// Each variable has its associated domain
|
||||||
|
domains: Vec<DomainValues<'p,V>>,
|
||||||
|
/// Set of constraints to validate
|
||||||
|
constraints: Vec<Constraint<'p,V,K>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'p, V: PartialEq, K: Eq + Hash + Clone> Problem<'p, V, K> {
|
||||||
|
|
||||||
|
pub fn build() -> ProblemBuilder<'p,V, K> {
|
||||||
ProblemBuilder::new()
|
ProblemBuilder::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_template() -> Problem<'a, V, K> {
|
pub fn from_template() -> Problem<'p, V, K> {
|
||||||
let mut builder = Self::build();
|
let builder = Self::build();
|
||||||
|
|
||||||
builder.finish()
|
builder.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns all possible Updates for next assignements, prepended with
|
/// Returns all possible Updates for next assignements, prepended with
|
||||||
/// a Clear to ensure the variable is unset before when leaving the branch.
|
/// a Clear to ensure the variable is unset before when leaving the branch.
|
||||||
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V, K>>> {
|
fn _push_updates(&self) -> Option<Vec<Assignment<'p,V>>> {
|
||||||
// TODO: should be able to inject a choosing strategy
|
if let Some(idx) = self._next_assign() {
|
||||||
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
|
// TODO: Domain will filter possible values for us
|
||||||
let domain_values = self.domains.get(key).expect("No domain for variable !");
|
// let values = self.domain.get(idx);
|
||||||
|
let domain_values = self.domains
|
||||||
|
.get(idx)
|
||||||
|
.expect("No domain for variable !");
|
||||||
|
// TODO: handle case of empty domain.values
|
||||||
|
assert!(!domain_values.is_empty());
|
||||||
// Push a clear assignment first, just before going up the stack.
|
// Push a clear assignment first, just before going up the stack.
|
||||||
let mut updates = vec![Assignment::Clear(key.clone())];
|
let mut updates = vec![Assignment::Clear(idx.clone())];
|
||||||
|
domain_values.iter().for_each(|value| {
|
||||||
if domain_values.is_empty() { panic!("No value in domain !"); }
|
updates.push(
|
||||||
// TODO: should be able to filter domain values (inference, pertinence)
|
Assignment::Update(idx, *value)
|
||||||
for value in domain_values.into_iter() {
|
);
|
||||||
updates.push(Assignment::Update(key.clone(), *value));
|
});
|
||||||
}
|
|
||||||
Some(updates)
|
Some(updates)
|
||||||
} else { // End of assignements
|
} else { // End of assignements
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn _next_assign(&self) -> Option<usize> {
|
||||||
|
// TODO: should be able to inject a choosing strategy
|
||||||
|
self.variables.iter()
|
||||||
|
.enumerate()
|
||||||
|
.find_map(|(idx, val)| {
|
||||||
|
if val.is_none() { Some(idx) }
|
||||||
|
else { None }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Checks that the current assignments doesn't violate any constraint
|
/// Checks that the current assignments doesn't violate any constraint
|
||||||
fn _is_valid(&self) -> bool {
|
fn _is_valid(&self) -> bool {
|
||||||
for validator in self.constraints.iter() {
|
for status in self.constraints.iter().map(|c| c.status()) {
|
||||||
if validator(&self.variables) == false { return false; }
|
if status == &Status::Violated { return false; }
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
|
fn _get_key(&self, idx: usize) -> &K {
|
||||||
pub fn solve_all(&mut self) -> Vec<Variables<'a,V,K>>
|
&self.keys[idx]
|
||||||
where V: Clone + fmt::Debug,
|
}
|
||||||
K: Clone + fmt::Debug,
|
|
||||||
{
|
fn _get_solution(&self) -> Solution<'p, V, K> {
|
||||||
let mut solutions: Vec<Variables<V, K>> = vec![];
|
// Returns the current state wrapped in a Solution type.
|
||||||
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
|
self.keys.iter().cloned()
|
||||||
stack.append(&mut self._push_updates().unwrap());
|
.zip(self.variables.iter().cloned())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assigns a new value to the given index, then calls update
|
||||||
|
/// on every constraints.
|
||||||
|
fn _assign(&mut self, idx: usize, value: Option<&'p V>) {
|
||||||
|
self.variables[idx] = value;
|
||||||
|
let var_key = &self.keys[idx];
|
||||||
|
// TODO: manage dynamic filters on Domain
|
||||||
|
// let filters: Filter::Chain = self.constraints.iter_mut().map([...]).collect();
|
||||||
|
// self.domain.set_global(idx, filters);
|
||||||
|
self.constraints.iter_mut()
|
||||||
|
.for_each(|c| {
|
||||||
|
c.update(&var_key, value);
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fn _solve(&mut self, limit: Option<usize>) -> Vec<Solution<'p, V, K>> {
|
||||||
|
let mut solutions: Vec<Solution<V, K>> = vec![];
|
||||||
|
let mut stack: Vec<Assignment<'p, V>> = vec![];
|
||||||
|
if let Some(mut init_updates) = self._push_updates() {
|
||||||
|
stack.append(&mut init_updates);
|
||||||
|
} else {
|
||||||
|
// Solution is complete
|
||||||
|
panic!("Could not initialize !");
|
||||||
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let node = stack.pop();
|
let node = stack.pop();
|
||||||
|
// There is no more combination to try out
|
||||||
if node.is_none() { break; };
|
if node.is_none() { break; };
|
||||||
|
// Exit early if we have enough solutions
|
||||||
|
if limit.is_some()
|
||||||
|
&& solutions.len() == limit.unwrap()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
|
||||||
match node.unwrap() {
|
match node.unwrap() {
|
||||||
Assignment::Update(key, val) => {
|
Assignment::Update(idx, val) => {
|
||||||
// Assign the variable and open new branches, if any.
|
// Assign the variable and open new branches, if any.
|
||||||
*self.variables.get_mut(&key).unwrap() = Some(val);
|
self._assign(idx, Some(val));
|
||||||
// TODO: handle case of empty domain.values
|
|
||||||
if let Some(mut nodes) = self._push_updates() {
|
if let Some(mut nodes) = self._push_updates() {
|
||||||
stack.append(&mut nodes);
|
stack.append(&mut nodes);
|
||||||
} else {
|
} else {
|
||||||
// Assignements are completed
|
// Assignements are completed
|
||||||
if self._is_valid() {
|
if self._is_valid() {
|
||||||
solutions.push(self.variables.clone());
|
solutions.push(self._get_solution());
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
Assignment::Clear(key) => {
|
Assignment::Clear(idx) => {
|
||||||
// We are closing this branch, unset the variable
|
// We are closing this branch, unset the variable
|
||||||
*self.variables.get_mut(&key).unwrap() = None;
|
self._assign(idx, None);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
solutions
|
solutions
|
||||||
|
|
||||||
|
}
|
||||||
|
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
|
||||||
|
pub fn solve_all(mut self) -> Vec<Solution<'p,V,K>>
|
||||||
|
where V: fmt::Debug,
|
||||||
|
K: fmt::Debug,
|
||||||
|
{
|
||||||
|
self._solve(None) // No limit
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn solve_one(&mut self) -> Option<Variables<'a,V,K>>
|
pub fn solve_one(mut self) -> Option<Solution<'p,V,K>>
|
||||||
where V: Clone + fmt::Debug,
|
where V: fmt::Debug,
|
||||||
K: Clone + fmt::Debug,
|
K: fmt::Debug,
|
||||||
{
|
{
|
||||||
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
|
self._solve(Some(1)).pop()
|
||||||
stack.append(&mut self._push_updates().unwrap());
|
|
||||||
loop {
|
|
||||||
let node = stack.pop();
|
|
||||||
if node.is_none() {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
match node.unwrap() {
|
|
||||||
Assignment::Update(key, val) => {
|
|
||||||
// Assign the variable and open new branches, if any.
|
|
||||||
*self.variables.get_mut(&key).unwrap() = Some(val);
|
|
||||||
// TODO: handle case of empty domain.values
|
|
||||||
if let Some(mut nodes) = self._push_updates() {
|
|
||||||
stack.append(&mut nodes);
|
|
||||||
} else {
|
|
||||||
// Assignements are completed
|
|
||||||
if self._is_valid() {
|
|
||||||
return Some(self.variables.clone());
|
|
||||||
};
|
|
||||||
};
|
|
||||||
},
|
|
||||||
Assignment::Clear(key) => {
|
|
||||||
// We are closing this branch, unset the variable
|
|
||||||
*self.variables.get_mut(&key).unwrap() = None;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);
|
pub struct ProblemBuilder<'p, V, K>(Problem<'p, V, K>);
|
||||||
|
|
||||||
impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
|
impl<'p, V, K: Eq + Hash + Clone> ProblemBuilder<'p, V, K> {
|
||||||
fn new() -> ProblemBuilder<'a, V, K> {
|
fn new() -> ProblemBuilder<'p, V, K> {
|
||||||
ProblemBuilder(
|
ProblemBuilder(
|
||||||
Problem{
|
Problem{
|
||||||
|
keys: Vec::new(),
|
||||||
variables: Variables::new(),
|
variables: Variables::new(),
|
||||||
domains: HashMap::new(),
|
domains: Vec::new(),
|
||||||
constraints: Vec::new(),
|
constraints: Vec::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
|
pub fn add_variable(mut self, name: K, static_filter: Vec<&'p V>, initial: Option<&'p V>) -> Self
|
||||||
{
|
{
|
||||||
self.0.variables.insert(name.clone(), value);
|
self.0.keys.push(name);
|
||||||
self.0.domains.insert(name, domain);
|
self.0.variables.push(initial);
|
||||||
|
self.0.domains.push(static_filter);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
|
pub fn add_constraint(mut self, cons: Constraint<'p,V,K>) -> Self {
|
||||||
self.0.constraints.push(cons);
|
self.0.constraints.push(cons);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish(self) -> Problem<'a, V, K> {
|
pub fn finish(self) -> Problem<'p,V, K> {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,18 +341,15 @@ mod tests {
|
|||||||
fn test_solver_find_pairs() {
|
fn test_solver_find_pairs() {
|
||||||
use super::*;
|
use super::*;
|
||||||
let domain = Domain::new(vec![1,2,3]);
|
let domain = Domain::new(vec![1,2,3]);
|
||||||
let mut problem: Problem<_, _> = Problem::build()
|
let problem: Problem<_, _> = Problem::build()
|
||||||
.add_variable(String::from("Left"), domain.all(), None)
|
.add_variable(String::from("Left"), domain.all(), None)
|
||||||
.add_variable(String::from("Right"), domain.all(), None)
|
.add_variable(String::from("Right"), domain.all(), None)
|
||||||
.add_constraint(|assign: &Variables<i32, _>| {
|
|
||||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
|
||||||
})
|
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let solutions: Vec<Variables<i32, _>> = vec![
|
let solutions: Vec<Solution<i32, _>> = vec![
|
||||||
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
|
[(String::from("Left"), Some(&3)), (String::from("Right"), Some(&3))].iter().cloned().collect(),
|
||||||
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
|
||||||
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
|
[(String::from("Left"), Some(&1)), (String::from("Right"), Some(&1))].iter().cloned().collect(),
|
||||||
];
|
];
|
||||||
|
|
||||||
assert_eq!(problem.solve_all(), solutions);
|
assert_eq!(problem.solve_all(), solutions);
|
||||||
@@ -236,16 +359,13 @@ mod tests {
|
|||||||
fn test_solver_find_pairs_with_initial() {
|
fn test_solver_find_pairs_with_initial() {
|
||||||
use super::*;
|
use super::*;
|
||||||
let domain = Domain::new(vec![1,2,3]);
|
let domain = Domain::new(vec![1,2,3]);
|
||||||
let mut problem: Problem<_, _> = Problem::build()
|
let problem: Problem<_, _> = Problem::build()
|
||||||
.add_variable("Left".to_string(), domain.all(), None)
|
.add_variable("Left".to_string(), domain.all(), None)
|
||||||
.add_variable("Right".to_string(), domain.all(), Some(&2))
|
.add_variable("Right".to_string(), domain.all(), Some(&2))
|
||||||
.add_constraint( |assign: &Variables<i32, _>| {
|
|
||||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
|
||||||
})
|
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let solutions: Vec<Variables<i32, _>> = vec![
|
let solutions: Vec<Solution<i32, String>> = vec![
|
||||||
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
|
||||||
];
|
];
|
||||||
|
|
||||||
assert_eq!(problem.solve_all(), solutions);
|
assert_eq!(problem.solve_all(), solutions);
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ mod api {
|
|||||||
pub struct CookbookDbConn(diesel::SqliteConnection);
|
pub struct CookbookDbConn(diesel::SqliteConnection);
|
||||||
|
|
||||||
/// A serializable wrapper for [`cookbook::recipes::Recipe`]
|
/// A serializable wrapper for [`cookbook::recipes::Recipe`]
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct RecipeObject {
|
pub struct RecipeObject {
|
||||||
id: i32,
|
id: i32,
|
||||||
title: String,
|
title: String,
|
||||||
@@ -76,13 +76,13 @@ mod api {
|
|||||||
Json( recipes::delete(&conn, id) )
|
Json( recipes::delete(&conn, id) )
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct TemplateItems {
|
pub struct TemplateItems {
|
||||||
key: (String, String),
|
key: (String, String),
|
||||||
value: Option<RecipeObject>,
|
value: Option<RecipeObject>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct TemplateObject {
|
pub struct TemplateObject {
|
||||||
items: Vec<TemplateItems>
|
items: Vec<TemplateItems>
|
||||||
}
|
}
|
||||||
@@ -100,9 +100,65 @@ mod api {
|
|||||||
for (var, dom, ini) in template::Template::generate_variables(&domain) {
|
for (var, dom, ini) in template::Template::generate_variables(&domain) {
|
||||||
problem = problem.add_variable(var, dom, ini);
|
problem = problem.add_variable(var, dom, ini);
|
||||||
}
|
}
|
||||||
let mut problem = problem
|
let problem = problem.finish();
|
||||||
.add_constraint(|_| true)
|
|
||||||
.finish();
|
if let Some(one_result) = problem.solve_one() {
|
||||||
|
Json(TemplateObject {
|
||||||
|
items: one_result
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k,v)| {
|
||||||
|
TemplateItems {
|
||||||
|
key: (format!("{}", k.0), format!("{:?}", k.1)),
|
||||||
|
value: v.map(|r| RecipeObject::from(&conn, r.clone())),
|
||||||
|
}})
|
||||||
|
.collect(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
panic!("No solution at all !");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[post("/solver/complete", data="<partial>")]
|
||||||
|
pub fn complete_problem(conn: CookbookDbConn, partial: Json<Vec<TemplateItems>>) -> Json<TemplateObject> {
|
||||||
|
use planner::{
|
||||||
|
template,
|
||||||
|
solver::{Domain, Problem}
|
||||||
|
};
|
||||||
|
|
||||||
|
let possible_values = recipes::load_all(&conn);
|
||||||
|
let domain = Domain::new(possible_values);
|
||||||
|
let mut problem = Problem::build();
|
||||||
|
for (var, dom, ini) in template::Template::generate_variables(&domain) {
|
||||||
|
// Let's hack for now
|
||||||
|
// BUGGY because template does not generate every variables, needs refactoring
|
||||||
|
// Find variable in partial
|
||||||
|
let initial_id = partial.iter()
|
||||||
|
.filter(|slot| slot.value.is_some())
|
||||||
|
.find_map(|slot| {
|
||||||
|
//println!("{:?} vs {:?}", slot, var);
|
||||||
|
if slot.key.0 == var.0
|
||||||
|
&& slot.key.1 == format!("{:?}",var.1)
|
||||||
|
{
|
||||||
|
let id = slot.value.as_ref().unwrap().id;
|
||||||
|
//println!("found initial : recipe with id {}", id);
|
||||||
|
Some(id)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let ini = if let Some(id) = initial_id {
|
||||||
|
let new_ini = domain.find(|r| {r.id == id});
|
||||||
|
//println!("Overrided {:?}", new_ini);
|
||||||
|
new_ini
|
||||||
|
} else {
|
||||||
|
ini
|
||||||
|
};
|
||||||
|
// If found, override initial value
|
||||||
|
problem = problem.add_variable(var, dom, ini);
|
||||||
|
};
|
||||||
|
let problem = problem.finish();
|
||||||
|
|
||||||
if let Some(one_result) = problem.solve_one() {
|
if let Some(one_result) = problem.solve_one() {
|
||||||
Json(TemplateObject {
|
Json(TemplateObject {
|
||||||
items: one_result
|
items: one_result
|
||||||
@@ -124,7 +180,7 @@ fn main() -> Result<(), Error> {
|
|||||||
let (allowed_origins, failed_origins) = AllowedOrigins::some(&["http://localhost:8080"]);
|
let (allowed_origins, failed_origins) = AllowedOrigins::some(&["http://localhost:8080"]);
|
||||||
assert!(failed_origins.is_empty());
|
assert!(failed_origins.is_empty());
|
||||||
|
|
||||||
// You can also deserialize this
|
// You can also deserialize this
|
||||||
let cors = rocket_cors::CorsOptions {
|
let cors = rocket_cors::CorsOptions {
|
||||||
allowed_origins: allowed_origins,
|
allowed_origins: allowed_origins,
|
||||||
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
|
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
|
||||||
@@ -137,7 +193,12 @@ fn main() -> Result<(), Error> {
|
|||||||
rocket::ignite()
|
rocket::ignite()
|
||||||
.attach(api::CookbookDbConn::fairing())
|
.attach(api::CookbookDbConn::fairing())
|
||||||
.mount("/", routes![index, files])
|
.mount("/", routes![index, files])
|
||||||
.mount("/api", routes![api::recipes_list, api::delete_recipe, api::one_solution])
|
.mount("/api", routes![
|
||||||
|
api::recipes_list,
|
||||||
|
api::delete_recipe,
|
||||||
|
api::one_solution,
|
||||||
|
api::complete_problem,
|
||||||
|
])
|
||||||
.attach(cors)
|
.attach(cors)
|
||||||
.launch();
|
.launch();
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -59,9 +59,8 @@ export default {
|
|||||||
closeActiveView: function() {
|
closeActiveView: function() {
|
||||||
this.active_view = -1;
|
this.active_view = -1;
|
||||||
},
|
},
|
||||||
addToPlanning: function(idx) {
|
addToPlanning: function(mealKey, id) {
|
||||||
let mealKey = ["Lundi", "Lunch"];
|
let mealData = this.items.find((recipe) => recipe.id == id);
|
||||||
let mealData = this.items[idx];
|
|
||||||
this.$refs.weekPlanning.setMeal(mealKey, mealData);
|
this.$refs.weekPlanning.setMeal(mealKey, mealData);
|
||||||
},
|
},
|
||||||
deleteRecipe: function(id) {
|
deleteRecipe: function(id) {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="box">
|
<div class="box">
|
||||||
<button @click="fetchSolution"
|
<button @click="fetchCompletion"
|
||||||
class="button is-primary is-fullwidth"
|
class="button is-primary is-fullwidth"
|
||||||
v-bind:class="{'is-loading': is_loading }">
|
v-bind:class="{'is-loading': is_loading }">
|
||||||
FetchSolution</button>
|
FetchSolution</button>
|
||||||
<div v-if="template">
|
<div class="box">
|
||||||
<div class="columns is-mobile is-vcentered is-multiline">
|
<div class="columns is-mobile is-vcentered is-multiline">
|
||||||
<div v-for="[day, meals] in itemsGroupedByDay"
|
<div v-for="[day, meals] in itemsGroupedByDay"
|
||||||
class="column is-one-quarter-desktop is-half-mobile">
|
class="column is-one-quarter-desktop is-half-mobile">
|
||||||
@@ -82,6 +82,15 @@ Template.prototype.findIndexByKey = function(slotKey) {
|
|||||||
return day_idx * 3 + meal_idx;
|
return day_idx * 3 + meal_idx;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Template.prototype.updateJson = function(data) {
|
||||||
|
var i;
|
||||||
|
for (i in data.items) {
|
||||||
|
let item = data.items[i];
|
||||||
|
let idx = this.findIndexByKey(item.key);
|
||||||
|
this.items[idx].value = item.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'Planner',
|
name: 'Planner',
|
||||||
data () {
|
data () {
|
||||||
@@ -99,8 +108,23 @@ export default {
|
|||||||
this.is_loading = false;
|
this.is_loading = false;
|
||||||
return res.json();}
|
return res.json();}
|
||||||
)
|
)
|
||||||
.then((data) => this.template = data) //TODO: update
|
.then((data) => this.template.updateJson(data))
|
||||||
.catch((err) => console.log(err));
|
.catch((err) => console.error(err));
|
||||||
|
},
|
||||||
|
fetchCompletion: function() {
|
||||||
|
this.is_loading = true;
|
||||||
|
// TODO: Keep only value's id
|
||||||
|
let body = JSON.stringify(this.template.items);
|
||||||
|
fetch("http://localhost:8000/api/solver/complete", {
|
||||||
|
method: 'POST',
|
||||||
|
body,
|
||||||
|
})
|
||||||
|
.then((res) => {
|
||||||
|
return res.json();}
|
||||||
|
)
|
||||||
|
.then((data) => this.template.updateJson(data))
|
||||||
|
.catch((err) => console.error(err));
|
||||||
|
this.is_loading = false;
|
||||||
},
|
},
|
||||||
unsetMeal: function(mealKey) {
|
unsetMeal: function(mealKey) {
|
||||||
let idx = this.template.findIndexByKey(mealKey);
|
let idx = this.template.findIndexByKey(mealKey);
|
||||||
|
|||||||
@@ -2,13 +2,14 @@
|
|||||||
<div class="columns">
|
<div class="columns">
|
||||||
<div class="column is-narrow">
|
<div class="column is-narrow">
|
||||||
<a @click="$emit('close')"
|
<a @click="$emit('close')"
|
||||||
class="has-text-dark">
|
class="button is-large is-outlined-dark is-fullwidth">
|
||||||
|
<span>Liste</span>
|
||||||
<span class="icon is-large">
|
<span class="icon is-large">
|
||||||
<i class="mdi mdi-48px mdi-view-list"></i>
|
<i class="mdi mdi-36px mdi-view-list"></i>
|
||||||
</span>
|
</span>
|
||||||
</a>
|
</a>
|
||||||
<br class="is-hidden-mobile"/>
|
<br class="is-hidden-mobile"/>
|
||||||
<SlotSelect />
|
<SlotSelect v-on:add="addToPlanning" />
|
||||||
</div>
|
</div>
|
||||||
<div class="column">
|
<div class="column">
|
||||||
<h4 class="title">{{ item.title }}</h4>
|
<h4 class="title">{{ item.title }}</h4>
|
||||||
@@ -51,6 +52,11 @@ export default {
|
|||||||
return {
|
return {
|
||||||
categories: categories,
|
categories: categories,
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
addToPlanning: function(slotKey) {
|
||||||
|
this.$emit('add', slotKey, this.item.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -13,9 +13,11 @@
|
|||||||
</div>
|
</div>
|
||||||
<div v-else class="columns">
|
<div v-else class="columns">
|
||||||
<div class="column is-narrow">
|
<div class="column is-narrow">
|
||||||
<a @click="setActiveCategory(-1)" class="has-text-dark">
|
<a @click="setActiveCategory(-1)"
|
||||||
|
class="button is-large is-fullwidth">
|
||||||
|
<span>Catégories</span>
|
||||||
<span class="icon is-large" >
|
<span class="icon is-large" >
|
||||||
<i class="mdi mdi-48px mdi-view-grid"></i>
|
<i class="mdi mdi-36px mdi-view-grid"></i>
|
||||||
</span>
|
</span>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,22 +1,36 @@
|
|||||||
<template>
|
<template>
|
||||||
<div>
|
<div class="box">
|
||||||
<a @click="$emit('add', item.id)"
|
<div class="columns">
|
||||||
class="has-text-success">
|
<div class="column">
|
||||||
<span class="icon is-large">
|
<div class="field">
|
||||||
<i class="mdi mdi-36px mdi-table-plus"></i>
|
<div class="control is-expanded">
|
||||||
</span>
|
<div class="select is-small is-fullwidth">
|
||||||
</a>
|
<select v-model="selected_day">
|
||||||
<div class="select">
|
<option value="Lundi">Lundi</option>
|
||||||
<select>
|
<option value="Mardi">Mardi</option>
|
||||||
<option>Lundi</option>
|
</select>
|
||||||
<option>Mardi</option>
|
</div>
|
||||||
</select>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="select">
|
<div class="field">
|
||||||
<select>
|
<p class="control">
|
||||||
<option>Breakfast</option>
|
<div class="select is-small">
|
||||||
<option>Lunch</option>
|
<select v-model="selected_meal">
|
||||||
</select>
|
<option value="Breakfast">Breakfast</option>
|
||||||
|
<option value="Lunch">Lunch</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="column">
|
||||||
|
<a @click="$emit('add', getSelectedKey)"
|
||||||
|
class="has-text-success">
|
||||||
|
<span class="icon is-large">
|
||||||
|
<i class="mdi mdi-36px mdi-table-plus"></i>
|
||||||
|
</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -24,6 +38,16 @@
|
|||||||
<script>
|
<script>
|
||||||
export default {
|
export default {
|
||||||
name: 'SlotSelect',
|
name: 'SlotSelect',
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
selected_day: "Lundi",
|
||||||
|
selected_meal: "Breakfast",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
getSelectedKey: function() {
|
||||||
|
return [this.selected_day, this.selected_meal];
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
Reference in New Issue
Block a user