diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js
index eb5654bc8fa8617b135165b646f9ff996ecfec32..5fa9a06d1f94a2f54866afcaea7c8154a3d6afe2 100644
--- a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js
+++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js
@@ -151,7 +151,7 @@ function billProjectionDatesForm(form) {
'X-CSRFToken': Cookies.get('csrftoken')
})
}).then(res => {
- if (!res.payload.err) {
+ if (!res.err) {
// Display response message. Add that loan options changed if fund was changed. Reset didFundChange to false.
responseMessage = 'Saved';
if (didFundChange) {
@@ -182,7 +182,9 @@ function billProjectionDatesForm(form) {
else {
// Display error message.
var resMsg = document.querySelector('#pro-forma-form-save-msg');
- resMsg.innerHTML = `${res.payload.err}`;
+ res.err.responseBody.then((error) => {
+ resMsg.innerHTML = `${error.error}`;
+ })
}
});
}
@@ -303,8 +305,20 @@ function sendFile(id, content) {
'X-CSRFToken': Cookies.get('csrftoken')
})
}).then(res => {
- var text = getText(res.payload.result, id);
- updateTable(id, text);
+ if (!res.err) {
+ document.querySelector('#bills-warning-message').innerHTML = `
+ ${id} bill upload success
+ `;
+ var text = getText(res.payload.result, id);
+ updateTable(id, text);
+ }
+ else {
+ res.err.responseBody.then((error) => {
+ document.querySelector('#bills-warning-message').innerHTML = `
+ ${error.error}
+ `;
+ })
+ }
});
}
@@ -480,7 +494,7 @@ function loadBillsOverview() {
const table = document.querySelector('#Energy-Bills-Overview');
var text = ``;
text += createEstimateModelForm();
- if (res.payload.instance.present) {
+ if (Object.keys(res.payload.instance).length !== 0) {
text += createBillsOverviewTable(res.payload.instance);
}
table.innerHTML = text;
@@ -508,8 +522,10 @@ function billsOverviewFormCalculate(data) {
'X-CSRFToken': Cookies.get('csrftoken')
})
}).then(res => {
- if (res.payload.instance['err']) {
- alert(res.payload.instance['err']);
+ if (res.err) {
+ res.err.responseBody.then((error) => {
+ alert(error.error);
+ })
return false;
}
table = document.querySelector('#Energy-Bills-Overview')
@@ -549,11 +565,13 @@ function billsOverviewFormSubmit(form) {
}).then(res => {
// Display error/success message.
var message = '';
- if (!res.payload.err) {
+ if (!res.err) {
message = 'Saved';
}
else {
- message = res.payload.err;
+ res.err.responseBody.then((error) => {
+ message = res.payload.err;
+ });
}
document.querySelector('#bills-overview-warning-message').innerHTML = `
${message}
diff --git a/blocnote/apps/financialInputs/templates/financialInputs/bills.html b/blocnote/apps/financialInputs/templates/financialInputs/bills.html
index 5af7c7961b932a07d5739f4ee3b51ebcc5ee3cae..98cc36e310ad50e4a28edae030401f517fa8b9e8 100644
--- a/blocnote/apps/financialInputs/templates/financialInputs/bills.html
+++ b/blocnote/apps/financialInputs/templates/financialInputs/bills.html
@@ -36,6 +36,8 @@
+
+
diff --git a/blocnote/apps/financialInputs/views.py b/blocnote/apps/financialInputs/views.py
index cd60eea8cf5eacefa23da9c783c670742528cbf7..35d0b4f588ce8f4b6112cfb924ee7eba71537b72 100644
--- a/blocnote/apps/financialInputs/views.py
+++ b/blocnote/apps/financialInputs/views.py
@@ -187,8 +187,11 @@ class BlocNoteHeader(View):
result = {}
try:
self.handle_form(put, building_id)
- except:
- result['err'] = 'Sorry, the data could not be saved.'
+ except Exception as err:
+ return JsonResponse(
+ {
+ 'error': 'Sorry, something went wrong. Please try again.',
+ }, status=400)
return JsonResponse(result)
def get(self, request, building_id):
@@ -255,7 +258,10 @@ class BillsTable(View):
rows to be displayed.
"""
put = json.loads(request.body.decode())
- result = self.handle_file(put, building_id)
+ try:
+ result = self.handle_file(put, building_id)
+ except ValueError as err:
+ return JsonResponse({'error': err.args[0] + 'Please make sure you uploaded the right file.'}, status=400)
return JsonResponse({'result': result})
def handle_file(self, data, building_id):
@@ -280,7 +286,10 @@ class BillsTable(View):
).delete()
text = data['text'].split('\n')
-
+ date_from_index = ""
+ date_to_index = ""
+ usage_index = ""
+ charge_index = ""
column_headings = text[0].split(',')
for index, heading in enumerate(column_headings):
if heading == "Bill From Date":
@@ -292,6 +301,15 @@ class BillsTable(View):
elif "Total Charges" in heading:
charge_index = index
+ if not date_from_index:
+ raise ValueError('Could not find "Bill From Date" column.')
+ if not date_to_index:
+ raise ValueError('Could not find "Bill To Date" column.')
+ if not usage_index:
+ raise ValueError('Could not find "Usage" column.')
+ if not charge_index:
+ raise ValueError('Could not find "Total Charge" column.')
+
result = []
for line in range(1, len(text)-1):
row_list = []
@@ -332,24 +350,21 @@ class BillsTable(View):
present = False
utility_type = request.GET.get('utility_type')
- try:
- model_obj = self.model.objects.filter(
- building_id=building_id,
- utility_type=utility_type
- )
- if model_obj:
- present = True
- for row in model_obj:
- row_list = []
- row_list.append(row.date_from)
- row_list.append(row.date_to)
- row_list.append(row.usage)
- row_list.append(row.charge)
- result.append(row_list)
-
- return JsonResponse({'result': result, 'present': present})
- except:
- return JsonResponse({'result': result, 'present': present})
+ model_obj = self.model.objects.filter(
+ building_id=building_id,
+ utility_type=utility_type
+ )
+ if model_obj:
+ present = True
+ for row in model_obj:
+ row_list = []
+ row_list.append(row.date_from)
+ row_list.append(row.date_to)
+ row_list.append(row.usage)
+ row_list.append(row.charge)
+ result.append(row_list)
+
+ return JsonResponse({'result': result, 'present': present})
def get_if_user_input(building_id):
@@ -413,37 +428,30 @@ class BillsOverviewView(View):
objs = self.model_bills_overview.objects.filter(building_id=building_id)
result = {}
total_annual_charge = []
+ electricity_user, gas_user, oil_user, water_user = get_if_user_input(building_id)
if objs:
- result['present'] = True
- else:
- result['present'] = False
- result['electricity'] = {}
- result['gas'] = {}
- result['oil'] = {}
- result['water'] = {}
- result['electricity_user'] = True
- result['gas_user'] = True
- result['oil_user'] = True
- result['water_user'] = True
- for obj in objs:
- store_year = str(obj.year)
- # Limit number of decimal places only if a value exists else keep it as None.
- result['electricity'][store_year] = (float("{0:.2f}".format(obj.electricity)) if obj.electricity else None)
- result['gas'][store_year] = (float("{0:.2f}".format(obj.gas)) if obj.gas else None)
- result['oil'][store_year] = (float("{0:.2f}".format(obj.oil)) if obj.oil else None)
- result['water'][store_year] = (float("{0:.2f}".format(obj.water)) if obj.water else None)
- result['electricity_user'] = obj.electricity_is_user_input
- result['gas_user'] = obj.gas_is_user_input
- result['oil_user'] = obj.oil_is_user_input
- result['water_user'] = obj.water_is_user_input
- # Calculate total charge for a year. Consider None as 0 for this purpose.
- total = 0
- for util in self.utility:
- if result[util][store_year]:
- total += result[util][store_year]
- total_annual_charge.append(total)
- result['total_annual_charge'] = total_annual_charge
-
+ result['electricity'] = {}
+ result['gas'] = {}
+ result['oil'] = {}
+ result['water'] = {}
+ result['electricity_user'] = electricity_user
+ result['gas_user'] = gas_user
+ result['oil_user'] = oil_user
+ result['water_user'] = water_user
+ for obj in objs:
+ store_year = str(obj.year)
+ # Limit number of decimal places only if a value exists else keep it as None.
+ result['electricity'][store_year] = (float("{0:.2f}".format(obj.electricity)) if obj.electricity else None)
+ result['gas'][store_year] = (float("{0:.2f}".format(obj.gas)) if obj.gas else None)
+ result['oil'][store_year] = (float("{0:.2f}".format(obj.oil)) if obj.oil else None)
+ result['water'][store_year] = (float("{0:.2f}".format(obj.water)) if obj.water else None)
+ # Calculate total charge for a year. Consider None as 0 for this purpose.
+ total = 0
+ for util in self.utility:
+ if result[util][store_year]:
+ total += result[util][store_year]
+ total_annual_charge.append(total)
+ result['total_annual_charge'] = total_annual_charge
return JsonResponse({'instance': result})
def put(self, request, building_id):
@@ -474,8 +482,7 @@ class BillsOverviewView(View):
projected_bills = {}
pro_forma_object = get_model_object(FinancingOverview, building_id)
if not pro_forma_object:
- projected_bills['err'] = 'Please fill in bill projection date, period and funds form'
- return JsonResponse({'instance': projected_bills})
+ return JsonResponse({'error': 'Please fill in bill projection date, period and funds form'}, status=400)
analysis_date = get_analysis_date(building_id)
if put['Estimation Model'] == 'Rough Estimation':
# Fetch all bills from the database.
@@ -536,7 +543,7 @@ class BillsOverviewView(View):
total_annual_charge.append(total)
projected_bills['total_annual_charge'] = total_annual_charge
else:
- projected_bills['err'] = 'Only Rough Estimation available at this point'
+ return JsonResponse({'error': 'Only Rough Estimation available at this point'}, status=400)
return JsonResponse({'instance': projected_bills})
def post(self, request, building_id):
@@ -581,7 +588,7 @@ class BillsOverviewView(View):
water_is_user_input=w_user
)
except:
- return JsonResponse({'err': 'Could not save table!'})
+ return JsonResponse({'error': 'Could not save table!'}, status=400)
return JsonResponse({})