Remove rebuild transaction consumptions
MODIFY
src/assets/server/rest/v1/docs/e-mobility-oas.json
src/assets/server/rest/v1/docs/e-mobility-oas.json
}
}
},
- "/api/transactions/{id}/consumptions/rebuild": {
- "post": {
- "security": [
- {
- "bearerAuth": []
- }
- ],
- "description": "Rebuild a Transaction consumptions",
- "parameters": [
- {
- "$ref": "#/components/parameters/transactionID"
- }
- ],
- "tags": [
- "Transactions"
- ],
- "responses": {
- "200": {
- "description": "Consumptions rebuild result",
- "content": {
- "application/json": {
- "example": {
- "status": "Success",
- "nbrOfConsumptions": 1
- }
- }
- }
- },
- "401": {
- "$ref": "#/components/responses/UnauthorizedError"
- },
- "403": {
- "$ref": "#/components/responses/ForbiddenError"
- },
- "500": {
- "$ref": "#/components/responses/BackendError"
- }
- }
- }
- },
"/api/transactions/{id}/soft-stop": {
"put": {
"security": [

MODIFY
src/server/ocpp/utils/OCPPUtils.ts
src/server/ocpp/utils/OCPPUtils.ts
@@ -25,7 +25,6 @@ import Logging from '../../../utils/Logging';
import OCPIClientFactory from '../../../client/ocpi/OCPIClientFactory';
import { OCPIRole } from '../../../types/ocpi/OCPIRole';
import { OCPPHeader } from '../../../types/ocpp/OCPPHeader';
-import OCPPStorage from '../../../storage/mongodb/OCPPStorage';
import OICPClientFactory from '../../../client/oicp/OICPClientFactory';
import { OICPRole } from '../../../types/oicp/OICPRole';
import OICPUtils from '../../oicp/OICPUtils';
@@ -564,135 +563,6 @@ export default class OCPPUtils {
await TransactionStorage.saveTransaction(tenant, transaction);
}
- public static async rebuildTransactionConsumptions(tenant: Tenant, transaction: Transaction): Promise<number> {
- let consumptions: Consumption[] = [];
- let transactionSimplePricePerkWh: number;
- if (!transaction) {
- throw new BackendError({
- source: transaction.chargeBoxID,
- action: ServerAction.REBUILD_TRANSACTION_CONSUMPTIONS,
- module: MODULE_NAME, method: 'rebuildTransactionConsumptions',
- message: 'Session does not exist',
- });
- }
- if (!transaction.stop) {
- throw new BackendError({
- source: transaction.chargeBoxID,
- action: ServerAction.REBUILD_TRANSACTION_CONSUMPTIONS,
- module: MODULE_NAME, method: 'rebuildTransactionConsumptions',
- message: `Session ID '${transaction.id}' is in progress`,
- });
- }
- // Check Simple Pricing
- if (transaction.pricingSource === PricingSettingsType.SIMPLE) {
- transactionSimplePricePerkWh = Utils.roundTo(transaction.stop.price / (transaction.stop.totalConsumptionWh / 1000), 2);
- }
- // Get the Charging Station
- const chargingStation = await ChargingStationStorage.getChargingStation(tenant,
- transaction.chargeBoxID, { includeDeleted: true });
- if (!chargingStation) {
- throw new BackendError({
- source: transaction.chargeBoxID,
- action: ServerAction.REBUILD_TRANSACTION_CONSUMPTIONS,
- module: MODULE_NAME, method: 'rebuildTransactionConsumptions',
- message: `Charging Station ID '${transaction.chargeBoxID}' does not exist`,
- });
- }
- // Get the Meter Values
- const meterValues = await OCPPStorage.getMeterValues(tenant, { transactionId: transaction.id }, Constants.DB_PARAMS_MAX_LIMIT);
- if (meterValues.count > 0) {
- // Build all Consumptions
- consumptions = await OCPPUtils.createConsumptionsFromMeterValues(tenant, chargingStation, transaction, meterValues.result);
- // Push last dummy consumption for Stop Transaction
- consumptions.push({} as Consumption);
- for (let i = 0; i < consumptions.length; i++) {
- // Last consumption is a Stop Transaction
- if (i === consumptions.length - 1) {
- // Create OCPP Stop Transaction
- const stopTransaction: OCPPStopTransactionRequestExtended = {
- idTag: transaction.stop.tagID,
- meterStop: transaction.stop.meterStop,
- timestamp: transaction.stop.timestamp.toISOString(),
- transactionId: transaction.id,
- chargeBoxID: transaction.chargeBoxID,
- };
- // Create last meter values based on history of transaction/stopTransaction
- const stopMeterValues = OCPPUtils.createTransactionStopMeterValues(chargingStation, transaction, stopTransaction);
- // Create last consumption
- const lastConsumptions = await OCPPUtils.createConsumptionsFromMeterValues(tenant, chargingStation, transaction, stopMeterValues);
- const lastConsumption = lastConsumptions[0];
- // No consumption or no duration, skip it
- if (!lastConsumption || lastConsumption.startedAt.getTime() === lastConsumption.endedAt.getTime()) {
- // Not a consumption: Remove last record and quit the loop
- consumptions.splice(consumptions.length - 1, 1);
- break;
- }
- consumptions.splice(consumptions.length - 1, 1, lastConsumption);
- }
- const consumption = consumptions[i];
- // Update Transaction with Consumption
- OCPPUtils.updateTransactionWithConsumption(chargingStation, transaction, consumption);
- if (consumption.toPrice) {
- // Pricing
- await OCPPUtils.processTransactionPricing(tenant, transaction, chargingStation, consumption, TransactionAction.UPDATE);
- // Billing
- await OCPPUtils.processTransactionBilling(tenant, transaction, TransactionAction.UPDATE);
- }
- // Override the price if simple pricing only
- if (transactionSimplePricePerkWh > 0) {
- consumption.amount = Utils.computeSimplePrice(transactionSimplePricePerkWh, consumption.consumptionWh);
- consumption.roundedAmount = Utils.truncTo(consumption.amount, 2);
- consumption.pricingSource = PricingSettingsType.SIMPLE;
- }
- // Cumulated props
- const currentDurationSecs = Math.trunc((new Date(consumption.endedAt).getTime() - new Date(consumption.startedAt).getTime()) / 1000);
- if (i === 0) {
- // Initial values
- consumption.cumulatedConsumptionWh = consumption.consumptionWh;
- consumption.cumulatedConsumptionAmps = Utils.convertWattToAmp(
- chargingStation, null, transaction.connectorId, consumption.cumulatedConsumptionWh);
- consumption.cumulatedAmount = consumption.amount;
- if (!consumption.consumptionWh) {
- consumption.totalInactivitySecs = currentDurationSecs;
- }
- consumption.totalDurationSecs = currentDurationSecs;
- } else {
- // Take total from previous consumption
- consumption.cumulatedConsumptionWh = Utils.createDecimal(consumptions[i - 1].cumulatedConsumptionWh).plus(
- Utils.convertToFloat(consumption.consumptionWh)).toNumber();
- consumption.cumulatedConsumptionAmps = Utils.convertWattToAmp(
- chargingStation, null, transaction.connectorId, consumption.cumulatedConsumptionWh);
- consumption.cumulatedAmount = Utils.createDecimal(consumptions[i - 1].cumulatedAmount).plus(consumption.amount).toNumber();
- if (!consumption.consumptionWh) {
- consumption.totalInactivitySecs = Utils.createDecimal(consumptions[i - 1].totalInactivitySecs).plus(currentDurationSecs).toNumber();
- }
- consumption.totalDurationSecs = Utils.createDecimal(consumptions[i - 1].totalDurationSecs).plus(currentDurationSecs).toNumber();
- }
- }
- // Delete first all transaction's consumptions
- await ConsumptionStorage.deleteConsumptions(tenant, [transaction.id]);
- // Save all
- await ConsumptionStorage.saveConsumptions(tenant, consumptions);
- // Update the Transaction
- if (!transaction.refundData) {
- transaction.roundedPrice = Utils.truncTo(transaction.price, 2);
- transaction.stop.price = transaction.currentCumulatedPrice;
- transaction.stop.roundedPrice = Utils.truncTo(transaction.currentCumulatedPrice, 2);
- transaction.stop.stateOfCharge = transaction.currentStateOfCharge;
- transaction.stop.totalConsumptionWh = transaction.currentTotalConsumptionWh;
- transaction.stop.totalInactivitySecs = transaction.currentTotalInactivitySecs;
- transaction.stop.totalDurationSecs = transaction.currentTotalDurationSecs;
- transaction.stop.inactivityStatus = Utils.getInactivityStatusLevel(
- transaction.chargeBox, transaction.connectorId, transaction.currentTotalInactivitySecs);
- }
- }
- // Build extra inactivity consumption
- const consumptionCreated = await OCPPUtils.buildExtraConsumptionInactivity(tenant, transaction);
- // Save
- await TransactionStorage.saveTransaction(tenant, transaction);
- return consumptions.length + (consumptionCreated ? 1 : 0);
- }
-
public static updateTransactionWithStopTransaction(transaction: Transaction, chargingStation: ChargingStation,
stopTransaction: OCPPStopTransactionRequestExtended, user: User, alternateUser: User, tagId: string): void {
// Set final data

MODIFY
src/server/rest/CentralRestServerService.ts
src/server/rest/CentralRestServerService.ts
@@ -130,7 +130,6 @@ class RequestMapper {
[ServerAction.TRANSACTIONS_ACTIVE]: TransactionService.handleGetTransactionsActive.bind(this),
[ServerAction.TRANSACTIONS_IN_ERROR]: TransactionService.handleGetTransactionsInError.bind(this),
[ServerAction.TRANSACTION_YEARS]: TransactionService.handleGetTransactionYears.bind(this),
- [ServerAction.REBUILD_TRANSACTION_CONSUMPTIONS]: TransactionService.handleRebuildTransactionConsumptions.bind(this),
[ServerAction.UNASSIGNED_TRANSACTIONS_COUNT]: TransactionService.handleGetUnassignedTransactionsCount.bind(this),
[ServerAction.TRANSACTION_OCPI_CDR_EXPORT]: TransactionService.handleExportTransactionOcpiCdr.bind(this),
[ServerAction.CHARGING_STATION_CONSUMPTION_STATISTICS]: StatisticService.handleGetChargingStationConsumptionStatistics.bind(this),

MODIFY
src/server/rest/v1/router/api/TransactionRouter.ts
src/server/rest/v1/router/api/TransactionRouter.ts
-/* eslint-disable @typescript-eslint/no-misused-promises */
import { ServerAction, ServerRoute } from '../../../../../types/Server';
+/* eslint-disable @typescript-eslint/no-misused-promises */
import express, { NextFunction, Request, Response } from 'express';
import RouterUtils from '../RouterUtils';
@@ -25,7 +25,6 @@ export default class TransactionRouter {
this.buildRouteDeleteTransactions();
this.buildRoutePushTransactionCDR();
this.buildRouteExportTransactionCDR();
- this.buildRouteRebuildTransactionConsumption();
this.buildRouteTransactionSoftStop();
this.buildRouteTransactionsRefund();
this.buildRouteTransactionsAssignUser();
@@ -113,13 +112,6 @@ export default class TransactionRouter {
});
}
- protected buildRouteRebuildTransactionConsumption(): void {
- this.router.post(`/${ServerRoute.REST_TRANSACTION_CONSUMPTIONS_REBUILD}`, async (req: Request, res: Response, next: NextFunction) => {
- req.query.ID = req.params.id;
- await RouterUtils.handleServerAction(TransactionService.handleRebuildTransactionConsumptions.bind(this), ServerAction.REBUILD_TRANSACTION_CONSUMPTIONS, req, res, next);
- });
- }
-
protected buildRouteTransactionSoftStop(): void {
this.router.put(`/${ServerRoute.REST_TRANSACTION_SOFT_STOP}`, async (req: Request, res: Response, next: NextFunction) => {
req.body.ID = req.params.id;

MODIFY
src/server/rest/v1/service/TransactionService.ts
src/server/rest/v1/service/TransactionService.ts
@@ -314,30 +314,6 @@ export default class TransactionService {
next();
}
- public static async handleRebuildTransactionConsumptions(action: ServerAction, req: Request, res: Response, next: NextFunction): Promise<void> {
- // Check Auth
- if (!await Authorizations.canUpdateTransaction(req.user)) {
- throw new AppAuthError({
- errorCode: HTTPAuthError.FORBIDDEN,
- user: req.user,
- action: Action.UPDATE, entity: Entity.TRANSACTION,
- module: MODULE_NAME, method: 'handleRebuildTransactionConsumptions'
- });
- }
- // Filter
- const filteredRequest = TransactionValidator.getInstance().validateTransactionGetReq(req.query);
- UtilsService.assertIdIsProvided(action, filteredRequest.ID.toString(), MODULE_NAME, 'handleRebuildTransactionConsumptions', req.user);
- // Get Transaction
- const transaction = await TransactionStorage.getTransaction(req.tenant, filteredRequest.ID, { withUser: true });
- UtilsService.assertObjectExists(action, transaction, `Transaction ID '${filteredRequest.ID}' does not exist`,
- MODULE_NAME, 'handleRebuildTransactionConsumptions', req.user);
- // Get unassigned transactions
- const nbrOfConsumptions = await OCPPUtils.rebuildTransactionConsumptions(req.tenant, transaction);
- // Return
- res.json({ nbrOfConsumptions, ...Constants.REST_RESPONSE_SUCCESS });
- next();
- }
-
public static async handleAssignTransactionsToUser(action: ServerAction, req: Request, res: Response, next: NextFunction): Promise<void> {
// Check auths
if (!await Authorizations.canUpdateTransaction(req.user)) {

MODIFY
src/types/Server.ts
src/types/Server.ts
@@ -514,7 +514,6 @@ export enum ServerRoute {
REST_TRANSACTION_CDR = 'transactions/:id/ocpi/cdr',
REST_TRANSACTION_CDR_EXPORT = 'transactions/:id/ocpi/cdr/export',
REST_TRANSACTION_CONSUMPTIONS = 'transactions/:id/consumptions',
- REST_TRANSACTION_CONSUMPTIONS_REBUILD = 'transactions/:id/consumptions/rebuild',
REST_TRANSACTION_SOFT_STOP = 'transactions/:id/soft-stop',
REST_TRANSACTIONS_REFUND_ACTION = 'transactions/action/refund',
REST_TRANSACTIONS_REFUND = 'transactions/status/refund',

Remove rebuild transaction consumptions