Skip to content

Commit

Permalink
Merged with master to bring to date. Removed language: :afr Preferenc…
Browse files Browse the repository at this point in the history
…e in Fixtures to avoid duplicate Preference issue.
  • Loading branch information
Aquaj committed Jan 4, 2017
2 parents 0e58f81 + d12b282 commit 8dfe258
Show file tree
Hide file tree
Showing 91 changed files with 1,747 additions and 262 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.27.2
2.28.0
38 changes: 29 additions & 9 deletions app/controllers/api/v1/intervention_participations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,22 @@ def create
params = permitted_params
return render json: { message: :unprocessable_entity }, status: :unprocessable_entity if params.blank?

intervention = Intervention.find(params[:request_intervention_id]).initialize_record(state: :in_progress)
intervention.creator_id = current_user
intervention.created_at = Time.zone.now
intervention.save!

participation = intervention.participations.find_or_initialize_by(
product_id: current_user.worker.id
)
if params[:request_intervention_id]
intervention = Intervention.find(params[:request_intervention_id]).initialize_record(state: :in_progress)

intervention.creator_id = current_user
intervention.created_at = Time.zone.now
intervention.save!
participation = InterventionParticipation.find_or_initialize_by(
product_id: current_user.worker.id,
intervention_id: intervention.id
)
else
participation = InterventionParticipation.new(
product_id: current_user.worker.id,
procedure_name: Procedo.find(params[:procedure_name]) ? params[:procedure_name] : nil
)
end
participation.request_compliant = !params[:request_compliant].to_i.zero?
participation.state = params[:state]
participation.save!
Expand All @@ -29,13 +36,26 @@ def create
period.destroy
end

if params[:crumbs].present?
params[:crumbs].each do |crumb|
participation.crumbs.create!(
nature: crumb['nature'],
geolocation: crumb['geolocation'],
read_at: crumb['read_at'],
accuracy: crumb['accuracy'],
device_uid: params[:device_uid],
user_id: current_user.worker.id
)
end
end

render json: { id: participation.id }, status: :created
end

private

def permitted_params
super.permit(:request_intervention_id, :procedure_name, { working_periods: [:started_at, :stopped_at, :nature] }, :request_compliant, :state)
super.permit(:request_intervention_id, :procedure_name, { working_periods: [:started_at, :stopped_at, :nature] }, :request_compliant, :state, :device_uid, crumbs: [:read_at, :accuracy, :geolocation, :nature])
end
end
end
Expand Down
50 changes: 50 additions & 0 deletions app/controllers/backend/intervention_participations_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# == License
# Ekylibre - Simple agricultural ERP
# Copyright (C) 2014 Sebastien Gauvrit, Brice Texier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

module Backend
class InterventionParticipationsController < Backend::BaseController
manage_restfully only: [:update, :destroy]

def index
@worked_on = if params[:worked_on].blank?
first_participation = current_user.intervention_participations.unprompted.order(created_at: :desc).first
first_participation.present? ? first_participation.created_at : Time.zone.today
else
params[:worked_on].to_date
end
end

# Creates an intervention from intervention participation and redirects to an edit form for
# the newly created intervention.
def convert
return unless intervention_participation = find_and_check
begin
if intervention = intervention_participation.convert!(params.slice(:procedure_name, :working_width))
redirect_to edit_backend_intervention_path(intervention)
elsif current_user.intervention_participations.unprompted.any?
redirect_to backend_intervention_participations_path(worked_on: params[:worked_on])
else
redirect_to backend_interventions_path
end
rescue StandardError => e
notify_error(e.message)
redirect_to backend_intervention_participations_path(worked_on: params[:worked_on])
end
end
end
end
43 changes: 26 additions & 17 deletions app/controllers/backend/outgoing_payment_lists_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,17 @@ class OutgoingPaymentListsController < Backend::BaseController
t.column :payments_sum, label: :total, datatype: :float, currency: true
end

list(:payments, model: 'OutgoingPayment', conditions: { list_id: 'params[:id]'.c }) do |t|
list(:payments, model: 'OutgoingPayment', conditions: {list_id: 'params[:id]'.c}) do |t|
t.column :number, url: true
t.column :payee, url: true
t.column :paid_at
t.column :amount, currency: true, url: true
t.column :mode
t.column :bank_check_number
t.column :to_bank_at
t.column :work_name, through: :affair, label: :affair_number, url: { controller: :purchase_affairs }
t.column :deal_work_name, through: :affair, label: :purchase_number, url: { controller: :purchases, id: 'RECORD.affair.deals_of_type(Purchase).first.id'.c }
t.column :bank_statement_number, through: :journal_entry, url: { controller: :bank_statements, id: 'RECORD.journal_entry.bank_statements.first.id'.c }
t.column :work_name, through: :affair, label: :affair_number, url: {controller: :purchase_affairs}
t.column :deal_work_name, through: :affair, label: :purchase_number, url: {controller: :purchases, id: 'RECORD.affair.deals_of_type(Purchase).first.id'.c}
t.column :bank_statement_number, through: :journal_entry, url: {controller: :bank_statements, id: 'RECORD.journal_entry.bank_statements.first.id'.c}
end

def show
Expand All @@ -52,18 +52,18 @@ def show
@entity_of_company_full_name = Entity.of_company.full_name

respond_with(@outgoing_payment_list, methods: [:currency, :payments_sum, :entity],
include: {
payer: { methods: [:picture_path], include: { default_mail_address: { methods: [:mail_coordinate] }, websites: {}, emails: {}, mobiles: {} } },
payments: {
methods: [:amount_to_letter, :label, :affair_reference_numbers],
include: {
responsible: {},
affair: {include: {purchases: {}}},
mode: {},
payee: { include: { default_mail_address: { methods: [:mail_coordinate] }, websites: {}, emails: {}, mobiles: {} } }
}
}
})
include: {
payer: {methods: [:picture_path], include: {default_mail_address: {methods: [:mail_coordinate]}, websites: {}, emails: {}, mobiles: {}}},
payments: {
methods: [:amount_to_letter, :label, :affair_reference_numbers],
include: {
responsible: {},
affair: {include: {purchases: {}}},
mode: {},
payee: {include: {default_mail_address: {methods: [:mail_coordinate]}, websites: {}, emails: {}, mobiles: {}}}
}
}
})
end

def export_to_sepa
Expand All @@ -78,13 +78,22 @@ def export_to_sepa

def new
@outgoing_payment_list = OutgoingPaymentList.new
@affairs = []

if params[:started_at].present? && params[:stopped_at].present? && params[:outgoing_payment_list] && params[:outgoing_payment_list][:mode_id]
mode = OutgoingPaymentMode.find_by(id: params[:outgoing_payment_list][:mode_id])
@outgoing_payment_list.mode = mode

if @outgoing_payment_list.valid?
@currency = mode.cash.currency
@thirds = Entity.includes(:purchase_affairs).where(affairs: { closed: false, currency: mode.cash.currency }).where('affairs.updated_at BETWEEN ? AND ?', params[:started_at], params[:stopped_at]).order('affairs.third_id, affairs.created_at')
@affairs = PurchaseAffair
.joins(:purchases)
.joins(:supplier)
.includes(:supplier)
.where(closed: false, currency: mode.cash.currency)
.where("((purchases.payment_at IS NOT NULL AND purchases.payment_at BETWEEN ? AND ?) OR (purchases.payment_at IS NULL AND purchases.invoiced_at BETWEEN ? AND ?)) AND purchases.state = 'invoice'", params[:started_at], params[:stopped_at], params[:started_at], params[:stopped_at])
.where(entities: {supplier_payment_mode_id: mode.id})
.order(:third_id, 'purchases.payment_at ASC', :number )
end
else
notify_warning :no_purchase_affair_found_on_given_period
Expand Down
5 changes: 5 additions & 0 deletions app/controllers/backend/parcels_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ def self.parcels_conditions
code << " c << params[:delivery_mode]\n"
code << " end\n"
code << "end\n"
code << "if params[:invoice_status] && params[:invoice_status] == 'invoiced'\n"
code << " c[0] << ' AND (#{Parcel.table_name}.purchase_id IS NOT NULL OR #{Parcel.table_name}.sale_id IS NOT NULL) '\n"
code << "elsif params[:invoice_status] && params[:invoice_status] == 'uninvoiced'\n"
code << " c[0] << ' AND (#{Parcel.table_name}.purchase_id IS NULL AND #{Parcel.table_name}.sale_id IS NULL) '\n"
code << "end\n"
code << "if params[:nature].present? && params[:nature] != 'all'\n"
code << " if Parcel.nature.values.include?(params[:nature].to_sym)\n"
code << " c[0] << ' AND #{Parcel.table_name}.nature = ?'\n"
Expand Down
10 changes: 10 additions & 0 deletions app/models/activity_production.rb
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ class ActivityProduction < Ekylibre::Record::Base
where(activity: Activity.of_families(*families))
}

scope :of_crumbs, lambda { |*crumbs|
options = crumbs.extract_options!
options[:campaigns] ||= Campaign.current

of_campaign(options[:campaigns].first).distinct
.joins(:support)
.joins('INNER JOIN crumbs ON ST_Contains(ST_CollectionExtract(activity_productions.support_shape, 3), crumbs.geolocation)')
.where(crumbs.any? ? ['crumbs.id IN (?)', crumbs.flatten.map(&:id)] : 'crumbs.id IS NOT NULL')
}

scope :at, ->(at) { where(':now BETWEEN COALESCE(started_on, :now) AND COALESCE(stopped_on, :now)', now: at.to_date) }
scope :current, -> { at(Time.zone.now) }

Expand Down
10 changes: 5 additions & 5 deletions app/models/bank_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,12 @@ class BankStatement < Ekylibre::Record::Base
b.journal_entry(cash_journal, printed_on: stopped_on, if: cash.suspend_until_reconciliation) do |entry|
label = "BS #{cash.name} #{number}"
balance = items.sum('credit - debit')
entry.add_debit(label, cash.main_account_id, balance, as: :bank)
items.each do |item|
entry.add_debit(item.name, cash.main_account_id, item.credit_balance, as: :bank)
# entry.add_credit(item.name, cash.suspense_account_id, item.credit_balance, as: :suspended)
end
# entry.add_debit(label, cash.main_account_id, balance, as: :bank)
entry.add_credit(label, cash.suspense_account_id, balance, as: :suspended)
# items.each do |item|
# entry.add_debit(item.name, cash.main_account_id, item.credit_balance, as: :bank)
# entry.add_credit(item.name, cash.suspense_account_id, item.credit_balance, as: :suspended)
# end
end
end

Expand Down
137 changes: 16 additions & 121 deletions app/models/crumb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,27 @@
#
# == Table: crumbs
#
# accuracy :decimal(19, 4) not null
# created_at :datetime not null
# creator_id :integer
# device_uid :string not null
# geolocation :geometry({:srid=>4326, :type=>"point"}) not null
# id :integer not null, primary key
# intervention_parameter_id :integer
# lock_version :integer default(0), not null
# metadata :text
# nature :string not null
# read_at :datetime not null
# updated_at :datetime not null
# updater_id :integer
# user_id :integer
# accuracy :decimal(19, 4) not null
# created_at :datetime not null
# creator_id :integer
# device_uid :string not null
# geolocation :geometry({:srid=>4326, :type=>"point"}) not null
# id :integer not null, primary key
# intervention_parameter_id :integer
# intervention_participation_id :integer
# lock_version :integer default(0), not null
# metadata :text
# nature :string not null
# read_at :datetime not null
# updated_at :datetime not null
# updater_id :integer
# user_id :integer
#

class Crumb < Ekylibre::Record::Base
enumerize :nature, in: [:point, :start, :stop, :pause, :resume, :scan, :hard_start, :hard_stop], predicates: true
belongs_to :user
belongs_to :intervention_participation
belongs_to :intervention_parameter, class_name: 'InterventionProductParameter'
has_one :worker, through: :user
# [VALIDATORS[ Do not edit these lines directly. Use `rake clean:validations`.
Expand All @@ -61,111 +63,4 @@ class Crumb < Ekylibre::Record::Base
scope :of_date, lambda { |start_date = Time.zone.now.midnight|
where(read_at: start_date.midnight..start_date.end_of_day)
}

before_validation do
if start?
if previous && original = previous.siblings.find_by(nature: :start)
self.metadata ||= original.metadata || {}
self.metadata['procedure_nature'] ||= original.metadata['procedure_nature']
else
self.metadata ||= {}
self.metadata['procedure_nature'] ||= 'administrative_task'
end
end
end

after_destroy do
intervention_path.delete_all if start? && intervention_path
end

after_update do
if start? && previous
previous.update_column(:nature, :stop) unless previous.stop?
end
end

# Returns the previous crumb if it exists
def previous
siblings.before(read_at).reorder(read_at: :desc).first
end

# Returns the next crumb if it exists
def following
siblings.after(read_at).reorder(read_at: :asc).first
end

# Returns siblings of the crumbs (same user, same device)
def siblings
Crumb.where(user_id: user_id, device_uid: device_uid).order(read_at: :asc)
end

class << self
# Returns all products whose shape contains the given crumbs or any crumb if no crumb is given
# options: no_content: excludes contents. Default: false
# TODO: when refactoring, move this method to Product model, as Product#of_crumbs(*crumbs)
def products(*crumbs)
options = crumbs.extract_options!
crumbs.flatten!
raw_products = Product.distinct.joins(:readings)
.joins("INNER JOIN crumbs ON (indicator_datatype = 'geometry' AND ST_Contains(ST_CollectionExtract(product_readings.geometry_value, 3), crumbs.geolocation))")
.where(crumbs.any? ? ['crumbs.id IN (?)', crumbs.map(&:id)] : 'crumbs.id IS NOT NULL')
contents = []
contents = raw_products.map(&:contents) unless options[:no_contents]
raw_products.concat(contents).flatten.uniq
end

# returns all production supports whose storage shape contains the given crumbs
# ==== Parameters
# - crumbs: an array of crumbs
# ==== Options
# - campaigns: one or several campaigns for which production supports are looked for. Default: current campaigns.
# Accepts the same parameters as ActivityProduction.of_campaign since it actually calls this method.
# TODO: when refactoring, move this method to ActivityProduction model, as ActivityProduction#of_crumbs(crumbs = [], options = {})
def production_supports(*crumbs)
options = crumbs.extract_options!
options[:campaigns] ||= Campaign.current
ActivityProduction.of_campaign(options[:campaigns].first).distinct
.joins(:support)
.where('products.id IN (?)', Crumb.products(*crumbs, no_contents: true).map(&:id))
end

# Returns all crumbs, grouped by interventions paths, for a given user.
# The result is an array of interventions paths.
# An intervention path is an array of crumbs, for a user, ordered by read_at,
# between a start crumb and a stop crumb.
# if data is inconsistent (e.g. no "stop" crumb corresponding to a "start" crumb)
# the buffer stores crumbs until the next "start" crumb in the chronological order,
# and the result receives what is found, whatever the crumbs table content, since the user may always
# requalify crumbs manually.
# TODO : put this into User model
def interventions_paths(user)
ActiveSupport::Deprecation.warn('Use User#interventions_paths instead')
user.interventions_paths
end
end

# Returns all the crumbs corresponding to the same intervention as the current
# crumb, i.e. the nearest start crumb including itself, the nearest stop crumb
# including itself, and all the crumbs in between including the crumb itself.
def intervention_path
start_read_at = read_at.utc
unless start?
start = siblings.where(nature: :start)
.where('read_at <= ?', start_read_at)
.order(read_at: :desc)
.first
start_read_at = start.read_at.utc if start
end
stop_read_at = read_at.utc
unless stop?
stop = siblings.where(nature: :stop)
.where('read_at >= ?', stop_read_at)
.order(nature: :desc, read_at: :asc)
.first
stop_read_at = stop.read_at.utc if stop
end
crumbs = siblings.where(read_at: start_read_at..stop_read_at).order(read_at: :asc)
return nil unless crumbs.any?
CrumbSet.new(crumbs)
end
end
Loading

0 comments on commit 8dfe258

Please sign in to comment.