Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix download transfers #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ 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":"10XuhtMToOKv59YPboFbDYzYvBazsk2Odo1j9XAyZHZUXCg-HGeyF0Oex","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>
6 changes: 6 additions & 0 deletions src/apiAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ function postSessionChallenge() {
json = content[0];

SaveSession(sheet.getRange('B16').getValue(), sheet.getRange('B17').getValue(), json["session"]["id"])

let paymentRequestExternalIdsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('paymentRequestExternal');
paymentRequestExternalIdsheet.getRange("C1").setValue("{}")
}

}
Expand Down Expand Up @@ -198,5 +201,8 @@ function signOut(displayMessage = true) {
sheet.getRange("B11").setValue("Ex: StarkBank")
sheet.getRange("D11").setValue("Ex: (11) 99999-9999")
sheet.getRange("J11").setValue("Ex: 20018-183")

let paymentRequestExternalIdsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('paymentRequestExternal');
paymentRequestExternalIdsheet.getRange("C1").setValue("{}")
}
}
189 changes: 130 additions & 59 deletions src/sdkSendOrder.js
Original file line number Diff line number Diff line change
@@ -1,87 +1,158 @@

function SendOrder(centerId) {
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Transferência com Aprovação');
let externalSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('paymentRequestExternal');
let line = 10;
let query = {};
let request = {};
let requests = [];
let payment = {};
let errorMessages = "";

let sentItems = "";
let bactchLineExternalId = 11;
formatHeader(sheet);

const initialLine = 11;
const batchSize = 100;

let stringJson = ""

if (externalSheet.getRange('C1').getValue().toString().length < 2) {
stringJson = "{}";
}

if (externalSheet.getRange('C1').getValue().toString().length >= 2) {
stringJson = externalSheet.getRange('C1').getValue().toString().trim()
}

let jsonExternalId = JSON.parse(stringJson);

for (let batchInitialLine = initialLine; batchInitialLine <= sheet.getLastRow(); batchInitialLine = line){
requests = [];
request = {};
externalIds = [];
anysent = true;

for (line = batchInitialLine; line < batchInitialLine + batchSize && line <= sheet.getLastRow(); line++){
payment = {
name: removeDiacritics(sheet.getRange('A' + line.toString()).getValue()),
taxId: sheet.getRange('B' + line.toString()).getValue(),
amount: parseInt(Math.round(100*sheet.getRange('C' + line.toString()).getValue()), 10),
bankCode: sheet.getRange('D' + line.toString()).getValue(),
branchCode: sheet.getRange('E' + line.toString()).getValue(),
accountNumber: sheet.getRange('F' + line.toString()).getValue()
};

var schedule = sheet.getRange('G' + line.toString()).getValue();

accountType = sheet.getRange('H' + line.toString()).getValue();
if (accountType) {
payment["accountType"] = accountType;

let customerName = removeDiacritics(sheet.getRange('A' + line.toString()).getValue());
let taxId = removeDiacritics(sheet.getRange('B' + line.toString()).getValue());
let amount = parseInt(Math.round(100*sheet.getRange('C' + line.toString()).getValue()), 10);
let bankCode = removeDiacritics(sheet.getRange('D' + line.toString()).getValue());
let branchCode = removeDiacritics(sheet.getRange('E' + line.toString()).getValue());
let accountNumber = removeDiacritics(sheet.getRange('F' + line.toString()).getValue());

let calculatedExternalId = calculateExternalId(amount, customerName, taxId, bankCode, branchCode, accountNumber)

if (jsonExternalId[calculatedExternalId]) {
bactchLineExternalId += 1;
jsonExternalId[calculatedExternalId] = line
externalIds.push(calculatedExternalId)
}

tags = removeDiacritics(sheet.getRange('I' + line.toString()).getValue());
if (tags) {
request["tags"] = tags.split(",");
if (!jsonExternalId[calculatedExternalId]) {

jsonExternalId[calculatedExternalId] = line

externalIds.push(calculatedExternalId)
payment = {
name: customerName,
taxId: taxId,
amount: amount,
bankCode: bankCode,
branchCode: branchCode,
accountNumber: accountNumber
};

var schedule = sheet.getRange('G' + line.toString()).getValue();

accountType = sheet.getRange('H' + line.toString()).getValue();
if (accountType) {
payment["accountType"] = accountType;
}

tags = removeDiacritics(sheet.getRange('I' + line.toString()).getValue());
if (tags) {
request["tags"] = tags.split(",");
}

description = removeDiacritics(sheet.getRange('J' + line.toString()).getValue())
if (description) {
payment["description"] = description;
}

request = {
centerId: centerId,
type: "transfer",
payment: payment,
};

if (schedule != "") {
request["due"] = formatToLocalDatetime(schedule)
}

requests.push(request);
}
}

if (requests.length > 0) {
let payload = {requests: requests};
let responseApi = fetch("/payment-request", method = 'POST', payload, query);

let [json, status] = parseResponse(responseApi)
if (status == 200) {
let lastExternalIdRow = 11
if (externalSheet.getLastRow() > 7) {
lastExternalIdRow = externalSheet.getLastRow() + 1
}

for (let c in jsonExternalId) {
sheet.getRange("K" + jsonExternalId[c].toString()).setValue("Pagemento Enviado")
}

description = removeDiacritics(sheet.getRange('J' + line.toString()).getValue())
if (description) {
payment["description"] = description;
sentItems = "!!";

externalSheet.getRange("C1").setValue(JSON.stringify(jsonExternalId))
}

request = {
centerId: centerId,
type: "transfer",
payment: payment,
};

if (schedule != "") {
request["due"] = formatToLocalDatetime(schedule)
switch (status) {
case 500:
throw new Error(JSON.parse(json)["errors"]["message"]);
case 400:
let errors = Array.from(json["errors"]);
errors.forEach(error => {
if (error.code == "invalidCredentials") {
sendMessage("Sessão expirada! \nFaça o login novamente");
return;
};
let errorMessage = error.message;

let message = errorMessage + "\n"
if (/Element [0-9]*:/.test(errorMessage)) {
let requestNumber = errorMessage.split('Element ').pop().split(':')[0];
let lineNumber = parseInt(requestNumber)

let tempJson = requests[lineNumber]["payment"]

let customerName = tempJson["name"]
let taxId = tempJson["taxId"]
let amount = tempJson["amount"]
let bankCode = tempJson["bankCode"]
let branchCode = tempJson["branchCode"]
let accountNumber = tempJson["accountNumber"]

let calculatedExternalId = calculateExternalId(amount, customerName, taxId, bankCode, branchCode, accountNumber)

message = "Erro - Linha " + jsonExternalId[calculatedExternalId].toString() + ":" + errorMessage.split(':')[1] + "\n";
};
errorMessages = errorMessages.concat(message);
})
sendMessage(errorMessages);
return
}

requests.push(request);
}
let payload = {requests: requests};
let responseApi = fetch("/payment-request", method = 'POST', payload, query);

let [json, status] = parseResponse(responseApi)
switch (status) {
case 500:
throw new Error(JSON.parse(json)["errors"]["message"]);
case 400:
let errors = Array.from(json["errors"]);
errors.forEach(error => {
if (error.code == "invalidCredentials") {
sendMessage("Sessão expirada! \nFaça o login novamente");
return;
};
let errorMessage = error.message;

let message = errorMessage + "\n"
if (/Element [0-9]*:/.test(errorMessage)) {
let requestNumber = errorMessage.split('Element ').pop().split(':')[0];
let lineNumber = parseInt(requestNumber) + batchInitialLine;
message = "Erro - Linha " + lineNumber + ":" + errorMessage.split(':')[1] + "\n";
};
errorMessages = errorMessages.concat(message);
})
}
}
let successMessage = "Sucesso! \nTodas as transferências foram enviadas para aprovação."
errorMessages ? sendMessage(errorMessages) : sendMessage(successMessage)

sentItems ? sendMessage("Items enviados\n" + sentItems + "\n\n" + errorMessages) : sendMessage(errorMessages);
}

function sendMessage(message){
Expand Down
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
6 changes: 3 additions & 3 deletions src/utilsBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,6 @@ function formatDateToISO(stringDate)
}


// function onOpen(e) {
// Browser.msgBox("Hello!!");
// }
function calculateExternalId(amount, name, taxId, bankCode, branchCode, accountNumber){
return bankCode + branchCode + accountNumber + name + taxId + amount.toString()
}
Loading