1
0

Updated Ingredients to use ItemsWithQuantities

This commit is contained in:
cryptogopher 2019-12-29 15:12:05 +01:00
parent 61bd34fdc5
commit 20deb944c3
19 changed files with 125 additions and 226 deletions

View File

@ -3,6 +3,8 @@ class IngredientsController < ApplicationController
menu_item :body_trackers menu_item :body_trackers
helper :body_trackers
before_action :init_session_filters before_action :init_session_filters
before_action :find_project_by_project_id, before_action :find_project_by_project_id,
only: [:index, :nutrients, :create, :import, :filter, :filter_nutrients] only: [:index, :nutrients, :create, :import, :filter, :filter_nutrients]
@ -204,29 +206,14 @@ class IngredientsController < ApplicationController
end end
def prepare_ingredients def prepare_ingredients
@ingredients, @formula_q = @project.ingredients.includes(:ref_unit, :source) @ingredients, @formula_q = @project.ingredients
.filter(@project, session[:i_filters]) .includes(:ref_unit, :source)
.filter(session[:i_filters])
end end
def prepare_nutrients def prepare_nutrients
@quantities = @project.nutrients_column_view.quantities @quantities = @project.nutrients_column_view.quantities
ingredients, requested_n, extra_n, @formula_q = @project.ingredients @ingredients, @requested_n, @extra_n, @formula_q = @project.ingredients
.filter(@project, session[:i_filters], @quantities) .filter(session[:i_filters], @quantities)
@nutrients = {}
@extra_nutrients = {}
ingredients.each_with_index do |i, index|
@nutrients[i] = []
requested_n[index].each do |q_name, value|
amount, unitname = value
@nutrients[i] << [q_name, amount.nil? ? '-' : "#{amount} [#{unitname || '-'}]"]
end
@extra_nutrients[i] = []
extra_n[index].each do |q_name, value|
amount, unitname = value
@extra_nutrients[i] << [q_name, amount.nil? ? '-' : "#{amount} [#{unitname || '-'}]"]
end
end
end end
end end

View File

@ -1,6 +1,8 @@
class MeasurementsController < ApplicationController class MeasurementsController < ApplicationController
menu_item :body_trackers menu_item :body_trackers
helper :body_trackers
before_action :init_session_filters before_action :init_session_filters
before_action :find_project_by_project_id, only: [:index, :new, :create, :filter] before_action :find_project_by_project_id, only: [:index, :new, :create, :filter]
before_action :find_quantity_by_quantity_id, only: [:toggle_column] before_action :find_quantity_by_quantity_id, only: [:toggle_column]

View File

@ -1,2 +1,6 @@
module BodyTrackersHelper module BodyTrackersHelper
def format_value(value)
amount, unitname = value
amount.nil? ? '-' : "#{amount} [#{unitname || '-'}]"
end
end end

View File

@ -38,4 +38,8 @@ module IngredientsHelper
[translations[k.to_sym], k] [translations[k.to_sym], k]
end end
end end
def action_links(i)
delete_link(ingredient_path(i), {remote: true, data: {}})
end
end end

View File

@ -9,11 +9,6 @@ module MeasurementsHelper
m.taken_at.getlocal.strftime("%R") m.taken_at.getlocal.strftime("%R")
end end
def format_value(value)
amount, unitname = value
amount.nil? ? '-' : "#{amount} [#{unitname || '-'}]"
end
def toggle_column_options def toggle_column_options
disabled = [] disabled = []
enabled_columns = @scoping_measurement.column_view.quantities enabled_columns = @scoping_measurement.column_view.quantities

View File

@ -1,6 +1,4 @@
class Ingredient < ActiveRecord::Base class Ingredient < ActiveRecord::Base
include BodyTracking::Formula
enum group: { enum group: {
other: 0, other: 0,
meat: 1 meat: 1
@ -23,7 +21,8 @@ class Ingredient < ActiveRecord::Base
} }
# Nutrient quantity_id uniqueness check for nested attributes # Nutrient quantity_id uniqueness check for nested attributes
validate do validate do
quantities = self.nutrients.map { |n| n.quantity_id } quantities = self.nutrients.reject { |n| n.marked_for_destruction? }
.map { |n| n.quantity_id }
if quantities.length != quantities.uniq.length if quantities.length != quantities.uniq.length
errors.add(:nutrients, :duplicated_quantity) errors.add(:nutrients, :duplicated_quantity)
end end
@ -46,95 +45,4 @@ class Ingredient < ActiveRecord::Base
def toggle_hidden! def toggle_hidden!
self.toggle!(:hidden) self.toggle!(:hidden)
end end
def self.filter(project, filters, requested_q = Quantity.none)
ingredients = all
if filters[:name].present?
ingredients = ingredients.where("name LIKE ?", "%#{filters[:name]}%")
end
if filters[:visibility].present?
ingredients = ingredients.where(hidden: filters[:visibility] == "1" ? false : true)
end
formula_q = if filters[:nutrients].present?
project.quantities.new(name: '__internal_q',
formula: filters[:nutrients],
domain: :diet)
end
apply_formula = formula_q.present? && formula_q.valid?
result =
if !requested_q.empty? || apply_formula
computed = ingredients.compute_nutrients(requested_q, apply_formula && formula_q)
requested_q.present? ? computed : [computed[0]]
else
[ingredients]
end
result.push(formula_q)
end
def self.compute_nutrients(requested_q, filter_q = nil)
ingredients = all
unchecked_q = requested_q.map { |q| [q, nil] }
unchecked_q << [filter_q, nil] if filter_q
nutrients = Hash.new { |h,k| h[k] = {} }
Nutrient.where(ingredient: ingredients).includes(:quantity, :unit)
.order('quantities.lft')
.pluck('quantities.name', :ingredient_id, :amount, 'units.shortname')
.each { |q_name, i_id, a, u_id| nutrients[q_name][i_id] = [a, u_id] }
extra_q = nutrients.keys - requested_q.pluck(:name)
completed_q = {}
# FIXME: loop should finish unless there is circular dependency in formulas
# for now we don't guard against that
while !unchecked_q.empty?
q, deps = unchecked_q.shift
# quantity not computable (no formula) or not requiring calculation/computed
if q.formula.blank? || (nutrients[q.name].length == ingredients.count)
completed_q[q.name] = nutrients.delete(q.name) { {} }
next
end
# quantity with formula requires refresh of dependencies availability
if deps.nil? || !deps.empty?
deps ||= q.formula_quantities
deps.reject! { |q| completed_q.has_key?(q.name) }
deps.each { |q| unchecked_q << [q, nil] unless unchecked_q.index { |u| u[0] == q } }
end
# quantity with formula has all dependencies satisfied, requires calculation
if deps.empty?
input_q = q.formula_quantities
inputs = ingredients.select { |i| nutrients[q.name][i.id].nil? }.map do |i|
[
i,
input_q.map do |i_q|
nutrient_data = completed_q[i_q.name][i.id] || [nil, nil]
[i_q.name, nutrient_data[0]]
end.to_h
]
end
q.calculate(inputs).each { |i, result| nutrients[q.name][i.id] = result }
unchecked_q.unshift([q, deps])
next
end
# quantity still has unsatisfied dependencies, move to the end of queue
unchecked_q << [q, deps]
end
all_q = nutrients.merge(completed_q)
[
filter_q ? ingredients.to_a.keep_if { |i| all_q[filter_q.name][i.id][0] } : ingredients,
ingredients.map { |i| requested_q.map { |q| [q.name, all_q[q.name][i.id]] } },
ingredients.map do |i|
extra_q.map { |q_name| [q_name, all_q[q_name][i.id]] if all_q[q_name][i.id] }
end
]
end
end end

View File

@ -10,9 +10,8 @@ class Measurement < ActiveRecord::Base
# Readout quantity_id + unit_id uniqueness validation. Cannot be effectively # Readout quantity_id + unit_id uniqueness validation. Cannot be effectively
# checked on Readout model level. # checked on Readout model level.
validate do validate do
quantities = self.readouts.map do |r| quantities = self.readouts.reject { |r| r.marked_for_destruction? }
[r.quantity_id, r.unit_id] unless r.marked_for_destruction? .map { |r| [r.quantity_id, r.unit_id] }
end
if quantities.length != quantities.uniq.length if quantities.length != quantities.uniq.length
errors.add(:readouts, :duplicated_quantity_unit_pair) errors.add(:readouts, :duplicated_quantity_unit_pair)
end end

View File

@ -19,7 +19,7 @@
onchange: '$("#filters-form").submit();' %> onchange: '$("#filters-form").submit();' %>
</td> </td>
<td style="width:100%;"> <td style="width:100%;">
<%= text_field_tag 'filters[nutrients]', session[:i_filters][:nutrients], <%= text_field_tag 'filters[formula]', session[:i_filters][:formula],
placeholder: 'conditional expression including nutrients', size: 40, placeholder: 'conditional expression including nutrients', size: 40,
style: 'box-sizing:border-box; width:100%;', style: 'box-sizing:border-box; width:100%;',
onblur: '$("#filters-form").submit(); return false;' %> onblur: '$("#filters-form").submit(); return false;' %>

View File

@ -32,9 +32,7 @@
<%= i.source.name if i.source.present? %> <%= i.source.name if i.source.present? %>
<%= ", #{i.source_ident}" if i.source_ident.present? %> <%= ", #{i.source_ident}" if i.source_ident.present? %>
</td> </td>
<td class="action unwrappable"> <td class="action unwrappable"><%= action_links(i) %></td>
<%= delete_link ingredient_path(i), {remote: true, data: {}} %>
</td>
</tr> </tr>
<% end %> <% end %>
</tbody> </tbody>

View File

@ -1,72 +0,0 @@
<%= render partial: 'ingredients/filters',
locals: {url: filter_nutrients_project_ingredients_path(@project)} %>
<% if @nutrients.any? %>
<%= render partial: 'ingredients/options' %>
<table class="nutrients list odd-even">
<thead>
<tr>
<% total_width = 3 + @quantities.length %>
<th style="width:<%= 3 * 100/total_width%>%"><%= l(:field_name) %></th>
<% @quantities.each do |q| %>
<th style="width:<%= 100/total_width %>%"><%= q.name %></th>
<% end %>
</tr>
</thead>
<tbody>
<% @nutrients.each do |i, values| %>
<% row_class = "ingredient#{' hidden' if i.hidden} #{cycle('odd', 'even')}" %>
<tr id="ingredient-<%= i.id %>" class="primary <%= row_class %>">
<td class="name ellipsible" style="cursor: pointer;"
onclick="$(this).closest('tr').toggle(); $(this).closest('tr').nextUntil('tr.primary', 'tr').toggle(); return false;">
<span class="icon icon-bullet-closed"><%= i.name %></span>
</td>
<% values.each do |*, value| %>
<td class="primary value"><%= value %></td>
<% end %>
</tr>
<tr class="<%= row_class %>" style="display:none">
<td class="name" style="cursor: pointer;" onclick="$(this).closest('tr').prev('tr.primary').toggle(); $(this).closest('tr').prev('tr.primary').nextUntil('tr.primary', 'tr').toggle(); return false;">
<span class="icon icon-bullet-closed"><%= i.name %></span>
</td>
<% values.each do |q_name, *| %>
<td class="primary quantity"><%= q_name %></td>
<% end %>
</tr>
<tr class="<%= row_class %>" style="display:none">
<td class="space"></td>
<% values.each do |*, value| %>
<td class="primary value"><%= value %></td>
<% end %>
</tr>
<% extras = @extra_nutrients[i] %>
<% extras.each_slice(@quantities.length).with_index do |values, index| %>
<tr class="extra <%= row_class %>" style="display:none">
<td class="space"></td>
<% values.each do |q_name, *| %>
<td class="extra quantity"><%= q_name %></td>
<% end %>
<% if @quantities.length > values.length %>
<td class="space" colspan="<%= @quantities.length-values.length %>"></td>
<% end %>
</tr>
<tr class="extra <%= row_class %>" style="display:none">
<td class="space"></td>
<% values.each do |*, value| %>
<td class="extra value"><%= value %></td>
<% end %>
<% if @quantities.length > values.length %>
<td class="space" colspan="<%= @quantities.length-values.length %>"></td>
<% end %>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<% else %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% end %>

View File

@ -0,0 +1,79 @@
<%= render partial: 'ingredients/filters',
locals: {url: filter_nutrients_project_ingredients_path(@project)} %>
<% if @ingredients.any? %>
<%= render partial: 'ingredients/options' %>
<table class="nutrients list odd-even">
<thead>
<tr>
<% total_width = 4 + @quantities.length %>
<th style="width:<%= 3 * 100/total_width%>%"><%= l(:field_name) %></th>
<% @quantities.each do |q| %>
<th style="width:<%= 100/total_width %>%" class="closable ellipsible">
<div style="float:right;position:relative;">
<%= link_to '',
toggle_column_project_ingredients_path(@project, quantity_id: q.id),
{class: "icon icon-close", method: :post, remote: true} %>
</div>
<%= q.name %>
</th>
<% end %>
<th style="width:<%= 100/total_width %>%"><%= l(:field_action) %></th>
</tr>
</thead>
<tbody>
<% @ingredients.each_with_index do |i, index| %>
<% row_class = "ingredient#{' hidden' if i.hidden} #{cycle('odd', 'even')}" %>
<tr id="ingredient-<%= i.id %>" class="primary <%= row_class %>">
<td class="name ellipsible" style="cursor: pointer;"
onclick="$(this).closest('tr').toggle(); $(this).closest('tr').nextUntil('tr.primary', '.ingredient').toggle(); return false;">
<span class="icon icon-bullet-closed"><%= i.name %></span>
</td>
<% @requested_n[index].each do |*, value| %>
<td class="primary value ellipsible"><%= format_value(value) %></td>
<% end %>
<td class="action unwrappable"><%= action_links(i) %></td>
</tr>
<tr class="<%= row_class %>" style="display:none">
<% if @quantities.length > 0
rows = (@extra_n[index].length - 1) / @quantities.length + 2
else
rows = 1
end %>
<td rowspan="<%= rows %>" class="name ellipsible" style="cursor: pointer;"
onclick="$(this).closest('tr').prev('tr.primary').toggle(); $(this).closest('tr').prev('tr.primary').nextUntil('tr.primary', '.ingredient').toggle(); return false;">
<span class="icon icon-bullet-open"><%= i.name %></span>
</td>
<% @requested_n[index].each do |q_name, value| %>
<td class="primary quantity ellipsible">
<%= q_name %>
<p class="value"><%= format_value(value) %></p>
</td>
<% end %>
<td rowspan="<%= rows %>" class="action unwrappable"><%= action_links(i) %></td>
</tr>
<% next unless @quantities.length > 0 %>
<% @extra_n[index].each_slice(@quantities.length) do |values| %>
<tr class="extra <%= row_class %>" style="display:none">
<% values.each do |q_name, value| %>
<td class="extra quantity ellipsible">
<%= q_name %>
<p class="value"><%= format_value(value) %></p>
</td>
<% end %>
<% if @quantities.length > values.length %>
<td class="space" colspan="<%= @quantities.length-values.length %>"></td>
<% end %>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<% else %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% end %>

View File

@ -8,28 +8,10 @@
<table> <table>
<tr> <tr>
<td style="width:100%"></td> <td style="width:100%"></td>
<td> <td><%= select_tag 'quantity_id', toggle_column_options %></td>
<%= select_tag 'quantity_id', toggle_column_options %> <td><%= submit_tag l(:button_add) %></td>
</td>
<td>
<%= submit_tag l(:button_add) %>
</td>
</tr> </tr>
</table> </table>
<% end %> <% end %>
</div> </div>
</fieldset> </fieldset>
<table class="list" style="border:none; width:100%">
<tr>
<% total_width = 3 + @quantities.length %>
<td style="visibility: hidden; border: none; width:<%= 3 * 100/total_width%>%"></td>
<% @quantities.each do |q| %>
<td class="action" style="width:<%= 100/total_width %>%">
<%= link_to l(:button_hide),
toggle_column_project_ingredients_path(@project, quantity_id: q.id),
{class: "icon icon-close", method: :post, remote: true} %>
</td>
<% end %>
</tr>
</table>

View File

@ -10,5 +10,5 @@
<h2><%= t ".heading" %></h2> <h2><%= t ".heading" %></h2>
<div id='ingredients'> <div id='ingredients'>
<%= render partial: 'ingredients/list' %> <%= render partial: 'ingredients/index' %>
</div> </div>

View File

@ -10,5 +10,5 @@
<h2><%= t ".heading" %></h2> <h2><%= t ".heading" %></h2>
<div id='nutrients'> <div id='nutrients'>
<%= render partial: 'ingredients/list_nutrients' %> <%= render partial: 'ingredients/nutrients' %>
</div> </div>

View File

@ -1,3 +1,3 @@
$('div[id^=flash_]').remove(); $('div[id^=flash_]').remove();
$('#content').prepend('<%= escape_javascript(render_flash_messages) %>'); $('#content').prepend('<%= escape_javascript(render_flash_messages) %>');
$('#ingredients').html('<%= escape_javascript(render partial: 'ingredients/list') %>'); $('#ingredients').html('<%= escape_javascript(render partial: 'ingredients/index') %>');

View File

@ -1,3 +1,3 @@
$('div[id^=flash_]').remove(); $('div[id^=flash_]').remove();
$('#content').prepend('<%= escape_javascript(render_flash_messages) %>'); $('#content').prepend('<%= escape_javascript(render_flash_messages) %>');
$('#nutrients').html('<%= escape_javascript(render partial: 'ingredients/list_nutrients') %>'); $('#nutrients').html('<%= escape_javascript(render partial: 'ingredients/nutrients') %>');

View File

@ -22,6 +22,7 @@
<th style="width:<%= 100/total_width %>%"><%= l(:field_action) %></th> <th style="width:<%= 100/total_width %>%"><%= l(:field_action) %></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<% @measurements.each_with_index do |m, index| %> <% @measurements.each_with_index do |m, index| %>
<% row_class = "measurement #{cycle('odd', 'even')}" %> <% row_class = "measurement #{cycle('odd', 'even')}" %>

View File

@ -1,5 +1,14 @@
module BodyTracking module BodyTracking
module ItemsWithQuantities module ItemsWithQuantities
QUANTITY_DOMAINS = {
Measurement => :measurement,
Ingredient => :diet
}
VALUE_COLUMNS = {
Measurement => :value,
Ingredient => :amount
}
def filter(filters, requested_q = nil) def filter(filters, requested_q = nil)
items = all.where(filters[:scope]) items = all.where(filters[:scope])
@ -12,7 +21,7 @@ module BodyTracking
end end
project = proxy_association.owner project = proxy_association.owner
domain = {Measurement => :measurement, Ingredient => :diet}[proxy_association.klass] domain = QUANTITY_DOMAINS[proxy_association.klass]
formula_q = if filters[:formula].present? formula_q = if filters[:formula].present?
project.quantities.new(name: '__internal_q', project.quantities.new(name: '__internal_q',
formula: filters[:formula], formula: filters[:formula],
@ -45,7 +54,8 @@ module BodyTracking
item_foreign_key = subitem_reflection.foreign_key item_foreign_key = subitem_reflection.foreign_key
subitems_scope.includes(:quantity, :unit) subitems_scope.includes(:quantity, :unit)
.order('quantities.lft') .order('quantities.lft')
.pluck(item_foreign_key, 'quantities.name', :value, 'units.shortname') .pluck(item_foreign_key, 'quantities.name', VALUE_COLUMNS[item_class],
'units.shortname')
.each { |item_id, q_name, a, u_id| subitems[q_name][item_id] = [a, u_id] } .each { |item_id, q_name, a, u_id| subitems[q_name][item_id] = [a, u_id] }
extra_q = subitems.keys - requested_q.pluck(:name) extra_q = subitems.keys - requested_q.pluck(:name)

View File

@ -1,8 +1,10 @@
module BodyTracking module BodyTracking
module ProjectPatch module ProjectPatch
Project.class_eval do Project.class_eval do
has_many :measurements, -> { order "taken_at DESC" }, dependent: :destroy, extend: ItemsWithQuantities has_many :measurements, -> { order "taken_at DESC" }, dependent: :destroy,
has_many :ingredients, -> { order "name" }, dependent: :destroy extend: ItemsWithQuantities
has_many :ingredients, -> { order "name" }, dependent: :destroy,
extend: ItemsWithQuantities
has_many :sources, dependent: :destroy has_many :sources, dependent: :destroy
has_many :column_views, dependent: :destroy has_many :column_views, dependent: :destroy