提交 54655e13 编写于 作者: nengyuangzhang's avatar nengyuangzhang

Merge branch 'develop'

......@@ -5,7 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]
### Added
- added working-days/non-working-days data into tenant energy categroy report
-
### Changed
### Fixed
......
......@@ -799,6 +799,8 @@ app
'app/services/settings/tenant/tenantmeter.service.js',
'app/services/settings/tenant/tenantpoint.service.js',
'app/services/settings/tenant/tenantsensor.service.js',
'app/services/settings/tenant/tenantworkingcalendar.service.js',
'app/services/settings/workingcalendar/workingcalendar.service.js',
'app/services/settings/datasource/datasource.service.js',
'app/services/settings/datasource/point.service.js',
'app/services/settings/sensor/sensor.service.js',
......@@ -807,6 +809,7 @@ app
'app/controllers/settings/tenant/tenantmeter.controller.js',
'app/controllers/settings/tenant/tenantpoint.controller.js',
'app/controllers/settings/tenant/tenantsensor.controller.js',
'app/controllers/settings/tenant/tenantworkingcalendar.controller.js',
]
}]);
}
......
'use strict';
app.controller('TenantWorkingCalendarController', function(
$scope ,
$window,
$timeout,
$translate,
TenantService,
WorkingCalendarService,
TenantWorkingCalendarService, toaster,SweetAlert) {
$scope.tenants = [];
$scope.currentTenantID = 1;
$scope.tenantworkingcalendars = [];
$scope.cur_user = JSON.parse($window.localStorage.getItem("myems_admin_ui_current_user"));
$scope.changeTenant=function(item,model){
$scope.currentTenant=item;
$scope.currentTenant.selected=model;
$scope.getWorkingCalendarsByTenantID($scope.currentTenant.id);
};
$scope.getAllTenants = function(id) {
TenantService.getAllTenants(function (response) {
if (angular.isDefined(response.status) && response.status === 200) {
$scope.tenants = response.data;
} else {
$scope.tenants = [];
}
});
};
$scope.getWorkingCalendarsByTenantID = function(id) {
$scope.tenantworkingcalendars=[];
TenantWorkingCalendarService.getWorkingCalendarsByTenantID(id, function (response) {
if (angular.isDefined(response.status) && response.status === 200) {
$scope.tenantworkingcalendars = response.data;
}
});
};
$scope.getAllWorkingCalendars = function() {
WorkingCalendarService.getAllWorkingCalendars(function (response) {
if (angular.isDefined(response.status) && response.status === 200) {
$scope.workingcalendars = response.data;
} else {
$scope.workingcalendars = [];
}
});
};
$scope.pairWorkingCalendar=function(dragEl,dropEl){
var workingcalendarid=angular.element('#'+dragEl).scope().workingcalendar.id;
var tenantid = $scope.currentTenant.id;
let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
TenantWorkingCalendarService.addPair(tenantid, workingcalendarid, headers, function (response) {
if (angular.isDefined(response.status) && response.status === 201) {
toaster.pop({
type: "success",
title: $translate.instant("TOASTER.SUCCESS_TITLE"),
body: $translate.instant("TOASTER.BIND_METER_SUCCESS"),
showCloseButton: true,
});
$scope.getWorkingCalendarsByTenantID(tenantid);
} else {
toaster.pop({
type: "error",
title: $translate.instant(response.data.title),
body: $translate.instant(response.data.description),
showCloseButton: true,
});
}
});
};
$scope.deleteWorkingCalendarPair=function(dragEl,dropEl){
if(angular.element('#'+dragEl).hasClass('source')){
return;
}
var tenantworkingcalendarid = angular.element('#' + dragEl).scope().tenantworkingcalendar.id;
var tenantid = $scope.currentTenant.id;
let headers = { "User-UUID": $scope.cur_user.uuid, "Token": $scope.cur_user.token };
TenantWorkingCalendarService.deletePair(tenantid, tenantworkingcalendarid, headers, function (response) {
if (angular.isDefined(response.status) && response.status === 204) {
toaster.pop({
type: "success",
title: $translate.instant("TOASTER.SUCCESS_TITLE"),
body: $translate.instant("TOASTER.UNBIND_METER_SUCCESS"),
showCloseButton: true,
});
$scope.getWorkingCalendarsByTenantID(tenantid);
} else {
toaster.pop({
type: "error",
title: $translate.instant(response.data.title),
body: $translate.instant(response.data.description),
showCloseButton: true,
});
}
});
};
$scope.getAllTenants();
$scope.getAllWorkingCalendars();
$scope.$on('handleBroadcastTenantChanged', function(event) {
$scope.tenantworkingcalendars = [];
$scope.getAllTenants();
});
});
'use strict';
app.factory('TenantWorkingCalendarService', function($http) {
return {
addPair: function(tenantID, workingcalendarID, headers, callback) {
$http.post(getAPI()+'tenants/'+tenantID+'/workingcalendars', {data: {"working_calendar_id": workingcalendarID}}, {headers})
.then(function (response) {
callback(response);
}, function (response) {
callback(response);
});
},
deletePair: function(tenantID, workingcalendarID, headers, callback) {
$http.delete(getAPI()+'tenants/'+tenantID+'/workingcalendars'+'/'+workingcalendarID, {headers})
.then(function (response) {
callback(response);
}, function (response) {
callback(response);
});
},
getWorkingCalendarsByTenantID: function(id, callback) {
$http.get(getAPI()+'tenants/'+id+'/workingcalendars')
.then(function (response) {
callback(response);
}, function (response) {
callback(response);
});
}
};
});
......@@ -311,6 +311,79 @@
</div>
</uib-tab>
<uib-tab heading="{{'WORKING_CALENDAR.BIND_WORKING_CALENDAR' | translate}}">
<div class="panel-body" ng-controller="TenantWorkingCalendarController">
<div class="row">
<div class="col-lg-3">
<div class="panel panel-info">
<div class="panel-heading">
{{'COMMON.TENANT' | translate}}
</div>
<div class="panel-body">
<form role="form">
<div class="form-group no-margin">
<label>{{'SETTING.SELECT_TENANT' | translate}}</label>
<ui-select on-select="changeTenant($item,$model)"
ng-model="currentTenant.selected" theme="bootstrap">
<ui-select-match
placeholder="{{'COMMON.PLACEHOLDER' | translate}}">
{{$select.selected.name}}</ui-select-match>
<ui-select-choices
repeat="tenant.id as tenant in tenants | filter: $select.search">
<div ng-bind-html="tenant.name | highlight: $select.search">
</div>
</ui-select-choices>
</ui-select>
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="panel panel-primary">
<div class="panel-heading">
{{'WORKING_CALENDAR.N_S_WORKING_CALENDAR' | translate}}
</div>
<div class="panel-body maxheight"
x-hjc-drop-target="true"
x-on-drop="pairWorkingCalendar(dragEl,dropEl)"
uib-tooltip="{{'SETTING.DRAG_TO_UNBIND' | translate}}">
<div class="btn btn-primary btn-rounded btn-block"
ng-repeat="tenantworkingcalendar in tenantworkingcalendars" x-hjc-draggable="true"
title="{{tenantworkingcalendar.name}}">
({{tenantworkingcalendar.name}})</div>
</div>
</div>
<div class="panel panel-danger">
<div class="panel-heading">
{{'SETTING.TRASH' | translate}}
</div>
<div class="panel-body trash">
<img class="trashcan" src="img/trashcan.png" x-hjc-drop-target="true"
x-on-drop="deleteWorkingCalendarPair(dragEl,dropEl)">
</div>
</div>
</div>
<div class="col-lg-4">
<!-- according panel-->
<div class="panel panel-primary">
<div class="panel-heading">
{{'SETTING.WORKING_CALENDAR' | translate}}
</div>
<div class="panel-body" uib-tooltip="{{'SETTING.DRAG_TO_BIND' | translate}}"
slim-scroll box-height="765px">
<div class="source btn btn-primary btn-rounded btn-block"
ng-repeat="workingcalendar in workingcalendars" x-hjc-draggable="true">
{{workingcalendar.name}}</div>
</div>
</div>
</div>
</div>
</div>
</uib-tab>
</uib-tabset>
</div>
</div>
......
......@@ -463,6 +463,10 @@ api.add_route('/tenants/{id_}/virtualmeters',
tenant.TenantVirtualMeterCollection())
api.add_route('/tenants/{id_}/virtualmeters/{mid}',
tenant.TenantVirtualMeterItem())
api.add_route('/tenants/{id_}/workingcalendars',
tenant.TenantWorkingCalendarCollection())
api.add_route('/tenants/{id_}/workingcalendars/{wcid}',
tenant.TenantWorkingCalendarItem())
api.add_route('/tenanttypes',
tenanttype.TenantTypeCollection())
......
from datetime import datetime, timedelta, timezone
import falcon
import mysql.connector
import simplejson as json
from core.useractivity import user_logger, access_control
import config
class SpaceNonWorkingDayCollection:
@staticmethod
def __init__():
""""Initializes WebMessageCollection"""
pass
@staticmethod
def on_options(req, resp):
resp.status = falcon.HTTP_200
@staticmethod
def on_get(req, resp, id_, startDate, endDate):
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_SPACE_ID')
start_datetime_utc = None
if startDate is not None and len(str.strip(startDate)) > 0:
start_datetime_utc = str.strip(startDate)
else:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_START_DATETIME")
end_datetime_utc = None
if endDate is not None and len(str.strip(endDate)) > 0:
end_datetime_utc = str.strip(endDate)
else:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_END_DATETIME")
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
cursor.execute(" SELECT date_local "
" FROM tbl_spaces_non_working_days "
" WHERE space_id = %s AND"
" date_local >= %s AND"
" date_local <= %s"
, (id_, start_datetime_utc, end_datetime_utc))
rows = cursor.fetchall()
if cursor:
cursor.close()
if cnx:
cnx.close()
result = dict()
result['non_working_days'] = list()
if rows is not None and len(rows) > 0:
for row in rows:
date = row[0].strftime("%Y-%m-%d")
result['non_working_days'].append(date)
resp.text = json.dumps(result)
class SpaceNonWorkingDayItem:
@staticmethod
def __init__():
""""Initializes WebMessageCollection"""
pass
@staticmethod
@user_logger
def on_post(req, resp, id_):
access_control(req)
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_SPACE_ID')
try:
raw_json = req.stream.read().decode('utf-8')
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=str(ex))
new_values = json.loads(raw_json)
if 'create_non_working_days_array' not in new_values['data'].keys() or \
not isinstance(new_values['data']['create_non_working_days_array'], (list, tuple)):
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_')
create_non_working_days_array = new_values['data']['create_non_working_days_array']
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
create_non_working_days_list= list()
if len(create_non_working_days_array) > 0:
add_row = (" INSERT INTO tbl_spaces_non_working_days"
" (space_id, date_local)"
" VALUES (%s, %s)")
for create_non_working_day in create_non_working_days_array:
create_non_working_days_list.append((id_, create_non_working_day))
cursor.executemany(add_row, create_non_working_days_list)
cnx.commit()
cursor.close()
cnx.close()
resp.status = falcon.HTTP_201
resp.location = '/spaces/' + str(id_) + '/nonworkingdays/'
@staticmethod
@user_logger
def on_options(req, resp):
resp.status = falcon.HTTP_200
@staticmethod
@user_logger
def on_put(req, resp, id_):
access_control(req)
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_SPACE_ID')
try:
raw_json = req.stream.read().decode('utf-8')
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=str(ex))
new_values = json.loads(raw_json)
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
if 'delete_non_working_days_array' not in new_values['data'].keys() or \
not isinstance(new_values['data']['delete_non_working_days_array'], (list, tuple)):
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_')
delete_non_working_days_array = new_values['data']['delete_non_working_days_array']
if len(delete_non_working_days_array) > 0:
for delete_non_working_day in delete_non_working_days_array:
cursor.execute(" DELETE from tbl_spaces_non_working_days "
" WHERE space_id = %s AND "
" date_local = %s", (id_, delete_non_working_day))
cnx.commit()
cursor.close()
cnx.close()
resp.status = falcon.HTTP_200
......@@ -1616,3 +1616,170 @@ class TenantVirtualMeterItem:
resp.status = falcon.HTTP_204
class TenantWorkingCalendarCollection:
@staticmethod
def __init__():
"""Initializes TenantWorkingCalendarCollection Class"""
pass
@staticmethod
def on_options(req, resp, id_):
resp.status = falcon.HTTP_200
@staticmethod
def on_get(req, resp, id_):
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_TENANT_ID')
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
cursor.execute(" SELECT name "
" FROM tbl_tenants "
" WHERE id = %s ", (id_,))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.TENANT_NOT_FOUND')
query = (" SELECT wc.id, wc.name, wc.description "
" FROM tbl_tenants t, tbl_tenants_working_calendars twc, tbl_working_calendars wc "
" WHERE twc.tenant_id = t.id AND wc.id = twc.working_calendar_id AND t.id = %s "
" ORDER BY wc.id ")
cursor.execute(query, (id_,))
rows = cursor.fetchall()
result = list()
if rows is not None and len(rows) > 0:
for row in rows:
meta_result = {"id": row[0], "name": row[1], "description": row[2]}
result.append(meta_result)
resp.text = json.dumps(result)
@staticmethod
@user_logger
def on_post(req, resp, id_):
"""Handles POST requests"""
access_control(req)
try:
raw_json = req.stream.read().decode('utf-8')
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=str(ex))
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_TENANT_ID')
new_values = json.loads(raw_json)
if 'working_calendar_id' not in new_values['data'].keys() or \
not isinstance(new_values['data']['working_calendar_id'], int) or \
new_values['data']['working_calendar_id'] <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_WORKING_CALENDAR_ID')
working_calendar_id = new_values['data']['working_calendar_id']
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
cursor.execute(" SELECT name "
" from tbl_tenants "
" WHERE id = %s ", (id_,))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.TENANT_NOT_FOUND')
cursor.execute(" SELECT name "
" FROM tbl_working_calendars "
" WHERE id = %s ", (working_calendar_id,))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.WORKING_CALENDAR_NOT_FOUND')
query = (" SELECT id "
" FROM tbl_tenants_working_calendars "
" WHERE tenant_id = %s AND working_calendar_id = %s")
cursor.execute(query, (id_, working_calendar_id,))
if cursor.fetchone() is not None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR',
description='API.TENANT_WORKING_CALENDAR_RELATION_EXISTS')
add_row = (" INSERT INTO tbl_tenants_working_calendars (tenant_id, working_calendar_id) "
" VALUES (%s, %s) ")
cursor.execute(add_row, (id_, working_calendar_id,))
cnx.commit()
cursor.close()
cnx.close()
resp.status = falcon.HTTP_201
resp.location = '/tenants/' + str(id_) + '/workingcalendars/' + str(working_calendar_id)
class TenantWorkingCalendarItem:
@staticmethod
def __init__():
"""Initializes TenantWorkingCalendarItem Class"""
pass
@staticmethod
def on_options(req, resp, id_, wcid):
resp.status = falcon.HTTP_200
@staticmethod
@user_logger
def on_delete(req, resp, id_, wcid):
access_control(req)
if not id_.isdigit() or int(id_) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_TENANT_ID')
if not wcid.isdigit() or int(wcid) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_WORKING_CALENDAR_ID')
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
cursor.execute(" SELECT name "
" FROM tbl_tenants "
" WHERE id = %s ", (id_,))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.TENANT_NOT_FOUND')
cursor.execute(" SELECT name "
" FROM tbl_working_calendars "
" WHERE id = %s ", (wcid,))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.WORKING_CALENDAR_NOT_FOUND')
cursor.execute(" SELECT id "
" FROM tbl_tenants_working_calendars "
" WHERE tenant_id = %s AND working_calendar_id = %s ", (id_, wcid))
if cursor.fetchone() is None:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
description='API.TENANT_WORKING_CALENDAR_RELATION_NOT_FOUND')
cursor.execute(" DELETE FROM tbl_tenants_working_calendars WHERE tenant_id = %s AND working_calendar_id = %s ", (id_, wcid))
cnx.commit()
cursor.close()
cnx.close()
resp.status = falcon.HTTP_204
\ No newline at end of file
......@@ -134,7 +134,7 @@ class WorkingCalendarItem:
cnx = mysql.connector.connect(**config.myems_system_db)
cursor = cnx.cursor()
# check relation with non working days
# check relation with space
cursor.execute(" SELECT id FROM tbl_spaces_working_calendars"
" WHERE working_calendar_id = %s ", (id_,))
......@@ -146,9 +146,21 @@ class WorkingCalendarItem:
title='API.BAD_REQUEST',
description='API.THERE_IS_RELATION_WITH_SPACES')
# check relation with space
# check relation with non working days
cursor.execute(" SELECT id FROM tbl_working_calendars_non_working_days"
" WHERE working_calendar_id = %s ", (id_,))
# check relation with tenants
cursor.execute(" SELECT tenant_id "
" FROM tbl_tenants_working_calendars "
" WHERE working_calendar_id = %s ", (id_,))
rows_tenants = cursor.fetchall()
if rows_tenants is not None and len(rows_tenants) > 0:
cursor.close()
cnx.close()
raise falcon.HTTPError(falcon.HTTP_400,
title='API.BAD_REQUEST',
description='API.THERE_IS_RELATION_WITH_TENANTS')
rows_non_working_days = cursor.fetchall()
if rows_non_working_days is not None and len(rows_non_working_days) > 0:
......
......@@ -614,7 +614,11 @@ def generate_excel(report,
len(report['base_period']['non_working_days_subtotals']) == 0 or \
"working_days_subtotals" not in report['base_period'].keys() or \
report['base_period']['working_days_subtotals'] is None or \
len(report['base_period']['working_days_subtotals']) == 0:
len(report['base_period']['working_days_subtotals']) == 0 or \
base_period_start_datetime_local is None or \
len(str.strip(base_period_start_datetime_local)) == 0 or \
base_period_end_datetime_local is None or \
len(str.strip(base_period_end_datetime_local)) == 0:
pass
else:
ws['B' + str(current_row_number)].font = title_font
......@@ -654,13 +658,15 @@ def generate_excel(report,
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = report['base_period']['non_working_days_subtotals'][i] if \
len(report['space']['working_calendars']) > 0 else '-'
len(report['space']['working_calendars']) > 0 and \
report['base_period']['non_working_days_subtotals'][i] > 0 else '-'
ws['D' + str(current_row_number)].font = title_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = report['base_period']['working_days_subtotals'][i] if \
len(report['space']['working_calendars']) > 0 else '-'
len(report['space']['working_calendars']) > 0 and \
report['base_period']['working_days_subtotals'][i] > 0 else '-'
current_row_number += 1
......@@ -711,13 +717,15 @@ def generate_excel(report,
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = report['reporting_period']['non_working_days_subtotals'][i] if \
len(report['space']['working_calendars']) > 0 else '-'
len(report['space']['working_calendars']) > 0 and \
report['reporting_period']['non_working_days_subtotals'][i] > 0 else '-'
ws['D' + str(current_row_number)].font = title_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = report['reporting_period']['working_days_subtotals'][i] if \
len(report['space']['working_calendars']) > 0 else '-'
len(report['space']['working_calendars']) > 0 and \
report['reporting_period']['working_days_subtotals'][i] > 0 else '-'
current_row_number += 1
......
......@@ -508,6 +508,130 @@ def generate_excel(report,
current_row_number += 1
####################################################################################################################
if "non_working_days_subtotals" not in report['base_period'].keys() or \
report['base_period']['non_working_days_subtotals'] is None or \
len(report['base_period']['non_working_days_subtotals']) == 0 or \
"working_days_subtotals" not in report['base_period'].keys() or \
report['base_period']['working_days_subtotals'] is None or \
len(report['base_period']['working_days_subtotals']) == 0 or \
base_period_start_datetime_local is None or \
len(str.strip(base_period_start_datetime_local)) == 0 or \
base_period_end_datetime_local is None or \
len(str.strip(base_period_end_datetime_local)) == 0:
pass
else:
ws['B' + str(current_row_number)].font = title_font
ws['B' + str(current_row_number)] = name + ' ' + _('Base Period Consumption')
current_row_number += 1
ws.row_dimensions[current_row_number].height = 60
ws['B' + str(current_row_number)].fill = table_fill
ws['B' + str(current_row_number)].font = name_font
ws['B' + str(current_row_number)].alignment = c_c_alignment
ws['B' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)].fill = table_fill
ws['C' + str(current_row_number)].font = name_font
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = _('Non Working Days') + _('Consumption')
ws['D' + str(current_row_number)].fill = table_fill
ws['D' + str(current_row_number)].font = name_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = _('Working Days') + _('Consumption')
current_row_number += 1
ca_len = len(report['base_period']['names'])
for i in range(0, ca_len):
ws['B' + str(current_row_number)].font = title_font
ws['B' + str(current_row_number)].alignment = c_c_alignment
ws['B' + str(current_row_number)] = report['base_period']['names'][i] + " (" + report['base_period']['units'][i] + ")"
ws['B' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)].font = title_font
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = report['base_period']['non_working_days_subtotals'][i] if \
len(report['tenant']['working_calendars']) > 0 and \
report['base_period']['non_working_days_subtotals'][i] > 0 else '-'
ws['D' + str(current_row_number)].font = title_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = report['base_period']['working_days_subtotals'][i] if \
len(report['tenant']['working_calendars']) > 0 and \
report['base_period']['working_days_subtotals'][i] > 0 else '-'
current_row_number += 1
current_row_number += 1
if "non_working_days_subtotals" not in report['reporting_period'].keys() or \
report['reporting_period']['non_working_days_subtotals'] is None or \
len(report['reporting_period']['non_working_days_subtotals']) == 0 or \
"working_days_subtotals" not in report['reporting_period'].keys() or \
report['reporting_period']['working_days_subtotals'] is None or \
len(report['reporting_period']['working_days_subtotals']) == 0:
pass
else:
ws['B' + str(current_row_number)].font = title_font
ws['B' + str(current_row_number)] = name + ' ' + _('Reporting Period Consumption')
current_row_number += 1
ws.row_dimensions[current_row_number].height = 60
ws['B' + str(current_row_number)].fill = table_fill
ws['B' + str(current_row_number)].font = name_font
ws['B' + str(current_row_number)].alignment = c_c_alignment
ws['B' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)].fill = table_fill
ws['C' + str(current_row_number)].font = name_font
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = _('Non Working Days') + _('Consumption')
ws['D' + str(current_row_number)].fill = table_fill
ws['D' + str(current_row_number)].font = name_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = _('Working Days') + _('Consumption')
current_row_number += 1
ca_len = len(report['reporting_period']['names'])
for i in range(0, ca_len):
ws['B' + str(current_row_number)].font = title_font
ws['B' + str(current_row_number)].alignment = c_c_alignment
ws['B' + str(current_row_number)] = report['reporting_period']['names'][i] + " (" + report['reporting_period']['units'][i] + ")"
ws['B' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)].font = title_font
ws['C' + str(current_row_number)].alignment = c_c_alignment
ws['C' + str(current_row_number)].border = f_border
ws['C' + str(current_row_number)] = report['reporting_period']['non_working_days_subtotals'][i] if \
len(report['tenant']['working_calendars']) > 0 and \
report['reporting_period']['non_working_days_subtotals'][i] > 0 else '-'
ws['D' + str(current_row_number)].font = title_font
ws['D' + str(current_row_number)].alignment = c_c_alignment
ws['D' + str(current_row_number)].border = f_border
ws['D' + str(current_row_number)] = report['reporting_period']['working_days_subtotals'][i] if \
len(report['tenant']['working_calendars']) > 0 and \
report['reporting_period']['working_days_subtotals'][i] > 0 else '-'
current_row_number+= 1
current_row_number += 2
####################################################################################################################
table_start_draw_flag = current_row_number + 1
if "timestamps" not in reporting_period_data.keys() or \
......
......@@ -343,21 +343,22 @@ class Reporting:
base = dict()
base['non_working_days'] = list()
if energy_category_set is not None and len(energy_category_set) > 0:
cursor_system.execute(" SELECT nwd.date_local "
" FROM tbl_spaces sp, tbl_spaces_working_calendars spwc, "
" tbl_working_calendars_non_working_days nwd "
" WHERE sp.id = %s AND "
" sp.id = spwc.space_id AND "
" spwc.working_calendar_id = nwd.working_calendar_id AND"
" nwd.date_local >= %s AND"
" nwd.date_local <= %s ",
(space['id'],
base_start_datetime_non_working_day,
base_end_datetime_non_working_day))
rows = cursor_system.fetchall()
for row in rows:
row_datetime = row[0].strftime('%Y-%m-%d')
base['non_working_days'].append(row_datetime)
if base_start_datetime_utc is not None and base_end_datetime_utc is not None:
cursor_system.execute(" SELECT nwd.date_local "
" FROM tbl_spaces sp, tbl_spaces_working_calendars spwc, "
" tbl_working_calendars_non_working_days nwd "
" WHERE sp.id = %s AND "
" sp.id = spwc.space_id AND "
" spwc.working_calendar_id = nwd.working_calendar_id AND"
" nwd.date_local >= %s AND"
" nwd.date_local <= %s ",
(space['id'],
base_start_datetime_non_working_day,
base_end_datetime_non_working_day))
rows = cursor_system.fetchall()
for row in rows:
row_datetime = row[0].strftime('%Y-%m-%d')
base['non_working_days'].append(row_datetime)
for energy_category_id in energy_category_set:
kgce = energy_category_dict[energy_category_id]['kgce']
kgco2e = energy_category_dict[energy_category_id]['kgco2e']
......
......@@ -29,11 +29,12 @@ class Reporting:
# Step 3: query energy categories
# Step 4: query associated sensors
# Step 5: query associated points
# Step 6: query base period energy input
# Step 7: query reporting period energy input
# Step 8: query tariff data
# Step 9: query associated sensors and points data
# Step 10: construct the report
# Step 6: query associated working calendars
# Step 7: query base period energy input
# Step 8: query reporting period energy input
# Step 9: query tariff data
# Step 10: query associated sensors and points data
# Step 11: construct the report
####################################################################################################################
@staticmethod
def on_get(req, resp):
......@@ -87,6 +88,7 @@ class Reporting:
base_period_start_datetime_local = str.strip(base_period_start_datetime_local)
try:
base_start_datetime_utc = datetime.strptime(base_period_start_datetime_local, '%Y-%m-%dT%H:%M:%S')
base_start_datetime_non_working_day = str(base_period_start_datetime_local).split('T')[0]
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_BASE_PERIOD_START_DATETIME")
......@@ -103,6 +105,7 @@ class Reporting:
base_period_end_datetime_local = str.strip(base_period_end_datetime_local)
try:
base_end_datetime_utc = datetime.strptime(base_period_end_datetime_local, '%Y-%m-%dT%H:%M:%S')
base_end_datetime_non_working_day = str(base_period_end_datetime_local).split('T')[0]
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_BASE_PERIOD_END_DATETIME")
......@@ -122,6 +125,7 @@ class Reporting:
try:
reporting_start_datetime_utc = datetime.strptime(reporting_period_start_datetime_local,
'%Y-%m-%dT%H:%M:%S')
reporting_start_datetime_non_working_day = str(reporting_period_start_datetime_local).split('T')[0]
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
......@@ -142,6 +146,7 @@ class Reporting:
reporting_end_datetime_utc = datetime.strptime(reporting_period_end_datetime_local,
'%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
timedelta(minutes=timezone_offset)
reporting_end_datetime_non_working_day = str(reporting_period_end_datetime_local).split('T')[0]
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
......@@ -302,10 +307,40 @@ class Reporting:
point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
################################################################################################################
# Step 6: query base period energy input
# Step 6: query associated working calendars
################################################################################################################
working_calendar_list = list()
cursor_system.execute(" SELECT twc.id "
" FROM tbl_tenants t, tbl_tenants_working_calendars twc "
" WHERE t.id = %s AND t.id = twc.tenant_id "
, (tenant['id'], ))
rows = cursor_system.fetchall()
if rows is not None and len(rows) > 0:
for row in rows:
working_calendar_list.append(row[0])
################################################################################################################
# Step 7: query base period energy input
################################################################################################################
base = dict()
base['non_working_days'] = list()
if energy_category_set is not None and len(energy_category_set) > 0:
if base_start_datetime_utc is not None and base_end_datetime_utc is not None:
cursor_system.execute(" SELECT nwd.date_local "
" FROM tbl_tenants t, tbl_tenants_working_calendars twc, "
" tbl_working_calendars_non_working_days nwd "
" WHERE t.id = %s AND "
" t.id = twc.tenant_id AND "
" twc.working_calendar_id = nwd.working_calendar_id AND"
" nwd.date_local >= %s AND"
" nwd.date_local <= %s ",
(tenant['id'],
base_start_datetime_non_working_day,
base_end_datetime_non_working_day))
rows = cursor_system.fetchall()
for row in rows:
row_datetime = row[0].strftime('%Y-%m-%d')
base['non_working_days'].append(row_datetime)
for energy_category_id in energy_category_set:
kgce = energy_category_dict[energy_category_id]['kgce']
kgco2e = energy_category_dict[energy_category_id]['kgco2e']
......@@ -316,6 +351,8 @@ class Reporting:
base[energy_category_id]['subtotal'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgce'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgco2e'] = Decimal(0.0)
base[energy_category_id]['non_working_days_subtotal'] = Decimal(0.0)
base[energy_category_id]['working_days_subtotal'] = Decimal(0.0)
cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_tenant_input_category_hourly "
......@@ -354,12 +391,32 @@ class Reporting:
base[energy_category_id]['subtotal'] += actual_value
base[energy_category_id]['subtotal_in_kgce'] += actual_value * kgce
base[energy_category_id]['subtotal_in_kgco2e'] += actual_value * kgco2e
if current_datetime in base['non_working_days']:
base[energy_category_id]['non_working_days_subtotal'] += actual_value
else:
base[energy_category_id]['working_days_subtotal'] += actual_value
################################################################################################################
# Step 8: query reporting period energy input
################################################################################################################
reporting = dict()
reporting['non_working_days'] = list()
if energy_category_set is not None and len(energy_category_set) > 0:
cursor_system.execute(" SELECT nwd.date_local "
" FROM tbl_tenants t, tbl_tenants_working_calendars twc, "
" tbl_working_calendars_non_working_days nwd "
" WHERE t.id = %s AND "
" t.id = twc.tenant_id AND "
" twc.working_calendar_id = nwd.working_calendar_id AND"
" nwd.date_local >= %s AND"
" nwd.date_local <= %s ",
(tenant['id'],
reporting_start_datetime_non_working_day,
reporting_end_datetime_non_working_day))
rows = cursor_system.fetchall()
for row in rows:
row_datetime = row[0].strftime('%Y-%m-%d')
reporting['non_working_days'].append(row_datetime)
for energy_category_id in energy_category_set:
kgce = energy_category_dict[energy_category_id]['kgce']
kgco2e = energy_category_dict[energy_category_id]['kgco2e']
......@@ -374,6 +431,8 @@ class Reporting:
reporting[energy_category_id]['onpeak'] = Decimal(0.0)
reporting[energy_category_id]['midpeak'] = Decimal(0.0)
reporting[energy_category_id]['offpeak'] = Decimal(0.0)
reporting[energy_category_id]['non_working_days_subtotal'] = Decimal(0.0)
reporting[energy_category_id]['working_days_subtotal'] = Decimal(0.0)
cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_tenant_input_category_hourly "
......@@ -412,6 +471,10 @@ class Reporting:
reporting[energy_category_id]['subtotal'] += actual_value
reporting[energy_category_id]['subtotal_in_kgce'] += actual_value * kgce
reporting[energy_category_id]['subtotal_in_kgco2e'] += actual_value * kgco2e
if current_datetime in reporting['non_working_days']:
reporting[energy_category_id]['non_working_days_subtotal'] += actual_value
else:
reporting[energy_category_id]['working_days_subtotal'] += actual_value
energy_category_tariff_dict = utilities.get_energy_category_peak_types(tenant['cost_center_id'],
energy_category_id,
......@@ -521,7 +584,7 @@ class Reporting:
parameters_data['values'].append(point_values)
################################################################################################################
# Step 12: construct the report
# Step 11: construct the report
################################################################################################################
if cursor_system:
cursor_system.close()
......@@ -543,6 +606,7 @@ class Reporting:
result['tenant'] = dict()
result['tenant']['name'] = tenant['name']
result['tenant']['area'] = tenant['area']
result['tenant']['working_calendars'] = working_calendar_list
result['base_period'] = dict()
result['base_period']['names'] = list()
......@@ -554,6 +618,10 @@ class Reporting:
result['base_period']['subtotals_in_kgco2e'] = list()
result['base_period']['total_in_kgce'] = Decimal(0.0)
result['base_period']['total_in_kgco2e'] = Decimal(0.0)
result['base_period']['non_working_days_subtotals'] = list()
result['base_period']['working_days_subtotals'] = list()
result['base_period']['non_working_days_total'] = Decimal(0.0)
result['base_period']['working_days_total'] = Decimal(0.0)
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
......@@ -565,6 +633,10 @@ class Reporting:
result['base_period']['subtotals_in_kgco2e'].append(base[energy_category_id]['subtotal_in_kgco2e'])
result['base_period']['total_in_kgce'] += base[energy_category_id]['subtotal_in_kgce']
result['base_period']['total_in_kgco2e'] += base[energy_category_id]['subtotal_in_kgco2e']
result['base_period']['non_working_days_subtotals'].append(base[energy_category_id]['non_working_days_subtotal'])
result['base_period']['working_days_subtotals'].append(base[energy_category_id]['working_days_subtotal'])
result['base_period']['non_working_days_total'] += base[energy_category_id]['non_working_days_subtotal']
result['base_period']['working_days_total'] += base[energy_category_id]['working_days_subtotal']
result['reporting_period'] = dict()
result['reporting_period']['names'] = list()
......@@ -586,6 +658,10 @@ class Reporting:
result['reporting_period']['total_in_kgco2e'] = Decimal(0.0)
result['reporting_period']['increment_rate_in_kgce'] = Decimal(0.0)
result['reporting_period']['increment_rate_in_kgco2e'] = Decimal(0.0)
result['reporting_period']['non_working_days_subtotals'] = list()
result['reporting_period']['working_days_subtotals'] = list()
result['reporting_period']['non_working_days_total'] = Decimal(0.0)
result['reporting_period']['working_days_total'] = Decimal(0.0)
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
......@@ -611,6 +687,10 @@ class Reporting:
if base[energy_category_id]['subtotal'] > 0.0 else None)
result['reporting_period']['total_in_kgce'] += reporting[energy_category_id]['subtotal_in_kgce']
result['reporting_period']['total_in_kgco2e'] += reporting[energy_category_id]['subtotal_in_kgco2e']
result['reporting_period']['non_working_days_subtotals'].append(reporting[energy_category_id]['non_working_days_subtotal'])
result['reporting_period']['working_days_subtotals'].append(reporting[energy_category_id]['working_days_subtotal'])
result['reporting_period']['non_working_days_total'] += reporting[energy_category_id]['non_working_days_subtotal']
result['reporting_period']['working_days_total'] += reporting[energy_category_id]['working_days_subtotal']
rate = list()
for index, value in enumerate(reporting[energy_category_id]['values']):
......
......@@ -553,6 +553,58 @@ const SpaceEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
})
});
setDetailedDataTableColumns(detailed_column_list);
let workding_days_table_column_list = [];
workding_days_table_column_list.push({
dataField: 'name',
text: t('Energy Category'),
sort: true
});
workding_days_table_column_list.push({
dataField: 'b0',
text: t('Reporting Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b1',
text: t('Reporting Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
setWorkingDaysConsumptionTableColumns(workding_days_table_column_list);
let working_days_table_value_list = [];
json['reporting_period']['names'].forEach((currentValue, index) => {
let working_days_table_value = {};
let unit = json['reporting_period']['units'][index];
working_days_table_value['name'] = currentValue + ' (' + unit + ')';
working_days_table_value['b0'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['working_days_subtotals'][index] : "-";
working_days_table_value['b1'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value_list.push(working_days_table_value);
});
setWorkingDaysConsumptionTableData(working_days_table_value_list);
} else {
/*
* Tip:
......@@ -638,6 +690,90 @@ const SpaceEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
setDetailedDataTableData(detailed_value_list);
}, 0)
}
let workding_days_table_column_list = [];
workding_days_table_column_list.push({
dataField: 'name',
text: t('Energy Category'),
sort: true
});
workding_days_table_column_list.push({
dataField: 'a0',
text: t('Base Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'a1',
text: t('Base Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b0',
text: t('Reporting Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b1',
text: t('Reporting Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
setWorkingDaysConsumptionTableColumns(workding_days_table_column_list);
let working_days_table_value_list = [];
json['base_period']['names'].forEach((currentValue, index) => {
let working_days_table_value = {};
let unit = json['base_period']['units'][index];
working_days_table_value['name'] = currentValue + ' (' + unit + ')';
working_days_table_value['a0'] = json['space']['working_calendars'].length > 0 ? json['base_period']['working_days_subtotals'][index] : "-";
working_days_table_value['a1'] = json['space']['working_calendars'].length > 0 ? json['base_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value['b0'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['working_days_subtotals'][index] : "-";
working_days_table_value['b1'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value_list.push(working_days_table_value);
});
setWorkingDaysConsumptionTableData(working_days_table_value_list);
}
let child_space_value_list = [];
......@@ -695,77 +831,6 @@ const SpaceEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
setChildSpacesTableColumns(child_space_column_list);
let workding_days_table_column_list = [];
workding_days_table_column_list.push({
dataField: 'name',
text: t('Energy Category'),
sort: true
});
workding_days_table_column_list.push({
dataField: 'a0',
text: t('Base Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'a1',
text: t('Base Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b0',
text: t('Reporting Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b1',
text: t('Reporting Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
setWorkingDaysConsumptionTableColumns(workding_days_table_column_list);
let working_days_table_value_list = [];
json['base_period']['names'].forEach((currentValue, index) => {
let working_days_table_value = {};
let unit = json['base_period']['units'][index];
working_days_table_value['name'] = currentValue + ' (' + unit + ')';
working_days_table_value['a0'] = json['space']['working_calendars'].length > 0 ? json['base_period']['working_days_subtotals'][index] : "-";
working_days_table_value['a1'] = json['space']['working_calendars'].length > 0 ? json['base_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value['b0'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['working_days_subtotals'][index] : "-";
working_days_table_value['b1'] = json['space']['working_calendars'].length > 0 ? json['reporting_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value_list.push(working_days_table_value);
});
setWorkingDaysConsumptionTableData(working_days_table_value_list);
setExcelBytesBase64(json['excel_bytes_base64']);
// enable submit button
......
......@@ -36,6 +36,7 @@ import AppContext from '../../../context/Context';
import MultipleLineChart from '../common/MultipleLineChart';
const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
const WorkingDaysConsumptionTable = loadable(() => import('../common/WorkingDaysConsumptionTable'));
const TenantEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
let current_moment = moment();
......@@ -136,6 +137,9 @@ const TenantEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
const [detailedDataTableData, setDetailedDataTableData] = useState([]);
const [detailedDataTableColumns, setDetailedDataTableColumns] = useState([{dataField: 'startdatetime', text: t('Datetime'), sort: true}]);
const [excelBytesBase64, setExcelBytesBase64] = useState(undefined);
const [workingDaysConsumptionTableData, setWorkingDaysConsumptionTableData] = useState([]);
const [workingDaysConsumptionTableColumns, setWorkingDaysConsumptionTableColumns] = useState([{dataField: 'name', text: t('Energy Category'), sort: true }]);
useEffect(() => {
let isResponseOK = false;
......@@ -595,6 +599,59 @@ const TenantEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
});
});
setDetailedDataTableColumns(detailed_column_list);
let workding_days_table_column_list = [];
workding_days_table_column_list.push({
dataField: 'name',
text: t('Energy Category'),
sort: true
});
workding_days_table_column_list.push({
dataField: 'b0',
text: t('Reporting Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b1',
text: t('Reporting Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
setWorkingDaysConsumptionTableColumns(workding_days_table_column_list);
let working_days_table_value_list = [];
json['reporting_period']['names'].forEach((currentValue, index) => {
let working_days_table_value = {};
let unit = json['reporting_period']['units'][index];
working_days_table_value['name'] = currentValue + ' (' + unit + ')';
working_days_table_value['b0'] = json['tenant']['working_calendars'].length > 0 ? json['reporting_period']['working_days_subtotals'][index] : "-";
working_days_table_value['b1'] = json['tenant']['working_calendars'].length > 0 ? json['reporting_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value_list.push(working_days_table_value);
});
setWorkingDaysConsumptionTableData(working_days_table_value_list);
}else {
/*
* Tip:
......@@ -681,6 +738,90 @@ const TenantEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
}, 0)
}
let workding_days_table_column_list = [];
workding_days_table_column_list.push({
dataField: 'name',
text: t('Energy Category'),
sort: true
});
workding_days_table_column_list.push({
dataField: 'a0',
text: t('Base Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'a1',
text: t('Base Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b0',
text: t('Reporting Period') + ' - ' + t('Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
workding_days_table_column_list.push({
dataField: 'b1',
text: t('Reporting Period') + ' - ' + t('Non Working Days'),
sort: false,
formatter: function (decimalValue) {
if (typeof decimalValue === 'number') {
if (decimalValue === 0) {
return '-'
}
return decimalValue.toFixed(2);
} else {
return decimalValue;
}
}
});
setWorkingDaysConsumptionTableColumns(workding_days_table_column_list);
let working_days_table_value_list = [];
json['base_period']['names'].forEach((currentValue, index) => {
let working_days_table_value = {};
let unit = json['base_period']['units'][index];
working_days_table_value['name'] = currentValue + ' (' + unit + ')';
working_days_table_value['a0'] = json['tenant']['working_calendars'].length > 0 ? json['base_period']['working_days_subtotals'][index] : "-";
working_days_table_value['a1'] = json['tenant']['working_calendars'].length > 0 ? json['base_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value['b0'] = json['tenant']['working_calendars'].length > 0 ? json['reporting_period']['working_days_subtotals'][index] : "-";
working_days_table_value['b1'] = json['tenant']['working_calendars'].length > 0 ? json['reporting_period']['non_working_days_subtotals'][index] : "-";
working_days_table_value_list.push(working_days_table_value);
});
setWorkingDaysConsumptionTableData(working_days_table_value_list);
}
setExcelBytesBase64(json['excel_bytes_base64']);
......@@ -912,6 +1053,11 @@ const TenantEnergyCategory = ({ setRedirect, setRedirectUrl, t }) => {
options={parameterLineChartOptions}>
</MultipleLineChart>
<br />
<WorkingDaysConsumptionTable
data={workingDaysConsumptionTableData}
title={t('CATEGORY Consumption UNIT', { 'CATEGORY': t('Working Days') + '/' + t('Non Working Days') })}
columns={workingDaysConsumptionTableColumns}>
</WorkingDaysConsumptionTable>
<DetailedDataTable data={detailedDataTableData} title={t('Detailed Data')} columns={detailedDataTableColumns} pagesize={50} >
</DetailedDataTable>
......
......@@ -121,18 +121,22 @@ const MultiTrendChart = ({
displayColors: false,
callbacks: {
title: function(context){
if (context[0].datasetIndex - 1) {
return `${reportingLabels[option][context[0].dataIndex]}`;
} else {
return `${baseLabels[option][context[0].dataIndex]}`;
}
if (context[0].datasetIndex - 1) {
return `${reportingLabels[option][context[0].dataIndex]}`;
} else {
return `${baseLabels[option][context[0].dataIndex]}`;
}
},
label: function(context) {
if (context.datasetIndex - 1) {
return `${parseTitleOrTooltipTitle(reportingTooltipTitle, option)} - ${context.raw != null ? context.raw.toFixed(3) : null}`;
} else {
return `${parseTitleOrTooltipTitle(baseTooltipTitle, option)} - ${context.raw != null ? context.raw.toFixed(3) : null}`;
}
let row = null;
if (context.raw != null && typeof context.raw === 'number'){
row = context.raw.toFixed(3)
}
if (context.datasetIndex - 1) {
return `${parseTitleOrTooltipTitle(reportingTooltipTitle, option)} - ${row}`;
} else {
return `${parseTitleOrTooltipTitle(baseTooltipTitle, option)} - ${row}`;
}
}
}
},
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册