Add getting billing cost by domain change

fixes https://gitlab.com/entgra/product-iots/-/issues/1226
temp
osh 3 years ago
parent c135105889
commit 053a57c4f5

@ -29,15 +29,15 @@ public class DeviceList extends BasePaginatedResult {
private List<Device> devices = new ArrayList<>(); private List<Device> devices = new ArrayList<>();
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost;
@ApiModelProperty(value = "List of devices returned") @ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices") @JsonProperty("devices")
public List<Device> getList() { public List<Device> getList() {
return devices; return devices;
} }
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost;
public void setList(List<Device> devices) { public void setList(List<Device> devices) {
this.devices = devices; this.devices = devices;
} }

@ -119,6 +119,7 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid; import javax.validation.Valid;
@ -134,6 +135,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue; import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@ -359,9 +361,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
PaginationRequest request = new PaginationRequest(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit);
PaginationResult result; PaginationResult result;
DeviceList devices = new DeviceList(); DeviceList devices = new DeviceList();
int tenantId = 0;
RealmService realmService = DeviceMgtAPIUtils.getRealmService();
if (!tenantDomain.isEmpty()) {
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
} else {
tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
}
try { try {
result = dms.getAllDevicesBillings(request, tenantDomain, startDate, endDate, generateBill); result = dms.getAllDevicesBillings(request, tenantId, tenantDomain, startDate, endDate, generateBill);
} catch (Exception exception) { } catch (Exception exception) {
String msg = "Error occurred when trying to retrieve billing data"; String msg = "Error occurred when trying to retrieve billing data";
log.error(msg, exception); log.error(msg, exception);

@ -75,7 +75,7 @@ public class Device implements Serializable {
private List<Application> applications; private List<Application> applications;
@ApiModelProperty(name = "cost", value = "Cost charged per device.", required = false) @ApiModelProperty(name = "cost", value = "Cost charged per device.", required = false)
private Double cost; private double cost;
@ApiModelProperty(name = "daysUsed", value = "Number of days gone since device enrollment.", @ApiModelProperty(name = "daysUsed", value = "Number of days gone since device enrollment.",
required = false) required = false)
@ -105,11 +105,11 @@ public class Device implements Serializable {
this.properties = properties; this.properties = properties;
} }
public Double getCost() { public double getCost() {
return cost; return cost;
} }
public void setCost(Double cost) { public void setCost(double cost) {
this.cost = cost; this.cost = cost;
} }

@ -28,8 +28,6 @@ public class Cost {
private String tenantDomain; private String tenantDomain;
private Double cost; private Double cost;
private long subscriptionBeginning;
private long subscriptionEnd;
@XmlElement(name = "tenantDomain", required = true) @XmlElement(name = "tenantDomain", required = true)
public String getTenantDomain() { public String getTenantDomain() {
@ -49,24 +47,6 @@ public class Cost {
this.cost = cost; this.cost = cost;
} }
@XmlElement(name = "subscriptionBeginning", required = true)
public long getSubscriptionBeginning() {
return subscriptionBeginning;
}
public void setSubscriptionBeginning(long subscriptionBeginning) {
this.subscriptionBeginning = subscriptionBeginning;
}
@XmlElement(name = "subscriptionEnd", required = true)
public long getSubscriptionEnd() {
return subscriptionEnd;
}
public void setSubscriptionEnd(long subscriptionEnd) {
this.subscriptionEnd = subscriptionEnd;
}
@Override @Override
public String toString() { public String toString() {
return new Gson().toJson(this); return new Gson().toJson(this);

@ -0,0 +1,46 @@
package org.wso2.carbon.device.mgt.core.config.ui;
import javax.xml.bind.annotation.XmlElement;
public class Billing {
private boolean isHideBillGenerationInSuperTenant;
private boolean isHideBillGenerationInSubTenant;
private boolean isHideTotalCalculationInSuperTenant;
private boolean isHideTotalCalculationInSubTenant;
@XmlElement(name = "HideBillGenerationInSuperTenant")
public boolean isHideBillGenerationInSuperTenant() {
return isHideBillGenerationInSuperTenant;
}
public void setHideBillGenerationInSuperTenant(boolean hideBillGenerationInSuperTenant) {
isHideBillGenerationInSuperTenant = hideBillGenerationInSuperTenant;
}
@XmlElement(name = "HideBillGenerationInSubTenant")
public boolean isHideBillGenerationInSubTenant() {
return isHideBillGenerationInSubTenant;
}
public void setHideBillGenerationInSubTenant(boolean hideBillGenerationInSubTenant) {
isHideBillGenerationInSubTenant = hideBillGenerationInSubTenant;
}
@XmlElement(name = "HideTotalCalculationInSuperTenant")
public boolean isHideTotalCalculationInSuperTenant() {
return isHideTotalCalculationInSuperTenant;
}
public void setHideTotalCalculationInSuperTenant(boolean hideTotalCalculationInSuperTenant) {
isHideTotalCalculationInSuperTenant = hideTotalCalculationInSuperTenant;
}
@XmlElement(name = "HideTotalCalculationInSubTenant")
public boolean isHideTotalCalculationInSubTenant() {
return isHideTotalCalculationInSubTenant;
}
public void setHideTotalCalculationInSubTenant(boolean hideTotalCalculationInSubTenant) {
isHideTotalCalculationInSubTenant = hideTotalCalculationInSubTenant;
}
}

@ -33,6 +33,7 @@ public class UIConfiguration {
private boolean isSsoEnable; private boolean isSsoEnable;
private int sessionTimeOut; private int sessionTimeOut;
private int loginCacheCapacity; private int loginCacheCapacity;
private Billing billing;
@XmlElement(name = "AppRegistration", required=true) @XmlElement(name = "AppRegistration", required=true)
public AppRegistration getAppRegistration() { public AppRegistration getAppRegistration() {
@ -62,6 +63,15 @@ public class UIConfiguration {
isSsoEnable = ssoEnable; isSsoEnable = ssoEnable;
} }
@XmlElement(name = "Billing", required=true)
public Billing getBilling() {
return billing;
}
public void setBilling(Billing billing) {
this.billing = billing;
}
@XmlElement(name = "SessionTimeOut") @XmlElement(name = "SessionTimeOut")
public int getSessionTimeOut() { public int getSessionTimeOut() {
return sessionTimeOut; return sessionTimeOut;

@ -205,8 +205,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
devices.add(device); devices.add(device);
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices '" + throw new DeviceManagementDAOException("Error occurred while fetching the list of device billing ", e);
request.getOwner() + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }

@ -143,6 +143,14 @@ public final class DeviceManagementDAOUtil {
public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException { public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
String columnName = "LAST_BILLED_DATE";
ResultSetMetaData rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
for (int x = 1; x <= columns; x++) {
if (columnName.equals(rsmd.getColumnName(x))) {
enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
}
}
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setOwner(rs.getString("OWNER")); enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP"))); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
@ -150,7 +158,6 @@ public final class DeviceManagementDAOUtil {
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
return enrolmentInfo; return enrolmentInfo;
} }
@ -218,13 +225,14 @@ public final class DeviceManagementDAOUtil {
device.setDescription(rs.getString("DESCRIPTION")); device.setDescription(rs.getString("DESCRIPTION"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED")); device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED"));
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device;
// if (removedDevices) { // if (removedDevices) {
// device.setDaysUsed((int) rs.getLong("DAYS_USED")); // device.setDaysUsed((int) rs.getLong("DAYS_USED"));
// } else { // } else {
// device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED")); // device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED"));
// } // }
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device;
} }
public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException { public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException {

@ -207,7 +207,7 @@ public interface DeviceManagementProviderService {
* @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of * @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of
* devices. * devices.
*/ */
PaginationResult getAllDevicesBillings(PaginationRequest request, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException; PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException;
/** /**
* Returns the device of specified id. * Returns the device of specified id.

@ -139,6 +139,7 @@ import java.lang.reflect.Type;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
//import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; //import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
@ -937,35 +938,35 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public PaginationResult getAllDevicesBillings(PaginationRequest request, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException { public PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException {
if (request == null) { if (request == null) {
String msg = "Received incomplete pagination request for method getAllDeviceBillings"; String msg = "Received incomplete pagination request for method getAllDeviceBillings";
log.error(msg); log.error(msg);
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
DeviceManagerUtil.validateDeviceListPageSize(request);
PaginationResult paginationResult = new PaginationResult(); PaginationResult paginationResult = new PaginationResult();
Double totalCost = 0.0; double totalCost = 0.0;
// List<DeviceBilling> allDevices;
List<Device> allDevices; List<Device> allDevices;
int count = 0; int count = 0;
int tenantId = this.getTenantId();
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.beginTransaction();
// allDevices = deviceDAO.getDeviceBillList(request, tenantId, startDate, endDate); // allDevices = deviceDAO.getDeviceBillList(request, tenantId, startDate, endDate);
allDevices = deviceDAO.getDevices(request, tenantId); allDevices = deviceDAO.getDevices(request, tenantId);
count = deviceDAO.getDeviceCount(request, tenantId); count = deviceDAO.getDeviceCount(request, tenantId);
String metaKey = "PER_DEVICE_COST"; String metaKey = "PER_DEVICE_COST";
MetadataManagementDAOFactory.openConnection(); MetadataManagementDAOFactory.beginTransaction();
Metadata metadata = metadataDAO.getMetadata(tenantId, metaKey); Metadata metadata = metadataDAO.getMetadata(tenantId, metaKey);
Gson g = new Gson(); Gson g = new Gson();
Collection<Cost> costData = null;
Type collectionType = new TypeToken<Collection<Cost>>(){}.getType(); Type collectionType = new TypeToken<Collection<Cost>>(){}.getType();
Collection<Cost> costData = g.fromJson(metadata.getMetaValue(), collectionType); if (metadata != null) {
costData = g.fromJson(metadata.getMetaValue(), collectionType);
for (Cost tenantCost: costData) { for (Cost tenantCost: costData) {
if (tenantCost.getTenantDomain().equals(tenantDomain)) { if (tenantCost.getTenantDomain().equals(tenantDomain)) {
for (Device device: allDevices) { for (Device device: allDevices) {
@ -978,7 +979,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
for (int i=0; i<deviceStatus.size(); i++) { for (int i=0; i<deviceStatus.size(); i++) {
if(deviceStatus.get(i).getStatus().toString().equals("ACTIVE")) { if(deviceStatus.get(i).getStatus().toString().equals("ACTIVE")) {
if (deviceStatus.size()> i+1) { if (deviceStatus.size()> i+1) {
if (lastBilledDate == false) { if (!lastBilledDate) {
lastBilledDate = true; lastBilledDate = true;
if (device.getEnrolmentInfo().getLastBilledDate() == 0) { if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime()); dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
@ -993,7 +994,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
} }
} else { } else {
if (lastBilledDate == false) { if (!lastBilledDate) {
lastBilledDate = true; lastBilledDate = true;
if (device.getEnrolmentInfo().getLastBilledDate() == 0) { if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime()); dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
@ -1009,10 +1010,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
} }
long dateInDays = dateDiff / (1000*60*60*24); long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS);;
double cost = (tenantCost.getCost()/365)*dateInDays; double cost = (tenantCost.getCost()/365)*dateInDays;
totalCost = cost + totalCost; totalCost = cost + totalCost;
device.setCost(cost); device.setCost(Math.round(cost * 100.0) / 100.0);
device.setDaysUsed((int) dateInDays); device.setDaysUsed((int) dateInDays);
if (generateBill) { if (generateBill) {
@ -1021,69 +1022,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
} }
// for (DeviceBilling device: allDevices) { }
// device.setDeviceStatusInfo(getDeviceStatusHistory(device, startDate, endDate, true));
// long dateDiff = 0;
//
// List<DeviceStatus> deviceStatus = device.getDeviceStatusInfo();
// boolean lastBilledDate = false;
//// int startIndex = deviceStatus.indexOf("ACTIVE");
// for (int i=0; i<deviceStatus.size(); i++) {
// if(deviceStatus.get(i).getStatus().toString().equals("ACTIVE")) {
// if (deviceStatus.size()> i+1) {
// if (lastBilledDate == false) {
// lastBilledDate = true;
// if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
// dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
// } else {
// if (deviceStatus.get(i+1).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
// dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - device.getEnrolmentInfo().getLastBilledDate());
// }
//// dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - device.getEnrolmentInfo().getLastBilledDate());
// }
// } else {
// if ( deviceStatus.get(i).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
// dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
// }
//// dateDiff = dateDiff + (deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
// }
//// dateDiff = deviceStatus.get(i+1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime();
// } else {
// if (lastBilledDate == false) {
// lastBilledDate = true;
// if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
// dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
// } else {
// if (endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
// dateDiff = dateDiff +(endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
// }
//// dateDiff = dateDiff +(endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
// }
// } else {
// dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
// }
//// dateDiff = endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime();
// }
// }
// }
//
// long dateInDays = dateDiff / (1000*60*60*24);
// double cost = (test.getCost()/365)*dateInDays;
// totalCost = cost + totalCost;
// device.setCost(cost);
// device.setDaysUsed((int) dateInDays);
//
// if (generateBill) {
// Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// enrollmentDAO.updateEnrollmentLastBilledDate(device.getEnrolmentInfo(), timestamp, tenantId);
// }
//
//// if (cost == 0) {
//// allDevices.remove(device);
//// }
//
// }
} }
} }
@ -1091,19 +1030,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
String msg = "Error occurred while retrieving device list pertaining to the current tenant"; String msg = "Error occurred while retrieving device list pertaining to the current tenant";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (SQLException e) { }
String msg = "Error occurred while opening a connection to the data source"; catch (Exception e) {
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getAllDevices"; String msg = "Error occurred in getAllDevices";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
MetadataManagementDAOFactory.closeConnection();
} }
paginationResult.setData(allDevices); paginationResult.setData(allDevices);
paginationResult.setTotalCost(totalCost); paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0);
paginationResult.setRecordsFiltered(count); paginationResult.setRecordsFiltered(count);
paginationResult.setRecordsTotal(count); paginationResult.setRecordsTotal(count);
return paginationResult; return paginationResult;

@ -24,6 +24,12 @@
<SessionTimeOut>3600</SessionTimeOut> <SessionTimeOut>3600</SessionTimeOut>
<!-- maximum number of login cache entries --> <!-- maximum number of login cache entries -->
<LoginCacheCapacity>10000</LoginCacheCapacity> <LoginCacheCapacity>10000</LoginCacheCapacity>
<Billing>
<HideBillGenerationInSuperTenant>true</HideBillGenerationInSuperTenant>
<HideBillGenerationInSubTenant>true</HideBillGenerationInSubTenant>
<HideTotalCalculationInSuperTenant>true</HideTotalCalculationInSuperTenant>
<HideTotalCalculationInSubTenant>true</HideTotalCalculationInSubTenant>
</Billing>
<AppRegistration> <AppRegistration>
<Tags> <Tags>
<Tag>analytics_management</Tag> <Tag>analytics_management</Tag>

Loading…
Cancel
Save