From 414a274c5c516ead7db543d3d1c8a80f0da0f736 Mon Sep 17 00:00:00 2001 From: luistarkbank Date: Mon, 1 Jul 2024 16:11:17 -0300 Subject: [PATCH 1/2] Fix duplieted PaymentRequest --- CHANGELOG.md | 2 + src/.clasp.json | 2 +- src/apiAuth.js | 6 ++ src/sdkSendOrder.js | 189 ++++++++++++++++++++++++++++++-------------- src/utilsBase.js | 6 +- 5 files changed, 142 insertions(+), 63 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c49a7d4..4e659f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ Given a version number MAJOR.MINOR.PATCH, increment: ## [Unreleased] +### Fixed +- paymentRequest duplicated payment ## [0.6.5] - 2024-06-28 ### Added diff --git a/src/.clasp.json b/src/.clasp.json index 8b94e30..f8833d9 100644 --- a/src/.clasp.json +++ b/src/.clasp.json @@ -1 +1 @@ -{"scriptId":"10XuhtMToOKv59YPboFbDYzYvBazsk2Odo1j9XAyZHZUXCg-HGeyF0Oex","rootDir":"/Users/luis.almeida/Documents/starkbank/google-sheets/src"} \ No newline at end of file +{"scriptId":"1JAupf57mwkjPaC3FFC8Ydx-yo6LkoIjnIrpQx2_95JenFfQ0G2ov4rbO","rootDir":"/Users/luis.almeida/Documents/starkbank/google-sheets/src"} \ No newline at end of file diff --git a/src/apiAuth.js b/src/apiAuth.js index fc5c0c8..f3b99c8 100644 --- a/src/apiAuth.js +++ b/src/apiAuth.js @@ -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("{}") } } @@ -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("{}") } } diff --git a/src/sdkSendOrder.js b/src/sdkSendOrder.js index 85f7b10..65179ff 100644 --- a/src/sdkSendOrder.js +++ b/src/sdkSendOrder.js @@ -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){ diff --git a/src/utilsBase.js b/src/utilsBase.js index eb2f5fe..a046e90 100644 --- a/src/utilsBase.js +++ b/src/utilsBase.js @@ -161,6 +161,6 @@ function formatDateToISO(stringDate) } -// function onOpen(e) { -// Browser.msgBox("Hello!!"); -// } \ No newline at end of file +function calculateExternalId(amount, name, taxId, bankCode, branchCode, accountNumber){ + return bankCode + branchCode + accountNumber + name + taxId + amount.toString() +} \ No newline at end of file From caefd3119114a26f8cfebb0314d8bacf5f9ea9a5 Mon Sep 17 00:00:00 2001 From: luistarkbank Date: Tue, 13 Aug 2024 19:02:50 -0300 Subject: [PATCH 2/2] Fix download transfer --- CHANGELOG.md | 1 + src/.clasp.json | 2 +- src/FormDownloadTransfers.html | 31 +++++++++-- src/sdkViewTransfer.js | 11 ++-- src/utilsRequest.js | 95 ++++++++++++++++++++-------------- 5 files changed, 91 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e659f8..777aba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/.clasp.json b/src/.clasp.json index f8833d9..9ae0549 100644 --- a/src/.clasp.json +++ b/src/.clasp.json @@ -1 +1 @@ -{"scriptId":"1JAupf57mwkjPaC3FFC8Ydx-yo6LkoIjnIrpQx2_95JenFfQ0G2ov4rbO","rootDir":"/Users/luis.almeida/Documents/starkbank/google-sheets/src"} \ No newline at end of file +{"scriptId":"199zM22Q3FVHJK5EOZtrz7EQ7bH5wm_vnQCu-YVI7kOz6N455TDq-XmMq"} \ No newline at end of file diff --git a/src/FormDownloadTransfers.html b/src/FormDownloadTransfers.html index 3f2d728..2fd76ce 100644 --- a/src/FormDownloadTransfers.html +++ b/src/FormDownloadTransfers.html @@ -9,7 +9,12 @@ - +
Aguarde enquanto os arquivos são baixados... @@ -20,8 +25,10 @@ \ No newline at end of file diff --git a/src/sdkViewTransfer.js b/src/sdkViewTransfer.js index d48fa3c..329cae8 100644 --- a/src/sdkViewTransfer.js +++ b/src/sdkViewTransfer.js @@ -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; } @@ -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()) diff --git a/src/utilsRequest.js b/src/utilsRequest.js index 6d59026..a6597fb 100644 --- a/src/utilsRequest.js +++ b/src/utilsRequest.js @@ -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] } }