Module: FacturX::Formatting

Defined in:
lib/factur_x/formatting.rb

Constant Summary collapse

AMOUNT_SCALE =
2
PERCENTAGE_SCALE =
2
UNIT_PRICE_SCALE =
4
QUANTITY_SCALE =
4
CII_DATE_FORMAT =
"%Y%m%d"
CII_DATE_FORMAT_CODE =
"102"

Class Method Summary collapse

Class Method Details

.amount(value) ⇒ Object



18
19
20
# File 'lib/factur_x/formatting.rb', line 18

def amount(value)
  fixed(value, AMOUNT_SCALE)
end

.date(value) ⇒ Object



34
35
36
# File 'lib/factur_x/formatting.rb', line 34

def date(value)
  to_date(value).strftime(CII_DATE_FORMAT)
end

.decimal(value) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/factur_x/formatting.rb', line 38

def decimal(value)
  case value
  when BigDecimal then value
  when Integer then BigDecimal(value)
  when Float then BigDecimal(value.to_s)
  when String then parse_string(value)
  when nil then raise Error, "expected a number, got nil"
  else coerce(value)
  end
end

.fixed(value, scale) ⇒ Object



49
50
51
52
# File 'lib/factur_x/formatting.rb', line 49

def fixed(value, scale)
  integer, fraction = decimal(value).round(scale).to_s("F").split(".")
  "#{integer}.#{fraction.ljust(scale, "0")}"
end

.percentage(value) ⇒ Object



22
23
24
# File 'lib/factur_x/formatting.rb', line 22

def percentage(value)
  fixed(value, PERCENTAGE_SCALE)
end

.quantity(value) ⇒ Object



30
31
32
# File 'lib/factur_x/formatting.rb', line 30

def quantity(value)
  trimmed(value, QUANTITY_SCALE, 0)
end

.trimmed(value, scale, minimum_scale) ⇒ Object

Renders with scale decimals at most, dropping trailing zeros but never falling below minimum_scale (BT-146 allows 4 decimals, BT-129 allows none).



56
57
58
59
60
61
# File 'lib/factur_x/formatting.rb', line 56

def trimmed(value, scale, minimum_scale)
  rounded = decimal(value).round(scale)
  integer, fraction = rounded.to_s("F").split(".")
  fraction = fraction.sub(/0+\z/, "").ljust(minimum_scale, "0")
  fraction.empty? ? integer : "#{integer}.#{fraction}"
end

.unit_price(value) ⇒ Object



26
27
28
# File 'lib/factur_x/formatting.rb', line 26

def unit_price(value)
  trimmed(value, UNIT_PRICE_SCALE, AMOUNT_SCALE)
end