Compare commits
17 Commits
planning
...
28afe8ece0
| Author | SHA1 | Date | |
|---|---|---|---|
| 28afe8ece0 | |||
| a7cc92f903 | |||
| 46532eee9e | |||
| ee3271f772 | |||
| 616f8095e2 | |||
| 66514eb192 | |||
| 1d091bd419 | |||
| d4454e7f16 | |||
| 253045c742 | |||
| 5e92e30f51 | |||
| 874a9f86f8 | |||
| 4576ffb03b | |||
| 202d7c5976 | |||
| fb4d24ef44 | |||
| 940927d376 | |||
| 14f604283c | |||
| f7ba3ed3a6 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -12,3 +12,7 @@
|
||||
**/target
|
||||
**/*.rs.bk
|
||||
**/Cargo.lock
|
||||
|
||||
# Node.js
|
||||
**/node_modules
|
||||
**/package-lock.json
|
||||
|
||||
14
Cargo.toml
14
Cargo.toml
@@ -1,9 +1,7 @@
|
||||
[package]
|
||||
name = "CookAssistant"
|
||||
version = "0.1.0"
|
||||
authors = ["artus <artus@landoftheunicorn.hd.free.fr>"]
|
||||
edition = "2018"
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
cookbook = { path = "cookbook/" }
|
||||
planner = { path = "planner/" }
|
||||
members = [
|
||||
"cookbook",
|
||||
"planner",
|
||||
"web",
|
||||
]
|
||||
|
||||
1
cookbook/.env
Normal file
1
cookbook/.env
Normal file
@@ -0,0 +1 @@
|
||||
DATABASE_URL=db.sqlite3
|
||||
@@ -5,3 +5,6 @@ authors = ["artus <artus@landoftheunicorn.hd.free.fr>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
libsqlite3-sys = { version = "*", features = ["bundled"] }
|
||||
diesel = { version = "1.4.1", features = ["sqlite"] }
|
||||
dotenv = "0.9.0"
|
||||
|
||||
BIN
cookbook/db.sqlite3
Normal file
BIN
cookbook/db.sqlite3
Normal file
Binary file not shown.
5
cookbook/diesel.toml
Normal file
5
cookbook/diesel.toml
Normal file
@@ -0,0 +1,5 @@
|
||||
# For documentation on how to configure this file,
|
||||
# see diesel.rs/guides/configuring-diesel-cli
|
||||
|
||||
[print_schema]
|
||||
file = "src/schema.rs"
|
||||
0
cookbook/migrations/.gitkeep
Normal file
0
cookbook/migrations/.gitkeep
Normal file
@@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE recipes
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Your SQL goes here
|
||||
CREATE TABLE recipes (
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
title VARCHAR NOT NULL,
|
||||
category INTEGER NOT NULL,
|
||||
ingredients TEXT NOT NULL,
|
||||
preparation TEXT NOT NULL
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE ingredients
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Your SQL goes here
|
||||
CREATE TABLE ingredients (
|
||||
id INTEGER PRIMARY KEY NOT NULL,
|
||||
alias VARCHAR NOT NULL
|
||||
)
|
||||
18
cookbook/src/bin/show_recipes.rs
Normal file
18
cookbook/src/bin/show_recipes.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
extern crate cookbook;
|
||||
extern crate diesel;
|
||||
|
||||
use self::cookbook::*;
|
||||
use self::models::*;
|
||||
use self::diesel::prelude::*;
|
||||
|
||||
fn main() {
|
||||
|
||||
let conn = establish_connection();
|
||||
let result = recipes::load_all(&conn);
|
||||
println!("Here are {} recipes [{}]:", result.len(), result.len() * std::mem::size_of::<Recipe>());
|
||||
for rec in result {
|
||||
println!("*************\n{}\n({:?})", rec.title, rec.category);
|
||||
println!("-------------\n");
|
||||
println!("{}", rec.ingredients);
|
||||
}
|
||||
}
|
||||
100
cookbook/src/bin/write_recipe.rs
Normal file
100
cookbook/src/bin/write_recipe.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
extern crate cookbook;
|
||||
extern crate diesel;
|
||||
|
||||
use std::io::{Read, stdin};
|
||||
use diesel::SqliteConnection;
|
||||
use self::cookbook::*;
|
||||
use self::models::{NewRecipe, fields::RecipeCategory};
|
||||
|
||||
struct CreateRecipe<'a> {
|
||||
connection: &'a SqliteConnection,
|
||||
title: &'a str,
|
||||
category: Option<RecipeCategory>,
|
||||
ingredients: String,
|
||||
}
|
||||
|
||||
impl<'a> CreateRecipe<'a> {
|
||||
fn new(conn: &'a SqliteConnection) -> Self {
|
||||
CreateRecipe{
|
||||
connection: conn,
|
||||
title: "New recipe",
|
||||
category: None,
|
||||
ingredients: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_title(&mut self, title: &'a str) {
|
||||
self.title = title;
|
||||
}
|
||||
|
||||
fn set_category(&mut self, id: i16) {
|
||||
self.category = RecipeCategory::from_id(id);
|
||||
}
|
||||
|
||||
fn add_ingredient(&mut self, name: String) {
|
||||
use crate::ingredients::*;
|
||||
|
||||
// Check it exists or create
|
||||
if let Some(_ingdt) = find(self.connection, &name) {
|
||||
println!("=");
|
||||
} else {
|
||||
create(self.connection, &name);
|
||||
println!("+{}", &name);
|
||||
}
|
||||
|
||||
self.ingredients.push_str(&name);
|
||||
}
|
||||
|
||||
/// Builds a NewRecipe instance from current data and insert it.
|
||||
fn insert(self) {
|
||||
let new_recipe = NewRecipe::new(
|
||||
self.title,
|
||||
self.category.unwrap_or(RecipeCategory::Breakfast),
|
||||
&self.ingredients,
|
||||
"");
|
||||
match new_recipe.insert(self.connection) {
|
||||
Ok(new) => println!("Added {}", new.title),
|
||||
Err(e) => println!("Error: {}", e),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
let conn = establish_connection();
|
||||
let mut builder = CreateRecipe::new(&conn);
|
||||
|
||||
println!("Title : ");
|
||||
let mut title = String::new();
|
||||
stdin().read_line(&mut title).unwrap();
|
||||
let title = &title[..(title.len() - 1)];
|
||||
builder.set_title(title);
|
||||
|
||||
println!("Category : ");
|
||||
for cat in &RecipeCategory::all() {
|
||||
println!("{} - {}", cat.id(), cat.name());
|
||||
}
|
||||
let mut category_id = String::new();
|
||||
stdin().read_line(&mut category_id).unwrap();
|
||||
let category_id = category_id.trim().parse::<i16>().unwrap_or(0);
|
||||
builder.set_category(category_id);
|
||||
|
||||
println!("Ingredients (empty line to finish): ");
|
||||
loop {
|
||||
let mut ingdts = String::new();
|
||||
stdin().read_line(&mut ingdts).unwrap();
|
||||
if &ingdts == "\r\n" {
|
||||
break;
|
||||
}
|
||||
builder.add_ingredient(ingdts);
|
||||
}
|
||||
|
||||
builder.insert();
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(windows))]
|
||||
const EOF: &'static str = "CTRL+D";
|
||||
|
||||
#[cfg(windows)]
|
||||
const EOF: &'static str = "CTRL+Z";
|
||||
@@ -1,16 +1,77 @@
|
||||
mod meal;
|
||||
mod storage;
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
extern crate dotenv;
|
||||
|
||||
pub mod schema;
|
||||
pub mod models;
|
||||
|
||||
mod importer;
|
||||
|
||||
pub use self::meal::Meal;
|
||||
use diesel::prelude::*;
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
|
||||
pub fn fetch_meals() -> Vec<Meal> {
|
||||
vec![
|
||||
Meal::new("Raclette".to_string(), 800),
|
||||
Meal::new("Soupe".to_string(), 400),
|
||||
]
|
||||
pub fn establish_connection() -> SqliteConnection {
|
||||
dotenv().ok();
|
||||
|
||||
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set !");
|
||||
SqliteConnection::establish(&db_url)
|
||||
.expect(&format!("Error connecting to {}", db_url))
|
||||
}
|
||||
|
||||
pub mod recipes {
|
||||
use crate::models::{Recipe};
|
||||
use super::{SqliteConnection, schema};
|
||||
use super::diesel::prelude::*;
|
||||
|
||||
/// Loads all recipes from database
|
||||
pub fn load_all(conn: &SqliteConnection) -> Vec<Recipe> {
|
||||
use self::schema::recipes::dsl::*;
|
||||
recipes.load::<Recipe>(conn)
|
||||
.expect("Error loading recipe's list")
|
||||
}
|
||||
|
||||
pub fn delete(conn: &SqliteConnection, recipe_id: i32) -> bool {
|
||||
use self::schema::recipes::dsl::*;
|
||||
|
||||
diesel::delete(recipes.filter(id.eq(recipe_id)))
|
||||
.execute(conn)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub mod ingredients {
|
||||
use crate::models::{Ingredient, NewIngredient};
|
||||
use super::{SqliteConnection, schema};
|
||||
use super::diesel::prelude::*;
|
||||
|
||||
pub fn find(conn: &SqliteConnection, name: &str) -> Option<Ingredient> {
|
||||
use self::schema::ingredients::dsl::*;
|
||||
|
||||
let results = ingredients.filter(alias.like(name))
|
||||
.limit(1)
|
||||
.load::<Ingredient>(conn)
|
||||
.expect("Error finding ingredient");
|
||||
|
||||
if !results.is_empty() {
|
||||
Some(results.into_iter().nth(0).unwrap())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create(conn: &SqliteConnection, name: &str) -> usize {
|
||||
use self::schema::ingredients;
|
||||
|
||||
diesel::insert_into(ingredients::table)
|
||||
.values(&NewIngredient { alias: name })
|
||||
.execute(conn)
|
||||
.expect("Error inserting ingredient")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
|
||||
/// An individual ingredient
|
||||
pub struct Ingredient {
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Ingredient {
|
||||
|
||||
pub(super) fn new(name: String) -> Ingredient {
|
||||
Ingredient { name }
|
||||
}
|
||||
}
|
||||
|
||||
/// An ordered set of dishes
|
||||
#[derive(Debug,Clone)]
|
||||
pub struct Meal {
|
||||
name: String,
|
||||
nutritional_value: i32,
|
||||
}
|
||||
|
||||
impl Meal {
|
||||
pub(super) fn new(name: String, nutritional_value: i32) -> Meal {
|
||||
Meal { name, nutritional_value }
|
||||
}
|
||||
|
||||
pub fn nutritional_value(&self) -> i32 {
|
||||
self.nutritional_value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
129
cookbook/src/models.rs
Normal file
129
cookbook/src/models.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use super::schema::recipes;
|
||||
use super::schema::ingredients;
|
||||
use super::diesel::prelude::*;
|
||||
|
||||
pub mod fields {
|
||||
use diesel::{
|
||||
backend::Backend,
|
||||
sql_types::*,
|
||||
deserialize::{self, FromSql},
|
||||
serialize::{self, Output, ToSql},
|
||||
};
|
||||
use std::io::Write;
|
||||
|
||||
/// All recipes have a single associated category
|
||||
/// representing the main use of the resulting preparation.
|
||||
///
|
||||
/// It is stored as Integer
|
||||
#[derive(Debug, Copy, Clone, FromSqlRow, AsExpression)]
|
||||
#[sql_type = "SmallInt"]
|
||||
pub enum RecipeCategory {
|
||||
Breakfast = 0,
|
||||
Starter = 1,
|
||||
MainCourse = 2,
|
||||
Dessert = 3
|
||||
}
|
||||
|
||||
impl RecipeCategory {
|
||||
pub fn id(&self) -> i16 {
|
||||
*self as i16
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
match *self {
|
||||
RecipeCategory::Breakfast => "Petit-déjeuner",
|
||||
RecipeCategory::Starter => "Entrée",
|
||||
RecipeCategory::MainCourse => "Plat principal",
|
||||
RecipeCategory::Dessert => "Dessert"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all() -> [Self; 4] {
|
||||
[RecipeCategory::Breakfast,
|
||||
RecipeCategory::Starter,
|
||||
RecipeCategory::MainCourse,
|
||||
RecipeCategory::Dessert]
|
||||
}
|
||||
|
||||
pub fn from_id(id: i16) -> Option<RecipeCategory> {
|
||||
match id {
|
||||
0 => Some(RecipeCategory::Breakfast),
|
||||
1 => Some(RecipeCategory::Starter),
|
||||
2 => Some(RecipeCategory::MainCourse),
|
||||
3 => Some(RecipeCategory::Dessert),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<DB: Backend> FromSql<SmallInt, DB> for RecipeCategory
|
||||
where
|
||||
i16: FromSql<SmallInt, DB>
|
||||
{
|
||||
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
|
||||
let v = i16::from_sql(bytes)?;
|
||||
if let Some(result) = RecipeCategory::from_id(v){ Ok(result) }
|
||||
else { Err("Invalid RecipeCategory id".into()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<DB: Backend> ToSql<SmallInt, DB> for RecipeCategory
|
||||
where
|
||||
i16: ToSql<SmallInt, DB>{
|
||||
fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
|
||||
i16::to_sql(&(*self as i16), out)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Data for a recipe stored in DB
|
||||
#[derive(Debug, Clone, Queryable)]
|
||||
pub struct Recipe {
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub category: fields::RecipeCategory,
|
||||
pub ingredients: String,
|
||||
pub preparation: String,
|
||||
}
|
||||
|
||||
#[derive(Insertable, Debug)]
|
||||
#[table_name="recipes"]
|
||||
pub struct NewRecipe<'a> {
|
||||
pub title: &'a str,
|
||||
pub category: fields::RecipeCategory,
|
||||
pub ingredients: &'a str,
|
||||
pub preparation: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> NewRecipe<'a> {
|
||||
pub fn new(title: &'a str, category: fields::RecipeCategory, ingredients: &'a str, preparation: &'a str) -> Self {
|
||||
NewRecipe{
|
||||
title,
|
||||
category,
|
||||
ingredients,
|
||||
preparation,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(self, conn: &SqliteConnection) -> Result<Self, String> {
|
||||
diesel::insert_into(recipes::table)
|
||||
.values(&self)
|
||||
.execute(conn)
|
||||
.expect("Error inserting recipe");
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Queryable)]
|
||||
pub struct Ingredient {
|
||||
pub id: i32,
|
||||
pub alias: String,
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name="ingredients"]
|
||||
pub struct NewIngredient<'a> {
|
||||
pub alias: &'a str,
|
||||
}
|
||||
21
cookbook/src/schema.rs
Normal file
21
cookbook/src/schema.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
table! {
|
||||
ingredients (id) {
|
||||
id -> Integer,
|
||||
alias -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
table! {
|
||||
recipes (id) {
|
||||
id -> Integer,
|
||||
title -> Text,
|
||||
category -> SmallInt,
|
||||
ingredients -> Text,
|
||||
preparation -> Text,
|
||||
}
|
||||
}
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
ingredients,
|
||||
recipes,
|
||||
);
|
||||
@@ -1,20 +0,0 @@
|
||||
//! Storage backend for persistent data
|
||||
//!
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// An entry in the storage
|
||||
struct Entry<T>(T);
|
||||
|
||||
/// A storage container
|
||||
pub struct Storage<T> {
|
||||
content: HashMap<String, Entry<T>>,
|
||||
}
|
||||
|
||||
impl<T> Storage<T> {
|
||||
pub(super) fn insert(&mut self, item: T) -> Result<(), ()> {
|
||||
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
1
planner/.env
Normal file
1
planner/.env
Normal file
@@ -0,0 +1 @@
|
||||
DATABASE_URL=../cookbook/db.sqlite3
|
||||
@@ -1,44 +1,80 @@
|
||||
//! The weekly menu planner
|
||||
//!
|
||||
extern crate cookbook;
|
||||
extern crate planner;
|
||||
|
||||
use cookbook::{Meal, fetch_meals};
|
||||
use planner::solver::{Variables, Domain, solve_all};
|
||||
use self::cookbook::*;
|
||||
use self::cookbook::models::Recipe;
|
||||
use self::planner::solver::{Variables, Domain, Problem};
|
||||
|
||||
/// We want a mapping of the week meals (matin, midi, soir)
|
||||
/// Breakfast => RecipeCategory::Breakfast
|
||||
/// Lunch => RecipeCategory::MainCourse
|
||||
/// Dinner => RecipeCategory::MainCourse
|
||||
type Day = String;
|
||||
const DAYS: &[&str] = &["Lundi", "Mardi", "Mercredi"];
|
||||
|
||||
fn generate_weekly_menu() -> String {
|
||||
let assignments: Variables<Meal> = [
|
||||
("LundiMidi".to_string(), None), ("LundiSoir".to_string(), None),
|
||||
("MardiMidi".to_string(), None), ("MardiSoir".to_string(), None),
|
||||
("MercrediMidi".to_string(), None), ("MercrediSoir".to_string(), None),
|
||||
].iter().cloned().collect();
|
||||
let meals: Domain<Meal> = Domain::new(fetch_meals());
|
||||
let validator = |vars: &Variables<Meal>| {
|
||||
let mut result = true;
|
||||
for day in ["Lundi", "Mardi", "Mercredi"].into_iter() {
|
||||
let all_day = vars.keys().filter(|k| k.starts_with(day));
|
||||
let mut nutri_value = 0;
|
||||
for key in all_day {
|
||||
nutri_value += vars.get(key)
|
||||
.expect("no value here !")
|
||||
.expect("no meal there !")
|
||||
.nutritional_value()
|
||||
enum Meals {
|
||||
Breakfast(Day),
|
||||
Lunch(Day),
|
||||
Dinner(Day)
|
||||
}
|
||||
println!("{} -> {}", day, nutri_value);
|
||||
if nutri_value != 1200 { result = false; };
|
||||
|
||||
impl Into<String> for Meals {
|
||||
fn into(self) -> String {
|
||||
match self {
|
||||
Meals::Breakfast(d) => format!("{}_Breakfast", d),
|
||||
Meals::Lunch(d) => format!("{}_Lunch", d),
|
||||
Meals::Dinner(d) => format!("{}_Dinner", d),
|
||||
}
|
||||
println!("Validator returns {}", result);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// It may also contains an initial value for each variable
|
||||
fn generate_variables<V>(domain: &Domain<V>) -> Vec<(String, &Domain<V>, Option<&V>)> {
|
||||
let mut vars = Vec::new();
|
||||
for day in DAYS {
|
||||
vars.push((Meals::Lunch(day.to_string()).into(), domain, None));
|
||||
vars.push((Meals::Dinner(day.to_string()).into(), domain, None));
|
||||
}
|
||||
vars
|
||||
}
|
||||
|
||||
fn ingredients_contains<'a>(assign: &Variables<'a,Recipe>) -> bool {
|
||||
assign.get("Lundi_Lunch").unwrap().unwrap().ingredients.contains("Patates")
|
||||
&& !assign.get("Mardi_Lunch").unwrap().unwrap().ingredients.contains("Patates")
|
||||
}
|
||||
|
||||
|
||||
fn pretty_output(res: &Variables<Recipe>) -> String {
|
||||
let mut repr = String::new();
|
||||
for (var,value) in res {
|
||||
let value = match value {
|
||||
Some(rec) => &rec.title,
|
||||
None => "---",
|
||||
};
|
||||
repr.push_str(&format!("{} => {}\n", var, value));
|
||||
}
|
||||
repr
|
||||
}
|
||||
|
||||
let solutions = solve_all(assignments, &meals, validator);
|
||||
format!("{:#?}", solutions)
|
||||
fn get_planning_all_results() -> String {
|
||||
let conn = establish_connection();
|
||||
let possible_values = recipes::load_all(&conn);
|
||||
let domain = Domain::new(possible_values);
|
||||
let mut problem = Problem::build();
|
||||
for (var, dom, ini) in generate_variables(&domain) {
|
||||
problem = problem.add_variable(var, dom, ini);
|
||||
}
|
||||
let mut problem = problem
|
||||
.add_constraint(
|
||||
ingredients_contains
|
||||
)
|
||||
.finish();
|
||||
let results = problem.solve_all();
|
||||
format!("{}\nTotal = {}", pretty_output(&results.first().unwrap()), results.len())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", generate_weekly_menu());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
println!("{}", get_planning_all_results());
|
||||
}
|
||||
|
||||
@@ -13,17 +13,36 @@ enum Assignment<'a, V> {
|
||||
Clear(String)
|
||||
}
|
||||
|
||||
|
||||
type Domains<'a, V> = HashMap<String, &'a Domain<V>>;
|
||||
/// The domain of values that can be assigned to variables
|
||||
#[derive(Clone)]
|
||||
pub struct Domain<V> {
|
||||
values: Vec<V>
|
||||
pub values: Vec<V>
|
||||
}
|
||||
|
||||
impl<V> Domain<V> {
|
||||
pub fn new(values: Vec<V>) -> Domain<V> {
|
||||
Domain { values }
|
||||
}
|
||||
|
||||
/// Returns a new domain with the given filter applied to inner values
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate planner;
|
||||
/// # use planner::solver::Domain;
|
||||
/// let domain = Domain::new(vec![1,2,3]);
|
||||
/// fn even(i: &i32) -> bool { i % 2 == 0 };
|
||||
/// assert_eq!(&domain.filter(even).values, &vec![2]);
|
||||
/// ```
|
||||
pub fn filter(&self, f: fn(&V) -> bool) -> Domain<V>
|
||||
where V: std::clone::Clone
|
||||
{
|
||||
Domain {
|
||||
values: self.values.iter().cloned().filter(f).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
||||
@@ -33,19 +52,32 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
|
||||
}
|
||||
|
||||
|
||||
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
|
||||
|
||||
pub struct Problem<'a, V> {
|
||||
/// The initial assignements map
|
||||
variables: Variables<'a, V>,
|
||||
/// Each variable has its associated domain
|
||||
domains: Domains<'a,V>,
|
||||
/// Set of constraints to validate
|
||||
constraints: Vec<Constraint<'a,V>>,
|
||||
}
|
||||
|
||||
impl<'a,V> Problem<'a, V> {
|
||||
|
||||
pub fn build() -> ProblemBuilder<'a,V> {
|
||||
ProblemBuilder::new()
|
||||
}
|
||||
|
||||
/// Returns all possible Updates for next assignements, prepended with
|
||||
/// a Clear to ensure the variable is unset before when leaving the branch.
|
||||
fn assign_next<'a,'b, V>(assign: &'b Variables<'a, V>, domain: &'a Domain<V>)
|
||||
-> Option<Vec<Assignment<'a, V>>>
|
||||
where V: fmt::Debug
|
||||
{
|
||||
// Panics on empty domain
|
||||
// If domain values are filtered, then the branch is a dead end
|
||||
if domain.values.is_empty() { panic!("No values in domain : {:?}", domain); };
|
||||
|
||||
fn _assign_next(&self) -> Option<Vec<Assignment<'a,V>>> {
|
||||
// TODO: should be able to inject a choosing strategy
|
||||
if let Some((key,_)) = assign.iter().find(|(_, val)| val.is_none()) {
|
||||
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
|
||||
let domain = self.domains.get(key).expect("No domain for variable !");
|
||||
let mut updates = vec![Assignment::Clear(key.clone())];
|
||||
|
||||
if domain.values.is_empty() { panic!("No value in domain !"); }
|
||||
// TODO: should be able to filter domain values (inference, pertinence)
|
||||
for value in domain.values.iter() {
|
||||
updates.push(Assignment::Update(key.clone(), value));
|
||||
@@ -56,42 +88,78 @@ fn assign_next<'a,'b, V>(assign: &'b Variables<'a, V>, domain: &'a Domain<V>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that the current assignments doesn't violate any constraint
|
||||
fn _is_valid(&self) -> bool {
|
||||
for validator in self.constraints.iter() {
|
||||
if validator(&self.variables) == false { return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Visit all possible solutions, using a stack.
|
||||
pub fn solve_all<'a, V>(
|
||||
mut assign: Variables<'a, V>,
|
||||
domain: &'a Domain<V>,
|
||||
is_valid: fn(&Variables<'a,V>) -> bool
|
||||
) -> Vec<Variables<'a, V>>
|
||||
pub fn solve_all(&mut self) -> Vec<Variables<'a,V>>
|
||||
where V: Clone + fmt::Debug
|
||||
{
|
||||
let mut solutions: Vec<Variables<V>> = vec![];
|
||||
let mut stack: Vec<Assignment<'a, V>> = vec![];
|
||||
stack.append(&mut assign_next(&assign,domain).unwrap());
|
||||
stack.append(&mut self._assign_next().unwrap());
|
||||
loop {
|
||||
let node = stack.pop();
|
||||
if node.is_none() { break; };
|
||||
match node.unwrap() {
|
||||
Assignment::Update(key, val) => {
|
||||
// Assign the variable and open new branches, if any.
|
||||
*assign.get_mut(&key).unwrap() = Some(val);
|
||||
*self.variables.get_mut(&key).unwrap() = Some(val);
|
||||
// TODO: handle case of empty domain.values
|
||||
if let Some(mut nodes) = assign_next(&assign, domain) {
|
||||
if let Some(mut nodes) = self._assign_next() {
|
||||
stack.append(&mut nodes);
|
||||
} else {
|
||||
// Assignements are completed
|
||||
if is_valid(&assign) {
|
||||
solutions.push(assign.clone());
|
||||
if self._is_valid() {
|
||||
solutions.push(self.variables.clone());
|
||||
};
|
||||
};
|
||||
},
|
||||
Assignment::Clear(key) => {
|
||||
// We are closing this branch, unset the variable
|
||||
*assign.get_mut(&key).unwrap() = None;
|
||||
*self.variables.get_mut(&key).unwrap() = None;
|
||||
},
|
||||
};
|
||||
};
|
||||
solutions
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProblemBuilder<'a, V>(Problem<'a, V>);
|
||||
|
||||
impl<'a, V> ProblemBuilder<'a, V> {
|
||||
fn new() -> ProblemBuilder<'a, V> {
|
||||
ProblemBuilder(
|
||||
Problem{
|
||||
variables: Variables::new(),
|
||||
domains: HashMap::new(),
|
||||
constraints: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_variable<S>(mut self, name: S, domain: &'a Domain<V>, value: Option<&'a V>) -> Self
|
||||
where S: Into<String>
|
||||
{
|
||||
let name = name.into();
|
||||
self.0.variables.insert(name.clone(), value);
|
||||
self.0.domains.insert(name, domain);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
|
||||
self.0.constraints.push(cons);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Problem<'a, V> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -99,41 +167,40 @@ mod tests {
|
||||
#[test]
|
||||
fn test_solver_find_pairs() {
|
||||
use super::*;
|
||||
// Find all pairs of two differents
|
||||
let assign: Variables<i32> = [
|
||||
("Left".to_string(), None),
|
||||
("Right".to_string(), None),
|
||||
].iter().cloned().collect();
|
||||
let domain = Domain::new(vec![1,2,3]);
|
||||
let constraint = |assign: &Variables<i32>| {
|
||||
let mut problem: Problem<_> = Problem::build()
|
||||
.add_variable(String::from("Left"), &domain, None)
|
||||
.add_variable(String::from("Right"), &domain, None)
|
||||
.add_constraint(|assign: &Variables<i32>| {
|
||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
||||
};
|
||||
})
|
||||
.finish();
|
||||
|
||||
let solutions: Vec<Variables<i32>> = vec![
|
||||
[("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(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
|
||||
];
|
||||
|
||||
assert_eq!(solve_all(assign, &domain, constraint), solutions);
|
||||
assert_eq!(problem.solve_all(), solutions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_solver_find_pairs_with_initial() {
|
||||
use super::*;
|
||||
// Find all pairs of two differents
|
||||
let assign: Variables<i32> = [
|
||||
("Left".to_string(), None),
|
||||
("Right".to_string(), Some(&2)),
|
||||
].iter().cloned().collect();
|
||||
let domain = Domain::new(vec![1,2,3]);
|
||||
let constraint = |assign: &Variables<i32>| {
|
||||
let mut problem: Problem<_> = Problem::build()
|
||||
.add_variable("Left".to_string(), &domain, None)
|
||||
.add_variable("Right".to_string(), &domain, Some(&2))
|
||||
.add_constraint( |assign: &Variables<i32>| {
|
||||
assign.get("Left").unwrap() == assign.get("Right").unwrap()
|
||||
};
|
||||
})
|
||||
.finish();
|
||||
|
||||
let solutions: Vec<Variables<i32>> = vec![
|
||||
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
|
||||
];
|
||||
|
||||
assert_eq!(solve_all(assign, &domain, constraint), solutions);
|
||||
assert_eq!(problem.solve_all(), solutions);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
17
web/Cargo.toml
Normal file
17
web/Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "web"
|
||||
version = "0.1.0"
|
||||
authors = ["artus40 <artus@landoftheunicorn.ovh>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
rocket = "0.4.0"
|
||||
cookbook = { path = "../cookbook/" }
|
||||
serde = "1.0"
|
||||
serde_derive = "1.0"
|
||||
|
||||
|
||||
[dependencies.rocket_contrib]
|
||||
version = "0.4.0"
|
||||
default-features = false
|
||||
features = ["json", "diesel_sqlite_pool"]
|
||||
2
web/Rocket.toml
Normal file
2
web/Rocket.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[global.databases]
|
||||
cookbook_db = { url = "../cookbook/db.sqlite3" }
|
||||
103
web/html/index.html
Normal file
103
web/html/index.html
Normal file
@@ -0,0 +1,103 @@
|
||||
<!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>{{ items[active_view].ingredients }}</strong></p>
|
||||
<button @click="deleteRecipe(active_view + 1)" 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) => console.log("Deleted :" + data))
|
||||
.catch((err) => console.error(err));
|
||||
this.closeActiveView();
|
||||
},
|
||||
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>
|
||||
72
web/src/main.rs
Normal file
72
web/src/main.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
#![feature(proc_macro_hygiene, decl_macro)]
|
||||
|
||||
#[macro_use] extern crate rocket;
|
||||
#[macro_use] extern crate rocket_contrib;
|
||||
#[macro_use] extern crate serde_derive;
|
||||
|
||||
extern crate cookbook;
|
||||
|
||||
use std::path::Path;
|
||||
use rocket::response::{NamedFile, status::NotFound};
|
||||
|
||||
#[get("/")]
|
||||
fn index() -> Result<NamedFile, NotFound<String>> {
|
||||
NamedFile::open(&Path::new("./html/index.html"))
|
||||
.map_err(|_| NotFound(format!("Server error : index not found")))
|
||||
}
|
||||
|
||||
mod api {
|
||||
use cookbook::*;
|
||||
use rocket_contrib::{
|
||||
json::Json,
|
||||
databases::diesel,
|
||||
};
|
||||
|
||||
#[database("cookbook_db")]
|
||||
pub struct CookbookDbConn(diesel::SqliteConnection);
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Recipe {
|
||||
id: i32,
|
||||
title: String,
|
||||
category: i16,
|
||||
ingredients: String,
|
||||
preparation: String,
|
||||
}
|
||||
|
||||
impl Recipe {
|
||||
fn from(rec: models::Recipe) -> Recipe {
|
||||
Recipe {
|
||||
id: rec.id,
|
||||
title: rec.title,
|
||||
category: rec.category as i16,
|
||||
ingredients: rec.ingredients,
|
||||
preparation: rec.preparation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/list")]
|
||||
pub fn recipes_list(conn: CookbookDbConn) -> Json<Vec<Recipe>> {
|
||||
Json(
|
||||
recipes::load_all(&conn)
|
||||
.into_iter()
|
||||
.map(|r| Recipe::from(r))
|
||||
.collect()
|
||||
)
|
||||
}
|
||||
|
||||
#[get("/delete/<id>")]
|
||||
pub fn delete_recipe(conn: CookbookDbConn, id: i32) -> Json<bool> {
|
||||
Json(
|
||||
recipes::delete(&conn, id)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
rocket::ignite()
|
||||
.attach(api::CookbookDbConn::fairing())
|
||||
.mount("/", routes![index])
|
||||
.mount("/api", routes![api::recipes_list, api::delete_recipe]).launch();
|
||||
}
|
||||
Reference in New Issue
Block a user