Class: Order

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
DateTimeAttributeValidate
Defined in:
app/models/order.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#ignore_warningsObject

Returns the value of attribute ignore_warnings


4
5
6
# File 'app/models/order.rb', line 4

def ignore_warnings
  @ignore_warnings
end

Class Method Details

.finish_ended!Object


285
286
287
288
289
290
291
292
293
294
# File 'app/models/order.rb', line 285

def self.finish_ended!
  orders = Order.where.not(end_action: Order.end_actions[:no_end_action]).where(state: 'open').where('ends <= ?', DateTime.now)
  orders.each do |order|
    begin
      order.do_end_action!
    rescue => error
      ExceptionNotifier.notify_exception(error, data: {order_id: order.id})
    end
  end
end

Instance Method Details

#article_idsObject


77
78
79
# File 'app/models/order.rb', line 77

def article_ids
  @article_ids ||= order_articles.map { |a| a.article_id.to_s }
end

#article_ids=(ids) ⇒ Object

Save ids, and create/delete order_articles after successfully saved the order


73
74
75
# File 'app/models/order.rb', line 73

def article_ids=(ids)
  @article_ids = ids
end

#articles_for_orderingObject


51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/models/order.rb', line 51

def articles_for_ordering
  if stockit?
    # make sure to include those articles which are no longer available
    # but which have already been ordered in this stock order
    StockArticle.available.includes(:article_category).
      order('article_categories.name', 'articles.name').reject{ |a|
      a.quantity_available <= 0 && !a.ordered_in_order?(self)
    }.group_by { |a| a..name }
  else
    supplier.articles.available.group_by { |a| a..name }
  end
end

#articles_grouped_by_categoryObject

Returns OrderArticles in a nested Array, grouped by category and ordered by article name. The array has the following form: e.g: [[“drugs”,[teethpaste, toiletpaper]], [“fruits” => [apple, banana, lemon]]]


138
139
140
141
142
143
144
# File 'app/models/order.rb', line 138

def articles_grouped_by_category
  @articles_grouped_by_category ||= order_articles.
      includes([:article_price, :group_order_articles, :article => :article_category]).
      order('articles.name').
      group_by { |a| a.article..name }.
      sort { |a, b| a[0] <=> b[0] }
end

#articles_sort_by_categoryObject


146
147
148
149
150
# File 'app/models/order.rb', line 146

def articles_sort_by_category
  order_articles.includes(:article).order('articles.name').sort do |a,b|
    a.article..name <=> b.article..name
  end
end

#boxfill?Boolean

Returns:

  • (Boolean)

98
99
100
# File 'app/models/order.rb', line 98

def boxfill?
  FoodsoftConfig[:use_boxfill] && open? && boxfill.present? && boxfill < Time.now
end

#close!(user, transaction_type = nil) ⇒ Object

Sets order.status to 'close' and updates all Ordergroup.account_balances


234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'app/models/order.rb', line 234

def close!(user, transaction_type = nil)
  raise I18n.t('orders.model.error_closed') if closed?
  transaction_note = I18n.t('orders.model.notice_close', :name => name,
                            :ends => ends.strftime(I18n.t('date.formats.default')))

  gos = group_orders.includes(:ordergroup)              # Fetch group_orders
  gos.each { |group_order| group_order.update_price! }  # Update prices of group_orders

  transaction do                                        # Start updating account balances
    for group_order in gos
      if group_order.ordergroup
        price = group_order.price * -1                  # decrease! account balance
        group_order.ordergroup.add_financial_transaction!(price, transaction_note, user, transaction_type)
      end
    end

    if stockit?                                         # Decreases the quantity of stock_articles
      for oa in order_articles.includes(:article)
        oa.update_results!                              # Update units_to_order of order_article
        stock_changes.create! :stock_article => oa.article, :quantity => oa.units_to_order*-1
      end
    end

    self.update_attributes! :state => 'closed', :updated_by => user, :foodcoop_result => profit
  end
end

#close_direct!(user) ⇒ Object

Close the order directly, without automaticly updating ordergroups account balances


262
263
264
265
266
# File 'app/models/order.rb', line 262

def close_direct!(user)
  raise I18n.t('orders.model.error_closed') if closed?
  comments.create(user: user, text: I18n.t('orders.model.close_direct_message')) unless FoodsoftConfig[:charge_members_manually]
  update_attributes! state: 'closed', updated_by: user
end

#closed?Boolean

Returns:

  • (Boolean)

94
95
96
# File 'app/models/order.rb', line 94

def closed?
  state == "closed"
end

#do_end_action!Object


273
274
275
276
277
278
279
280
281
282
283
# File 'app/models/order.rb', line 273

def do_end_action!
  if auto_close?
    finish!(created_by)
  elsif auto_close_and_send?
    finish!(created_by)
    send_to_supplier!(created_by)
  elsif auto_close_and_send_min_quantity?
    finish!(created_by)
    send_to_supplier!(created_by) if sum >= supplier.min_order_quantity.to_r
  end
end

#erroneous_article_idsObject

Returns an array of article ids that lead to a validation error.


82
83
84
# File 'app/models/order.rb', line 82

def erroneous_article_ids
  @erroneous_article_ids ||= []
end

#expired?Boolean

Returns:

  • (Boolean)

106
107
108
# File 'app/models/order.rb', line 106

def expired?
  ends.present? && ends < Time.now
end

#finish!(user) ⇒ Object

Finishes this order. This will set the order state to “finish” and the end property to the current time. Ignored if the order is already finished.


199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'app/models/order.rb', line 199

def finish!(user)
  unless finished?
    Order.transaction do
      # set new order state (needed by notify_order_finished)
      update_attributes!(:state => 'finished', :ends => Time.now, :updated_by => user)

      # Update order_articles. Save the current article_price to keep price consistency
      # Also save results for each group_order_result
      # Clean up
      order_articles.includes(:article).each do |oa|
        oa.update_attribute(:article_price, oa.article.article_prices.first)
        oa.group_order_articles.each do |goa|
          goa.save_results!
          # Delete no longer required order-history (group_order_article_quantities) and
          # TODO: Do we need articles, which aren't ordered? (units_to_order == 0 ?)
          #    A: Yes, we do - for redistributing articles when the number of articles
          #       delivered changes, and for statistics on popular articles. Records
          #       with both tolerance and quantity zero can be deleted.
          #goa.group_order_article_quantities.clear
        end
      end

      # Update GroupOrder prices
      group_orders.each(&:update_price!)

      # Stats
      ordergroups.each(&:update_stats!)

      # Notifications
      Resque.enqueue(UserNotifier, FoodsoftConfig.scope, 'finished_order', self.id)
    end
  end
end

#finished?Boolean

Returns:

  • (Boolean)

90
91
92
# File 'app/models/order.rb', line 90

def finished?
  state == "finished"
end

#group_order(ordergroup) ⇒ Object

search GroupOrder of given Ordergroup


127
128
129
# File 'app/models/order.rb', line 127

def group_order(ordergroup)
  group_orders.where(:ordergroup_id => ordergroup.id).first
end

#include_articlesObject (protected)


305
306
307
# File 'app/models/order.rb', line 305

def include_articles
  errors.add(:articles, I18n.t('orders.model.error_nosel')) if article_ids.empty?
end

#init_datesObject

sets up first guess of dates when initializing a new object I guess `def initialize` would work, but it's tricky stackoverflow.com/questions/1186400


112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'app/models/order.rb', line 112

def init_dates
  self.starts ||= Time.now
  if FoodsoftConfig[:order_schedule]
    # try to be smart when picking a reference day
    last = (DateTime.parse(FoodsoftConfig[:order_schedule][:initial]) rescue nil)
    last ||= Order.finished.reorder(:starts).first.try(:starts)
    last ||= self.starts
    # adjust boxfill and end date
    self.boxfill ||= FoodsoftDateUtil.next_occurrence last, self.starts, FoodsoftConfig[:order_schedule][:boxfill] if is_boxfill_useful?
    self.ends ||= FoodsoftDateUtil.next_occurrence last, self.starts, FoodsoftConfig[:order_schedule][:ends]
  end
  self
end

#is_boxfill_useful?Boolean

Returns:

  • (Boolean)

102
103
104
# File 'app/models/order.rb', line 102

def is_boxfill_useful?
  FoodsoftConfig[:use_boxfill] && supplier.try(:has_tolerance?)
end

#keep_ordered_articlesObject (protected)


309
310
311
312
313
314
315
316
317
# File 'app/models/order.rb', line 309

def keep_ordered_articles
  chosen_order_articles = order_articles.where(article_id: article_ids)
  to_be_removed = order_articles - chosen_order_articles
  to_be_removed_but_ordered = to_be_removed.select { |a| a.quantity > 0 || a.tolerance > 0 }
  unless to_be_removed_but_ordered.empty? || ignore_warnings
    errors.add(:articles, I18n.t(stockit? ? 'orders.model.warning_ordered_stock' : 'orders.model.warning_ordered'))
    @erroneous_article_ids = to_be_removed_but_ordered.map { |a| a.article_id }
  end
end

#nameObject


47
48
49
# File 'app/models/order.rb', line 47

def name
  stockit? ? I18n.t('orders.model.stock') : supplier.name
end

#open?Boolean

Returns:

  • (Boolean)

86
87
88
# File 'app/models/order.rb', line 86

def open?
  state == "open"
end

#profit(options = {}) ⇒ Object

Returns the defecit/benefit for the foodcoop Requires a valid invoice, belonging to this order FIXME: Consider order.foodcoop_result


155
156
157
158
159
160
161
# File 'app/models/order.rb', line 155

def profit(options = {})
  markup = options[:without_markup] || false
  if invoice
    groups_sum = markup ? sum(:groups_without_markup) : sum(:groups)
    groups_sum - invoice.net_amount
  end
end

#save_order_articlesObject (protected)


319
320
321
322
323
324
325
326
327
328
# File 'app/models/order.rb', line 319

def save_order_articles
  # fetch selected articles
  articles_list = Article.find(article_ids)
  # create new order_articles
  (articles_list - articles).each { |article| order_articles.create(:article => article) }
  # delete old order_articles
  articles.reject { |article| articles_list.include?(article) }.each do |article|
    order_articles.detect { |order_article| order_article.article_id == article.id }.destroy
  end
end

#send_to_supplier!(user) ⇒ Object


268
269
270
271
# File 'app/models/order.rb', line 268

def send_to_supplier!(user)
  Mailer.order_result_supplier(user, self).deliver_now
  update!(last_sent_mail: Time.now)
end

#starts_before_endsObject (protected)


298
299
300
301
302
303
# File 'app/models/order.rb', line 298

def starts_before_ends
  delta = Rails.env.test? ? 1 : 0 # since Rails 4.2 tests appear to have time differences, with this validation failing
  errors.add(:ends, I18n.t('orders.model.error_starts_before_ends')) if ends && starts && ends <= (starts-delta)
  errors.add(:ends, I18n.t('orders.model.error_boxfill_before_ends')) if ends && boxfill && ends <= (boxfill-delta)
  errors.add(:boxfill, I18n.t('orders.model.error_starts_before_boxfill')) if boxfill && starts && boxfill <= (starts-delta)
end

#stock_group_orderObject


131
132
133
# File 'app/models/order.rb', line 131

def stock_group_order
  group_orders.where(:ordergroup_id => nil).first
end

#stockit?Boolean

Returns:

  • (Boolean)

43
44
45
# File 'app/models/order.rb', line 43

def stockit?
  supplier_id == 0
end

#sum(type = :gross) ⇒ Object

Returns the all round price of a finished order :groups returns the sum of all GroupOrders :clear returns the price without tax, deposit and markup :gross includes tax and deposit. this amount should be equal to suppliers bill :fc, guess what…


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'app/models/order.rb', line 168

def sum(type = :gross)
  total = 0
  if type == :net || type == :gross || type == :fc
    for oa in order_articles.ordered.includes(:article, :article_price)
      quantity = oa.units * oa.price.unit_quantity
      case type
        when :net
          total += quantity * oa.price.price
        when :gross
          total += quantity * oa.price.gross_price
        when :fc
          total += quantity * oa.price.fc_price
      end
    end
  elsif type == :groups || type == :groups_without_markup
    for go in group_orders.includes(group_order_articles: {order_article: [:article, :article_price]})
      for goa in go.group_order_articles
        case type
          when :groups
            total += goa.result * goa.order_article.price.fc_price
          when :groups_without_markup
            total += goa.result * goa.order_article.price.gross_price
        end
      end
    end
  end
  total
end

#supplier_articlesObject


64
65
66
67
68
69
70
# File 'app/models/order.rb', line 64

def supplier_articles
  if stockit?
    StockArticle.undeleted.reorder('articles.name')
  else
    supplier.articles.undeleted.reorder('articles.name')
  end
end