Skip to content

Commit

Permalink
PlanReleaseDate: clean and optimize code (#1035)
Browse files Browse the repository at this point in the history
* test README

* PlanReleaseDate: updated UTC display

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* PlanReleaseDate: test and clean code

* Update to use System TZ as default

* Add env APP_TIMEZONE

* Update and clean code

Co-authored-by: TueHoang <[email protected]>
  • Loading branch information
ubc-tuehoang and tuehoang authored Jul 1, 2022
1 parent 4efaf42 commit 948a99a
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 19 deletions.
20 changes: 10 additions & 10 deletions compair/api/assignment_search_enddate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from flask import jsonify
import pytz


from bouncer.constants import READ, EDIT, CREATE, DELETE, MANAGE
from flask import Blueprint, current_app
from flask_bouncer import can
Expand All @@ -26,13 +25,11 @@
from .util import new_restful_api, get_model_changes, pagination_parser

from datetime import datetime
import time

assignment_search_enddate_api = Blueprint('assignment_search_enddate_api', __name__)
api = new_restful_api(assignment_search_enddate_api)

##event
on_assignment_get = event.signal('ASSIGNMENT_GET')

def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
Expand All @@ -45,29 +42,32 @@ class AssignmentRootAPI1(Resource):
@login_required
def get(self):

# get app timezone in settings
appTimeZone = current_app.config.get('APP_TIMEZONE', time.strftime('%Z') )

search_date_assignment_parser = RequestParser()
search_date_assignment_parser.add_argument('compare_start', default=datetime.now().strftime("%Y-%m-%d"))
search_date_assignment_parser.add_argument('compare_end', default=datetime.now().strftime("%Y-%m-%d"))
search_date_assignment_parser.add_argument('compare_localTimeZone', default='UTC')
search_date_assignment_parser.add_argument('compare_localTimeZone', default=appTimeZone)

args = search_date_assignment_parser.parse_args()

end_date = datetime.now().strftime("%Y-%m-%d 00:00:00")
start_date = datetime.now().strftime("%Y-%m-%d")
compare_localTimeZone = 'UTC'
compare_localTimeZone = appTimeZone

if (args['compare_localTimeZone']):
compare_localTimeZone = str(args['compare_localTimeZone'])

if validate(args['compare_end']):
end_date = str(args['compare_end']) + ' 00:00:00'

##convert this to UTC
##convert this to System TZ
local = pytz.timezone(compare_localTimeZone)
naive = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
end_date = str(utc_dt)
systemTZ_dt = local_dt.astimezone(pytz.timezone(appTimeZone))
end_date = str(systemTZ_dt)

if validate(args['compare_start']):
start_date = str(args['compare_start'])
Expand All @@ -76,7 +76,7 @@ def get(self):
engine = create_engine(db_url, pool_size=5, pool_recycle=3600)
conn = engine.connect()

sql_text = str("SELECT JSON_OBJECT('course_name', t1.name,'name', t2.name,'answer_start', date_format(t2.answer_start, '%%M %%d, %%Y'),'answer_end', date_format(t2.answer_end, '%%M %%d, %%Y'),'compare_start', date_format(t2.compare_start, '%%M %%d, %%Y'), 'compare_end', date_format(t2.compare_end, '%%M %%d, %%Y'), 'self_eval_end', date_format(t2.self_eval_end, '%%M %%d, %%Y'), 'self_eval_start', date_format(t2.self_eval_start, '%%M %%d, %%Y')) FROM course as t1, assignment as t2 WHERE (t1.id = t2.course_id) AND (t2.active=TRUE AND t1.active=TRUE) AND (t2.compare_end >= '" + end_date + "' OR answer_end >= '" + end_date + "' OR self_eval_end >= '" + end_date + "');");
sql_text = str("SELECT JSON_OBJECT('course_name', t1.name,'name', t2.name,'answer_start', date_format(CONVERT_TZ(t2.answer_start, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y'),'answer_end', date_format(CONVERT_TZ(t2.answer_end, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y'),'compare_start', date_format(CONVERT_TZ(t2.compare_start, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y'), 'compare_end', date_format(CONVERT_TZ(t2.compare_end, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y'), 'self_eval_end', date_format(CONVERT_TZ(t2.self_eval_end, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y'), 'self_eval_start', date_format(CONVERT_TZ(t2.self_eval_start, '" + appTimeZone + "','" + compare_localTimeZone + "'), '%%b %%d, %%Y')) FROM course as t1, assignment as t2 WHERE (t1.id = t2.course_id) AND (t2.active=TRUE AND t1.active=TRUE) AND (t2.compare_end >= '" + end_date + "' OR answer_end >= '" + end_date + "' OR self_eval_end >= '" + end_date + "');");

result = conn.execute(sql_text)

Expand Down
8 changes: 7 additions & 1 deletion compair/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import os
import json
import re
import pytz
import time

from distutils.util import strtobool
from flask import Config
Expand Down Expand Up @@ -91,7 +93,7 @@
'KALTURA_SECRET', 'KALTURA_PLAYER_ID',
'MAIL_SERVER', 'MAIL_DEBUG', 'MAIL_USERNAME', 'MAIL_PASSWORD',
'MAIL_DEFAULT_SENDER', 'MAIL_SUPPRESS_SEND',
'GA_TRACKING_ID'
'GA_TRACKING_ID', 'APP_TIMEZONE'
]

env_bool_overridables = [
Expand Down Expand Up @@ -150,3 +152,7 @@
config['APP_LOGIN_ENABLED'] = True
config['CAS_LOGIN_ENABLED'] = False
config['SAML_LOGIN_ENABLED'] = False

# configuring APP_TIMEZONE
if not(config['APP_TIMEZONE'] in pytz.all_timezones):
config['APP_TIMEZONE'] = time.strftime('%Z')
6 changes: 5 additions & 1 deletion compair/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os

import time
"""
Default settings, if no other settings is specified, values here are used.
"""
Expand Down Expand Up @@ -163,3 +163,7 @@

# Allow impersonation
IMPERSONATION_ENABLED = True

# when APP_TIMEZONE is empty or incorrect, it will default to system timezone
# example America/Vancouver or America/Montreal
APP_TIMEZONE = time.strftime('%Z')
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ <h1 class="col-sm-8">Plan Release Date</h1>
<!--calendar-->
<div ng-app="ubc.ctlt.compair.assignment" ng-controller="AssignmentSearchEndDateController as ctrlEndDate" >
<div class="input-group" style="width:200px" >
<input type="text" class="form-control" uib-datepicker-popup="yyyy-MMM-dd" ng-model="dt" is-open="isDatepickerOpen" ng-change="searchDate();" datepicker-options="datepickerOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats"/>
<input type="text" class="form-control" uib-datepicker-popup="yyyy-MMM-dd" ng-model="dt" is-open="isDatepickerOpen" ng-change="searchDate();" datepicker-options="datepickerOptions" ng-required="true" ng-readonly="true" close-text="Close" alt-input-formats="altInputFormats"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="isDatepickerOpen = !isDatepickerOpen">
<i class="glyphicon glyphicon-calendar"></i>
Expand Down
30 changes: 24 additions & 6 deletions compair/static/script-assignment-search.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,42 @@
let api_url = "/api/assignment/search/enddate";

const options = { year: 'numeric', month: 'short', day: 'numeric' };
var searchDay = new Date().toLocaleDateString('en-us', options);
let localeLang = 'en-ca';
var searchDay = new Date().toLocaleDateString(localeLang, options);

const d = new Date();
let diff = d.getTimezoneOffset();
let localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

function formatDateYYMMDD(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;

return [year, month, day].join('-');
}

function formatDate(date) {
if (date.includes("Invalid Date")){
return searchDay;
}
var d = (new Date(date.toString().replace(/-/g, '\/')) );
return d.toLocaleDateString('en-ca', options);
return d.toLocaleDateString(localeLang, options);
}

function getObjectDate(object)
{
searchDay = formatDate(object);
strURL = api_url.concat('?compare_end=').concat(object).concat('&compare_localTimeZone=').concat(localTimeZone.toString());

console.log(localTimeZone);
if (object.includes("Invalid Date")){
searchDay = new Date().toLocaleDateString(localeLang, options);
}
strURL = api_url.concat('?compare_end=').concat(formatDateYYMMDD(searchDay)).concat('&compare_localTimeZone=').concat(localTimeZone.toString());

getsearchapi(strURL);
}
Expand Down Expand Up @@ -55,7 +74,6 @@ function showsearchapi(search_data) {

var iKey = 0;
for (let key in search_data) {
//tab += `<tr><td colspan="4">${search_data[key]}</td></tr>`;
let obj = JSON.parse(search_data[key])

if (obj.compare_start == null){
Expand Down

0 comments on commit 948a99a

Please sign in to comment.