Skip to content

Commit

Permalink
Fix download transfer
Browse files Browse the repository at this point in the history
  • Loading branch information
luistarkbank committed Aug 13, 2024
1 parent 414a274 commit caefd31
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 49 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Given a version number MAJOR.MINOR.PATCH, increment:
## [Unreleased]
### Fixed
- paymentRequest duplicated payment
- download transfer locally

## [0.6.5] - 2024-06-28
### Added
Expand Down
2 changes: 1 addition & 1 deletion src/.clasp.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"scriptId":"1JAupf57mwkjPaC3FFC8Ydx-yo6LkoIjnIrpQx2_95JenFfQ0G2ov4rbO","rootDir":"/Users/luis.almeida/Documents/starkbank/google-sheets/src"}
{"scriptId":"199zM22Q3FVHJK5EOZtrz7EQ7bH5wm_vnQCu-YVI7kOz6N455TDq-XmMq"}
31 changes: 27 additions & 4 deletions src/FormDownloadTransfers.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>

<div id="alert" class="alert alert-dismissible fade show alert-danger front" role="alert" style="padding-bottom: 10px;">
<a id="alert-message"></a>
<button type="button" class="close" onclick="hideAlert()" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="d-flex justify-content-center">
<div class="spinner-border text-primary" role="status">
<span class="sr-only">Aguarde enquanto os arquivos são baixados...</span>
Expand All @@ -20,15 +25,18 @@

<script>
var downloaded = 0;
var items = 0;

function onLoad(){
$("#alert").hide();
google.script.run.withSuccessHandler(downloadAll)
.withFailureHandler(onFailure)
.getTransferDownloadList();
}

function downloadAll(result){
for (let id of result){
items = result.length
google.script.run.withSuccessHandler(pdfSave)
.withFailureHandler(onFailure)
.TransferDownloadBase64Encoded(id);
Expand All @@ -51,13 +59,18 @@

document.body.removeChild(element);
downloaded += 1;
// if (downloaded >= 30) {
// setTimeout(google.script.host.close, 20000);
// }

if (downloaded >= items) {
setTimeout(google.script.host.close, 10000);
}
}

function onFailure(error) {
console.log(error)
$("#alert").show();
var alertMessage = document.getElementById("alert-message");
alertMessage.innerHTML = "Não foi possivel realizar o download dos itens"
stopLoading()
}

function save() {
Expand All @@ -66,6 +79,16 @@
.withFailureHandler(onFailure)
.SendOrder(teamSelected);
}

function startLoading() {
$('.btn').hide();
$('.spinner-border').show();
}

function stopLoading() {
$('.btn').show();
$('.spinner-border').hide();
}

window.onload = onLoad;
</script>
11 changes: 7 additions & 4 deletions src/sdkViewTransfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,13 @@ function getTransferDownloadList(){
break;
}
}
if (idList.length == 0) {
Browser.msgBox("Nenhuma transferência válida (sucesso) para download listada.")
}
return idList;
}


function TransferDownload(id) {
let path = "/transfer/" + id + "/pdf";
let pdfContent = fetchBuffer(path)[0];
let pdfContent = fetchBuffer(path);
return pdfContent;
}

Expand Down Expand Up @@ -122,6 +119,12 @@ function TransferDownloadAllLocal(){

function TransferDownloadBase64Encoded(id){
let blob = TransferDownload(id);
blob = blob[0]
let status = blob[1]

if (status != 200) {
throw new Error(blob[0])
}
return {
id: id,
content: Utilities.base64Encode(blob.getBytes())
Expand Down
95 changes: 55 additions & 40 deletions src/utilsRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,65 +102,80 @@ function parseResponse(responseApi) {
}


function fetchBuffer(path, method = 'GET', payload = null, query = null, version = 'v2') {
function fetchBuffer(path, method='GET', payload=null, query=null, version="v2", environment=null, privateKeyPem=null, challengeId=null) {
let user = new getDefaultUser();
let hostname = getHostname(user.environment.toLowerCase(), version);
let options = {method: method};
if (!user.privateKey) {
throw JSON.stringify({"message": "Erro de autenticação! Por favor, faça login novamente."});
}
if (!environment) {
environment = environment || user.environment.toLowerCase();
}
let hostname = getHostname(environment, version);
let options = {
method: method,
muteHttpExceptions: true,
};
let url = hostname + path;

if (query) {
let queryString = '';
let separator = '?';
for (let key in query) {
if (query[key]) {
queryString += separator + key + '=' + query[key];
separator = '&';
let queryString = '';
let separator = '?';
for (let key in query) {
if (query[key]) {
queryString += separator + key + '=' + query[key];
separator = '&';
}
}
}
url += queryString;
url += queryString;
}

paths = ["/session", "/boleto-payment"]

if (paths.includes(path) && method != "GET") {
var accessId = KeyGen.generateMemberAccessId(user.workspaceId, user.email)
} else {
var accessId = user.accessId;
}

let accessTime = Math.round((new Date()).getTime() / 1000).toString();
options['headers'] = {
'Access-Id': accessId,
'User-Agent': 'GoogleSheets-SDK-0.4.3',
'Accept-Language': 'pt-BR',
'Content-Type': 'application/json',
'Access-Time': accessTime
};

let body = JSON.stringify(payload);
if (!payload) {
body = "";
}
if (privateKeyPem) {
var accessId = KeyGen.generateMemberAccessId(user.workspaceId, user.email)
} else {
var accessId = user.accessId;
}

options['payload'] = body;

if (!privateKeyPem) {
var privateKeyPem = user.privateKey;
var privateKeyPem = user.privateKey;
}

let message = accessId + ':' + accessTime + ':' + body;

let accessTime = Math.round((new Date()).getTime() / 1000).toString();
options['headers'] = {
'Access-Id': accessId,
'User-Agent': 'App-StarkBank-GSheets-v0.6.5b',
'User-Agent-Override': 'App-StarkBank-GSheets-v0.6.5b',
'PlatFormId' : 'gsheets',
'PlatFormVersion' : '0.6.5',
'Accept-Language': 'pt-BR',
'Content-Type': 'application/pdf',
'Access-Time': accessTime
};

let body = ""
if (payload) {
body = payload;
}

options['payload'] = body;

let message = accessId + ':' + accessTime + ':' + body

if (challengeId) {
message += ":" + challengeId
options['headers']['Access-Challenge-Ids'] = challengeId
}

let signature = easySign(message, privateKeyPem);
options['headers']['Access-Signature'] = signature;

response = UrlFetchApp.fetch(url, options);

let content = response.getAs("application/pdf");
let status = response.getResponseCode();

if (status != 200) {
Browser.msgBox(parseResponse(response)[0]["errors"][0]["message"])
return new Error()
return [parseResponse(response)[0]["errors"][0]["code"], status]
} else {
let content = response.getAs("application/pdf");
return [content, status]
}
}
Expand Down

0 comments on commit caefd31

Please sign in to comment.