Compare commits

...

3 Commits

Author SHA1 Message Date
e2e0cc587e lets stop minor design fixes and get real... 2019-02-12 15:24:07 +01:00
1e91d98581 adds solve_one 2019-02-12 14:15:27 +01:00
8801596de7 adds mdi icons, improves recipe design 2019-02-12 14:07:50 +01:00
11 changed files with 186 additions and 87 deletions

Binary file not shown.

View File

@@ -3,6 +3,7 @@
extern crate planner; extern crate planner;
extern crate cookbook; extern crate cookbook;
use std::time;
use std::fmt::Debug; use std::fmt::Debug;
use std::fmt::Display; use std::fmt::Display;
use std::hash::Hash; use std::hash::Hash;
@@ -30,6 +31,7 @@ fn pretty_output<K: Eq + Hash + Debug>(res: &Variables<Value, K>) -> String {
} }
fn main() { fn main() {
let start_time = time::Instant::now();
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);
@@ -39,5 +41,6 @@ fn main() {
} }
let mut problem = problem.finish(); let mut problem = problem.finish();
let results = problem.solve_all(); let results = problem.solve_all();
println!("{:?}", pretty_output(results.first().unwrap())); println!("Took {:?}", start_time.elapsed());
println!("{}", pretty_output(results.first().unwrap()));
} }

View File

@@ -77,9 +77,10 @@ impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
ProblemBuilder::new() ProblemBuilder::new()
} }
pub fn from_template(_template: i32) -> Problem<'a, V, K> { pub fn from_template() -> Problem<'a, V, K> {
Self::build() let mut builder = Self::build();
.finish()
builder.finish()
} }
/// Returns all possible Updates for next assignements, prepended with /// Returns all possible Updates for next assignements, prepended with
@@ -143,6 +144,39 @@ impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
}; };
solutions solutions
} }
pub fn solve_one(&mut self) -> Option<Variables<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
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<'a, V, K>(Problem<'a, V, K>);

View File

@@ -6,7 +6,6 @@ const DAYS: &[&str] = &[
"Dimanche"]; "Dimanche"];
/// An enum to discriminate every meals /// An enum to discriminate every meals
#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq, Clone, Hash)] #[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum Meal { pub enum Meal {
Breakfast, Breakfast,
@@ -16,7 +15,6 @@ pub enum Meal {
type Key<'a> = (&'a str, &'a Meal); type Key<'a> = (&'a str, &'a Meal);
/// Options set on a meal /// Options set on a meal
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct MealOpts<V> { struct MealOpts<V> {
@@ -50,28 +48,32 @@ impl<'a> Template {
-> Vec<(Key, DomainValues<Value>, Option<&Value>)> -> Vec<(Key, DomainValues<Value>, Option<&Value>)>
{ {
use cookbook::recipes::RecipeCategory; use cookbook::recipes::RecipeCategory;
let mut vars_opts = Vec::new(); Self::keys()
for key in Self::keys().into_iter() { .into_iter()
//TODO: is key used ? MealOpts.is_used .filter(|key| {
match *key {
//TODO: Initial values ("Samedi", _) | ("Dimanche", _) => true,
let category_filter: fn(&Value) -> bool = match key { (_, Meal::Breakfast) => false,
(_, Meal::Breakfast) => |r: &Value| { (_,_) => true,
r.category == RecipeCategory::Breakfast // Breakfast
},
(_, Meal::Lunch) => |r: &Value| {
r.category == RecipeCategory::MainCourse // MainCourse
},
(_, Meal::Dinner) => |r: &Value| {
r.category == RecipeCategory::Starter // Starter
} }
}; })
.map(|key| {
// TODO: has initial ? //TODO: is key used ? MealOpts.is_used
//let key_name = format!("{}_{:?}", key.0, key.1); let category_filter: fn(&Value) -> bool = match key {
let initial = None; (_, Meal::Breakfast) => |r: &Value| {
vars_opts.push((key, domain.filter(category_filter), initial)); r.category == RecipeCategory::Breakfast // Breakfast
} },
vars_opts (_, Meal::Lunch) => |r: &Value| {
r.category == RecipeCategory::MainCourse // MainCourse
},
(_, Meal::Dinner) => |r: &Value| {
r.category == RecipeCategory::Starter // Starter
}
};
// TODO: has initial ?
let initial = None;
(key, domain.filter(category_filter), initial)
})
.collect()
} }
} }

View File

@@ -103,19 +103,20 @@ mod api {
let mut problem = problem let mut problem = problem
.add_constraint(|_| true) .add_constraint(|_| true)
.finish(); .finish();
let results = problem.solve_all(); if let Some(one_result) = problem.solve_one() {
let one_result = results.first().unwrap(); Json(TemplateObject {
items: one_result
Json(TemplateObject { .into_iter()
items: one_result .map(|(k,v)| {
.into_iter() TemplateItems {
.map(|(k,v)| { key: (format!("{}", k.0), format!("{:?}", k.1)),
TemplateItems { value: v.map(|r| RecipeObject::from(&conn, r.clone())),
key: (format!("{}", k.0), format!("{:?}", k.1)), }})
value: v.map(|r| RecipeObject::from(&conn, r.clone())), .collect(),
}}) })
.collect(), } else {
}) panic!("No solution at all !");
}
} }
} }

View File

@@ -8,6 +8,7 @@
"lint": "vue-cli-service lint" "lint": "vue-cli-service lint"
}, },
"dependencies": { "dependencies": {
"@mdi/font": "^3.4.93",
"bulma": "^0.7.2", "bulma": "^0.7.2",
"vue": "^2.5.22" "vue": "^2.5.22"
}, },

View File

@@ -2,14 +2,14 @@
<div id="app"> <div id="app">
<Heading msg="Cook-Assistant"/> <Heading msg="Cook-Assistant"/>
<section class="section" id="recipes-view"> <section class="section" id="recipes-view">
<p v-if="status.loading">Loading...</p> <div v-if="status.loading" class="notification is-info">Loading...</div>
<div v-if="status.error" class="notification is-danger">Error: {{ status.error_msg }}</div> <div v-if="status.error" class="notification is-danger">Error: {{ status.error_msg }}</div>
<h2 v-else class="subtitle">Livre de recettes</h2>
<div class="container"> <div class="container">
<keep-alive> <keep-alive>
<RecipeDetails v-if="active_view > -1" <RecipeDetails v-if="active_view > -1"
v-bind:item="items[active_view]" v-bind:item="items[active_view]"
v-on:close="closeActiveView" /> v-on:close="closeActiveView"
v-on:add="addToPlanning" />
<RecipeList v-else <RecipeList v-else
v-bind:items="items" v-bind:items="items"
v-on:open-details="setActiveView" /> v-on:open-details="setActiveView" />
@@ -18,13 +18,14 @@
</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 /> <Planner ref="weekPlanning" />
</section> </section>
</div> </div>
</template> </template>
<script> <script>
import 'bulma/css/bulma.css' import 'bulma/css/bulma.css'
import '@mdi/font/css/materialdesignicons.min.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'
@@ -59,6 +60,11 @@ export default {
closeActiveView: function() { closeActiveView: function() {
this.active_view = -1; this.active_view = -1;
}, },
addToPlanning: function(idx) {
let mealKey = ["Lundi", "Lunch"];
let mealData = this.items[idx];
this.$refs.weekPlanning.setMeal(mealKey, mealData);
},
deleteRecipe: function(id) { deleteRecipe: function(id) {
fetch("http://localhost:8000/api/delete/" + id) fetch("http://localhost:8000/api/delete/" + id)
.then((res) => res.json()) .then((res) => res.json())
@@ -86,10 +92,14 @@ export default {
this.statue.error_msg = err; this.statue.error_msg = err;
console.error(err); console.error(err);
}); });
},
initWeekPlanning: function() {
this.$refs.weekPlanning.fetchSolution();
} }
}, },
mounted () { mounted () {
this.fetchRecipesList(); this.fetchRecipesList();
this.initWeekPlanning();
} }
} }
</script> </script>

View File

@@ -1,5 +1,5 @@
<template> <template>
<nav class="navbar" role="navigation" aria-label="main navigation"> <nav class="navbar is-dark" role="navigation" aria-label="main navigation">
<div class="navbar-brand"> <div class="navbar-brand">
<a class="navbar-item" href="#"> <a class="navbar-item" href="#">
{{ msg }} {{ msg }}

View File

@@ -1,18 +1,21 @@
<template> <template>
<div class="box"> <div class="box">
<button @click="fetchSolution" class="button is-primary">FetchSolution</button> <button @click="fetchSolution"
<hr /> class="button is-primary is-fullwidth"
v-bind:class="{'is-loading': is_loading }">
FetchSolution</button>
<div v-if="template"> <div v-if="template">
<div class="columns is-desktop is-vcentered"> <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"> class="column is-one-quarter-desktop is-half-mobile">
<strong> {{ day_meals[0] }}</strong> <p class="subtitle"><strong> {{ day_meals[0] }}</strong></p>
<div v-for="meal in day_meals[1]"> <div v-for="meal in day_meals[1]">
<div v-if="meal.value" class="tags has-addons"> <p v-if="meal.value" class="tags has-addons">
<span class="tag is-info">{{ meal.value.title }}</span> <span class="tag is-info">{{ meal.key[1] }}</span>
<span class="tag is-light">{{ meal.value.title }}</span>
<a @click="unsetMeal(meal.key)" <a @click="unsetMeal(meal.key)"
class="tag is-delete"></a> class="tag is-delete"></a>
</div> </p>
<div v-else class="tag is-warning">Empty</div> <div v-else class="tag is-warning">Empty</div>
</div> </div>
</div> </div>
@@ -52,11 +55,16 @@ export default {
data () { data () {
return { return {
template: null, template: null,
is_loading: false,
};}, };},
methods: { methods: {
fetchSolution: function() { fetchSolution: function() {
this.is_loading = true;
fetch("http://localhost:8000/api/solver/one") fetch("http://localhost:8000/api/solver/one")
.then((res) => res.json()) .then((res) => {
this.is_loading = false;
return res.json();}
)
.then((data) => this.template = data) .then((data) => this.template = data)
.catch((err) => console.log(err)); .catch((err) => console.log(err));
}, },
@@ -66,6 +74,15 @@ export default {
return item.key == mealKey; return item.key == mealKey;
}); });
this.template.items[idx].value = null; this.template.items[idx].value = null;
//console.log("vm" + this.vm.items);
},
setMeal: function(mealKey, mealData) {
let idx = this.template.items.findIndex((item) => {
return (item.key[0] == mealKey[0]
&& item.key[1] == mealKey[1]);
});
console.log(idx)
this.template.items[idx].value = mealData;
} }
}, },
computed: { computed: {

View File

@@ -1,16 +1,35 @@
<template> <template>
<div class="container box"> <div class="columns">
<button @click="$emit('close')" class="button is-pulled-left">Return to list</button> <div class="column is-narrow">
<h4 class="title">{{ item.title }}</h4> <a @click="$emit('close')"
<h6 class="subtitle">{{ categories[item.category].name }}</h6> class="has-text-dark">
<p><strong>Ingredients : </strong></p> <span class="icon is-large">
<ul> <i class="mdi mdi-48px mdi-view-list"></i>
<li v-for="ing in item.ingredients.split('\n')">{{ ing }}</li> </span>
</ul> </a>
<button @click="$emit('delete', item.id)" <br class="is-hidden-mobile"/>
class="button is-danger is-pulled-right"> <a @click="$emit('add', item.id)"
DELETE ! class="has-text-success">
</button> <span class="icon is-large">
<i class="mdi mdi-36px mdi-table-plus"></i>
</span>
</a>
</div>
<div class="column">
<h4 class="title">{{ item.title }}</h4>
<h6 class="subtitle">{{ categories[item.category].name }}</h6>
<p><strong>Ingredients</strong></p>
<ul>
<li v-for="ing in item.ingredients.split('\n')">{{ ing }}</li>
</ul>
</div>
<div class="column is-narrow">
<a @click="$emit('delete', item.id)">
<span class="icon is-large has-text-danger">
<i class="mdi mdi-48px mdi-delete-forever"></i>
</span>
</a>
</div>
</div> </div>
</template> </template>

View File

@@ -3,34 +3,47 @@
<div v-if="active_category == -1" class="columns is-multiline is-mobile"> <div v-if="active_category == -1" class="columns is-multiline is-mobile">
<div v-for="c in categories" :key="c.id" class="column is-one-quarter-desktop is-half-tablet"> <div v-for="c in categories" :key="c.id" class="column is-one-quarter-desktop is-half-tablet">
<button @click="setActiveCategory(c.id)" <button @click="setActiveCategory(c.id)"
class="button is-large is-primary has-text-dark button-block"> class="button is-large is-info is-fullwidth button-block">
{{ c.name }}</button> <span class="icon is-large">
<i class="mdi mdi-24px" v-bind:class="c.icon"></i>
</span>
<br />
<p>{{ c.name }}</p></button>
</div> </div>
</div> </div>
<div v-else class="box"> <div v-else class="columns">
<button @click="setActiveCategory(-1)" class="button is-pulled-left">Categories</button> <div class="column is-narrow">
<h2 class="subtitle">{{ categories[active_category].name }}</h2> <a @click="setActiveCategory(-1)" class="has-text-dark">
<ul> <span class="icon is-large" >
<li v-for="item in displayed" :key="item.id" class="has-text-left"> <i class="mdi mdi-48px mdi-view-grid"></i>
<a href="" </span>
@click.prevent="$emit( </a>
'open-details', </div>
items.findIndex((i) => i.id ==item.id))"> <div class="column">
{{ item.title }}</a> <h2 class="title">{{ categories[active_category].name }}</h2>
</li> <ul class="content">
</ul> <li v-for="item in displayed" :key="item.id" class="has-text-left">
<a href=""
@click.prevent="$emit(
'open-details',
items.findIndex((i) => i.id ==item.id))">
{{ item.title }}</a>
</li>
</ul>
</div>
</div> </div>
</div> </div>
</template> </template>
<script> <script>
export const categories = [ export const categories = [
{id: 0, name: "Petit-déjeuner"}, {id: 0, name: "Petit-déjeuner", icon: "mdi-food-croissant"},
{id: 1, name: "Entrée"}, {id: 1, name: "Entrée", icon: "mdi-bowl"},
{id: 2, name: "Plat principal"}, {id: 2, name: "Plat principal", icon: "mdi-food"},
{id: 3, name: "Dessert"} {id: 3, name: "Dessert", icon: "mdi-cupcake"}
]; ];
export default { export default {
name: 'RecipeList', name: 'RecipeList',
props: ["items"], props: ["items"],
@@ -57,8 +70,7 @@ export default {
<style scoped> <style scoped>
.button-block { .button-block {
width: 200px; min-height: 150px;
height: 200px;
} }
.li { .li {