adds Key generic parameters, use custom Key type from template.rs
This commit is contained in:
@@ -1,117 +1,35 @@
|
|||||||
//! The weekly menu planner
|
//! The weekly menu planner
|
||||||
//!
|
//!
|
||||||
extern crate cookbook;
|
|
||||||
extern crate planner;
|
extern crate planner;
|
||||||
|
extern crate cookbook;
|
||||||
|
|
||||||
use self::cookbook::*;
|
use std::fmt::Debug;
|
||||||
use self::cookbook::recipes::Recipe;
|
use std::fmt::Display;
|
||||||
use self::planner::solver::{Variables, Domain, Problem};
|
use std::hash::Hash;
|
||||||
|
use cookbook::*;
|
||||||
type DomainValues<'a, V> = Vec<&'a V>;
|
use planner::{
|
||||||
/// We want a mapping of the week meals (matin, midi, soir)
|
*, Value,
|
||||||
/// Breakfast => RecipeCategory::Breakfast
|
solver::{
|
||||||
/// Lunch => RecipeCategory::MainCourse
|
Variables,
|
||||||
/// Dinner => RecipeCategory::MainCourse
|
Domain,
|
||||||
|
Problem
|
||||||
mod template {
|
|
||||||
//! Exports the [`Template`] struct.
|
|
||||||
use super::{Domain, DomainValues, Variables, Recipe};
|
|
||||||
|
|
||||||
type Day = String;
|
|
||||||
const DAYS: &[&str] = &[
|
|
||||||
"Lundi", "Mardi", "Mercredi",
|
|
||||||
"Jeudi", "Vendredi", "Samedi",
|
|
||||||
"Dimanche"];
|
|
||||||
|
|
||||||
/// An enum to discriminate every meals
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub enum Meals {
|
|
||||||
Breakfast(Day),
|
|
||||||
Lunch(Day),
|
|
||||||
Dinner(Day)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Meals> for String {
|
|
||||||
fn from(item: Meals) -> String {
|
|
||||||
match item {
|
|
||||||
Meals::Breakfast(d) => format!("{}_Breakfast", d),
|
|
||||||
Meals::Lunch(d) => format!("{}_Lunch", d),
|
|
||||||
Meals::Dinner(d) => format!("{}_Dinner", d),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// A fixed template of meals
|
|
||||||
///
|
|
||||||
/// TODO: mask -> disabled choosen meals
|
|
||||||
/// initials -> fixed values
|
|
||||||
pub struct Template;
|
|
||||||
|
|
||||||
impl Template {
|
|
||||||
|
|
||||||
fn keys() -> Vec<Meals> {
|
|
||||||
let mut keys = Vec::new();
|
|
||||||
for day in DAYS {
|
|
||||||
for meal in &[Meals::Breakfast, Meals::Lunch, Meals::Dinner] {
|
|
||||||
keys.push(meal(day.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
keys
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build a [`Template`] from a variables assignment map,
|
|
||||||
/// usually a solution returned by solver
|
|
||||||
pub(super) fn from_variables<'a, V>(_vars: Variables<'a,V>) -> Template{
|
|
||||||
Template
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds a vector of variables, to be used with
|
|
||||||
/// [`ProblemBuilder`].
|
|
||||||
pub(super) fn generate_variables(domain: &Domain<Recipe>)
|
|
||||||
-> Vec<(String, DomainValues<Recipe>, Option<&Recipe>)>
|
|
||||||
{
|
|
||||||
use cookbook::recipes::RecipeCategory;
|
|
||||||
let mut vars = Vec::new();
|
|
||||||
for key in Self::keys().into_iter() {
|
|
||||||
//TODO: Use key variants to set filters on domain
|
|
||||||
//TODO: Initial values
|
|
||||||
let _filter: fn(&&Recipe) -> bool = match key {
|
|
||||||
Meals::Breakfast(_) => |r: &&Recipe| {
|
|
||||||
r.category == RecipeCategory::Breakfast // Breakfast
|
|
||||||
},
|
|
||||||
Meals::Lunch(_) => |r: &&Recipe| {
|
|
||||||
r.category as i16 == 2i16 // MainCourse
|
|
||||||
},
|
|
||||||
Meals::Dinner(_) => |r: &&Recipe| {
|
|
||||||
r.category as i16 == 1i16 // Starter
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
vars.push((key.into(), domain.filter(_filter), None));
|
|
||||||
}
|
|
||||||
vars
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ingredients_contains<'a>(_assign: &Variables<'a,Recipe>) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fn pretty_output(res: &Variables<Recipe>) -> String {
|
fn pretty_output<K: Eq + Hash + Debug>(res: &Variables<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 {
|
||||||
Some(rec) => &rec.title,
|
Some(rec) => &rec.title,
|
||||||
None => "---",
|
None => "---",
|
||||||
};
|
};
|
||||||
repr.push_str(&format!("{} => {}\n", var, value));
|
repr.push_str(&format!("{:?} => {}\n", var, value));
|
||||||
}
|
}
|
||||||
repr
|
repr
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_planning_all_results() -> String {
|
fn main() {
|
||||||
let conn = establish_connection();
|
let conn = establish_connection();
|
||||||
let possible_values = recipes::load_all(&conn);
|
let possible_values = recipes::load_all(&conn);
|
||||||
let domain = Domain::new(possible_values);
|
let domain = Domain::new(possible_values);
|
||||||
@@ -119,15 +37,7 @@ fn get_planning_all_results() -> String {
|
|||||||
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 mut problem = problem.finish();
|
||||||
.add_constraint(
|
|
||||||
ingredients_contains
|
|
||||||
)
|
|
||||||
.finish();
|
|
||||||
let results = problem.solve_all();
|
let results = problem.solve_all();
|
||||||
format!("{}\nTotal = {}", pretty_output(&results.first().unwrap()), results.len())
|
println!("{:?}", pretty_output(results.first().unwrap()));
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
println!("{}", get_planning_all_results());
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
extern crate cookbook;
|
extern crate cookbook;
|
||||||
|
use cookbook::recipes::Recipe;
|
||||||
|
|
||||||
pub mod solver;
|
pub mod solver;
|
||||||
|
pub mod template;
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
pub use solver::{Domain, DomainValues};
|
||||||
#[test]
|
/// We mainly use Recipe as the domain value type
|
||||||
fn it_works() {
|
pub type Value = Recipe;
|
||||||
assert_eq!(2 + 2, 4);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,15 +2,16 @@
|
|||||||
//!
|
//!
|
||||||
//! Provides `Variables`, `Domain` structs and `solve_all` function.
|
//! Provides `Variables`, `Domain` structs and `solve_all` function.
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
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
|
/// An assignments map of variables
|
||||||
pub type Variables<'a, V> = HashMap<String, Option<&'a V>>;
|
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
|
||||||
|
|
||||||
enum Assignment<'a, V> {
|
enum Assignment<'a, V, K> {
|
||||||
Update(String, &'a V),
|
Update(K, &'a V),
|
||||||
Clear(String)
|
Clear(K)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -38,13 +39,17 @@ impl<V> Domain<V> {
|
|||||||
/// # extern crate planner;
|
/// # extern crate planner;
|
||||||
/// # use planner::solver::Domain;
|
/// # use planner::solver::Domain;
|
||||||
/// let domain = Domain::new(vec![1,2,3]);
|
/// let domain = Domain::new(vec![1,2,3]);
|
||||||
/// fn even(i: &i32) -> bool { i % 2 == 0 };
|
/// fn even(i: &i32) -> bool {
|
||||||
/// assert_eq!(&domain.filter(even).values, &vec![2]);
|
/// i % 2 == 0
|
||||||
|
/// };
|
||||||
|
/// assert_eq!(domain.filter(even), vec![&2]);
|
||||||
|
/// assert_eq!(domain.filter(|i: &i32| i % 2 == 1), vec![&1,&3]);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn filter(&self, f: fn(&&V) -> bool) -> DomainValues<V>
|
pub fn filter(&self, filter_func: fn(&V) -> bool) -> DomainValues<V> {
|
||||||
where V: std::clone::Clone
|
self.values
|
||||||
{
|
.iter()
|
||||||
self.values.iter().filter(f).collect()
|
.filter(|v: &&V| filter_func(*v))
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,26 +60,31 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
|
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
|
||||||
|
|
||||||
pub struct Problem<'a, V> {
|
pub struct Problem<'a, V, K> {
|
||||||
/// The initial assignements map
|
/// The initial assignements map
|
||||||
variables: Variables<'a, V>,
|
variables: Variables<'a, V, K>,
|
||||||
/// Each variable has its associated domain
|
/// Each variable has its associated domain
|
||||||
domains: HashMap<String, DomainValues<'a,V>>,
|
domains: HashMap<K, DomainValues<'a,V>>,
|
||||||
/// Set of constraints to validate
|
/// Set of constraints to validate
|
||||||
constraints: Vec<Constraint<'a,V>>,
|
constraints: Vec<Constraint<'a,V,K>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a,V> Problem<'a, V> {
|
impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
|
||||||
|
|
||||||
pub fn build() -> ProblemBuilder<'a,V> {
|
pub fn build() -> ProblemBuilder<'a,V, K> {
|
||||||
ProblemBuilder::new()
|
ProblemBuilder::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn from_template(_template: i32) -> Problem<'a, V, K> {
|
||||||
|
Self::build()
|
||||||
|
.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>>> {
|
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V, K>>> {
|
||||||
// TODO: should be able to inject a choosing strategy
|
// TODO: should be able to inject a choosing strategy
|
||||||
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
|
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
|
||||||
let domain_values = self.domains.get(key).expect("No domain for variable !");
|
let domain_values = self.domains.get(key).expect("No domain for variable !");
|
||||||
@@ -100,12 +110,13 @@ impl<'a,V> Problem<'a, V> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visit all possible solutions, using a stack (DFS).
|
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
|
||||||
pub fn solve_all(&mut self) -> Vec<Variables<'a,V>>
|
pub fn solve_all(&mut self) -> Vec<Variables<'a,V,K>>
|
||||||
where V: Clone + fmt::Debug
|
where V: Clone + fmt::Debug,
|
||||||
|
K: Clone + fmt::Debug,
|
||||||
{
|
{
|
||||||
let mut solutions: Vec<Variables<V>> = vec![];
|
let mut solutions: Vec<Variables<V, K>> = vec![];
|
||||||
let mut stack: Vec<Assignment<'a, V>> = vec![];
|
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
|
||||||
stack.append(&mut self._push_updates().unwrap());
|
stack.append(&mut self._push_updates().unwrap());
|
||||||
loop {
|
loop {
|
||||||
let node = stack.pop();
|
let node = stack.pop();
|
||||||
@@ -134,10 +145,10 @@ impl<'a,V> Problem<'a, V> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ProblemBuilder<'a, V>(Problem<'a, V>);
|
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);
|
||||||
|
|
||||||
impl<'a, V> ProblemBuilder<'a, V> {
|
impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
|
||||||
fn new() -> ProblemBuilder<'a, V> {
|
fn new() -> ProblemBuilder<'a, V, K> {
|
||||||
ProblemBuilder(
|
ProblemBuilder(
|
||||||
Problem{
|
Problem{
|
||||||
variables: Variables::new(),
|
variables: Variables::new(),
|
||||||
@@ -146,21 +157,19 @@ impl<'a, V> ProblemBuilder<'a, V> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_variable<S>(mut self, name: S, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
|
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
|
||||||
where S: Into<String>
|
|
||||||
{
|
{
|
||||||
let name = name.into();
|
|
||||||
self.0.variables.insert(name.clone(), value);
|
self.0.variables.insert(name.clone(), value);
|
||||||
self.0.domains.insert(name, domain);
|
self.0.domains.insert(name, domain);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
|
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
|
||||||
self.0.constraints.push(cons);
|
self.0.constraints.push(cons);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish(self) -> Problem<'a, V> {
|
pub fn finish(self) -> Problem<'a, V, K> {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -172,15 +181,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 mut 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>| {
|
.add_constraint(|assign: &Variables<i32, _>| {
|
||||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let solutions: Vec<Variables<i32>> = vec![
|
let solutions: Vec<Variables<i32, _>> = vec![
|
||||||
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
|
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
|
||||||
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
||||||
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
|
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
|
||||||
@@ -193,15 +202,15 @@ 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 mut 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>| {
|
.add_constraint( |assign: &Variables<i32, _>| {
|
||||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
|
|
||||||
let solutions: Vec<Variables<i32>> = vec![
|
let solutions: Vec<Variables<i32, _>> = vec![
|
||||||
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
77
planner/src/template.rs
Normal file
77
planner/src/template.rs
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
use super::{Domain, DomainValues, Value};
|
||||||
|
|
||||||
|
const DAYS: &[&str] = &[
|
||||||
|
"Lundi", "Mardi", "Mercredi",
|
||||||
|
"Jeudi", "Vendredi", "Samedi",
|
||||||
|
"Dimanche"];
|
||||||
|
|
||||||
|
/// An enum to discriminate every meals
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
||||||
|
pub enum Meal {
|
||||||
|
Breakfast,
|
||||||
|
Lunch,
|
||||||
|
Dinner
|
||||||
|
}
|
||||||
|
|
||||||
|
type Key<'a> = (&'a str, &'a Meal);
|
||||||
|
|
||||||
|
|
||||||
|
/// Options set on a meal
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct MealOpts<V> {
|
||||||
|
is_used: bool,
|
||||||
|
initial: Option<V>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets do a fixed template for now
|
||||||
|
/// * Breakfast only on weekends.
|
||||||
|
/// * Lunch has a starter and main course.
|
||||||
|
/// * Plus dessert on weekend ?
|
||||||
|
/// * Dinner is just a starter (hot in winter, cold in summer)
|
||||||
|
pub struct Template;
|
||||||
|
|
||||||
|
impl<'a> Template {
|
||||||
|
|
||||||
|
/// Returns all possible meals
|
||||||
|
fn keys() -> Vec<Key<'a>> {
|
||||||
|
let mut keys = Vec::new();
|
||||||
|
for day in DAYS {
|
||||||
|
for meal in &[Meal::Breakfast, Meal::Lunch, Meal::Dinner] {
|
||||||
|
keys.push((*day, meal))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a vector of variables, to be used with
|
||||||
|
/// [ProblemBuilder](struct.ProblemBuilder.html).
|
||||||
|
pub fn generate_variables(domain: &Domain<Value>)
|
||||||
|
-> Vec<(Key, DomainValues<Value>, Option<&Value>)>
|
||||||
|
{
|
||||||
|
use cookbook::recipes::RecipeCategory;
|
||||||
|
let mut vars_opts = Vec::new();
|
||||||
|
for key in Self::keys().into_iter() {
|
||||||
|
//TODO: is key used ? MealOpts.is_used
|
||||||
|
|
||||||
|
//TODO: Initial values
|
||||||
|
let category_filter: fn(&Value) -> bool = match key {
|
||||||
|
(_, Meal::Breakfast) => |r: &Value| {
|
||||||
|
r.category == RecipeCategory::Breakfast // Breakfast
|
||||||
|
},
|
||||||
|
(_, Meal::Lunch) => |r: &Value| {
|
||||||
|
r.category == RecipeCategory::MainCourse // MainCourse
|
||||||
|
},
|
||||||
|
(_, Meal::Dinner) => |r: &Value| {
|
||||||
|
r.category == RecipeCategory::Starter // Starter
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: has initial ?
|
||||||
|
//let key_name = format!("{}_{:?}", key.0, key.1);
|
||||||
|
let initial = None;
|
||||||
|
vars_opts.push((key, domain.filter(category_filter), initial));
|
||||||
|
}
|
||||||
|
vars_opts
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ edition = "2018"
|
|||||||
rocket = "0.4.0"
|
rocket = "0.4.0"
|
||||||
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
|
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
|
||||||
cookbook = { path = "../cookbook/" }
|
cookbook = { path = "../cookbook/" }
|
||||||
|
planner = { path = "../planner/" }
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
|
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title>Hello Bulma!</title>
|
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="app">
|
|
||||||
<div class="hero hero-body">
|
|
||||||
<h1 class="title">Cook Assistant</h1>
|
|
||||||
<h2 class="subtitle">Recettes</h2>
|
|
||||||
</div>
|
|
||||||
<!-- Details View -->
|
|
||||||
<section v-if="active_view > -1" class="section has-background-grey-lighter">
|
|
||||||
<div class="box">
|
|
||||||
<button @click="closeActiveView" class="button is-pulled-right">X close</button>
|
|
||||||
<h4 class="title">{{ items[active_view].title }}</h4>
|
|
||||||
<h6 class="subtitle">{{ categories[items[active_view].category].name }}</h6>
|
|
||||||
<p><strong>Ingredients : </strong></p>
|
|
||||||
<ul>
|
|
||||||
<li v-for="ing in items[active_view].ingredients.split('\n')">{{ ing }}</li>
|
|
||||||
</ul>
|
|
||||||
<button @click="deleteRecipe(items[active_view].id)" class="button is-danger is-pulled-right">DELETE !</button>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
<!-- Category List View -->
|
|
||||||
<section v-else class="section has-background-grey-lighter">
|
|
||||||
<div class="container">
|
|
||||||
<div v-if="active_category == -1" class="columns">
|
|
||||||
<div v-for="c in categories" :key="c.id" class="column">
|
|
||||||
<button @click="setActiveCategory(c.id)" class="button is-large is-primary has-text-dark">{{ c.name }}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-else class="box">
|
|
||||||
<button @click="setActiveCategory(-1)" class="button is-pulled-left"><< back</button>
|
|
||||||
<h2 class="subtitle">{{ categories[active_category].name }}</h2>
|
|
||||||
<ul>
|
|
||||||
<li v-for="item in displayed" :key="item.id">
|
|
||||||
<a href="" @click.prevent="setActiveView(items.findIndex((i) => i.id ==item.id))">{{ item.title }}</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
<script type="text/javascript">
|
|
||||||
|
|
||||||
// TODO: Must find a viable use of Recipe.id instead of active_view !
|
|
||||||
var app = new Vue({
|
|
||||||
el: '#app',
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
categories: [
|
|
||||||
{id: 0, name: "Petit-déjeuner"},
|
|
||||||
{id: 1, name: "Entrée"},
|
|
||||||
{id: 2, name: "Plat principal"},
|
|
||||||
{id: 3, name: "Dessert"}
|
|
||||||
],
|
|
||||||
active_category: -1,
|
|
||||||
active_view: -1,
|
|
||||||
items: []
|
|
||||||
};
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
setActiveCategory: function(id) {
|
|
||||||
this.active_category = id;
|
|
||||||
},
|
|
||||||
setActiveView: function(idx) {
|
|
||||||
this.active_view = idx;
|
|
||||||
},
|
|
||||||
closeActiveView: function() {
|
|
||||||
this.active_view = -1;
|
|
||||||
},
|
|
||||||
deleteRecipe: function(id) {
|
|
||||||
fetch("/api/delete/" + id)
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => {
|
|
||||||
if (data === true) {
|
|
||||||
this.items.splice(this.active_view, 1);
|
|
||||||
this.closeActiveView();
|
|
||||||
console.log("Deleted :" + data);
|
|
||||||
} else {
|
|
||||||
console.log("Error deleting");
|
|
||||||
}})
|
|
||||||
.catch((err) => console.error(err));
|
|
||||||
},
|
|
||||||
fetchRecipesList: function() {
|
|
||||||
fetch("/api/list")
|
|
||||||
.then((res) => res.json())
|
|
||||||
.then((data) => this.items = data)
|
|
||||||
.catch(function(err) {
|
|
||||||
console.error(err);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
displayed: function() {
|
|
||||||
return this.items.filter(
|
|
||||||
rec => rec.category == this.active_category
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mounted () {
|
|
||||||
this.fetchRecipesList()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</html>
|
|
||||||
@@ -5,8 +5,9 @@
|
|||||||
#[macro_use] extern crate serde_derive;
|
#[macro_use] extern crate serde_derive;
|
||||||
extern crate rocket_cors;
|
extern crate rocket_cors;
|
||||||
extern crate cookbook;
|
extern crate cookbook;
|
||||||
|
extern crate planner;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::{Path, PathBuf};
|
||||||
use rocket::{
|
use rocket::{
|
||||||
response::{NamedFile, status::NotFound},
|
response::{NamedFile, status::NotFound},
|
||||||
http::Method,
|
http::Method,
|
||||||
@@ -15,8 +16,14 @@ use rocket_cors::{AllowedHeaders, AllowedOrigins, Error};
|
|||||||
|
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
fn index() -> Result<NamedFile, NotFound<String>> {
|
fn index() -> Result<NamedFile, NotFound<String>> {
|
||||||
NamedFile::open(&Path::new("./html/index.html"))
|
files(PathBuf::from("index.html"))
|
||||||
.map_err(|_| NotFound(format!("Server error : index not found")))
|
}
|
||||||
|
|
||||||
|
#[get("/<file..>", rank=6)]
|
||||||
|
fn files(file: PathBuf) -> Result<NamedFile, NotFound<String>> {
|
||||||
|
let path = Path::new("vue/dist/").join(file);
|
||||||
|
NamedFile::open(&path)
|
||||||
|
.map_err(|_| NotFound(format!("Bad path: {:?}", path)))
|
||||||
}
|
}
|
||||||
|
|
||||||
mod api {
|
mod api {
|
||||||
@@ -68,6 +75,27 @@ mod api {
|
|||||||
pub fn delete_recipe(conn: CookbookDbConn, id: i32) -> Json<bool> {
|
pub fn delete_recipe(conn: CookbookDbConn, id: i32) -> Json<bool> {
|
||||||
Json( recipes::delete(&conn, id) )
|
Json( recipes::delete(&conn, id) )
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[get("/solver/one")]
|
||||||
|
pub fn one_solution(conn: CookbookDbConn) -> Json<String> {
|
||||||
|
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) {
|
||||||
|
problem = problem.add_variable(var, dom, ini);
|
||||||
|
}
|
||||||
|
let mut problem = problem
|
||||||
|
.add_constraint(|_| true)
|
||||||
|
.finish();
|
||||||
|
let results = problem.solve_all();
|
||||||
|
|
||||||
|
Json(format!("{:?}", results.first().unwrap()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<(), Error> {
|
fn main() -> Result<(), Error> {
|
||||||
@@ -86,8 +114,8 @@ fn main() -> Result<(), Error> {
|
|||||||
|
|
||||||
rocket::ignite()
|
rocket::ignite()
|
||||||
.attach(api::CookbookDbConn::fairing())
|
.attach(api::CookbookDbConn::fairing())
|
||||||
.mount("/", routes![index])
|
.mount("/", routes![index, files])
|
||||||
.mount("/api", routes![api::recipes_list, api::delete_recipe])
|
.mount("/api", routes![api::recipes_list, api::delete_recipe, api::one_solution])
|
||||||
.attach(cors)
|
.attach(cors)
|
||||||
.launch();
|
.launch();
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
<template>
|
<template>
|
||||||
<div id="app">
|
<div id="app">
|
||||||
<section class="section has-background-primary" id="heading">
|
|
||||||
<Heading msg="Cook-Assistant"/>
|
<Heading msg="Cook-Assistant"/>
|
||||||
</section>
|
|
||||||
<section class="section" id="recipes-view">
|
<section class="section" id="recipes-view">
|
||||||
<p v-if="is_loading">Loading...</p>
|
<p v-if="status.loading">Loading...</p>
|
||||||
|
<div v-if="status.error">Error</div>
|
||||||
<h2 v-else class="subtitle">Livre de recettes</h2>
|
<h2 v-else class="subtitle">Livre de recettes</h2>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<keep-alive>
|
<keep-alive>
|
||||||
@@ -19,6 +18,7 @@
|
|||||||
</section>
|
</section>
|
||||||
<section class="section has-background-grey-lighter" id="planner-view">
|
<section class="section has-background-grey-lighter" id="planner-view">
|
||||||
<h2 class="subtitle">Planning</h2>
|
<h2 class="subtitle">Planning</h2>
|
||||||
|
<Planner />
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -28,6 +28,7 @@ import 'bulma/css/bulma.css'
|
|||||||
import Heading from './components/Heading.vue'
|
import Heading from './components/Heading.vue'
|
||||||
import RecipeDetails from './components/RecipeDetails.vue'
|
import RecipeDetails from './components/RecipeDetails.vue'
|
||||||
import RecipeList from './components/RecipeList.vue'
|
import RecipeList from './components/RecipeList.vue'
|
||||||
|
import Planner from './components/Planner.vue'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -37,10 +38,15 @@ export default {
|
|||||||
Heading,
|
Heading,
|
||||||
RecipeDetails,
|
RecipeDetails,
|
||||||
RecipeList,
|
RecipeList,
|
||||||
|
Planner,
|
||||||
},
|
},
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
is_loading: true,
|
status: {
|
||||||
|
loading: true,
|
||||||
|
error: false,
|
||||||
|
error_msg: "",
|
||||||
|
},
|
||||||
items: [],
|
items: [],
|
||||||
// Index of the item
|
// Index of the item
|
||||||
// activated for details view
|
// activated for details view
|
||||||
@@ -71,10 +77,14 @@ export default {
|
|||||||
fetch("http://localhost:8000/api/list")
|
fetch("http://localhost:8000/api/list")
|
||||||
.then((res) => res.json())
|
.then((res) => res.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
|
console.log(data);
|
||||||
this.items = data;
|
this.items = data;
|
||||||
this.is_loading = false;
|
this.status.loading = false;
|
||||||
})
|
})
|
||||||
.catch(function(err) {
|
.catch(function(err) {
|
||||||
|
this.status.loading = false;
|
||||||
|
this.status.error = true;
|
||||||
|
this.statue.error_msg = err;
|
||||||
console.error(err);
|
console.error(err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
25
web/vue/src/components/Planner.vue
Normal file
25
web/vue/src/components/Planner.vue
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<template>
|
||||||
|
<div class="box">
|
||||||
|
<h2 class="subtitle">Week</h2>
|
||||||
|
<button @click="fetchSolution" class="button is-primary">FetchSolution</button>
|
||||||
|
<p>{{ template }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
name: 'Planner',
|
||||||
|
data () {
|
||||||
|
return {
|
||||||
|
template: "",
|
||||||
|
};},
|
||||||
|
methods: {
|
||||||
|
fetchSolution: function() {
|
||||||
|
fetch("http://localhost:8000/api/solver/one")
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => this.template = data)
|
||||||
|
.catch((err) => console.log(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container box">
|
<div class="container box">
|
||||||
<button @click="$emit('close')" class="button is-pulled-right">X close</button>
|
<button @click="$emit('close')" class="button is-pulled-left">Return to list</button>
|
||||||
<h4 class="title">{{ item.title }}</h4>
|
<h4 class="title">{{ item.title }}</h4>
|
||||||
<h6 class="subtitle">{{ categories[item.category].name }}</h6>
|
<h6 class="subtitle">{{ categories[item.category].name }}</h6>
|
||||||
<p><strong>Ingredients : </strong></p>
|
<p><strong>Ingredients : </strong></p>
|
||||||
@@ -15,6 +15,8 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
import _, {categories} from './RecipeList.vue'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'RecipeDetails',
|
name: 'RecipeDetails',
|
||||||
props: {
|
props: {
|
||||||
@@ -28,7 +30,7 @@ export default {
|
|||||||
},
|
},
|
||||||
data () {
|
data () {
|
||||||
return {
|
return {
|
||||||
categories: ["test", "test", "test"],
|
categories: categories,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,16 @@
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<div v-if="active_category == -1" class="columns">
|
<div v-if="active_category == -1" class="columns">
|
||||||
<div v-for="c in categories" :key="c.id" class="column">
|
<div v-for="c in categories" :key="c.id" class="column">
|
||||||
<button @click="setActiveCategory(c.id)" class="button is-large is-primary has-text-dark">{{ c.name }}</button>
|
<button @click="setActiveCategory(c.id)"
|
||||||
|
class="button is-large is-primary has-text-dark button-block">
|
||||||
|
{{ c.name }}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="box">
|
<div v-else class="box">
|
||||||
<button @click="setActiveCategory(-1)" class="button is-pulled-left"><< back</button>
|
<button @click="setActiveCategory(-1)" class="button is-pulled-left">Categories</button>
|
||||||
<h2 class="subtitle">{{ categories[active_category].name }}</h2>
|
<h2 class="subtitle">{{ categories[active_category].name }}</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li v-for="item in displayed" :key="item.id">
|
<li v-for="item in displayed" :key="item.id" class="has-text-left">
|
||||||
<a href=""
|
<a href=""
|
||||||
@click.prevent="$emit(
|
@click.prevent="$emit(
|
||||||
'open-details',
|
'open-details',
|
||||||
@@ -52,3 +54,14 @@ export default {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.button-block {
|
||||||
|
width: 200px;
|
||||||
|
height: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.li {
|
||||||
|
list-style: circle;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
Reference in New Issue
Block a user