Skip to content

Commit

Permalink
Fix duplieted PaymentRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
luistarkbank committed Jul 1, 2024
1 parent d1a738b commit 414a274
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 63 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ Given a version number MAJOR.MINOR.PATCH, increment:


## [Unreleased]
### Fixed
- paymentRequest duplicated payment

## [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":"1JAupf57mwkjPaC3FFC8Ydx-yo6LkoIjnIrpQx2_95JenFfQ0G2ov4rbO","rootDir":"/Users/luis.almeida/Documents/starkbank/google-sheets/src"}
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
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()
}

0 comments on commit 414a274

Please sign in to comment.