From 5d06485a251ef7209387725c1ebde53818678696 Mon Sep 17 00:00:00 2001 From: osh Date: Tue, 12 Sep 2023 08:31:47 +0530 Subject: [PATCH 1/3] Add device deletion scenario for billing --- .../core/device/mgt/common/EnrolmentInfo.java | 2 +- .../core/device/mgt/core/dao/DeviceDAO.java | 2 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 135 +++++++++++++----- .../core/dao/impl/DeviceStatusDAOImpl.java | 2 +- .../dao/impl/device/GenericDeviceDAOImpl.java | 12 +- .../DeviceManagementProviderServiceImpl.java | 16 ++- 6 files changed, 123 insertions(+), 46 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java index 6cfd4092dc..450fe0c5df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/EnrolmentInfo.java @@ -32,7 +32,7 @@ public class EnrolmentInfo implements Serializable { public enum Status { CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED, CONFIGURED, READY_TO_CONNECT, RETURN_PENDING, RETURNED, DEFECTIVE, WARRANTY_PENDING, WARRANTY_SENT, - WARRANTY_REPLACED, ASSIGNED + WARRANTY_REPLACED, ASSIGNED, DELETED } public enum OwnerShip { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java index 68e475d2a4..7b05067899 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/DeviceDAO.java @@ -634,7 +634,7 @@ public interface DeviceDAO { * @param enrollmentIds list of enrollment ids. * @throws DeviceManagementDAOException when no enrolments are found for the given device. */ - void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds) throws DeviceManagementDAOException; + void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds, List validDevices) throws DeviceManagementDAOException; boolean transferDevice(String deviceType, String deviceId, String owner, int destinationTenantId) throws DeviceManagementDAOException, SQLException; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 6b06c28d60..5696c0b23f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -52,6 +52,7 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.StringJoiner; +import java.util.Random; public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @@ -2155,7 +2156,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds) + public void deleteDevices(List deviceIdentifiers, List deviceIds, List enrollmentIds, List validDevices) throws DeviceManagementDAOException { Connection conn; try { @@ -2210,7 +2211,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "operation response, enrollment operation mapping data of " + "devices with identifiers: " + deviceIdentifiers); } - removeDeviceEnrollment(conn, deviceIds); + refactorEnrolment(conn, deviceIds); + refactorDeviceStatus(conn, validDevices); if (log.isDebugEnabled()) { log.debug("Successfully removed device enrollment data of devices: " + deviceIdentifiers); } @@ -2218,7 +2220,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { if (log.isDebugEnabled()) { log.debug("Successfully removed device group mapping data of devices: " + deviceIdentifiers); } - removeDevice(conn, deviceIds); + refactorDevice(conn, deviceIds); if (log.isDebugEnabled()) { log.debug("Successfully permanently deleted the device of devices: " + deviceIdentifiers); } @@ -2750,73 +2752,138 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } /*** - * This method removes records of a given list of enrollments from the DM_ENROLMENT table + * This method removes records of a given list of devices from the DM_DEVICE_GROUP_MAP table * @param conn Connection object - * @param enrollmentIds list of enrollment ids (primary keys) + * @param deviceIds list of device ids (primary keys) * @throws DeviceManagementDAOException if deletion fails */ - private void removeDeviceEnrollment(Connection conn, List enrollmentIds) - throws DeviceManagementDAOException { - String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ?"; + private void removeDeviceGroupMapping(Connection conn, List deviceIds) throws DeviceManagementDAOException { + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ?"; try { - if (!executeBatchOperation(conn, sql, enrollmentIds)) { - String msg = "Failed to remove enrollments of devices with enrollmentIds : " + enrollmentIds + if (!executeBatchOperation(conn, sql, deviceIds)) { + String msg = "Failed to remove device group mapping of devices with deviceIds : " + deviceIds + " while executing batch operation"; log.error(msg); throw new DeviceManagementDAOException(msg); } } catch (SQLException e) { - String msg = "SQL error occurred while removing enrollments of devices with enrollmentIds : " - + enrollmentIds; + String msg = "SQL error occurred while removing device group mapping of devices with deviceIds : " + + deviceIds; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } } /*** - * This method removes records of a given list of devices from the DM_DEVICE_GROUP_MAP table + * This method refactors some attributes of a given list of devices which are being deleted by the user * @param conn Connection object * @param deviceIds list of device ids (primary keys) - * @throws DeviceManagementDAOException if deletion fails + * @throws DeviceManagementDAOException if refactoring fails */ - private void removeDeviceGroupMapping(Connection conn, List deviceIds) throws DeviceManagementDAOException { - String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ?"; - try { - if (!executeBatchOperation(conn, sql, deviceIds)) { - String msg = "Failed to remove device group mapping of devices with deviceIds : " + deviceIds - + " while executing batch operation"; - log.error(msg); - throw new DeviceManagementDAOException(msg); + public void refactorDevice(Connection conn, List deviceIds) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_DEVICE SET DEVICE_IDENTIFICATION = ?, NAME = ? WHERE ID = ?"; + + try (PreparedStatement preparedStatement = conn.prepareStatement(updateQuery)) { + for (int deviceId : deviceIds) { + + String randomIdentification = generateRandomString(10); + String randomName = generateRandomString(20); + + preparedStatement.setString(1, randomIdentification); + preparedStatement.setString(2, randomName); + preparedStatement.setInt(3, deviceId); + + preparedStatement.executeUpdate(); } + } catch (SQLException e) { - String msg = "SQL error occurred while removing device group mapping of devices with deviceIds : " - + deviceIds; + String msg = "SQL error occurred while refactoring device properties of deviceIds: " + deviceIds; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } } + /*** - * This method removes records of a given list of devices from the DM_DEVICE table + * This method refactors some attributes of a given list of devices in the DM_ENROLMENT table * @param conn Connection object * @param deviceIds list of device ids (primary keys) - * @throws DeviceManagementDAOException if deletion fails + * @throws DeviceManagementDAOException if refactoring fails */ - private void removeDevice(Connection conn, List deviceIds) throws DeviceManagementDAOException { - String sql = "DELETE FROM DM_DEVICE WHERE ID = ?"; - try { - if (!executeBatchOperation(conn, sql, deviceIds)) { - String msg = "Failed to remove devices with deviceIds : " + deviceIds + " while executing batch operation"; - log.error(msg); - throw new DeviceManagementDAOException(msg); + public void refactorEnrolment(Connection conn, List deviceIds) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_ENROLMENT SET OWNER = ?, OWNERSHIP = ?, STATUS = ? WHERE DEVICE_ID = ?"; + + try (PreparedStatement preparedStatement = conn.prepareStatement(updateQuery)) { + for (int deviceId : deviceIds) { + + String randomOwner = generateRandomString(4); + String randomOwnership = generateRandomString(6); + + preparedStatement.setString(1, randomOwner); + preparedStatement.setString(2, randomOwnership); + preparedStatement.setString(3, String.valueOf(Status.DELETED)); + preparedStatement.setInt(4, deviceId); + + preparedStatement.executeUpdate(); } + } catch (SQLException e) { - String msg = "SQL error occurred while removing devices with deviceIds : " + deviceIds; + String msg = "SQL error occurred while refactoring device enrolment properties of deviceIds: " + deviceIds; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } } + /*** + * This method updates the status of a given list of devices to DELETED state in the DM_DEVICE_STATUS table + * @param conn Connection object + * @param validDevices list of devices + * @throws DeviceManagementDAOException if updating fails + */ + public void refactorDeviceStatus(Connection conn, List validDevices) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_DEVICE_STATUS SET STATUS = ? WHERE ID = ?"; + String selectLastMatchingRecordQuery = "SELECT ID FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? AND DEVICE_ID = ? ORDER BY ID DESC LIMIT 1"; + + try (PreparedStatement selectStatement = conn.prepareStatement(selectLastMatchingRecordQuery); + PreparedStatement updateStatement = conn.prepareStatement(updateQuery)) { + + for (Device device : validDevices) { + + selectStatement.setInt(1, device.getEnrolmentInfo().getId()); + selectStatement.setInt(2, device.getId()); + + ResultSet resultSet = selectStatement.executeQuery(); + int lastRecordId = 0; + if (resultSet.next()) { + lastRecordId = resultSet.getInt("ID"); + } + + updateStatement.setString(1, String.valueOf(Status.DELETED)); + updateStatement.setInt(2, lastRecordId); + updateStatement.execute(); + } + + } catch (SQLException e) { + String msg = "SQL error occurred while updating device status properties."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + private String generateRandomString(int length) { + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + StringBuilder randomString = new StringBuilder(); + + Random random = new Random(); + + for (int i = 0; i < length; i++) { + int index = random.nextInt(characters.length()); + randomString.append(characters.charAt(index)); + } + + return randomString.toString(); + } + /*** * This method executes batch operations for a given list of primary keys * where the statement only has one param of type int, following the given pattern: diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java index 4657b7e119..60c86f0876 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java @@ -54,7 +54,7 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO { } if (billingStatus) { - sql += " ORDER BY UPDATE_TIME DESC"; + sql += " ORDER BY ID DESC"; } stmt = conn.prepareStatement(sql); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index b3c6b8f18a..46595d94dc 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -205,7 +205,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "WHERE " + "e.TENANT_ID=? AND " + "d.ID=e.DEVICE_ID AND " + - "STATUS !='REMOVED' AND " + + "STATUS NOT IN ('REMOVED', 'DELETED') AND " + "(" + "DATE_OF_ENROLMENT BETWEEN ? AND ? " + ")"; @@ -244,7 +244,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "from DM_DEVICE d, DM_ENROLMENT e " + "where " + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + - "STATUS ='REMOVED' and " + + "(" + + "STATUS = 'REMOVED' OR STATUS = 'DELETED' " + + ") and " + "(" + "DATE_OF_ENROLMENT between ? and ? " + ") and " + @@ -287,7 +289,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "where " + "e.TENANT_ID=? and " + "d.ID=e.DEVICE_ID and " + - "STATUS !='REMOVED' and " + + "STATUS NOT IN ('REMOVED', 'DELETED') and " + "(" + "DATE_OF_ENROLMENT < ? " + ")"; @@ -326,7 +328,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "from DM_DEVICE d, DM_ENROLMENT e " + "where " + "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " + - "STATUS ='REMOVED' and " + + "(" + + "STATUS = 'REMOVED' OR STATUS = 'DELETED' " + + ") and " + "(" + "DATE_OF_ENROLMENT < ? " + ") and " + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index ffd74099e7..00f68fc74d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -652,6 +652,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Map deviceManagerMap = new HashMap<>(); List deviceCacheKeyList = new ArrayList<>(); List existingDevices; + List validDevices = new ArrayList<>();; int tenantId = this.getTenantId(); try { @@ -684,6 +685,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceCacheKey.setDeviceType(device.getType()); deviceCacheKey.setTenantId(tenantId); deviceCacheKeyList.add(deviceCacheKey); + validDevices.add(device); deviceIds.add(device.getId()); validDeviceIdentifiers.add(device.getDeviceIdentifier()); enrollmentIds.add(device.getEnrolmentInfo().getId()); @@ -713,7 +715,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv try { DeviceManagementDAOFactory.beginTransaction(); //deleting device from the core - deviceDAO.deleteDevices(validDeviceIdentifiers, new ArrayList<>(deviceIds), enrollmentIds); + deviceDAO.deleteDevices(validDeviceIdentifiers, new ArrayList<>(deviceIds), enrollmentIds, validDevices); for (Map.Entry entry : deviceManagerMap.entrySet()) { try { // deleting device from the plugin level @@ -1057,19 +1059,23 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); List deviceStatus = device.getDeviceStatusInfo(); if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { - if (!deviceStatus.isEmpty() && String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); } - } else if (!deviceStatus.isEmpty() && !String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { dateDiff = endDate.getTime() - startDate.getTime(); } } else { - if (!deviceStatus.isEmpty() && String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); } - } else if (!deviceStatus.isEmpty() && !String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")) { + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); } } From 6fd84dcbef139a976637110d24d9c06dfba68568 Mon Sep 17 00:00:00 2001 From: osh Date: Wed, 13 Sep 2023 14:50:23 +0530 Subject: [PATCH 2/3] Comment out cost related code --- .../DeviceManagementAdminServiceImpl.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 60 +++++++++---------- 2 files changed, 30 insertions(+), 32 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 5a9c4fa55d..31bf740d95 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -248,7 +248,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe devices.setList((List) result.getData()); devices.setDeviceCount(result.getTotalDeviceCount()); devices.setMessage(result.getMessage()); - devices.setTotalCost(result.getTotalCost()); +// devices.setTotalCost(result.getTotalCost()); devices.setBillPeriod(startDate.toString() + " - " + endDate.toString()); return Response.status(Response.Status.OK).entity(devices).build(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 00f68fc74d..4f4624aa84 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -1034,26 +1034,27 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * @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 { + public BillingResponse calculateUsage(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException { + // All code related to cost calculation has being commented out to comply with the current requirements BillingResponse billingResponse = new BillingResponse(); List deviceStatusNotAvailable = new ArrayList<>(); - double totalCost = 0.0; +// double totalCost = 0.0; try { - MetadataManagementService meta = DeviceManagementDataHolder - .getInstance().getMetadataManagementService(); - Metadata metadata = meta.retrieveMetadata(DeviceManagementConstants.META_KEY); - - Gson g = new Gson(); - Collection costData = null; - - Type collectionType = new TypeToken>() { - }.getType(); - if (metadata != null) { - costData = g.fromJson(metadata.getMetaValue(), collectionType); - for (Cost tenantCost : costData) { - if (tenantCost.getTenantDomain().equals(tenantDomain)) { +// MetadataManagementService meta = DeviceManagementDataHolder +// .getInstance().getMetadataManagementService(); +// Metadata metadata = meta.retrieveMetadata(DeviceManagementConstants.META_KEY); +// +// Gson g = new Gson(); +// Collection costData = null; +// +// 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) { long dateDiff = 0; device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); @@ -1088,9 +1089,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } long dateInDays = (long) dateDiffInDays; - double cost = (tenantCost.getCost() / 365) * dateInDays; - totalCost += cost; - device.setCost(Math.round(cost * 100.0) / 100.0); +// 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()) { @@ -1098,17 +1099,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } - } - } - } +// } +// } +// } } catch (DeviceManagementException e) { String msg = "Error occurred calculating cost of devices"; log.error(msg, e); throw new DeviceManagementException(msg, e); - } catch (MetadataManagementException e) { - String msg = "Error when retrieving metadata of billing feature"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); } if (!deviceStatusNotAvailable.isEmpty()) { @@ -1125,7 +1122,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv 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.setTotalCostPerYear(Math.round(totalCost * 100.0) / 100.0); billingResponse.setDeviceCount(allDevices.size()); return billingResponse; @@ -1134,6 +1131,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { + // All code related to cost calculation has being commented out to comply with the current requirements PaginationResult paginationResult = new PaginationResult(); List allDevices = new ArrayList<>(); List billingResponseList = new ArrayList<>(); @@ -1192,10 +1190,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv // 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); + BillingResponse billingResponse = calculateUsage(tenantDomain, newStartDate, newEndDate, allDevicesPerYear); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); - totalCost = totalCost + billingResponse.getTotalCostPerYear(); +// totalCost = totalCost + billingResponse.getTotalCostPerYear(); deviceCount = deviceCount + billingResponse.getDeviceCount(); LocalDateTime nextStartDate = oneYearAfterStart.plusDays(1).with(LocalTime.of(00, 00, 00)); startDate = Timestamp.valueOf(nextStartDate); @@ -1216,10 +1214,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv // 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); + BillingResponse billingResponse = calculateUsage(tenantDomain, startDate, endDate, allDevicesPerRemainingDays); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); - totalCost = totalCost + billingResponse.getTotalCostPerYear(); +// totalCost = totalCost + billingResponse.getTotalCostPerYear(); deviceCount = deviceCount + billingResponse.getDeviceCount(); } @@ -1231,7 +1229,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv 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.setTotalCost(Math.round(totalCost * 100.0) / 100.0); paginationResult.setTotalDeviceCount(deviceCount); BillingCacheManagerImpl.getInstance().addBillingToCache(paginationResult, tenantDomain, initialStartDate, endDate); return paginationResult; From 8bc0fa37de9810edacc12d65ab99a8495533fd64 Mon Sep 17 00:00:00 2001 From: osh Date: Thu, 14 Sep 2023 14:35:18 +0530 Subject: [PATCH 3/3] Add cost calculation for carbon super --- .../DeviceManagementAdminServiceImpl.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 146 ++++++++++-------- 2 files changed, 80 insertions(+), 68 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 31bf740d95..5a9c4fa55d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -248,7 +248,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe devices.setList((List) result.getData()); devices.setDeviceCount(result.getTotalDeviceCount()); devices.setMessage(result.getMessage()); -// devices.setTotalCost(result.getTotalCost()); + devices.setTotalCost(result.getTotalCost()); devices.setBillPeriod(startDate.toString() + " - " + endDate.toString()); return Response.status(Response.Status.OK).entity(devices).build(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 4f4624aa84..8413b1499f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -1036,76 +1036,39 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv */ public BillingResponse calculateUsage(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException { - // All code related to cost calculation has being commented out to comply with the current requirements BillingResponse billingResponse = new BillingResponse(); List deviceStatusNotAvailable = new ArrayList<>(); -// double totalCost = 0.0; + double totalCost = 0.0; try { -// MetadataManagementService meta = DeviceManagementDataHolder -// .getInstance().getMetadataManagementService(); -// Metadata metadata = meta.retrieveMetadata(DeviceManagementConstants.META_KEY); -// -// Gson g = new Gson(); -// Collection costData = null; -// -// 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) { - long dateDiff = 0; - device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); - List deviceStatus = device.getDeviceStatusInfo(); - if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { - if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") - || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { - if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { - dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); - } - } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") - && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { - dateDiff = endDate.getTime() - startDate.getTime(); - } - } else { - if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") - || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { - if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { - dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); - } - } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") - && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { - dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); - } - } - - // Convert dateDiff to days as a decimal value - double dateDiffInDays = (double) dateDiff / (24 * 60 * 60 * 1000); - - if (dateDiffInDays % 1 >= 0.9) { - dateDiffInDays = Math.ceil(dateDiffInDays); - } - - long dateInDays = (long) dateDiffInDays; -// 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); - } - } - -// } -// } -// } + MetadataManagementService meta = DeviceManagementDataHolder + .getInstance().getMetadataManagementService(); + Metadata metadata = meta.retrieveMetadata(DeviceManagementConstants.META_KEY); + + Gson g = new Gson(); + Collection costData = null; + int tenantIdContext = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + + Type collectionType = new TypeToken>() { + }.getType(); + if (tenantIdContext == MultitenantConstants.SUPER_TENANT_ID && metadata != null) { + costData = g.fromJson(metadata.getMetaValue(), collectionType); + for (Cost tenantCost : costData) { + if (tenantCost.getTenantDomain().equals(tenantDomain)) { + totalCost = generateCost(allDevices, startDate, endDate, tenantCost, deviceStatusNotAvailable, totalCost); + } + } + } else { + totalCost = generateCost(allDevices, startDate, endDate, null, deviceStatusNotAvailable, totalCost); + } } catch (DeviceManagementException e) { String msg = "Error occurred calculating cost of devices"; log.error(msg, e); throw new DeviceManagementException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error when retrieving metadata of billing feature"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); } if (!deviceStatusNotAvailable.isEmpty()) { @@ -1122,16 +1085,65 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv 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.setTotalCostPerYear(Math.round(totalCost * 100.0) / 100.0); billingResponse.setDeviceCount(allDevices.size()); return billingResponse; } + public double generateCost(List allDevices, Timestamp startDate, Timestamp endDate, Cost tenantCost, List deviceStatusNotAvailable, double totalCost) throws DeviceManagementException { + for (Device device : allDevices) { + long dateDiff = 0; + device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true)); + List deviceStatus = device.getDeviceStatusInfo(); + if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime(); + } + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + dateDiff = endDate.getTime() - startDate.getTime(); + } + } else { + if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + || String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) { + dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); + } + } else if (!deviceStatus.isEmpty() && (!String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED") + && !String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) { + dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment(); + } + } + + // Convert dateDiff to days as a decimal value + double dateDiffInDays = (double) dateDiff / (24 * 60 * 60 * 1000); + + if (dateDiffInDays % 1 >= 0.9) { + dateDiffInDays = Math.ceil(dateDiffInDays); + } + + long dateInDays = (long) dateDiffInDays; + double cost = 0; + if (tenantCost != null) { + 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); + } + } + return totalCost; + } + @Override public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException { - // All code related to cost calculation has being commented out to comply with the current requirements PaginationResult paginationResult = new PaginationResult(); List allDevices = new ArrayList<>(); List billingResponseList = new ArrayList<>(); @@ -1193,7 +1205,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv BillingResponse billingResponse = calculateUsage(tenantDomain, newStartDate, newEndDate, allDevicesPerYear); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); -// totalCost = totalCost + billingResponse.getTotalCostPerYear(); + totalCost = totalCost + billingResponse.getTotalCostPerYear(); deviceCount = deviceCount + billingResponse.getDeviceCount(); LocalDateTime nextStartDate = oneYearAfterStart.plusDays(1).with(LocalTime.of(00, 00, 00)); startDate = Timestamp.valueOf(nextStartDate); @@ -1217,7 +1229,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv BillingResponse billingResponse = calculateUsage(tenantDomain, startDate, endDate, allDevicesPerRemainingDays); billingResponseList.add(billingResponse); allDevices.addAll(billingResponse.getDevice()); -// totalCost = totalCost + billingResponse.getTotalCostPerYear(); + totalCost = totalCost + billingResponse.getTotalCostPerYear(); deviceCount = deviceCount + billingResponse.getDeviceCount(); } @@ -1229,7 +1241,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv 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.setTotalCost(Math.round(totalCost * 100.0) / 100.0); paginationResult.setTotalDeviceCount(deviceCount); BillingCacheManagerImpl.getInstance().addBillingToCache(paginationResult, tenantDomain, initialStartDate, endDate); return paginationResult;