Skip to content

Commit

Permalink
Added dynamic subsheet selection during Google Sheet import
Browse files Browse the repository at this point in the history
  • Loading branch information
kenkuhhaut committed Jul 8, 2021
1 parent 36ca021 commit 03fd5ed
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 26 deletions.
35 changes: 15 additions & 20 deletions gsheets_import/admin.py
Expand Up @@ -23,6 +23,15 @@
'GSHEETS_IMPORT_APP_ID',
]

## list of keys that need to exist in the POST request data
POST_REQUEST_KEYS = [
'google_file_id',
'google_file_name',
'oauth_token',
'subsheet_name',
]




###############################################################
Expand All @@ -32,20 +41,6 @@
###############################################################


## get the names of all subsheets within the given Google Sheet
def get_subsheets_names(service, sheet_id):
## extract metadata from specified sheet
result_dict = service.spreadsheets().get(
spreadsheetId = sheet_id
).execute()
## get the sheet name (file name)
sheet_name = result_dict.get('properties', {}).get('title')
## get the names of the subsheets (tab names)
subsheets_info = result_dict.get('sheets', None)
if subsheets_info is not None:
return ([info.get('properties', {}).get('title') for info in subsheets_info], sheet_name)


## download the given sheet's content as an in-memory CSV file to the server
def download_csv(service, sheet_id, subsheet_name, sheet_name):
"""
Expand Down Expand Up @@ -96,6 +91,7 @@ def get_import_context_data(self, **kwargs):
if len(failed_settings_vars) > 0:
raise AttributeError("Variables in settings.py related to the Google Sheet import app not set correctly (" + ', '.join(failed_settings_vars) + ').')
else:
context['dummy_choice_txt'] = forms.DUMMY_CHOICE_TXT
context.update(gsheets_import_context)
return context

Expand All @@ -105,20 +101,19 @@ def import_action(self, request, *args, **kwargs):
## process google sheet
if request.POST and request.POST.get('is_google') == 'true':
## only proceed if the required data was sent and is not empty
if all([ (key in request.POST) and (request.POST[key] != '') for key in ['google_file_id', 'oauth_token'] ]):
## extract information about file ('file_id') and user authorization ('oauth_token')
if all([ (key in request.POST) and (request.POST[key] != '') for key in POST_REQUEST_KEYS ]):
## extract information about file ('file_id', 'file_name', and 'subsheet_name') and user authorization ('oauth_token')
file_id = request.POST['google_file_id']
file_name = request.POST['google_file_name']
oauth_token = request.POST['oauth_token']
subsheet_name = request.POST['subsheet_name']

## create sheets service using the provided OAuth 2.0 token
creds = Credentials(oauth_token)
sheets_service = build('sheets', 'v4', credentials=creds)

## extract subsheet names from selected Google Sheet
subsheet_names, sheet_name = get_subsheets_names(sheets_service, file_id)

## download the specified sheet to an in-memory file
sheet_file = download_csv(sheets_service, file_id, subsheet_names[0], sheet_name)
sheet_file = download_csv(sheets_service, file_id, subsheet_name, file_name)

## NB: The request.FILES property cannot be set for an object of WSGIRequest;
## set the _files attribute instead, which might not be the most elegant way... (rather implement custom upload handler?)
Expand Down
10 changes: 10 additions & 0 deletions gsheets_import/forms.py
Expand Up @@ -37,6 +37,11 @@



## text to be displayed in the subsheet name selection widget by default
DUMMY_CHOICE_TXT = '--------'




#################################################
# #
Expand All @@ -62,6 +67,11 @@ class CustomImportForm(forms.Form):
label = _('File to import'),
widget = FileAndGoogleInput
)
subsheet_name = forms.CharField(
label = _('Subsheet name'),
widget = forms.Select(choices = (('dummy-choice', DUMMY_CHOICE_TXT),)),
required = False
)

def __init__(self, import_formats, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down
21 changes: 15 additions & 6 deletions gsheets_import/static/gsheets_import/js/import_gs.js
Expand Up @@ -39,10 +39,13 @@ const select_format = document.getElementById("id_input_format");
const button_import = document.getElementById("id_import_file");
const span_import = document.getElementById("id_import_file_span");
const input_os_file = document.getElementById("id_import_file_os_file");
const input_google_file = document.getElementById("id_import_file_google_id");
const input_google_file_id = document.getElementById("id_import_file_google_id");
const input_google_file_name = document.getElementById("id_import_file_google_name");
const input_google_oauth = document.getElementById("id_import_file_google_oauth_token");
const input_is_google = document.getElementById("id_import_file_is_google");

// relevant HTML elements for subsheet selection
const select_subsheet = document.getElementById("id_subsheet_name");



Expand Down Expand Up @@ -94,7 +97,7 @@ var pickerApiLoaded = false;
var oauthToken;
var googleAuth;

// additional variables 'developerKey', 'clientId', and 'appId' are
// additional variables 'developerKey', 'clientId', 'appId', and 'dummyChoiceTxt' are
// already set in the 'import.html' template


Expand Down Expand Up @@ -184,19 +187,25 @@ function createPicker() {
// Function to call once the picker was successfully built.
function pickerCallback(data) {
if(data.action == google.picker.Action.PICKED) {
input_google_file.value = data.docs[0].id;
input_google_file_id.value = data.docs[0].id;
input_google_file_name.value = data.docs[0].name;
input_google_oauth.value = oauthToken;
span_import.innerHTML = data.docs[0].name + " (1st sheet)";

/* display all subsheets
// display all subsheets
gapi.client.sheets.spreadsheets.get({
spreadsheetId: data.docs[0].id
}).then(function(response) {
console.log(response.result.sheets)
select_subsheet.innerHTML = "";
for(let subsheet_meta of response.result.sheets) {
var opt = document.createElement("option");
opt.text = subsheet_meta.properties.title;
select_subsheet.appendChild(opt);
console.log(subsheet_meta.properties.title)
}
}).catch(function(response) {
console.log('Error: ' + response.result.error.message);
});
*/
}
}

1 change: 1 addition & 0 deletions gsheets_import/templates/admin/gsheets_import/import.html
Expand Up @@ -231,6 +231,7 @@ <h2>{% trans "Preview" %}</h2>
const developerKey = '{{ gsheets_import_api_key }}';
const clientId = '{{ gsheets_import_client_id }}';
const appId = '{{ gsheets_import_app_id }}';
const dummyChoiceTxt = '{{ dummy_choice_txt }}';
</script>
<script type="text/javascript" src="{% static 'gsheets_import/js/import_gs.js' %}"></script>
<script async defer src="https://apis.google.com/js/api.js"
Expand Down
Expand Up @@ -5,5 +5,6 @@
<input type="file" style="display: none" name="import_file" id="id_import_file_os_file" class="os-file">

<input type="hidden" name="google_file_id" class="google-file" id="id_import_file_google_id">
<input type="hidden" name="google_file_name" class="google-file" id="id_import_file_google_name">
<input type="hidden" name="oauth_token" class="google-file" id="id_import_file_google_oauth_token">
<input type="hidden" name="is_google" class="google-file" id="id_import_file_is_google">

0 comments on commit 03fd5ed

Please sign in to comment.