diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java index 8c6c4945c4..9f0d32127e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java @@ -35,8 +35,11 @@ public class DeviceList extends BasePaginatedResult { @ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false) private String message; - @ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false) - private boolean billedDateIsValid; + @ApiModelProperty(name = "deviceCount", value = "Total count of all devices per tenant", required = false) + private double deviceCount; + + @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false) + private String billPeriod; @ApiModelProperty(value = "List of devices returned") @JsonProperty("devices") @@ -48,12 +51,20 @@ public class DeviceList extends BasePaginatedResult { this.devices = devices; } - public boolean isBilledDateIsValid() { - return billedDateIsValid; + public String getBillPeriod() { + return billPeriod; + } + + public void setBillPeriod(String billPeriod) { + this.billPeriod = billPeriod; + } + + public double getDeviceCount() { + return deviceCount; } - public void setBilledDateIsValid(boolean billedDateIsValid) { - this.billedDateIsValid = billedDateIsValid; + public void setDeviceCount(double deviceCount) { + this.deviceCount = deviceCount; } public String getMessage() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 469091d21e..585e4ffecf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -344,179 +344,6 @@ public interface DeviceManagementService { @QueryParam("limit") int limit); - - @GET - @Path("/billing") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Cost details of devices in a tenant", - notes = "Provides individual cost and total cost of all devices per tenant.", - tags = "Device Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", - response = DeviceList.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 304, - message = "Not Modified. \n Empty body because the client already has the latest version of " + - "the requested resource.\n"), - @ApiResponse( - code = 400, - message = "The incoming request has more than one selection criteria defined via the query parameters.", - response = ErrorResponse.class), - @ApiResponse( - code = 404, - message = "The search criteria did not match any device registered with the server.", - response = ErrorResponse.class), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the device list.", - response = ErrorResponse.class) - }) - Response getDevicesBilling( - @ApiParam( - name = "tenantDomain", - value = "The tenant domain.", - required = false) - @QueryParam("tenantDomain") - String tenantDomain, - @ApiParam( - name = "startDate", - value = "The start date.", - required = false) - @QueryParam("startDate") - Timestamp startDate, - @ApiParam( - name = "endDate", - value = "The end date.", - required = false) - @QueryParam("endDate") - Timestamp endDate, - @ApiParam( - name = "generateBill", - value = "The generate bill boolean.", - required = false) - @QueryParam("generateBill") - boolean generateBill, - @ApiParam( - name = "offset", - value = "The starting pagination index for the complete list of qualified items.", - required = false, - defaultValue = "0") - @QueryParam("offset") - int offset, - @ApiParam( - name = "limit", - value = "Provide how many device details you require from the starting pagination index/offset.", - required = false, - defaultValue = "10") - @QueryParam("limit") - int limit); - - - @GET - @Path("/billing/file") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Cost details of devices in a tenant", - notes = "Provides individual cost and total cost of all devices per tenant.", - tags = "Device Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", - response = DeviceList.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Content-Disposition", - description = "The content disposition of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 304, - message = "Not Modified. \n Empty body because the client already has the latest version of " + - "the requested resource.\n"), - @ApiResponse( - code = 400, - message = "The incoming request has more than one selection criteria defined via the query parameters.", - response = ErrorResponse.class), - @ApiResponse( - code = 404, - message = "The search criteria did not match any device registered with the server.", - response = ErrorResponse.class), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the device list.", - response = ErrorResponse.class) - }) - Response exportBilling( - @ApiParam( - name = "tenantDomain", - value = "The tenant domain.", - required = false) - @QueryParam("tenantDomain") - String tenantDomain, - @ApiParam( - name = "startDate", - value = "The start date.", - required = false) - @QueryParam("startDate") - Timestamp startDate, - @ApiParam( - name = "endDate", - value = "The end date.", - required = false) - @QueryParam("endDate") - Timestamp endDate, - @ApiParam( - name = "generateBill", - value = "The generate bill boolean.", - required = false) - @QueryParam("generateBill") - boolean generateBill); - @GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java index 3079dd4ad3..b0c850de95 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -65,6 +65,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.sql.Timestamp; import java.util.List; @SwaggerDefinition( @@ -110,7 +111,14 @@ import java.util.List; key = "perm:devices:permanent-delete", roles = {"Internal/devicemgt-admin"}, permissions = {"/device-mgt/admin/devices/permanent-delete"} - ) + ), + @Scope( + name = "Get Usage of Devices", + description = "Get Usage of Devices", + key = "perm:admin:usage:view", + roles = {"Internal/devicemgt-admin"}, + permissions = {"/device-mgt/admin/devices/usage/view"} + ), } ) public interface DeviceManagementAdminService { @@ -423,4 +431,78 @@ public interface DeviceManagementAdminService { List actions ); + @GET + @Path("/billing") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Cost details of devices in a tenant", + notes = "Provides individual cost and total cost of all devices per tenant.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:usage:view") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", + response = DeviceList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Content-Disposition", + description = "The content disposition of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client already has the latest version of " + + "the requested resource.\n"), + @ApiResponse( + code = 400, + message = "The incoming request has more than one selection criteria defined via the query parameters.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "The search criteria did not match any device registered with the server.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the device list.", + response = ErrorResponse.class) + }) + Response getBilling( + @ApiParam( + name = "tenantDomain", + value = "The tenant domain.", + required = false) + @QueryParam("tenantDomain") + String tenantDomain, + @ApiParam( + name = "startDate", + value = "The start date.", + required = false) + @QueryParam("startDate") + Timestamp startDate, + @ApiParam( + name = "endDate", + value = "The end date.", + required = false) + @QueryParam("endDate") + Timestamp endDate); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index b8c626cb41..9ffece7230 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -355,105 +355,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } - @GET - @Override - @Path("/billing") - public Response getDevicesBilling( - @QueryParam("tenantDomain") String tenantDomain, - @QueryParam("startDate") Timestamp startDate, - @QueryParam("endDate") Timestamp endDate, - @QueryParam("generateBill") boolean generateBill, - @QueryParam("offset") int offset, - @DefaultValue("10") - @QueryParam("limit") int limit) { - try { - RequestValidationUtil.validatePaginationParameters(offset, limit); - DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); - 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, tenantId, tenantDomain, startDate, endDate, generateBill); - } catch (Exception exception) { - String msg = "Error occurred when trying to retrieve billing data"; - log.error(msg, exception); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); - } - - int resultCount = result.getRecordsTotal(); - if (resultCount == 0) { - Response.status(Response.Status.OK).entity(devices).build(); - } - - devices.setList((List) result.getData()); - devices.setBilledDateIsValid(result.isBilledDateIsValid()); - devices.setMessage(result.getMessage()); - devices.setCount(result.getRecordsTotal()); - devices.setTotalCost(result.getTotalCost()); - return Response.status(Response.Status.OK).entity(devices).build(); - } catch (Exception e) { - String msg = "Error occurred while retrieving billing data"; - log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); - } - } - - @GET - @Override - @Path("/billing/file") - public Response exportBilling( - @QueryParam("tenantDomain") String tenantDomain, - @QueryParam("startDate") Timestamp startDate, - @QueryParam("endDate") Timestamp endDate, - @QueryParam("generateBill") boolean generateBill) { - - try { - DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); - PaginationResult result; - int tenantId = 0; - RealmService realmService = DeviceMgtAPIUtils.getRealmService(); - DeviceList devices = new DeviceList(); - - if (!tenantDomain.isEmpty()) { - tenantId = realmService.getTenantManager().getTenantId(tenantDomain); - } else { - tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - } - - try { - result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate, generateBill); - - } catch (Exception exception) { - String msg = "Error occurred when trying to retrieve billing data without pagination"; - log.error(msg, exception); - return null; - } - - devices.setList((List) result.getData()); - devices.setBilledDateIsValid(result.isBilledDateIsValid()); - devices.setMessage(result.getMessage()); - devices.setCount(result.getRecordsTotal()); - devices.setTotalCost(result.getTotalCost()); - return Response.status(Response.Status.OK).entity(devices).build(); - } catch (Exception e) { - String msg = "Error occurred while retrieving billing data without pagination"; - log.error(msg, e); - return null; - } - - } - @GET @Override @Path("/user-devices") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index e8314e3b00..acadf926f2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -52,12 +52,15 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.service.RealmService; import javax.validation.constraints.Size; import javax.ws.rs.Consumes; @@ -71,6 +74,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.sql.Timestamp; import java.util.List; @Path("/admin/devices") @@ -147,7 +151,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @Path("/device-owner") public Response updateEnrollOwner( @QueryParam("owner") String owner, - List deviceIdentifiers){ + List deviceIdentifiers) { try { if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) { String msg = "Device owner is updated successfully."; @@ -190,8 +194,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); - } - catch (InvalidDeviceException e) { + } catch (InvalidDeviceException e) { String msg = "Found Invalid devices"; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity( @@ -205,7 +208,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe public Response triggerCorrectiveActions( @PathParam("deviceId") String deviceIdentifier, @PathParam("featureCode") String featureCode, - List actions){ + List actions) { DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); PlatformConfigurationManagementService platformConfigurationManagementService = DeviceMgtAPIUtils .getPlatformConfigurationManagementService(); @@ -233,4 +236,51 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe } return Response.status(Response.Status.OK).entity("Triggered action successfully").build(); } + + @GET + @Override + @Path("/billing") + public Response getBilling( + @QueryParam("tenantDomain") String tenantDomain, + @QueryParam("startDate") Timestamp startDate, + @QueryParam("endDate") Timestamp endDate) { + try { + PaginationResult result; + int tenantId = 0; + RealmService realmService = DeviceMgtAPIUtils.getRealmService(); + + int tenantIdContext = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + + if (!tenantDomain.isEmpty()) { + tenantId = realmService.getTenantManager().getTenantId(tenantDomain); + } + if (tenantIdContext != MultitenantConstants.SUPER_TENANT_ID && tenantIdContext != tenantId) { + String msg = "Current logged in user is not authorized to access billing details of other tenants"; + log.error(msg); + return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); + } else { + DeviceList devices = new DeviceList(); + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate); + devices.setList((List) result.getData()); + devices.setDeviceCount(result.getTotalDeviceCount()); + devices.setMessage(result.getMessage()); + devices.setTotalCost(result.getTotalCost()); + devices.setBillPeriod(startDate.toString() + " - " + endDate.toString()); + return Response.status(Response.Status.OK).entity(devices).build(); + } + } catch (BadRequestException e) { + String msg = "Bad request, can't proceed. Hence verify the request and re-try"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving billing data"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (UserStoreException e) { + String msg = "Error occurred while processing tenant configuration."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java new file mode 100644 index 0000000000..ad7f9eaeb3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.Serializable; +import java.util.List; + +@ApiModel(value = "BillingResponse", description = "This class carries all information related to a billing response.") +public class BillingResponse implements Serializable { + + private static final long serialVersionUID = 1998101711L; + + @ApiModelProperty(name = "year", value = "Year of the billed period", + required = false) + private String year; + + @ApiModelProperty(name = "totalCostPerYear", value = "Bill for a period of year", required = false) + private double totalCostPerYear; + + @ApiModelProperty(name = "devices", value = "Billed list of devices per year", required = false) + private List device; + + @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false) + private String billPeriod; + + @ApiModelProperty(name = "startDate", value = "Start Date of period", required = false) + private String startDate; + + @ApiModelProperty(name = "endDate", value = "End Date of period", required = false) + private String endDate; + + @ApiModelProperty(name = "deviceCount", value = "Device count for a billing period", + required = false) + private int deviceCount; + + public BillingResponse() { + } + + public BillingResponse(String year, double totalCostPerYear, List device, String billPeriod, String startDate, String endDate, int deviceCount) { + this.year = year; + this.totalCostPerYear = totalCostPerYear; + this.device = device; + this.billPeriod = billPeriod; + this.startDate = startDate; + this.endDate = endDate; + this.deviceCount = deviceCount; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + public double getTotalCostPerYear() { + return totalCostPerYear; + } + + public void setTotalCostPerYear(double totalCostPerYear) { + this.totalCostPerYear = totalCostPerYear; + } + + public String getYear() { + return year; + } + + public void setYear(String year) { + this.year = year; + } + + public List getDevice() { + return device; + } + + public void setDevice(List device) { + this.device = device; + } + + public String getBillPeriod() { + return billPeriod; + } + + public void setBillPeriod(String billPeriod) { + this.billPeriod = billPeriod; + } + + public int getDeviceCount() { + return deviceCount; + } + + public void setDeviceCount(int deviceCount) { + this.deviceCount = deviceCount; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java index 553618d80c..b76f40471b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java @@ -47,18 +47,29 @@ public class PaginationResult implements Serializable { @ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false) private double totalCost; - @ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false) - private boolean billedDateIsValid; + @ApiModelProperty(name = "totalDeviceCount", value = "Total count of all devices per tenant", required = false) + private double totalDeviceCount; + + @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false) + private String billPeriod; @ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false) private String message; - public boolean isBilledDateIsValid() { - return billedDateIsValid; + public String getBillPeriod() { + return billPeriod; + } + + public void setBillPeriod(String billPeriod) { + this.billPeriod = billPeriod; + } + + public double getTotalDeviceCount() { + return totalDeviceCount; } - public void setBilledDateIsValid(boolean billedDateIsValid) { - this.billedDateIsValid = billedDateIsValid; + public void setTotalDeviceCount(double totalDeviceCount) { + this.totalDeviceCount = totalDeviceCount; } public String getMessage() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 8e03917f55..76cce46e99 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -44,6 +44,7 @@ public final class DeviceManagementConstants { public static final String DEVICE_CACHE = "DEVICE_CACHE"; public static final String API_RESOURCE_PERMISSION_CACHE = "API_RESOURCE_CACHE_CACHE"; public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE"; + public static final String BILLING_CACHE = "BILLING_CACHE"; public static final String META_KEY = "PER_DEVICE_COST"; public static final String ACTIVE_STATUS = "ACTIVE"; public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java new file mode 100644 index 0000000000..c805529849 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.cache; + +import java.sql.Timestamp; +import java.util.Objects; + +public class BillingCacheKey { + + private String tenantDomain; + private Timestamp startDate; + private Timestamp endDate; + private volatile int hashCode; + + public String getTenantDomain() { + return tenantDomain; + } + + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + public Timestamp getStartDate() { + return startDate; + } + + public void setStartDate(Timestamp startDate) { + this.startDate = startDate; + } + + public Timestamp getEndDate() { + return endDate; + } + + public void setEndDate(Timestamp endDate) { + this.endDate = endDate; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!BillingCacheKey.class.isAssignableFrom(obj.getClass())) { + return false; + } + final BillingCacheKey other = (BillingCacheKey) obj; + String thisId = this.tenantDomain + "_" + this.startDate + "_" + this.endDate; + String otherId = other.tenantDomain + "_" + other.startDate + "_" + this.endDate; + if (!thisId.equals(otherId)) { + return false; + } + return true; + } + + @Override + public int hashCode() { + if (hashCode == 0) { + hashCode = Objects.hash(tenantDomain, startDate, endDate); + } + return hashCode; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java new file mode 100644 index 0000000000..18723dc2d8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.cache; + +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; + +import java.sql.Timestamp; +import java.util.List; + +public interface BillingCacheManager { + /** + * Adds a given billing object to the billing-cache. + * @param startDate - startDate of the billing period. + * @param endDate - endDate of the billing period. + * @param paginationResult - PaginationResult object to be added. + * @param tenantDomain - Owning tenant of the billing. + * + */ + void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException; + + /** + * Removes a billing object from billing-cache. + * @param startDate - startDate of the billing period. + * @param endDate - endDate of the billing period. + * @param tenantDomain - Owning tenant of the billing. + * + */ + void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException; + + /** + * Removes a list of devices from billing-cache. + * @param billingList - List of Cache-Keys of the billing objects to be removed. + * + */ + void removeBillingsFromCache(List billingList) throws DeviceManagementException; + + /** + * Updates a given billing object in the billing-cache. + * @param startDate - startDate of the billing period. + * @param endDate - endDate of the billing period. + * @param paginationResult - PaginationResult object to be updated. + * @param tenantDomain - Owning tenant of the billing. + * + */ + void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException; + + /** + * Fetches a billing object from billing-cache. + * @param startDate - startDate of the billing period. + * @param endDate - endDate of the billing period. + * @param tenantDomain - Owning tenant of the billing. + * @return Device object + * + */ + PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java new file mode 100644 index 0000000000..e5b6cddaa1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.cache.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey; +import org.wso2.carbon.device.mgt.core.cache.BillingCacheManager; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; + +import javax.cache.Cache; +import java.sql.Timestamp; +import java.util.List; + +/** + * Implementation of BillingCacheManager. + */ +public class BillingCacheManagerImpl implements BillingCacheManager { + + private static final Log log = LogFactory.getLog(BillingCacheManagerImpl.class); + + private static BillingCacheManagerImpl billingCacheManager; + + private BillingCacheManagerImpl() { + } + + public static BillingCacheManagerImpl getInstance() { + if (billingCacheManager == null) { + synchronized (BillingCacheManagerImpl.class) { + if (billingCacheManager == null) { + billingCacheManager = new BillingCacheManagerImpl(); + } + } + } + return billingCacheManager; + } + + @Override + public void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { + Cache lCache = DeviceManagerUtil.getBillingCache(); + if (lCache != null) { + BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate); + if (lCache.containsKey(cacheKey)) { + this.updateBillingInCache(paginationResult, tenantDomain, startDate, endDate); + } else { + lCache.put(cacheKey, paginationResult); + } + } + } + + @Override + public void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { + Cache lCache = DeviceManagerUtil.getBillingCache(); + if (lCache != null) { + BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate); + if (lCache.containsKey(cacheKey)) { + lCache.remove(cacheKey); + } + } else { + String msg = "Failed to remove selected billing from cache"; + log.error(msg); + throw new DeviceManagementException(msg); + } + } + + @Override + public void removeBillingsFromCache(List billingList) throws DeviceManagementException { + Cache lCache = DeviceManagerUtil.getBillingCache(); + if (lCache != null) { + for (BillingCacheKey cacheKey : billingList) { + if (lCache.containsKey(cacheKey)) { + lCache.remove(cacheKey); + } + } + } else { + String msg = "Failed to remove billing from cache"; + log.error(msg); + throw new DeviceManagementException(msg); + } + } + + @Override + public void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { + Cache lCache = DeviceManagerUtil.getBillingCache(); + if (lCache != null) { + BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate); + if (lCache.containsKey(cacheKey)) { + lCache.replace(cacheKey, paginationResult); + } + } else { + String msg = "Failed to update billing cache"; + log.error(msg); + throw new DeviceManagementException(msg); + } + } + + // TODO remove null check from here and do cache enable check in the methods calling this + @Override + public PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) { + Cache lCache = DeviceManagerUtil.getBillingCache(); + if (lCache != null) { + return lCache.get(getCacheKey(tenantDomain, startDate, endDate)); + } + return null; + } + + /** + * This method generates the billing CacheKey and returns it. + */ + private BillingCacheKey getCacheKey(String tenantDomain, Timestamp startDate, Timestamp endDate) { + BillingCacheKey billingCacheKey = new BillingCacheKey(); + billingCacheKey.setTenantDomain(tenantDomain); + billingCacheKey.setStartDate(startDate); + billingCacheKey.setEndDate(endDate); + return billingCacheKey; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java index ebdfa35bfc..f2ad40abb7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java @@ -21,6 +21,7 @@ import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotif import org.wso2.carbon.device.mgt.common.roles.config.DefaultRoles; import org.wso2.carbon.device.mgt.core.config.analytics.OperationAnalyticsConfiguration; import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration; +import org.wso2.carbon.device.mgt.core.config.cache.BillingCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration; @@ -58,6 +59,7 @@ public final class DeviceManagementConfig { private DeviceStatusTaskConfig deviceStatusTaskConfig; private DeviceCacheConfiguration deviceCacheConfiguration; private GeoFenceCacheConfiguration geoFenceCacheConfiguration; + private BillingCacheConfiguration billingCacheConfiguration; private EventOperationTaskConfiguration eventOperationTaskConfiguration; private CertificateCacheConfiguration certificateCacheConfiguration; private OperationAnalyticsConfiguration operationAnalyticsConfiguration; @@ -169,6 +171,15 @@ public final class DeviceManagementConfig { this.geoFenceCacheConfiguration = geoFenceCacheConfiguration; } + @XmlElement(name = "BillingCacheConfiguration", required = true) + public BillingCacheConfiguration getBillingCacheConfiguration() { + return billingCacheConfiguration; + } + + public void setBillingCacheConfiguration(BillingCacheConfiguration billingCacheConfiguration) { + this.billingCacheConfiguration = billingCacheConfiguration; + } + @XmlElement(name = "EventOperationTaskConfiguration", required = true) public EventOperationTaskConfiguration getEventOperationTaskConfiguration() { return eventOperationTaskConfiguration; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java new file mode 100644 index 0000000000..b34b9c2b6e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.config.cache; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "BillingCacheConfiguration") +public class BillingCacheConfiguration { + private boolean isEnabled; + private int expiryTime; + private long capacity; + + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + @XmlElement(name = "ExpiryTime", required = true) + public int getExpiryTime() { + return expiryTime; + } + + public void setExpiryTime(int expiryTime) { + this.expiryTime = expiryTime; + } + + @XmlElement(name = "Capacity", required = true) + public long getCapacity() { + return capacity; + } + + public void setCapacity(long capacity) { + this.capacity = capacity; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java deleted file mode 100644 index dd0ddf4e28..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.wso2.carbon.device.mgt.core.dao; - -import org.wso2.carbon.device.mgt.common.Billing; - -import java.sql.Timestamp; -import java.util.List; - -public interface BillingDAO { - - void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException; - - List getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException; -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index fcf414ff08..e9c4e1bf9e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -293,6 +293,50 @@ public interface DeviceDAO { */ List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the not removed device list in a year of a given tenant without pagination. + * + * @param tenantId tenant id. + * @param startDate start date of usage period. + * @param endDate end date of usage period. + * @return returns a list of not removed devices enrolled in that year. + * @throws DeviceManagementDAOException + */ + List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException; + + /** + * This method is used to retrieve the removed device list in a year of a given tenant without pagination. + * + * @param tenantId tenant id. + * @param startDate start date of usage period. + * @param endDate end date of usage period. + * @return returns a list of removed devices enrolled in that year. + * @throws DeviceManagementDAOException + */ + List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException; + + /** + * This method is used to retrieve the not removed device list in the prior year of a given tenant without pagination. + * + * @param tenantId tenant id. + * @param startDate start date of usage period. + * @param endDate end date of usage period. + * @return returns a list of not removed devices enrolled prior to that year. + * @throws DeviceManagementDAOException + */ + List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException; + + /** + * This method is used to retrieve the removed device list in the prior year of a given tenant without pagination. + * + * @param tenantId tenant id. + * @param startDate start date of usage period. + * @param endDate end date of usage period. + * @return returns a list of removed devices enrolled prior to that year. + * @throws DeviceManagementDAOException + */ + List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException; + /** * This method is used to retrieve the devices of a given tenant without pagination. * @param tenantId tenant id. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 230a958d19..cbd7c697f4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -125,11 +125,6 @@ public class DeviceManagementDAOFactory { return new EnrollmentDAOImpl(); } - public static BillingDAO getBillingDAO() { - return new BillingDAOImpl(); - } - - public static TrackerDAO getTrackerDAO() { if (databaseEngine != null) { switch (databaseEngine) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java index 825fa64797..612ebb7609 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java @@ -33,8 +33,6 @@ public interface EnrollmentDAO { boolean updateEnrollmentStatus(List enrolmentInfos) throws DeviceManagementDAOException; - boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfos, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException; - int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; @Deprecated diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java deleted file mode 100644 index 4af343012b..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.wso2.carbon.device.mgt.core.dao.impl; - -import org.wso2.carbon.device.mgt.common.Billing; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.core.dao.BillingDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; - -import java.sql.*; -import java.util.ArrayList; -import java.util.List; - -public class BillingDAOImpl implements BillingDAO { - - @Override - public void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException { - - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "INSERT INTO DM_BILLING(DEVICE_ID, TENANT_ID, BILLING_START, BILLING_END) VALUES(?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[] {"invoice_id"}); - stmt.setInt(1, deviceId); - stmt.setInt(2,tenantId); - stmt.setTimestamp(3, billingStart); - stmt.setTimestamp(4, billingEnd); - stmt.execute(); - } catch (SQLException e) { - e.printStackTrace(); - throw new DeviceManagementDAOException("Error occurred while adding billing period", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public List getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException { - List billings = new ArrayList<>(); - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - EnrolmentInfo.Status status = null; - try { - conn = this.getConnection(); - String sql; - - sql = "SELECT * FROM DM_BILLING WHERE DEVICE_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, deviceId); - rs = stmt.executeQuery(); - - while (rs.next()) { - Billing bill = new Billing(rs.getInt("INVOICE_ID"), rs.getInt("DEVICE_ID"),rs.getInt("TENANT_ID"), - (rs.getTimestamp("BILLING_START").getTime()), (rs.getTimestamp("BILLING_END").getTime())); - billings.add(bill); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred getting billing periods", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return billings; - } - - private Connection getConnection() throws SQLException { - return DeviceManagementDAOFactory.getConnection(); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java index c237d4ce22..eb5373e2cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java @@ -25,13 +25,7 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO { conn = this.getConnection(); // either we list all status values for the device using the device id or only get status values for the given enrolment id String idType = isDeviceId ? "DEVICE_ID" : "ENROLMENT_ID"; - String sql; - - if (billingStatus) { - sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE STATUS IN ('ACTIVE','REMOVED') AND " + idType + " = ?"; - } else { - sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?"; - } + String sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?"; // filter the data based on a date range if specified if (fromDate != null){ @@ -41,6 +35,10 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO { sql += " AND UPDATE_TIME <= ?"; } + if (billingStatus) { + sql += " ORDER BY UPDATE_TIME DESC"; + } + stmt = conn.prepareStatement(sql); int i = 1; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index a8fbad8ff9..7b3e08cd50 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -144,28 +144,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { return status; } - @Override - public boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfo, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET LAST_BILLED_DATE = ? WHERE ID = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setLong(1, lastBilledDate.getTime()); - stmt.setInt(2, enrolmentInfo.getId()); - stmt.setInt(3, tenantId); - stmt.executeUpdate(); - return true; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while updating enrolment last billed date.", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override public int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 38fc88825d..b40b5f5f20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -84,7 +84,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + - "e.LAST_BILLED_DATE, " + "e.ID AS ENROLMENT_ID " + "FROM DM_ENROLMENT e, " + "(SELECT d.ID, " + @@ -188,6 +187,169 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + List devices = new ArrayList<>(); + try { + Connection conn = getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, " + + "DEVICE_IDENTIFICATION, " + + "DESCRIPTION, " + + "NAME, " + + "DATE_OF_ENROLMENT, " + + "STATUS, " + + "DATE_OF_LAST_UPDATE, " + + "TIMESTAMPDIFF(DAY, ?, DATE_OF_ENROLMENT) as DAYS_SINCE_ENROLLED " + + "FROM DM_DEVICE d, DM_ENROLMENT e " + + "WHERE " + + "e.TENANT_ID=? AND " + + "d.ID=e.DEVICE_ID AND " + + "STATUS !='REMOVED' AND " + + "(" + + "DATE_OF_ENROLMENT BETWEEN ? AND ? " + + ")"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, String.valueOf(endDate)); + stmt.setInt(2, tenantId); + stmt.setString(3, String.valueOf(startDate)); + stmt.setString(4, String.valueOf(endDate)); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs)); + } + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedYearly device billing ", e); + } + return devices; + } + + @Override + public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + Connection conn; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "select d.ID AS DEVICE_ID, " + + "DEVICE_IDENTIFICATION, " + + "DESCRIPTION, " + + "NAME, " + + "DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, " + + "STATUS, " + + "TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, DATE_OF_ENROLMENT) AS DAYS_USED " + + "from DM_DEVICE d, DM_ENROLMENT e " + + "where " + + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + + "STATUS ='REMOVED' and " + + "(" + + "DATE_OF_ENROLMENT between ? and ? " + + ") and " + + "(" + + "DATE_OF_LAST_UPDATE >= ? " + + ")"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.setString(2, String.valueOf(startDate)); + stmt.setString(3, String.valueOf(endDate)); + stmt.setString(4, String.valueOf(startDate)); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs)); + } + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedYearly device billing ", e); + } + return devices; + } + + @Override + public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + Connection conn; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "select d.ID AS DEVICE_ID, " + + "DEVICE_IDENTIFICATION, " + + "DESCRIPTION, " + + "NAME, " + + "DATE_OF_ENROLMENT, " + + "STATUS, " + + "DATE_OF_LAST_UPDATE, " + + "TIMESTAMPDIFF(DAY, ?, ?) as DAYS_SINCE_ENROLLED " + + "from DM_DEVICE d, DM_ENROLMENT e " + + "where " + + "e.TENANT_ID=? and " + + "d.ID=e.DEVICE_ID and " + + "STATUS !='REMOVED' and " + + "(" + + "DATE_OF_ENROLMENT < ? " + + ")"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, String.valueOf(endDate)); + stmt.setString(2, String.valueOf(startDate)); + stmt.setInt(3, tenantId); + stmt.setString(4, String.valueOf(startDate)); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs)); + } + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedPriorYears device billing ", e); + } + return devices; + } + + @Override + public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + Connection conn; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + String sql = "select d.ID AS DEVICE_ID, " + + "DEVICE_IDENTIFICATION, " + + "DESCRIPTION, " + + "NAME, " + + "DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, " + + "STATUS, " + + "TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, ?) AS DAYS_USED " + + "from DM_DEVICE d, DM_ENROLMENT e " + + "where " + + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + + "STATUS ='REMOVED' and " + + "(" + + "DATE_OF_ENROLMENT < ? " + + ") and " + + "(" + + "DATE_OF_LAST_UPDATE >= ? " + + ")"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, String.valueOf(startDate)); + stmt.setInt(2, tenantId); + stmt.setString(3, String.valueOf(startDate)); + stmt.setString(4, String.valueOf(startDate)); + ResultSet rs = stmt.executeQuery(); + + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs)); + } + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedPriorYears device billing ", e); + } + return devices; + } + //Return only not removed id list @Override public List getDeviceListWithoutPagination(int tenantId) @@ -197,10 +359,26 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT DM_DEVICE.ID AS DEVICE_ID, DEVICE_IDENTIFICATION, DESCRIPTION, DM_DEVICE.NAME AS DEVICE_NAME, DM_DEVICE_TYPE.NAME AS DEVICE_TYPE,\n" + - "DM_ENROLMENT.ID AS ENROLMENT_ID, DATE_OF_ENROLMENT,OWNER, OWNERSHIP,IS_TRANSFERRED, STATUS, DATE_OF_LAST_UPDATE, LAST_BILLED_DATE,\n" + - "TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED FROM DM_DEVICE JOIN DM_ENROLMENT\n" + - "ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) WHERE DM_ENROLMENT.TENANT_ID=?"; + String sql = "SELECT " + + "DM_DEVICE.ID AS DEVICE_ID, " + + "DEVICE_IDENTIFICATION, " + + "DESCRIPTION, " + + "DM_DEVICE.NAME AS DEVICE_NAME, " + + "DM_DEVICE_TYPE.NAME AS DEVICE_TYPE, " + + "DM_ENROLMENT.ID AS ENROLMENT_ID, " + + "DATE_OF_ENROLMENT, " + + "OWNER, " + + "OWNERSHIP, " + + "IS_TRANSFERRED, " + + "STATUS, " + + "DATE_OF_LAST_UPDATE, " + + "TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED " + + "FROM " + + "DM_DEVICE " + + "JOIN DM_ENROLMENT ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) " + + "JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) " + + "WHERE " + + "DM_ENROLMENT.TENANT_ID = ? "; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); ResultSet rs = stmt.executeQuery(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 08c5afd311..c65e37d15a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -263,6 +263,34 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } +// TODO - add Oracle support for below billing method + @Override + public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add Oracle support for below billing method + @Override + public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add Oracle support for below billing method + @Override + public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add Oracle support for below billing method + @Override + public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 7fdaaca4bd..b23056de98 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -179,6 +179,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + // TODO - add PostgreSQL support for below billing method + @Override + public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add PostgreSQL support for below billing method + @Override + public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add PostgreSQL support for below billing method + @Override + public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add PostgreSQL support for below billing method + @Override + public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + //Return only not removed id list @Override public List getDevicesIds(PaginationRequest request, int tenantId) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index baf3f92f61..e8f86c5c10 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -189,6 +189,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + // TODO - add SQL support for below billing method + @Override + public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add SQL support for below billing method + @Override + public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add SQL support for below billing method + @Override + public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + // TODO - add SQL support for below billing method + @Override + public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) + throws DeviceManagementDAOException { + return null; + } + + //Return only not removed id list @Override public List getDevicesIds(PaginationRequest request, int tenantId) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index 089bb4cf03..0fd111d76e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -144,14 +144,6 @@ 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"))); @@ -162,15 +154,12 @@ public final class DeviceManagementDAOUtil { return enrolmentInfo; } + /* This is used to set the enrollment data of the billing query */ public static EnrolmentInfo loadEnrolmentBilling(ResultSet rs) throws SQLException { EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); - enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE")); + enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); - if (EnrolmentInfo.Status.valueOf(rs.getString("STATUS")).equals("REMOVED")) { - enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); - } return enrolmentInfo; } @@ -245,29 +234,23 @@ public final class DeviceManagementDAOUtil { return device; } - public static Device loadDeviceIds(ResultSet rs) throws SQLException { + /* This is used to set the device data of the billing query */ + public static Device loadDeviceBilling(ResultSet rs) throws SQLException { Device device = new Device(); device.setId(rs.getInt("DEVICE_ID")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - device.setEnrolmentInfo(loadEnrolmentStatus(rs)); + device.setName(rs.getString("DESCRIPTION")); + device.setDescription(rs.getString("NAME")); + device.setEnrolmentInfo(loadEnrolmentBilling(rs)); return device; } - public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException { - DeviceBilling device = new DeviceBilling(); - device.setId(rs.getInt("ID")); - device.setName(rs.getString("DEVICE_NAME")); - device.setDescription(rs.getString("DESCRIPTION")); + public static Device loadDeviceIds(ResultSet rs) throws SQLException { + Device device = new Device(); + device.setId(rs.getInt("DEVICE_ID")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED")); - device.setEnrolmentInfo(loadEnrolmentBilling(rs)); + device.setEnrolmentInfo(loadEnrolmentStatus(rs)); return device; -// if (removedDevices) { -// device.setDaysUsed((int) rs.getLong("DAYS_USED")); -// } else { -// device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED")); -// } - } public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index a84deb8894..adfb67f003 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -208,16 +208,6 @@ public interface DeviceManagementProviderService { */ PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; - /** - * Method to retrieve all the devices with pagination support. - * - * @param request PaginationRequest object holding the data for pagination - * @return PaginationResult - Result including the required parameters necessary to do pagination. - * @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of - * devices. - */ - PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException; - /** * Method to retrieve all the devices with pagination support. * @@ -225,9 +215,7 @@ public interface DeviceManagementProviderService { * @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of * devices. */ - PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException; - - + PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException; /** * Method to retrieve all the devices with pagination support. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index d6cf2d7fc3..97f58b3f3c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -69,8 +69,10 @@ import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.StartupOperationConfig; +import org.wso2.carbon.device.mgt.common.BillingResponse; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes; import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; @@ -119,11 +121,11 @@ import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformVersion; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; +import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; -import org.wso2.carbon.device.mgt.core.dao.BillingDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -141,6 +143,7 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; +import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; @@ -164,8 +167,7 @@ import java.io.StringWriter; import java.lang.reflect.Type; import java.sql.SQLException; import java.sql.Timestamp; -import java.text.Format; -import java.text.SimpleDateFormat; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; @@ -193,7 +195,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private final EnrollmentDAO enrollmentDAO; private final ApplicationDAO applicationDAO; private MetadataDAO metadataDAO; - private final BillingDAO billingDAO; private final DeviceStatusDAO deviceStatusDAO; public DeviceManagementProviderServiceImpl() { @@ -203,7 +204,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); - this.billingDAO = DeviceManagementDAOFactory.getBillingDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); /* Registering a listener to retrieve events when some device management service plugin is installed after @@ -1021,236 +1021,232 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return this.getAllDevices(request, true); } - public PaginationResult calculateCost(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill, List allDevices) throws DeviceManagementException { + /** + * Calculate cost of a tenants Device List. + * Once the full device list of a tenant is sent here devices are looped for cost calculation + * Cost per tenant is retrieved from the Meta Table + * When looping the devices the most recent device status of that device is retrieved from status table + * If device is enrolled prior to start date now in removed state --> time is calculated from - startDate to last updated time + * If device is enrolled prior to start date now in not removed --> time is calculated from - startDate to endDate + * If device is enrolled after the start date now in removed state --> time is calculated from - dateOfEnrollment to last updated time + * If device is enrolled after the start date now in not removed --> time is calculated from - dateOfEnrollment to endDate + * Once time is calculated cost is set for each device + * + * @param tenantDomain Tenant domain cost id calculated for. + * @param startDate start date of usage period. + * @param endDate end date of usage period. + * @param allDevices device list of the tenant for the selected time-period. + * @return Whether status is changed or not + * @throws DeviceManagementException on errors while trying to calculate Cost + */ + public BillingResponse calculateCost(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException { - PaginationResult paginationResult = new PaginationResult(); + BillingResponse billingResponse = new BillingResponse(); + List deviceStatusNotAvailable = new ArrayList<>(); double totalCost = 0.0; - boolean allDevicesBilledDateIsValid = true; - ArrayList lastBilledDatesList = new ArrayList<>(); - List invalidDevices = new ArrayList<>(); - List removeBillingPeriodInvalidDevices = new ArrayList<>() ; - List removeStatusUpdateInvalidDevices = new ArrayList<>() ; try { - MetadataManagementDAOFactory.beginTransaction(); + MetadataManagementDAOFactory.openConnection(); Metadata metadata = metadataDAO.getMetadata(MultitenantConstants.SUPER_TENANT_ID, DeviceManagementConstants.META_KEY); Gson g = new Gson(); Collection costData = null; - - Type collectionType = new TypeToken>() {}.getType(); + Type collectionType = new TypeToken>() { + }.getType(); 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, null, null, true)); long dateDiff = 0; - + device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); List deviceStatus = device.getDeviceStatusInfo(); - boolean firstDateBilled = false; - boolean deviceStatusIsValid = false; - - List deviceBilling = billingDAO.getBilling(device.getId(), startDate, endDate); - boolean billDateIsInvalid = false; - - if (deviceBilling.isEmpty()) { - billDateIsInvalid = false; - } - - if (generateBill) { - for (Billing bill : deviceBilling) { - if ((bill.getBillingStart() <= startDate.getTime() && startDate.getTime() <= bill.getBillingEnd()) || - (bill.getBillingStart() <= endDate.getTime() && endDate.getTime() <= bill.getBillingEnd())) { - billDateIsInvalid = true; - invalidDevices.add(bill); - } - } - } - - if (!billDateIsInvalid) { - for (int i = 0; i < deviceStatus.size(); i++) { - if (DeviceManagementConstants.ACTIVE_STATUS.equals(deviceStatus.get(i).getStatus().toString())) { - if (deviceStatus.size() > i + 1) { - if (!firstDateBilled) { - firstDateBilled = true; - if (device.getEnrolmentInfo().getLastBilledDate() == 0) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime()); - } else { - if (deviceStatus.get(i + 1).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - device.getEnrolmentInfo().getLastBilledDate()); - } - } - } else { - if (deviceStatus.get(i).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime()); - } - } - } else { - - // If only one status row is retrieved this block is executed - if (!firstDateBilled) { - firstDateBilled = true; - - // Is executed if there is no lastBilled date and if the updates time is before the end date - if (device.getEnrolmentInfo().getLastBilledDate() == 0) { - if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime()); - } - } else { - if (endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate()); - } - } - } else { - if (device.getEnrolmentInfo().getLastBilledDate() <= deviceStatus.get(i).getUpdateTime().getTime() - && endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime()); - } - if (device.getEnrolmentInfo().getLastBilledDate() >= deviceStatus.get(i).getUpdateTime().getTime() - && endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) { - deviceStatusIsValid = true; - dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate()); - } - } - } + if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { + if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); } + } else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) { + dateDiff = endDate.getTime() - startDate.getTime(); } - - 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) { - enrollmentDAO.updateEnrollmentLastBilledDate(device.getEnrolmentInfo(), endDate, tenantId); - billingDAO.addBilling(device.getId(), tenantId, startDate, endDate); - DeviceManagementDAOFactory.commitTransaction(); - } - } else { - - for (int i = 0; i < deviceStatus.size(); i++) { - if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime() - && startDate.getTime() <= deviceStatus.get(i).getUpdateTime().getTime()) { - deviceStatusIsValid = true; - } - } - if (device.getEnrolmentInfo().getLastBilledDate() != 0) { - Date date = new Date(device.getEnrolmentInfo().getLastBilledDate()); - Format format = new SimpleDateFormat("yyyy MM dd"); - - for (String lastBillDate : lastBilledDatesList) { - if (!lastBillDate.equals(format.format(date))) { - lastBilledDatesList.add(format.format(date)); - } + if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); } + } else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) { + dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); } - removeBillingPeriodInvalidDevices.add(device); } - - if (!deviceStatusIsValid) { - removeStatusUpdateInvalidDevices.add(device); + long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS); + double cost = (tenantCost.getCost() / 365) * dateInDays; + totalCost += cost; + device.setCost(Math.round(cost * 100.0) / 100.0); + long totalDays = dateInDays + device.getDaysUsed(); + device.setDaysUsed((int) totalDays); + if (deviceStatus.isEmpty()) { + deviceStatusNotAvailable.add(device); } } } } } - } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while retrieving device list pertaining to the current tenant"; + } catch (DeviceManagementException e) { + String msg = "Error occurred calculating cost of devices"; log.error(msg, e); throw new DeviceManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred in getAllDevices"; + } catch (SQLException e) { + String msg = "Error when retrieving data"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (MetadataManagementDAOException e) { + String msg = "Error when retrieving metadata of billing feature"; log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { - DeviceManagementDAOFactory.closeConnection(); MetadataManagementDAOFactory.closeConnection(); } - if(!removeBillingPeriodInvalidDevices.isEmpty() && removeBillingPeriodInvalidDevices.size() == allDevices.size()) { - allDevicesBilledDateIsValid = false; - paginationResult.setMessage("Invalid bill period."); + if (!deviceStatusNotAvailable.isEmpty()) { + allDevices.removeAll(deviceStatusNotAvailable); } - if(!removeStatusUpdateInvalidDevices.isEmpty() && removeStatusUpdateInvalidDevices.size() == allDevices.size()) { - allDevicesBilledDateIsValid = false; - if (paginationResult.getMessage() != null){ - paginationResult.setMessage(paginationResult.getMessage() + " and no device updates within entered bill period."); - } else { - paginationResult.setMessage("Devices have not been updated within the given period or entered end date comes before the " + - "last billed date."); - } - } - allDevices.removeAll(removeBillingPeriodInvalidDevices); - allDevices.removeAll(removeStatusUpdateInvalidDevices); + Calendar calStart = Calendar.getInstance(); + Calendar calEnd = Calendar.getInstance(); + calStart.setTimeInMillis(startDate.getTime()); + calEnd.setTimeInMillis(endDate.getTime()); - paginationResult.setBilledDateIsValid(allDevicesBilledDateIsValid); - paginationResult.setData(allDevices); - paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0); - return paginationResult; + billingResponse.setDevice(allDevices); + billingResponse.setYear(String.valueOf(calStart.get(Calendar.YEAR))); + billingResponse.setStartDate(startDate.toString()); + billingResponse.setEndDate(endDate.toString()); + billingResponse.setBillPeriod(calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR)); + billingResponse.setTotalCostPerYear(Math.round(totalCost * 100.0) / 100.0); + billingResponse.setDeviceCount(allDevices.size()); + + return billingResponse; } @Override - 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); - } + public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { - DeviceManagerUtil.validateDeviceListPageSize(request); PaginationResult paginationResult = new PaginationResult(); - List allDevices; - int count = 0; - + List allDevices = new ArrayList<>(); + List billingResponseList = new ArrayList<>(); + double totalCost = 0.0; + int deviceCount = 0; + Timestamp initialStartDate = startDate; + boolean remainingDaysConsidered = false; try { - DeviceManagementDAOFactory.beginTransaction(); - allDevices = deviceDAO.getDevices(request, tenantId); - count = deviceDAO.getDeviceCount(request, tenantId); - paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices); + DeviceManagementDAOFactory.openConnection(); - } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while retrieving device bill list pertaining to the current tenant"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred in getAllDevicesBillings"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - paginationResult.setRecordsFiltered(count); - paginationResult.setRecordsTotal(count); - return paginationResult; - } + // TODO Do the check of cache enabling here + paginationResult = BillingCacheManagerImpl.getInstance().getBillingFromCache(tenantDomain, startDate, endDate); + if (paginationResult == null) { + paginationResult = new PaginationResult(); + long difference_In_Time = endDate.getTime() - startDate.getTime(); + + long difference_In_Years = (difference_In_Time / (1000L * 60 * 60 * 24 * 365)); + + long difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365; + + for (int i = 1; i <= difference_In_Years; i++) { + List allDevicesPerYear = new ArrayList<>(); + LocalDateTime oneYearAfterStart = startDate.toLocalDateTime().plusYears(1); + Timestamp newStartDate; + Timestamp newEndDate; + + if (i == difference_In_Years) { + if (difference_In_Days == 0 || Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) { + remainingDaysConsidered = true; + oneYearAfterStart = startDate.toLocalDateTime(); + newEndDate = endDate; + } else if (Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) { + newEndDate = Timestamp.valueOf(oneYearAfterStart); + } else { + oneYearAfterStart = startDate.toLocalDateTime().plusYears(1); + newEndDate = Timestamp.valueOf(oneYearAfterStart); + } + } else { + oneYearAfterStart = startDate.toLocalDateTime().plusYears(1); + newEndDate = Timestamp.valueOf(oneYearAfterStart); + } - @Override - public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException { - PaginationResult paginationResult = new PaginationResult(); - List allDevices; - try { - DeviceManagementDAOFactory.beginTransaction(); - allDevices = deviceDAO.getDeviceListWithoutPagination(tenantId); - paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices); + newStartDate = startDate; + + // The query returns devices which are enrolled in this year now in not removed state + allDevicesPerYear.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate)); + + // The query returns devices which are enrolled in this year now in removed state + allDevicesPerYear.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate)); + + // The query returns devices which are enrolled prior this year now in not removed state + allDevicesPerYear.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate)); + + // The query returns devices which are enrolled prior this year now in removed state + allDevicesPerYear.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate)); + + BillingResponse billingResponse = calculateCost(tenantDomain, newStartDate, newEndDate, allDevicesPerYear); + billingResponseList.add(billingResponse); + allDevices.addAll(billingResponse.getDevice()); + totalCost = totalCost + billingResponse.getTotalCostPerYear(); + deviceCount = deviceCount + billingResponse.getDeviceCount(); + LocalDateTime nextStartDate = oneYearAfterStart.plusDays(1); + startDate = Timestamp.valueOf(nextStartDate); + } + + if (difference_In_Days != 0 && !remainingDaysConsidered) { + List allDevicesPerRemainingDays = new ArrayList<>(); + + // The query returns devices which are enrolled in this year now in not removed state + allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, startDate, endDate)); + + // The query returns devices which are enrolled in this year now in removed state + allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, startDate, endDate)); + + // The query returns devices which are enrolled prior this year now in not removed state + allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, startDate, endDate)); + + // The query returns devices which are enrolled prior this year now in removed state + allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, startDate, endDate)); + + BillingResponse billingResponse = calculateCost(tenantDomain, startDate, endDate, allDevicesPerRemainingDays); + billingResponseList.add(billingResponse); + allDevices.addAll(billingResponse.getDevice()); + totalCost = totalCost + billingResponse.getTotalCostPerYear(); + deviceCount = deviceCount + billingResponse.getDeviceCount(); + } + + Calendar calStart = Calendar.getInstance(); + Calendar calEnd = Calendar.getInstance(); + calStart.setTimeInMillis(initialStartDate.getTime()); + calEnd.setTimeInMillis(endDate.getTime()); + + BillingResponse billingResponse = new BillingResponse("all", Math.round(totalCost * 100.0) / 100.0, allDevices, calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR), initialStartDate.toString(), endDate.toString(), allDevices.size()); + billingResponseList.add(billingResponse); + paginationResult.setData(billingResponseList); + paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0); + paginationResult.setTotalDeviceCount(deviceCount); + BillingCacheManagerImpl.getInstance().addBillingToCache(paginationResult, tenantDomain, initialStartDate, endDate); + return paginationResult; + } } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while retrieving device bill list without pagination pertaining to the current tenant"; + String msg = "Error occurred while retrieving device bill list related to the current tenant"; log.error(msg, e); throw new DeviceManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred in createBillingFile"; + } catch (MetadataManagementDAOException e) { + String msg = "Error when retrieving metadata of billing feature"; 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); + } finally { + DeviceManagementDAOFactory.closeConnection(); } return paginationResult; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 8a88d53ac0..65a26d1330 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -58,6 +58,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; @@ -76,6 +77,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; @@ -137,6 +139,7 @@ public final class DeviceManagerUtil { public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; private static boolean isDeviceCacheInitialized = false; + private static boolean isBillingCacheInitialized = false; private static boolean isAPIResourcePermissionCacheInitialized = false; private static boolean isGeoFenceCacheInitialized = false; @@ -652,6 +655,47 @@ public final class DeviceManagerUtil { } } + /** + * Enable Billing caching according to the configurations provided by cdm-config.xml + */ + public static void initializeBillingCache() { + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + int billingCacheExpiry = config.getBillingCacheConfiguration().getExpiryTime(); + long billingCacheCapacity = config.getBillingCacheConfiguration().getCapacity(); + CacheManager manager = getCacheManager(); + if (config.getBillingCacheConfiguration().isEnabled()) { + if(!isBillingCacheInitialized) { + isBillingCacheInitialized = true; + if (manager != null) { + if (billingCacheExpiry > 0) { + manager.createCacheBuilder(DeviceManagementConstants.BILLING_CACHE). + setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, + billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. + Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build(); + if(billingCacheCapacity > 0 ) { + ((CacheImpl) manager.getCache(DeviceManagementConstants.BILLING_CACHE)). + setCapacity(billingCacheCapacity); + } + } else { + manager.getCache(DeviceManagementConstants.BILLING_CACHE); + } + } else { + if (billingCacheExpiry > 0) { + Caching.getCacheManager(). + createCacheBuilder(DeviceManagementConstants.BILLING_CACHE). + setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, + billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. + Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build(); + ((CacheImpl)(manager.getCache(DeviceManagementConstants.BILLING_CACHE))). + setCapacity(billingCacheCapacity); + } else { + Caching.getCacheManager().getCache(DeviceManagementConstants.BILLING_CACHE); + } + } + } + } + } + /** * Enable Geofence caching according to the configurations proviced by cdm-config.xml */ @@ -711,6 +755,28 @@ public final class DeviceManagerUtil { return deviceCache; } + /** + * Get billing cache object + * @return {@link Cache} + */ + public static Cache getBillingCache() { + DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + CacheManager manager = getCacheManager(); + Cache billingCache = null; + if (config.getBillingCacheConfiguration().isEnabled()) { + if(!isBillingCacheInitialized) { + initializeBillingCache(); + } + if (manager != null) { + billingCache = manager.getCache(DeviceManagementConstants.BILLING_CACHE); + } else { + billingCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER) + .getCache(DeviceManagementConstants.BILLING_CACHE); + } + } + return billingCache; + } + /** * Get geofence cache object * @return {@link Cache} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index 005db8fb7d..d3b81f2655 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -94,7 +94,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, @@ -564,16 +563,6 @@ ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- -CREATE TABLE IF NOT EXISTS DM_BILLING ( - INVOICE_ID INTEGER AUTO_INCREMENT NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - DEVICE_ID INTEGER DEFAULT NULL, - BILLING_START TIMESTAMP NOT NULL, - BILLING_END TIMESTAMP NOT NULL, - PRIMARY KEY (INVOICE_ID), -CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) -REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); -- DM_EXT_GROUP_MAPPING TABLE-- CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING ( ID INT NOT NULL AUTO_INCREMENT, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml index 50e3afd824..340b22802b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml @@ -94,6 +94,11 @@ 600 10000 + + true + 600 + 10000 + true diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index 4bffc45a0b..56fbaadc0b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -211,6 +211,7 @@ perm:windows:location perm:admin:tenant:view perm:admin:metadata:view + perm:admin:usage:view device-mgt diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 index 28b00241af..f567bb9dd2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 @@ -165,6 +165,17 @@ 10000 {% endif %} + + {% if device_mgt_conf.billing_cache_conf is defined %} + {{device_mgt_conf.billing_cache_conf.enable}} + {{device_mgt_conf.billing_cache_conf.expiry_time}} + {{device_mgt_conf.billing_cache_conf.capacity}} + {% else %} + true + 600 + 10000 + {% endif %} + {% if device_mgt_conf.event_operation_task_conf is defined %} {{device_mgt_conf.event_operation_task_conf.enable}} diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index bbcbcaf791..0e8d1b8466 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -52,17 +52,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) ); -CREATE TABLE IF NOT EXISTS DM_BILLING ( - INVOICE_ID INTEGER auto_increment NOT NULL, - TENANT_ID INTEGER default 0, - DEVICE_ID INT default NULL, - BILLING_START TIMESTAMP not null, - BILLING_END TIMESTAMP not null, - PRIMARY KEY (INVOICE_ID), - CONSTRAINT FK_DM_BILLING_DM_DEVICE - FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) -); - CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, @@ -114,7 +103,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index c03580d03a..a682f457be 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -66,18 +66,6 @@ CREATE TABLE DM_DEVICE ( REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_BILLING]') AND TYPE IN (N'U')) -CREATE TABLE DM_BILLING ( - INVOICE_ID INTEGER IDENTITY(1,1) NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - DEVICE_ID INTEGER DEFAULT NULL, - BILLING_START DATETIME2 NOT NULL, - BILLING_END DATETIME2 NOT NULL, - PRIMARY KEY (INVOICE_ID), - CONSTRAINT FK_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_PROPERTIES]') AND TYPE IN (N'U')) CREATE TABLE DM_DEVICE_PROPERTIES ( DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, @@ -158,7 +146,6 @@ CREATE TABLE DM_ENROLMENT ( DATE_OF_ENROLMENT DATETIME2 DEFAULT NULL, DATE_OF_LAST_UPDATE DATETIME2 DEFAULT NULL, TENANT_ID INTEGER NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index b0e85d1cf4..33ac7964dd 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -59,17 +59,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION )ENGINE = InnoDB; -CREATE TABLE IF NOT EXISTS DM_BILLING ( - INVOICE_ID INTEGER AUTO_INCREMENT NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - DEVICE_ID INTEGER DEFAULT NULL, - BILLING_START TIMESTAMP NOT NULL, - BILLING_END TIMESTAMP NOT NULL, - PRIMARY KEY (INVOICE_ID), - CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -)ENGINE = InnoDB; - CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION); @@ -129,7 +118,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, TENANT_ID INT NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index 5f5952ca18..bbfe9bbcfb 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -124,19 +124,6 @@ WHEN (NEW.ID IS NULL) END; / -CREATE TABLE DM_BILLING ( - INVOICE_ID NUMBER(10) NOT NULL, - TENANT_ID NUMBER(10) DEFAULT 0, - DEVICE_ID NUMBER(10) DEFAULT NULL, - BILLING_START TIMESTAMP NOT NULL, - BILLING_END TIMESTAMP NOT NULL, - CONSTRAINT PK_DM_BILLING PRIMARY KEY (INVOICE_ID), - CONSTRAINT fk_DM_BILLING_DM_DEVICE2 - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) -) -/ - CREATE TABLE DM_DEVICE_PROPERTIES ( DEVICE_TYPE_NAME VARCHAR2(300) NOT NULL, DEVICE_IDENTIFICATION VARCHAR2(300) NOT NULL, @@ -221,7 +208,6 @@ CREATE TABLE DM_ENROLMENT ( DATE_OF_ENROLMENT TIMESTAMP(0) DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL, TENANT_ID NUMBER(10) NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, CONSTRAINT PK_DM_ENROLMENT PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 89a4e2dcac..67ba8f1b6a 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -57,17 +57,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE ( REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_BILLING ( - INVOICE_ID INTEGER DEFAULT NEXTVAL ('DM_BILLING_seq') NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - DEVICE_ID INTEGER DEFAULT NULL, - BILLING_START TIMESTAMP(0) NOT NULL, - BILLING_END TIMESTAMP(0) NOT NULL, - PRIMARY KEY (INVOICE_ID), - CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION - ); - CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION); @@ -127,7 +116,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( DATE_OF_ENROLMENT TIMESTAMP(0) NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP(0) NULL DEFAULT NULL, TENANT_ID INTEGER NOT NULL, - LAST_BILLED_DATE BIGINT DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION