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<>();
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost;
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
public List<Device> getList() {
return devices;
}
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost;
public void setList(List<Device> 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.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid;
@ -134,6 +135,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -359,9 +361,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
PaginationRequest request = new PaginationRequest(offset, limit);
PaginationResult result;
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 {
result = dms.getAllDevicesBillings(request, tenantDomain, startDate, endDate, generateBill);
result = dms.getAllDevicesBillings(request, tenantId, tenantDomain, startDate, endDate, generateBill);
} catch (Exception exception) {
String msg = "Error occurred when trying to retrieve billing data";
log.error(msg, exception);

@ -75,7 +75,7 @@ public class Device implements Serializable {
private List<Application> applications;
@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.",
required = false)
@ -105,11 +105,11 @@ public class Device implements Serializable {
this.properties = properties;
}
public Double getCost() {
public double getCost() {
return cost;
}
public void setCost(Double cost) {
public void setCost(double cost) {
this.cost = cost;
}

@ -28,8 +28,6 @@ public class Cost {
private String tenantDomain;
private Double cost;
private long subscriptionBeginning;
private long subscriptionEnd;
@XmlElement(name = "tenantDomain", required = true)
public String getTenantDomain() {
@ -49,24 +47,6 @@ public class 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
public String toString() {
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 int sessionTimeOut;
private int loginCacheCapacity;
private Billing billing;
@XmlElement(name = "AppRegistration", required=true)
public AppRegistration getAppRegistration() {
@ -62,6 +63,15 @@ public class UIConfiguration {
isSsoEnable = ssoEnable;
}
@XmlElement(name = "Billing", required=true)
public Billing getBilling() {
return billing;
}
public void setBilling(Billing billing) {
this.billing = billing;
}
@XmlElement(name = "SessionTimeOut")
public int getSessionTimeOut() {
return sessionTimeOut;

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

@ -143,6 +143,14 @@ public final class DeviceManagementDAOUtil {
public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
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.setOwner(rs.getString("OWNER"));
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.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
return enrolmentInfo;
}
@ -218,13 +225,14 @@ public final class DeviceManagementDAOUtil {
device.setDescription(rs.getString("DESCRIPTION"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED"));
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device;
// if (removedDevices) {
// device.setDaysUsed((int) rs.getLong("DAYS_USED"));
// } else {
// device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED"));
// }
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device;
}
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
* 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.

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

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

Loading…
Cancel
Save