/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2017 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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/>.
 */
package com.axelor.db.mapper.types;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;

import javax.validation.constraints.Digits;

import com.axelor.db.mapper.TypeAdapter;

public class DecimalAdapter implements TypeAdapter<BigDecimal> {

	@Override
	public Object adapt(Object value, Class<?> actualType, Type genericType,
			Annotation[] annotations) {
		
		Integer scale = null;
		for (Annotation a : annotations) {
			if (a instanceof Digits) {
				scale = ((Digits) a).fraction();
			}
		}
		
		if (value == null || (value instanceof String && "".equals(((String) value).trim())))
			return BigDecimal.ZERO;

		if (value instanceof BigDecimal)
			return adjust((BigDecimal)value, scale);
		
		return adjust(new BigDecimal(value.toString()), scale);
	}
	
	private BigDecimal adjust(BigDecimal value, Integer scale) {
		if (scale != null)
			return value.setScale(scale, RoundingMode.HALF_UP);
		return value;
	}
}

@@ -866,16 +866,49 @@
 gMode;%0A%0A
+import javax.persistence.Column;%0A
 import j
@@ -1136,20 +1136,17 @@
 ricType,
-%0A%09%09%09
+ 
 Annotati
@@ -1165,18 +1165,16 @@
 ions) %7B%0A
-%09%09
 %0A%09%09Integ
@@ -1190,16 +1190,43 @@
 = null;%0A
+%09%09Boolean nullable = null;%0A
 %09%09for (A
@@ -1332,19 +1332,106 @@
 %7D%0A%09%09
-%7D%0A%09%09%0A%09%09if (
+%09if (a instanceof Column) %7B%0A%09%09%09%09nullable = ((Column) a).nullable();%0A%09%09%09%7D%0A%09%09%7D%0A%09%09%0A%09%09boolean empty = 
 valu
@@ -1506,27 +1506,76 @@
 trim()))
-)%0A%09%09%09return
+;%0A%09%09if (empty) %7B%0A%09%09%09return nullable == Boolean.TRUE ? null :
  BigDeci
@@ -1583,16 +1583,20 @@
 al.ZERO;
+%0A%09%09%7D
 %0A%0A%09%09if (
@@ -1623,16 +1623,18 @@
 Decimal)
+ %7B
 %0A%09%09%09retu
@@ -1655,16 +1655,17 @@
 Decimal)
+ 
 value, s
@@ -1673,16 +1673,17 @@
 ale);%0A%09%09
+%7D
 %0A%09%09retur
@@ -1736,17 +1736,16 @@
 le);%0A%09%7D%0A
-%09
 %0A%09privat
@@ -1819,16 +1819,18 @@
 != null)
+ %7B
 %0A%09%09%09retu
@@ -1877,16 +1877,20 @@
 LF_UP);%0A
+%09%09%7D%0A
 %09%09return

Fix decimal adapter