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 cookbook;
use std::time;
use std::fmt::Debug;
use std::fmt::Display;
use std::hash::Hash;
@@ -30,6 +31,7 @@ fn pretty_output<K: Eq + Hash + Debug>(res: &Variables<Value, K>) -> String {
}
fn main() {
let start_time = time::Instant::now();
let conn = establish_connection();
let possible_values = recipes::load_all(&conn);
let domain = Domain::new(possible_values);
@@ -39,5 +41,6 @@ fn main() {
}
let mut problem = problem.finish();
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()
}
pub fn from_template(_template: i32) -> Problem<'a, V, K> {
Self::build()
.finish()
pub fn from_template() -> Problem<'a, V, K> {
let mut builder = Self::build();
builder.finish()
}
/// 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
}
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>);

View File

@@ -6,7 +6,6 @@ const DAYS: &[&str] = &[
"Dimanche"];
/// An enum to discriminate every meals
#[allow(dead_code)]
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum Meal {
Breakfast,
@@ -16,7 +15,6 @@ pub enum Meal {
type Key<'a> = (&'a str, &'a Meal);
/// Options set on a meal
#[derive(Debug, Default)]
struct MealOpts<V> {
@@ -50,28 +48,32 @@ impl<'a> Template {
-> 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
Self::keys()
.into_iter()
.filter(|key| {
match *key {
("Samedi", _) | ("Dimanche", _) => true,
(_, Meal::Breakfast) => false,
(_,_) => true,
}
};
// 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
})
.map(|key| {
//TODO: is key used ? MealOpts.is_used
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 initial = None;
(key, domain.filter(category_filter), initial)
})
.collect()
}
}

View File

@@ -103,19 +103,20 @@ mod api {
let mut problem = problem
.add_constraint(|_| true)
.finish();
let results = problem.solve_all();
let one_result = results.first().unwrap();
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(),
})
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 !");
}
}
}

View File

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

View File

@@ -2,14 +2,14 @@
<div id="app">
<Heading msg="Cook-Assistant"/>
<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>
<h2 v-else class="subtitle">Livre de recettes</h2>
<div class="container">
<keep-alive>
<RecipeDetails v-if="active_view > -1"
v-bind:item="items[active_view]"
v-on:close="closeActiveView" />
v-on:close="closeActiveView"
v-on:add="addToPlanning" />
<RecipeList v-else
v-bind:items="items"
v-on:open-details="setActiveView" />
@@ -18,13 +18,14 @@
</section>
<section class="section has-background-grey-lighter" id="planner-view">
<h2 class="subtitle">Planning</h2>
<Planner />
<Planner ref="weekPlanning" />
</section>
</div>
</template>
<script>
import 'bulma/css/bulma.css'
import '@mdi/font/css/materialdesignicons.min.css'
import Heading from './components/Heading.vue'
import RecipeDetails from './components/RecipeDetails.vue'
import RecipeList from './components/RecipeList.vue'
@@ -59,6 +60,11 @@ export default {
closeActiveView: function() {
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) {
fetch("http://localhost:8000/api/delete/" + id)
.then((res) => res.json())
@@ -86,10 +92,14 @@ export default {
this.statue.error_msg = err;
console.error(err);
});
},
initWeekPlanning: function() {
this.$refs.weekPlanning.fetchSolution();
}
},
mounted () {
this.fetchRecipesList();
this.initWeekPlanning();
}
}
</script>

View File

@@ -1,5 +1,5 @@
<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">
<a class="navbar-item" href="#">
{{ msg }}

View File

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

View File

@@ -1,16 +1,35 @@
<template>
<div class="container box">
<button @click="$emit('close')" class="button is-pulled-left">Return to list</button>
<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>
<button @click="$emit('delete', item.id)"
class="button is-danger is-pulled-right">
DELETE !
</button>
<div class="columns">
<div class="column is-narrow">
<a @click="$emit('close')"
class="has-text-dark">
<span class="icon is-large">
<i class="mdi mdi-48px mdi-view-list"></i>
</span>
</a>
<br class="is-hidden-mobile"/>
<a @click="$emit('add', item.id)"
class="has-text-success">
<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>
</template>

View File

@@ -3,34 +3,47 @@
<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">
<button @click="setActiveCategory(c.id)"
class="button is-large is-primary has-text-dark button-block">
{{ c.name }}</button>
class="button is-large is-info is-fullwidth button-block">
<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 v-else class="box">
<button @click="setActiveCategory(-1)" class="button is-pulled-left">Categories</button>
<h2 class="subtitle">{{ categories[active_category].name }}</h2>
<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 v-else class="columns">
<div class="column is-narrow">
<a @click="setActiveCategory(-1)" class="has-text-dark">
<span class="icon is-large" >
<i class="mdi mdi-48px mdi-view-grid"></i>
</span>
</a>
</div>
<div class="column">
<h2 class="title">{{ categories[active_category].name }}</h2>
<ul class="content">
<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>
</template>
<script>
export const categories = [
{id: 0, name: "Petit-déjeuner"},
{id: 1, name: "Entrée"},
{id: 2, name: "Plat principal"},
{id: 3, name: "Dessert"}
{id: 0, name: "Petit-déjeuner", icon: "mdi-food-croissant"},
{id: 1, name: "Entrée", icon: "mdi-bowl"},
{id: 2, name: "Plat principal", icon: "mdi-food"},
{id: 3, name: "Dessert", icon: "mdi-cupcake"}
];
export default {
name: 'RecipeList',
props: ["items"],
@@ -57,8 +70,7 @@ export default {
<style scoped>
.button-block {
width: 200px;
height: 200px;
min-height: 150px;
}
.li {