Class: Ekylibre::PurchasesExchanger

Inherits:
ActiveExchanger::Base show all
Defined in:
app/exchangers/ekylibre/purchases_exchanger.rb

Instance Attribute Summary

Attributes inherited from ActiveExchanger::Base

#file, #supervisor

Instance Method Summary collapse

Methods inherited from ActiveExchanger::Base

build, check, check_by_default, deprecated?, exchanger_name, export, exporters, find, find_and_import, find_by, human_name, import, import!, importers, importers_selection, inherited, register_exchanger

Constructor Details

#initialize(file, supervisor, options = {}) ⇒ PurchasesExchanger

Returns a new instance of PurchasesExchanger.


3
4
5
6
7
# File 'app/exchangers/ekylibre/purchases_exchanger.rb', line 3

def initialize(file, supervisor, options = {})
  super file, supervisor
  @attachments_dir = options['attachments_path']
  @attachments_dir &&= Pathname.new(@attachments_dir)
end

Instance Method Details

#checkObject


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/exchangers/ekylibre/purchases_exchanger.rb', line 9

def check
  rows = CSV.read(file, headers: true)
  w.count = rows.size
  purchase_ids = []
  now = Time.zone.now
  valid = true

  vinfos = 9 - 1

  rows.each_with_index do |row, index|
    line_number = index + 2
    prompt = "L#{line_number.to_s.yellow}"

    r = {
      invoiced_at:        (row[0].blank? ? nil : Date.parse(row[0].to_s)),
      supplier_full_name: (row[1].blank? ? nil : row[1]),
      reference_number:   (row[2].blank? ? nil : row[2].upcase),
      variant_code:       (row[3].blank? ? nil : row[3]),
      annotation:         (row[4].blank? ? nil : row[4]),
      quantity:           (row[5].blank? ? nil : row[5].tr(',', '.').to_d),
      unit_pretax_amount: (row[6].blank? ? nil : row[6].tr(',', '.').to_d),
      vat_percentage:     (row[7].blank? ? nil : row[7].tr(',', '.').to_d),
      depreciate:         %w[1 t true yes ok].include?(row[8].to_s.strip.downcase),
      # Variant definition
      variant: {
        variety:                 row[vinfos + 1],
        product_account:         row[vinfos + 2],
        charge_account:          row[vinfos + 3],
        fixed_asset_account: row[vinfos + 4],
        fixed_asset_allocation_account: row[vinfos + 5],
        fixed_asset_expenses_account:   row[vinfos + 6]
      }
    }.to_struct

    # Check date
    unless r.invoiced_at
      w.error "No date given at #{prompt}"
      valid = false
    end

    # Check variant
    unless r.variant_code
      w.error "Variant identifiant must be given at #{prompt}"
      valid = false
    end

    # Check supplier
    unless supplier = Entity.where('full_name ILIKE ?', r.supplier_full_name).first
      w.error "Cannot find supplier #{r.supplier_full_name} at #{prompt}"
      valid = false
    end
  end
  valid
end

#importObject


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
# File 'app/exchangers/ekylibre/purchases_exchanger.rb', line 64

def import
  rows = CSV.read(file, headers: true)
  w.count = rows.size
  purchase_ids = []
  now = Time.zone.now

  vinfos = 9 - 1

  rows.each_with_index do |row, index|
    line_index = index + 2

    r = {
      invoiced_at:        (row[0].blank? ? nil : Date.parse(row[0].to_s)),
      supplier_full_name: (row[1].blank? ? nil : row[1]),
      reference_number:   (row[2].blank? ? nil : row[2].upcase),
      variant_code:       (row[3].blank? ? nil : row[3]),
      annotation:         (row[4].blank? ? nil : row[4]),
      quantity:           (row[5].blank? ? nil : row[5].tr(',', '.').to_d),
      unit_pretax_amount: (row[6].blank? ? nil : row[6].tr(',', '.').to_d),
      vat_percentage:     (row[7].blank? ? nil : row[7].tr(',', '.').to_d),
      depreciate:         %w[1 t true yes ok].include?(row[8].to_s.strip.downcase),
      # Variant definition
      variant: {
        variety:                 row[vinfos + 1],
        product_account:         row[vinfos + 2],
        charge_account:          row[vinfos + 3],
        fixed_asset_account: row[vinfos + 4],
        fixed_asset_allocation_account: row[vinfos + 5],
        fixed_asset_expenses_account:   row[vinfos + 6]
      },

      # Extra infos
      document_reference_number: "#{Date.parse(row[0].to_s)}_#{row[1]}_#{row[2]}".tr(' ', '-'),
      description: now.l
    }.to_struct

    # Find or import a variant
    unless r.variant_code
      raise "Variant identifiant must be given at line #{line_index}"
    end
    unless variant = ProductNatureVariant.find_by(work_number: r.variant_code)
      if Nomen::ProductNatureVariant.find(r.variant_code)
        variant = ProductNatureVariant.import_from_nomenclature(r.variant_code)
      else
        if r.variant[:fixed_asset_account]
          suffix = r.variant[:fixed_asset_account][1..-1]
          r.variant[:fixed_asset_allocation_account] ||= "28#{suffix}"
          r.variant[:fixed_asset_expenses_account] ||= "68#{suffix}"
          r.variant[:fixed_asset_depreciation_method] ||= :simplified_linear
          r.variant[:fixed_asset_depreciation_percentage] ||= 15
        end
        %w[product charge fixed_asset fixed_asset_allocation fixed_asset_expenses].each do |type|
          key = "#{type}_account".to_sym
           = r.variant[key].to_s.split(':')
           = .shift
           = .shift
          next if .blank?
          unless  = Account.find_by(number: .strip)
             = Account.create!(name:  || , number: )
          end
          r.variant[key] = 
        end
        attrs = r.variant.select { |k, v| v.present? && k != :variety }
        attrs[:name] = r.variant_code
        attrs[:saleable] = true if attrs[:product_account]
        attrs[:purchasable] = true if attrs[:charge_account]
        attrs[:depreciable] = true if attrs[:fixed_asset_account]
        unless category = ProductNatureCategory.find_by(attrs)
          category = ProductNatureCategory.create!(attrs.merge(active: true, pictogram: :undefined))
        end
        attrs[:variety] = r.variant[:variety] || :product
        # puts r.variant[:variety].inspect.red
        unless nature = category.natures.first
          nature = category.natures.create!(name: attrs[:name], variety: attrs[:variety], population_counting: :decimal)
        end
        unless variant = nature.variants.first
          variant = nature.variants.create!(name: attrs[:name], variety: attrs[:variety], unit_name: 'Unit')
        end
      end
    end
    raise "Unknown variant at line #{line_index}" unless variant

    # Find or create a purchase
    # if supplier and r.invoiced_at and r.reference_number
    # see if purchase exist anyway
    unless purchase = PurchaseInvoice.find_by(reference_number: r.reference_number)
      # Find supplier
      unless supplier = Entity.where('full_name ILIKE ?', r.supplier_full_name).first
        raise "Cannot find supplier #{r.supplier_full_name} at line #{line_index}"
      end
      raise "Missing invoice date at line #{line_index}" unless r.invoiced_at
      purchase = PurchaseInvoice.create!(
        planned_at: r.invoiced_at,
        invoiced_at: r.invoiced_at,
        reference_number: r.reference_number,
        supplier: supplier,
        nature: PurchaseNature.actives.first,
        description: r.description
      )
      if @attachments_dir.present?
        attachment_potential_path = @attachments_dir.join(purchase.supplier.name.parameterize,
                                                          purchase.reference_number + ".*")
        attachment_paths = Dir.glob(attachment_potential_path)
        attachment_paths.each do |attachment_path|
          doc = Document.new(file: File.open(attachment_path))
          purchase.attachments.create!(document: doc)
        end
      end
      purchase_ids << purchase.id
    end

    # Find or create a tax
    # TODO: search country before for good tax request (country and amount)
    # country via supplier if information exist
    raise "Missing VAT at line #{line_index}" unless r.vat_percentage
    item = Nomen::Tax.find_by(country: purchase.supplier.country.to_sym, amount: r.vat_percentage)
    tax = Tax.import_from_nomenclature(item.name)

    # find or create a purchase line
    unless purchase.items.find_by(pretax_amount: r.pretax_amount, variant_id: variant.id, tax_id: tax.id)
      raise "Missing quantity at line #{line_index}" unless r.quantity
      # puts r.variant_code.inspect.red
      purchase.items.create!(quantity: r.quantity, tax: tax, unit_pretax_amount: r.unit_pretax_amount, variant: variant, fixed: r.depreciate)
    end

    w.check_point
  end

end