Class: Backend::EntitiesController

Inherits:
BaseController show all
Defined in:
app/controllers/backend/entities_controller.rb

Instance Attribute Summary

Attributes inherited from ApplicationController

#current_theme

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseController

accounts_range_crit, crit_params, journal_entries_states_crit, journal_period_crit, journals_crit, search_conditions

Methods inherited from ApplicationController

#after_sign_in_path_for, #authorized?, human_action_name, #human_action_name

Class Method Details

.entities_conditionsObject

params:

:q Text search

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/controllers/backend/entities_controller.rb', line 32

def self.entities_conditions
  code = ''
  code = search_conditions(entities: [:number, :full_name]) + " ||= []\n"
  code << "unless params[:state].blank?\n"
  code << "  if params[:state].include?('client')\n"
  code << "    c[0] << ' AND #{Entity.table_name}.client IS TRUE'\n"
  code << "  end\n"
  code << "  if params[:state].include?('supplier')\n"
  code << "    c[0] << ' AND #{Entity.table_name}.supplier IS TRUE'\n"
  code << "  end\n"
  code << "  if params[:state].include?('active')\n"
  code << "    c[0] << ' AND #{Entity.table_name}.active IS TRUE'\n"
  code << "  end\n"
  code << "end\n"
  code << "unless params[:nature].blank?\n"
  code << "  if Entity.nature.values.include?(params[:nature].to_sym)\n"
  code << "    c[0] << ' AND #{Entity.table_name}.nature = ?'\n"
  code << "    c << params[:nature]\n"
  code << "  end\n"
  code << "end\n"
  code << "c\n"
  code.c
end

Instance Method Details

#exportObject


193
194
195
196
197
198
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
232
233
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'app/controllers/backend/entities_controller.rb', line 193

def export
    if request.xhr?
      render partial: 'export_condition'
    else
      @columns = Entity.exportable_columns
      @conditions = ['special-subscriber'] # , "special-buyer", "special-relation"]
      @conditions += Entity.exportable_columns.collect { |c| "generic-entity-#{c.name}" }.sort
      @conditions += EntityAddress.exportable_columns.collect { |c| "generic-entity-address-#{c.name}" }.sort
      @conditions += ['generic-postal_zone-postal_code', 'generic-postal_zone-city']
      @conditions += ['generic-district-name']
      if request.post?
        from  = " FROM #{Entity.table_name} AS entity"
        from += " LEFT JOIN #{EntityAddress.table_name} AS address ON (address.entity_id=entity.id AND address.by_default IS TRUE AND address.deleted_at IS NULL)"
        from += " LEFT JOIN #{PostalZone.table_name} AS postal_zone ON (address.postal_zone_id=postal_zone.id})"
        from += " LEFT JOIN #{District.table_name} AS district ON (postal_zone.district_id=district.id)"
        where = ' WHERE entity.active'
        select_array = []
        for k, v in params[:columns].select { |_k, v| v[:check].to_i == 1 }.sort { |a, b| a[1][:order].to_i <=> b[1][:order].to_i }
          if k =~ /^custom_field\-/
            id = k.split('-')[1][2..-1].to_i
            if custom_field = CustomField.find_by_id(id)
              # from += " LEFT JOIN #{CustomFieldDatum.table_name} AS _c#{id} ON (entity.id=_c#{id}.entity_id AND _c#{id}.custom_field_id=#{id})"
              if custom_field.nature == 'choice'
                select_array << ["_cc#{id}.value AS custom_field_#{id}", v[:label]]
                # from += " LEFT JOIN #{CustomFieldChoice.table_name} AS _cc#{id} ON (_cc#{id}.id=_c#{id}.choice_value_id)"
                from += " LEFT JOIN #{CustomFieldChoice.table_name} AS _cc#{id} ON (_cc#{id}.id=#{custom_field.column_name})"
              else
                # select_array << [ "_c#{id}.#{custom_field.nature}_value AS custom_field_#{id}", v[:label]]
                select_array << ["#{custom_field.column_name} AS custom_field_#{id}", v[:label]]
              end
            end
          else
            select_array << [k.tr('-', '.'), v[:label]]
          end
        end
        if params[:conditions]
          code = params[:conditions].collect do |_id, preferences|
            condition = preferences[:type]
            expr = if condition == 'special-subscriber'
                     if nature = SubscriptionNature.find_by_id(preferences[:nature])
                       subn = preferences[preferences[:nature]]
                       products = (subn[:products] || {}).select { |_k, v| v.to_i == 1 }.collect { |k, _v| k }
                       products = "product_id IN (#{products.join(', ')})" unless products.empty?
                       products = "#{products + ' OR ' if products.is_a?(String) && subn[:no_products]}#{'product_id IS NULL' if subn[:no_products]}"
                       products = " AND (#{products})" unless products.blank?
                       subscribed_at = ''
                       if subn[:use_subscribed_at]
                         subscribed_at = ' AND (' + if nature.period?
                                                      x = begin
                                                            subn[:subscribed_at].to_date
                                                          rescue
                                                            Time.zone.today
                                                          end
                                                      "'" + ActiveRecord::Base.connection.quoted_date(x) + "'"
                                                    else
                                                      subn[:subscribed_at].to_i.to_s
                       end + " BETWEEN #{nature.start} AND #{nature.finish})"
                     end
                       timestamp = ''
                       if condition[:use_timestamp]
                         x = begin
                               condition[:timestamp][:started_at].to_date
                             rescue
                               Time.zone.today
                             end
                         y = begin
                               condition[:timestamp][:stopped_at].to_date
                             rescue
                               Time.zone.today
                             end
                         timestamp = " AND (created_at BETWEEN '#{ActiveRecord::Base.connection.quoted_date(x)}' AND '#{ActiveRecord::Base.connection.quoted_date(y)}')"
                       end
                       "entity.id IN (SELECT entity_id FROM #{Subscription.table_name} AS subscriptions WHERE nature_id=#{nature.id}" + products + subscribed_at + timestamp + ')'
                     else
                       'true'
                   end
                   elsif condition =~ /^generic/
                     klass = condition.split(/\-/)[1].classify.constantize
                     attribute = condition.split(/\-/)[2]
                     column = klass.columns_hash[attribute]
                     ListingNode.condition(condition.split(/\-/)[1..2].join('.'), preferences[:comparator], preferences[:comparated], column.sql_type)
          end
            "\n" + (preferences[:reverse].to_i == 1 ? 'NOT ' : '') + "(#{expr})"
          end.join(params[:check] == 'and' ? ' AND ' : ' OR ')
          where += " AND (#{code})"
      end
        select = 'SELECT ' + select_array.collect { |x| x[0] }.join(', ')
        query = select + "\n" + from + "\n" + where

        result = ActiveRecord::Base.connection.select_rows(query)
        result.insert(0, select_array.collect { |x| x[1] })
        csv_string = CSV.generate do |csv|
          for item in result
            csv << item
          end
        end
        send_data(csv_string, filename: 'export.csv', type: Mime::CSV)
    end
  end
end

#importObject


294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'app/controllers/backend/entities_controller.rb', line 294

def import
  @step = begin
            params[:id].to_sym
          rescue
            :upload
          end
  if @step == :upload
    @formats = [['CSV', :csv]] # , ["CSV Excel", :xcsv], ["XLS Excel", :xls], ["OpenDocument", :ods]]
    if request.post? && params[:upload]
      data = params[:upload]
      tmp = Rails.root.join('tmp', 'uploads')
      FileUtils.mkdir_p(tmp)
      file = tmp.join("entities_import_#{data.original_filename.gsub(/[^\w]/, '_')}")
      File.open(file, 'wb') { |f| f.write(data.read) }
      session[:entities_import_file] = file
      redirect_to action: :import, id: :columns
    end
  elsif @step == :columns
    unless File.exist?(session[:entities_import_file].to_s)
      redirect_to action: :import, id: :upload
    end
    csv = CSV.open(session[:entities_import_file])
    @columns = csv.shift
    @first_item = csv.shift
    @options = Entity.importable_columns
    if request.post?
      all_columns = params[:columns].dup.delete_if { |_k, v| v.match(/^special-dont_use/) || v.blank? }
      columns = params[:columns].delete_if { |_k, v| v.match(/^special-/) || v.blank? }
      if (columns.values.size - columns.values.uniq.size) > 0
        notify_error_now(:columns_are_already_uses)
        return
      end
      cols = {}
      columns = all_columns
      for prefix in columns.values.collect { |x| x.split(/\-/)[0] }.uniq
        cols[prefix.to_sym] = {}
        columns.select { |_k, v| v.match(/^#{prefix}-/) }.each { |k, v| cols[prefix.to_sym][k.to_s] = v.split(/\-/)[1].to_sym }
      end
      cols[:entity] ||= {}
      if cols[:entity].keys.size <= 0 || !cols[:entity].values.detect { |x| x == :last_name }
        notify_error_now(:entity_columns_are_needed)
        return
      end
      # raise StandardError.new columns.inspect+"\n"+cols.inspect
      session[:entities_import_cols] = cols
      redirect_to action: :import, id: :validate
    end
  elsif @step == :validate
    file = session[:entities_import_file]
    cols = session[:entities_import_cols]
    if request.post?
      @report = Entity.import(file, cols, no_simulation: true, ignore: session[:entities_import_ignore])
      notify_success(:importation_finished)
      redirect_to action: :import, id: :upload
    else
      @report = Entity.import(file, cols)
      session[:entities_import_ignore] = @report[:errors].keys
    end
  end
end

#mergeObject


355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'app/controllers/backend/entities_controller.rb', line 355

def merge
  if request.post?
    return unless @master = find_and_check(id: params[:master])
    return unless @double = find_and_check(id: params[:double])
    if @master.id == @double.id
      notify_error_now(:cannot_merge_an_entity_with_itself)
      return
    end
    @master.merge_with(@double, current_user)
    begin
      notify_success(:merge_is_done)
      redirect_to action: :show, id: @master.id
    rescue
      notify_error_now(:cannot_merge_entities)
    end
  end
end