From 8c621f6f4ac57635f6856e55c7ff058b9b838839 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 22 Jun 2017 16:54:16 -0400 Subject: [PATCH 01/17] Remove bills table code from old views to put in the new file. Remove change date format and put it in the functions file in lib. --- blocnote/apps/financialInputs/old_views.py | 151 --------------------- 1 file changed, 151 deletions(-) diff --git a/blocnote/apps/financialInputs/old_views.py b/blocnote/apps/financialInputs/old_views.py index f3d9210..e4cf853 100644 --- a/blocnote/apps/financialInputs/old_views.py +++ b/blocnote/apps/financialInputs/old_views.py @@ -46,23 +46,6 @@ def get_model_object(model, building_id): return 0 -def change_date_format(dates): - """Change date format. - - The CSV file contains date in MM/DD/YYYY format. The database needs it - to be in YYYY-MM-DD. This function performs this task. - - Args: - date: The date in MM/DD/YYYY format. - - Returns: - new_date: The date in YYYY-MM-DD format. - """ - date_split = dates.split('/') - new_date = date_split[2] + '-' + date_split[0] + '-' + date_split[1] - return new_date - - def get_raw_bill(building_id): """Fetch all the bills in the database. @@ -128,140 +111,6 @@ class Index(View): return render(request, 'financialInputs/index.html', context=context) -class BillsTable(View): - """Create the Energy Bills tables. - - Class to upload energy bills for each utility, store bills and send - the data to the frontend. - """ - - model = Bills - - def put(self, request, building_id): - """Handle HTTP PUT request. - - Obtain bill information from frontend as JSON. The data is in CSV. - The relevant data is stored in the database. Upon successfull upload, - the data is sent to the frontend to create the table. - - Args: - request: HTTP PUT request. - building_id: id of the building. - - Returns: - JsonResponse: JSON of the result which is a list containing - rows to be displayed. - """ - put = json.loads(request.body.decode()) - 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): - """Handle file input. - - Take file data from frontend and obtain the indices of the relevant - columns. Go through the file and get the relevant data and store in the - database. - - Args: - data: The file data obtained from frontend. - building_id: id of the building. - - Returns: - result: List of rows to be sent to the frontend to display table. - """ - utility_type = data['utility_type'] - - self.model.objects.filter( - building_id=building_id, - utility_type=utility_type - ).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": - date_from_index = index - elif heading == "Bill To Date": - date_to_index = index - elif heading == "Usage": - usage_index = index - 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 = [] - line_array = text[line].split(',') - date_from = change_date_format(line_array[date_from_index]) - row_list.append(date_from) - date_to = change_date_format(line_array[date_to_index]) - row_list.append(date_to) - usage = line_array[usage_index] - row_list.append(usage) - charge = line_array[charge_index] - row_list.append(charge) - self.model.objects.create(building_id=building_id, - date_from=date_from, - date_to=date_to, - utility_type=data['utility_type'], - usage=usage, - charge=charge) - result.append(row_list) - - return result - - def get(self, request, building_id): - """Handle HTTP GET request. - - Fetch stored utility bills data and send to the frontend to display as - table. - - Args: - request: HTTP GET request. - building_id: id of the building. - - Return: - JsonResponse: JSON of the result which is a list of rows to populate - the table. - """ - result = [] - present = False - utility_type = request.GET.get('utility_type') - - 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): """Check if utility charge input was user or from bills. -- GitLab From 2cf8bbee0ee15356cc5501dcddab72f38512e6dd Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 22 Jun 2017 16:54:56 -0400 Subject: [PATCH 02/17] Create bills.py file and put the code for bills table in this file. --- blocnote/apps/financialInputs/views/bills.py | 145 +++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 blocnote/apps/financialInputs/views/bills.py diff --git a/blocnote/apps/financialInputs/views/bills.py b/blocnote/apps/financialInputs/views/bills.py new file mode 100644 index 0000000..4dc6b6a --- /dev/null +++ b/blocnote/apps/financialInputs/views/bills.py @@ -0,0 +1,145 @@ +"""Views for bills component in financialInputs.""" +import json + +from django.views import View +from django.http import JsonResponse + +from blocnote.lib.functions import change_date_format + +from blocnote.apps.financialInputs.models import Bills + + +class BillsTable(View): + """Create the Energy Bills tables. + + Class to upload energy bills for each utility, store bills and send + the data to the frontend. + """ + + model = Bills + + def put(self, request, building_id): + """Handle HTTP PUT request. + + Obtain bill information from frontend as JSON. The data is in CSV. + The relevant data is stored in the database. Upon successfull upload, + the data is sent to the frontend to create the table. + + Args: + request: HTTP PUT request. + building_id: id of the building. + + Returns: + JsonResponse: JSON of the result which is a list containing + rows to be displayed. + """ + put = json.loads(request.body.decode()) + 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): + """Handle file input. + + Take file data from frontend and obtain the indices of the relevant + columns. Go through the file and get the relevant data and store in the + database. + + Args: + data: The file data obtained from frontend. + building_id: id of the building. + + Returns: + result: List of rows to be sent to the frontend to display table. + """ + utility_type = data['utility_type'] + + self.model.objects.filter( + building_id=building_id, + utility_type=utility_type + ).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": + date_from_index = index + elif heading == "Bill To Date": + date_to_index = index + elif heading == "Usage": + usage_index = index + 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 = [] + line_array = text[line].split(',') + date_from = change_date_format(line_array[date_from_index]) + row_list.append(date_from) + date_to = change_date_format(line_array[date_to_index]) + row_list.append(date_to) + usage = line_array[usage_index] + row_list.append(usage) + charge = line_array[charge_index] + row_list.append(charge) + self.model.objects.create( + building_id=building_id, + date_from=date_from, + date_to=date_to, + utility_type=data['utility_type'], + usage=usage, + charge=charge, + ) + result.append(row_list) + + return result + + def get(self, request, building_id): + """Handle HTTP GET request. + + Fetch stored utility bills data and send to the frontend to display as + table. + + Args: + request: HTTP GET request. + building_id: id of the building. + + Return: + JsonResponse: JSON of the result which is a list of rows to populate + the table. + """ + result = [] + present = False + utility_type = request.GET.get('utility_type') + + 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}) -- GitLab From e8feec44d67ec8c2b8802e08ae42df545a01e8f3 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 22 Jun 2017 16:55:47 -0400 Subject: [PATCH 03/17] Create functions.py which will contain functions used across files/apps. Move the change date_format code to this file. --- blocnote/lib/functions.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 blocnote/lib/functions.py diff --git a/blocnote/lib/functions.py b/blocnote/lib/functions.py new file mode 100644 index 0000000..f102abf --- /dev/null +++ b/blocnote/lib/functions.py @@ -0,0 +1,16 @@ +"""Define functions used across apps or are generic and not a fetch data.""" +def change_date_format(dates): + """Change date format. + + The CSV file contains date in MM/DD/YYYY format. The database needs it + to be in YYYY-MM-DD. This function performs this task. + + Args: + date: The date in MM/DD/YYYY format. + + Returns: + new_date: The date in YYYY-MM-DD format. + """ + date_split = dates.split('/') + new_date = date_split[2] + '-' + date_split[0] + '-' + date_split[1] + return new_date -- GitLab From d428b3595629941ef05e1eba7fb5f48b03f91fb6 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 22 Jun 2017 17:25:31 -0400 Subject: [PATCH 04/17] Create a bills.js file that will have all the bills code. Fix all styling issues --- .../static/financialInputs/scripts/app.js | 109 ------------------ .../static/financialInputs/scripts/bills.js | 109 ++++++++++++++++++ 2 files changed, 109 insertions(+), 109 deletions(-) create mode 100644 blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js index 416d0b5..78b3f9a 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js @@ -1,13 +1,9 @@ -const utilities = ['electricity', 'gas', 'oil', 'water']; var today = new Date(); const todaysDate = { 'day': today.getDate(), 'month': today.getMonth()+1, 'year': today.getFullYear(), } -for (var utility_index in utilities) { - loadInitialBillsTable(utilities[utility_index]); -} loadBillsOverview(); getIncomeStatementTable(); @@ -39,111 +35,6 @@ function validateDate(startDate, endDate) { return true; } -/** - * Load initial bills table given a utility. Send GET request to obtain - * bill information and call updateTable function to update the bills table - * with the data obtained from backend. - */ -function loadInitialBillsTable(utility) { - const table = document.querySelector('#'+utility); - - request(`bills/?utility_type=${utility}`, { - method: 'GET', - credentials: 'same-origin', - headers: { - 'Content-Type': 'application/json' - }, - }).then(res => { - if (res.payload.present) { - var text = getText(res.payload.result, utility); - updateTable(utility, text); - } - }) -} - -/** - * Update the Bills table with the data. Function queries to get the table - * component and then updates the component with the text. - */ -function updateTable(utility, text) { - table = document.querySelector('#'+utility); - table.innerHTML = text; -} - -/** Generate html text for a given utility and bills data from backend. */ -function getText(result, utility) { - units = {}; - units['electricity'] = `kWh`; - units['gas'] = `mmBTU`; - units['oil'] = `mmBTU`; - units['water'] = `Gallons`; - var text = ` - - - - - - - - - `; - for (var i =0; i`; - for (var j=0; j` + result[i][j] + ``; - } - text += ``; - } - text += ``; - return text; -} - -/** - * Upload an energy bill. Get the id of the component to identify the - * utility type. Use reader to read as text and call the sendFile function - * to send the contents to the backend. - */ -function uploadFile(data) { - const id = document.getElementsByClassName("show")[0].getAttribute("id"); - csvFile = data.files[0]; - var reader = new FileReader(); - reader.onload = function(e) { - var content = {} - content.text = reader.result; - content.utility_type = id; - sendFile(id, content); - } - reader.readAsText(csvFile); - return false; -} - -/** HTTP PUT request to upload the contents of the utility bills file */ -function sendFile(id, content) { - request(`bills/`, { - method: 'PUT', - credentials: 'same-origin', - body: JSON.stringify(content), - headers: new Headers({ - 'Content-Type': 'application/json', - 'X-CSRFToken': Cookies.get('csrftoken') - }) - }).then(res => { - if (!res.err) { - document.querySelector('#bills-response-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} - `; - }) - } - }); -} function createEstimateModelForm() { var estimateModelForm = ``; diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js new file mode 100644 index 0000000..df9a439 --- /dev/null +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -0,0 +1,109 @@ +/** + * Load initial bills table given a utility. Send GET request to obtain + * bill information and call updateTable function to update the bills table + * with the data obtained from backend. + */ +function loadInitialBillsTable(utility) { + request(`bills/?utility_type=${utility}`, { + method: 'GET', + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json' + }, + }).then(res => { + if (res.payload.present) { + let text = getText(res.payload.result, utility); + updateTable(utility, text); + } + }); +} + +/** + * Update the Bills table with the data. Function queries to get the table + * component and then updates the component with the text. + */ +function updateTable(utility, text) { + const table = document.querySelector('#'+utility); + table.innerHTML = text; +} + +/** Generate html text for a given utility and bills data from backend. */ +function getText(result, utility) { + let units = {}; + units['electricity'] = 'kWh'; + units['gas'] = 'mmBTU'; + units['oil'] = 'mmBTU'; + units['water'] = 'Gallons'; + var text = ` +
Date FromDate ToUsage (${units[utility]})Bill Charge ($)
+ + + + + + + + + + `; + for (var i =0; i'; + } + text += ''; + } + text += ''; + return text; +} + +/** + * Upload an energy bill. Get the id of the component to identify the + * utility type. Use reader to read as text and call the sendFile function + * to send the contents to the backend. + */ +function uploadFile(data) { + const id = document.getElementsByClassName('show')[0].getAttribute('id'); + const csvFile = data.files[0]; + var reader = new FileReader(); + reader.onload = function(e) { + var content = {}; + content.text = reader.result; + content.utility_type = id; + sendFile(id, content); + }; + reader.readAsText(csvFile); + return false; +} + +/** HTTP PUT request to upload the contents of the utility bills file */ +function sendFile(id, content) { + request('bills/', { + method: 'PUT', + credentials: 'same-origin', + body: JSON.stringify(content), + headers: new Headers({ + 'Content-Type': 'application/json', + 'X-CSRFToken': Cookies.get('csrftoken') + }) + }).then(res => { + if (!res.err) { + document.querySelector('#bills-response-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} + `; + }); + } + }); +} +const utilities = ['electricity', 'gas', 'oil', 'water']; +for (var utility_index in utilities) { + loadInitialBillsTable(utilities[utility_index]); +} -- GitLab From 1573f0c1d0a15de6c5cccb150ed2dbf2fe8056af Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 22 Jun 2017 17:33:57 -0400 Subject: [PATCH 05/17] Change the route in financialInputs for bills to go to the view in the new file rather than old_views. --- blocnote/apps/financialInputs/urls.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/blocnote/apps/financialInputs/urls.py b/blocnote/apps/financialInputs/urls.py index f27b683..9e71e74 100644 --- a/blocnote/apps/financialInputs/urls.py +++ b/blocnote/apps/financialInputs/urls.py @@ -1,14 +1,15 @@ from django.conf.urls import url from . import old_views -from .views import proforma_input -from .views import customer_preference +from .views import ( + proforma_input, customer_preference, bills, +) app_name = 'financial-inputs' urlpatterns = [ url(r'^$', old_views.Index.as_view(), name='index'), url(r'^finance-overview/$', proforma_input.ProformaInputs.as_view(), name='header_new'), - url(r'^bills/$', old_views.BillsTable.as_view(), name='bills'), + url(r'^bills/$', bills.BillsTable.as_view(), name='bills'), url(r'^bills-overview/$', old_views.BillsOverviewView.as_view(), name='bills_overview'), url(r'^customer-preference/$', customer_preference.CustomerPreferenceView.as_view(), name='customer_preference'), url(r'^liabilities/$', old_views.LiabilitiesTable.as_view(), name='liabilities'), -- GitLab From 9dc18aa6c33164d945df679100d367a07578f544 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:05:39 -0400 Subject: [PATCH 06/17] Move code of bills table from old views to the new file, bills.py. Make modifications in the code to check for column headings which are case insensitive and raise errors when date is not of the mm/dd/yyyy format. --- blocnote/apps/financialInputs/views/bills.py | 35 +++++++++++--------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/blocnote/apps/financialInputs/views/bills.py b/blocnote/apps/financialInputs/views/bills.py index 4dc6b6a..cdb208f 100644 --- a/blocnote/apps/financialInputs/views/bills.py +++ b/blocnote/apps/financialInputs/views/bills.py @@ -62,37 +62,42 @@ class BillsTable(View): ).delete() text = data['text'].split('\n') - date_from_index = "" - date_to_index = "" - usage_index = "" - charge_index = "" + date_from_index = None + date_to_index = None + usage_index = None + charge_index = None column_headings = text[0].split(',') for index, heading in enumerate(column_headings): - if heading == "Bill From Date": + if "bill from date" in heading.lower(): date_from_index = index - elif heading == "Bill To Date": + elif "bill to date" in heading.lower(): date_to_index = index - elif heading == "Usage": + elif heading.lower() == "usage": usage_index = index - elif "Total Charges" in heading: + elif "total charge" in heading.lower(): charge_index = index - - if not date_from_index: + if date_from_index is None: raise ValueError('Could not find "Bill From Date" column.') - if not date_to_index: + if date_to_index is None: raise ValueError('Could not find "Bill To Date" column.') - if not usage_index: + if usage_index is None: raise ValueError('Could not find "Usage" column.') - if not charge_index: + if charge_index is None: raise ValueError('Could not find "Total Charge" column.') result = [] for line in range(1, len(text)-1): row_list = [] line_array = text[line].split(',') - date_from = change_date_format(line_array[date_from_index]) + try: + date_from = change_date_format(line_array[date_from_index]) + except ValueError as err: + raise ValueError(err.args[0]) row_list.append(date_from) - date_to = change_date_format(line_array[date_to_index]) + try: + date_to = change_date_format(line_array[date_to_index]) + except ValueError as err: + raise ValueError(err.args[0]) row_list.append(date_to) usage = line_array[usage_index] row_list.append(usage) -- GitLab From e8c03c2c6c55771b34eacfcc61b0d8aa4a750ca6 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:06:39 -0400 Subject: [PATCH 07/17] Add bills.js to index.html file. --- .../apps/financialInputs/templates/financialInputs/index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/blocnote/apps/financialInputs/templates/financialInputs/index.html b/blocnote/apps/financialInputs/templates/financialInputs/index.html index b9b7c29..77ebb8d 100644 --- a/blocnote/apps/financialInputs/templates/financialInputs/index.html +++ b/blocnote/apps/financialInputs/templates/financialInputs/index.html @@ -58,4 +58,5 @@ + {% endblock %} -- GitLab From 2a0b15b2f94d291ae33896de9b79e4c16c829768 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:08:34 -0400 Subject: [PATCH 08/17] Create a functions file in lib directory that will hold functions that can be used accross multiple files/apps in blocnote. Put the change date format function in this file. --- blocnote/lib/functions.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/blocnote/lib/functions.py b/blocnote/lib/functions.py index f102abf..53a5372 100644 --- a/blocnote/lib/functions.py +++ b/blocnote/lib/functions.py @@ -12,5 +12,8 @@ def change_date_format(dates): new_date: The date in YYYY-MM-DD format. """ date_split = dates.split('/') - new_date = date_split[2] + '-' + date_split[0] + '-' + date_split[1] + try: + new_date = date_split[2] + '-' + date_split[0] + '-' + date_split[1] + except Exception: + raise ValueError('Please make sure the date is in mm/dd/yyyy format.') return new_date -- GitLab From 1426a4fa769cea3ca0b57c21c3f4950bb685081e Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:10:21 -0400 Subject: [PATCH 09/17] Add message under the upload button saying what kind of file to upload and the required date format. --- .../apps/financialInputs/templates/financialInputs/bills.html | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/blocnote/apps/financialInputs/templates/financialInputs/bills.html b/blocnote/apps/financialInputs/templates/financialInputs/bills.html index 98cc36e..99c49c6 100644 --- a/blocnote/apps/financialInputs/templates/financialInputs/bills.html +++ b/blocnote/apps/financialInputs/templates/financialInputs/bills.html @@ -36,6 +36,10 @@ +
+ Please make sure the file you upload is in csv format, has bill from and to date, usage and total + charges. The dates MUST be in mm/dd/yyyy format. +
-- GitLab From 111bdbb651355a0977a76e09397b5d9f3a076d8c Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:11:38 -0400 Subject: [PATCH 10/17] Make sure that in bills overview the value of the input is in quotes. --- .../apps/financialInputs/static/financialInputs/scripts/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js index 78b3f9a..4e7971e 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/app.js @@ -118,7 +118,7 @@ function createBillsOverviewTableCellInput(id, state, value, year) { if (value === null) { value = ''; } - text = ``; + text = ``; return text; } -- GitLab From d43b69b6e36f54bd25c00cede490744c85b91e78 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:13:15 -0400 Subject: [PATCH 11/17] Move bills table code from app.js to bills.js. Make sure that type of file uploaded is checked before actually getting the file contents and sending it the backend. If uploadd file is not a csv, display an error message that its not a csv. --- .../static/financialInputs/scripts/bills.js | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js index df9a439..8669661 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -63,16 +63,25 @@ function getText(result, utility) { * to send the contents to the backend. */ function uploadFile(data) { - const id = document.getElementsByClassName('show')[0].getAttribute('id'); - const csvFile = data.files[0]; - var reader = new FileReader(); - reader.onload = function(e) { - var content = {}; - content.text = reader.result; - content.utility_type = id; - sendFile(id, content); - }; - reader.readAsText(csvFile); + if (data.files.length > 0) { + const id = document.getElementsByClassName('show')[0].getAttribute('id'); + const csvFile = data.files[0]; + let type = /text.csv/; + if (csvFile.type.match(type)) { + var reader = new FileReader(); + reader.onload = function(e) { + var content = {}; + content.text = reader.result; + content.utility_type = id; + sendFile(id, content); + }; + reader.readAsText(csvFile); + } else { + document.querySelector('#bills-response-message').innerHTML = ` + Please upload a csv file. + `; + } + } return false; } @@ -96,7 +105,7 @@ function sendFile(id, content) { } else { res.err.responseBody.then((error) => { - document.querySelector('#bills-warning-message').innerHTML = ` + document.querySelector('#bills-response-message').innerHTML = ` ${error.error} `; }); -- GitLab From 21bc69493f5a7fd92cec66306a4347c894eac5c1 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 23 Jun 2017 17:27:38 -0400 Subject: [PATCH 12/17] Update change date format function to check if date provided is right. --- blocnote/lib/functions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/blocnote/lib/functions.py b/blocnote/lib/functions.py index 53a5372..4b02ad7 100644 --- a/blocnote/lib/functions.py +++ b/blocnote/lib/functions.py @@ -16,4 +16,6 @@ def change_date_format(dates): new_date = date_split[2] + '-' + date_split[0] + '-' + date_split[1] except Exception: raise ValueError('Please make sure the date is in mm/dd/yyyy format.') + if len(date_split[2]) < 4: + raise ValueError('Please make sure the date is in mm/dd/yyyy format.') return new_date -- GitLab From 0f4c508f1b95c28142a080e3bce6a17a60b56a6f Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 7 Jul 2017 10:07:56 -0400 Subject: [PATCH 13/17] Remove the use of variable present as it is not needed. --- .../financialInputs/static/financialInputs/scripts/bills.js | 2 +- blocnote/apps/financialInputs/views/bills.py | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js index 8669661..76333c4 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -11,7 +11,7 @@ function loadInitialBillsTable(utility) { 'Content-Type': 'application/json' }, }).then(res => { - if (res.payload.present) { + if (res.payload) { let text = getText(res.payload.result, utility); updateTable(utility, text); } diff --git a/blocnote/apps/financialInputs/views/bills.py b/blocnote/apps/financialInputs/views/bills.py index cdb208f..227cb3e 100644 --- a/blocnote/apps/financialInputs/views/bills.py +++ b/blocnote/apps/financialInputs/views/bills.py @@ -130,7 +130,6 @@ class BillsTable(View): the table. """ result = [] - present = False utility_type = request.GET.get('utility_type') model_obj = self.model.objects.filter( @@ -138,7 +137,6 @@ class BillsTable(View): utility_type=utility_type ) if model_obj: - present = True for row in model_obj: row_list = [] row_list.append(row.date_from) @@ -147,4 +145,4 @@ class BillsTable(View): row_list.append(row.charge) result.append(row_list) - return JsonResponse({'result': result, 'present': present}) + return JsonResponse({'result': result}) -- GitLab From 1345e9c67399af5f34a92ba408a85e7d0e221c0c Mon Sep 17 00:00:00 2001 From: Adarsh Date: Fri, 7 Jul 2017 12:32:26 -0400 Subject: [PATCH 14/17] Rename loadInitialTables to getInitialTables. Create one function that takes in the utility type and the table contents for that utility and displays it on the frontend. Make appropriate html changes. Change all the vars to either const or let. --- .../static/financialInputs/scripts/bills.js | 91 ++++++++++--------- .../templates/financialInputs/bills.html | 40 +++++++- 2 files changed, 84 insertions(+), 47 deletions(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js index 76333c4..2b8f99c 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -3,7 +3,7 @@ * bill information and call updateTable function to update the bills table * with the data obtained from backend. */ -function loadInitialBillsTable(utility) { +function getInitialBillsTable(utility) { request(`bills/?utility_type=${utility}`, { method: 'GET', credentials: 'same-origin', @@ -12,51 +12,55 @@ function loadInitialBillsTable(utility) { }, }).then(res => { if (res.payload) { - let text = getText(res.payload.result, utility); - updateTable(utility, text); + document.querySelector(`#${utility}-bill-status`).innerHTML = ''; + createBillTable(utility, res.payload.result); } }); } + /** - * Update the Bills table with the data. Function queries to get the table - * component and then updates the component with the text. + * createBillTable() Take in the utility and the utility bill content and display it in the repective table. + * + * @param {...} utility - String denoting which utility it is. + * @param {...} content - List of lists which represents the table. + * */ -function updateTable(utility, text) { - const table = document.querySelector('#'+utility); - table.innerHTML = text; -} +function createBillTable(utility, content) { + const utilityTable = document.querySelector(`#${utility}-table`); + const head = utilityTable.querySelector('thead'); + const body = utilityTable.querySelector('tbody'); + head.innerHTML = ''; + body.innerHTML = ''; + const headRow = head.insertRow(0); + const headings = ['Date From', 'Date To', 'Usage', 'Bill Charge ($)']; + const units = { + 'electricity': 'kWh', + 'gas': 'mmBTU', + 'oil': 'mmBTU', + 'water': 'Gallons', + }; -/** Generate html text for a given utility and bills data from backend. */ -function getText(result, utility) { - let units = {}; - units['electricity'] = 'kWh'; - units['gas'] = 'mmBTU'; - units['oil'] = 'mmBTU'; - units['water'] = 'Gallons'; - var text = ` -
Date FromDate ToUsage (${units[utility]})Bill Charge ($)
- - - - - - - - - - `; - for (var i =0; i'; + headings.forEach((heading, cellIndex) => { + let cell = headRow.insertCell(cellIndex); + let cellValue = heading; + if(cellIndex == 2) { + cellValue += ` (${units[utility]})`; } - text += ''; - } - text += ''; - return text; + cell.innerHTML = cellValue; + }); + + content.forEach((rowContents, rowCount) => { + let bodyRow = body.insertRow(rowCount); + rowContents.forEach((cellValue, cellIndex) => { + let cell = bodyRow.insertCell(cellIndex); + cell.innerHTML = cellValue; + }); + }); + } + /** * Upload an energy bill. Get the id of the component to identify the * utility type. Use reader to read as text and call the sendFile function @@ -68,9 +72,9 @@ function uploadFile(data) { const csvFile = data.files[0]; let type = /text.csv/; if (csvFile.type.match(type)) { - var reader = new FileReader(); + const reader = new FileReader(); reader.onload = function(e) { - var content = {}; + let content = {}; content.text = reader.result; content.utility_type = id; sendFile(id, content); @@ -100,8 +104,7 @@ function sendFile(id, content) { document.querySelector('#bills-response-message').innerHTML = ` ${id} bill upload success `; - var text = getText(res.payload.result, id); - updateTable(id, text); + createBillTable(id, res.payload.result); } else { res.err.responseBody.then((error) => { @@ -112,7 +115,9 @@ function sendFile(id, content) { } }); } + const utilities = ['electricity', 'gas', 'oil', 'water']; -for (var utility_index in utilities) { - loadInitialBillsTable(utilities[utility_index]); -} + +utilities.forEach((utility) => { + getInitialBillsTable(utility); +}); diff --git a/blocnote/apps/financialInputs/templates/financialInputs/bills.html b/blocnote/apps/financialInputs/templates/financialInputs/bills.html index 99c49c6..3400376 100644 --- a/blocnote/apps/financialInputs/templates/financialInputs/bills.html +++ b/blocnote/apps/financialInputs/templates/financialInputs/bills.html @@ -24,10 +24,42 @@
-
No Bills available
-
No Bills available
-
No Bills available
-
No Bills available
+
+
+ No Bills available +
+
Date FromDate ToUsage (${units[utility]})Bill Charge ($)
+ + +
+ +
+
+ No Bills available +
+ + + +
+
+
+
+ No Bills available +
+ + + +
+
+
+
+ No Bills available +
+ + + +
+
-- GitLab From 0583a8bafa8e58ce12c6f3ead2ca594dcde071ce Mon Sep 17 00:00:00 2001 From: Adarsh Date: Mon, 10 Jul 2017 09:31:00 -0400 Subject: [PATCH 15/17] Remove utility bill file requirements as message and make it a tooltip. --- .../templates/financialInputs/bills.html | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/blocnote/apps/financialInputs/templates/financialInputs/bills.html b/blocnote/apps/financialInputs/templates/financialInputs/bills.html index 3400376..726783a 100644 --- a/blocnote/apps/financialInputs/templates/financialInputs/bills.html +++ b/blocnote/apps/financialInputs/templates/financialInputs/bills.html @@ -65,13 +65,17 @@
-
- Please make sure the file you upload is in csv format, has bill from and to date, usage and total - charges. The dates MUST be in mm/dd/yyyy format. -
-- GitLab From 50eae4e42777ee5365c2ea1caec358e2839f1a33 Mon Sep 17 00:00:00 2001 From: Adarsh Date: Mon, 10 Jul 2017 12:28:38 -0400 Subject: [PATCH 16/17] Make some comment changes. --- .../financialInputs/static/financialInputs/scripts/bills.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js index 2b8f99c..97144f6 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -20,7 +20,7 @@ function getInitialBillsTable(utility) { /** - * createBillTable() Take in the utility and the utility bill content and display it in the repective table. + * Take in the utility and the utility bill content and display it in the repective table. * * @param {...} utility - String denoting which utility it is. * @param {...} content - List of lists which represents the table. @@ -62,7 +62,7 @@ function createBillTable(utility, content) { /** - * Upload an energy bill. Get the id of the component to identify the + * Upload an utility bill. Get the id of the component to identify the * utility type. Use reader to read as text and call the sendFile function * to send the contents to the backend. */ -- GitLab From 10e73e667d850b0466eb8115a5e3c2a212ccfb4e Mon Sep 17 00:00:00 2001 From: Adarsh Date: Thu, 13 Jul 2017 12:01:09 -0400 Subject: [PATCH 17/17] Change some variable declaration from let to const. --- .../static/financialInputs/scripts/bills.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js index 97144f6..b7c0346 100644 --- a/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js +++ b/blocnote/apps/financialInputs/static/financialInputs/scripts/bills.js @@ -42,7 +42,7 @@ function createBillTable(utility, content) { }; headings.forEach((heading, cellIndex) => { - let cell = headRow.insertCell(cellIndex); + const cell = headRow.insertCell(cellIndex); let cellValue = heading; if(cellIndex == 2) { cellValue += ` (${units[utility]})`; @@ -51,9 +51,9 @@ function createBillTable(utility, content) { }); content.forEach((rowContents, rowCount) => { - let bodyRow = body.insertRow(rowCount); + const bodyRow = body.insertRow(rowCount); rowContents.forEach((cellValue, cellIndex) => { - let cell = bodyRow.insertCell(cellIndex); + const cell = bodyRow.insertCell(cellIndex); cell.innerHTML = cellValue; }); }); @@ -70,7 +70,7 @@ function uploadFile(data) { if (data.files.length > 0) { const id = document.getElementsByClassName('show')[0].getAttribute('id'); const csvFile = data.files[0]; - let type = /text.csv/; + const type = /text.csv/; if (csvFile.type.match(type)) { const reader = new FileReader(); reader.onload = function(e) { -- GitLab