From 50c3cbf21ccbeb636869f1305e241d24b40542b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio=20C=C3=A9sar?= Date: Wed, 9 Oct 2019 22:02:06 -0300 Subject: [PATCH 01/17] code style --- .gitignore | 1 + lib/additional.js | 28 +- lib/address.js | 44 +- lib/antifraud.js | 26 +- lib/authorization.js | 30 +- lib/capture.js | 30 +- lib/cart.js | 52 +-- lib/consumer.js | 50 +-- lib/environment.js | 24 +- lib/erede.js | 84 ++-- lib/exception/RedeError.js | 12 +- lib/flight.js | 28 +- lib/iata.js | 10 +- lib/item.js | 36 +- lib/passenger.js | 12 +- lib/phone.js | 36 +- lib/refund.js | 30 +- lib/service/CancelTransactionService.js | 27 +- lib/service/CaptureTransactionService.js | 27 +- lib/service/CreateTransactionService.js | 21 +- lib/service/GetTransactionService.js | 42 +- lib/service/TransactionService.js | 122 +++--- lib/store.js | 12 +- lib/submerchant.js | 12 +- lib/threedsecure.js | 40 +- lib/transaction.js | 508 ++++++++++++----------- lib/url.js | 54 +-- 27 files changed, 730 insertions(+), 668 deletions(-) diff --git a/.gitignore b/.gitignore index c1605d3..e41bb60 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .idea node_modules/ package-lock.json +yarn.lock \ No newline at end of file diff --git a/lib/additional.js b/lib/additional.js index 231326c..16f163b 100644 --- a/lib/additional.js +++ b/lib/additional.js @@ -1,20 +1,20 @@ "use strict"; module.exports = class Additional { - constructor(gateway, module) { - this.gateway = gateway; - this.module = module; - } - - static fromJSON(json) { - let additional = new Additional(); + constructor(gateway, module) { + this.gateway = gateway; + this.module = module; + } - for (let property in json) { - if (json.hasOwnProperty(property)) { - additional[property] = json[property]; - } - } + static fromJSON(json) { + let additional = new Additional(); - return additional; + for (let property in json) { + if (json.hasOwnProperty(property)) { + additional[property] = json[property]; + } } -}; \ No newline at end of file + + return additional; + } +}; diff --git a/lib/address.js b/lib/address.js index 7397e56..22eb0be 100644 --- a/lib/address.js +++ b/lib/address.js @@ -1,31 +1,31 @@ "use strict"; module.exports = class Address { - static get BILLING() { - return 1; - } + static get BILLING() { + return 1; + } - static get SHIPPING() { - return 2; - } + static get SHIPPING() { + return 2; + } - static get BOTH() { - return 3; - } + static get BOTH() { + return 3; + } - static get APARTMENT() { - return 1; - } + static get APARTMENT() { + return 1; + } - static get HOUSE() { - return 2; - } + static get HOUSE() { + return 2; + } - static get COMMERCIAL() { - return 3; - } + static get COMMERCIAL() { + return 3; + } - static get OTHER() { - return 4; - } -}; \ No newline at end of file + static get OTHER() { + return 4; + } +}; diff --git a/lib/antifraud.js b/lib/antifraud.js index 638940a..0ec2042 100644 --- a/lib/antifraud.js +++ b/lib/antifraud.js @@ -1,19 +1,19 @@ "use strict"; module.exports = class Antifraud { - constructor() { - this.success = false; - } - - static fromJSON(json) { - let antifraud = new self(); + constructor() { + this.success = false; + } - for (let property in json) { - if (json.hasOwnProperty(property)) { - antifraud[property] = json[property]; - } - } + static fromJSON(json) { + let antifraud = new self(); - return antifraud; + for (let property in json) { + if (json.hasOwnProperty(property)) { + antifraud[property] = json[property]; + } } -}; \ No newline at end of file + + return antifraud; + } +}; diff --git a/lib/authorization.js b/lib/authorization.js index a591ee5..791e535 100644 --- a/lib/authorization.js +++ b/lib/authorization.js @@ -1,21 +1,25 @@ "use strict"; module.exports = class Authorization { - static fromJSON(json) { - let authorization = new Authorization(); + static fromJSON(json) { + let authorization = new Authorization(); - for (let property in json) { - if (json.hasOwnProperty(property)) { - let value = json[property]; + for (let property in json) { + if (json.hasOwnProperty(property)) { + let value = json[property]; - if (property === 'requestDateTime' || property === 'dateTime' || property === 'refundDateTime') { - value = new Date(value); - } - - authorization[property] = value; - } + if ( + property === "requestDateTime" || + property === "dateTime" || + property === "refundDateTime" + ) { + value = new Date(value); } - return authorization; + authorization[property] = value; + } } -}; \ No newline at end of file + + return authorization; + } +}; diff --git a/lib/capture.js b/lib/capture.js index a4fb205..f797892 100644 --- a/lib/capture.js +++ b/lib/capture.js @@ -1,21 +1,25 @@ "use strict"; module.exports = class Capture { - static fromJSON(json) { - let capture = new Capture(); + static fromJSON(json) { + let capture = new Capture(); - for (let property in json) { - if (json.hasOwnProperty(property)) { - let value = json[property]; + for (let property in json) { + if (json.hasOwnProperty(property)) { + let value = json[property]; - if (property === 'requestDateTime' || property === 'dateTime' || property === 'refundDateTime') { - value = new Date(value); - } - - capture[property] = value; - } + if ( + property === "requestDateTime" || + property === "dateTime" || + property === "refundDateTime" + ) { + value = new Date(value); } - return capture; + capture[property] = value; + } } -}; \ No newline at end of file + + return capture; + } +}; diff --git a/lib/cart.js b/lib/cart.js index 6aeddd9..7436c52 100644 --- a/lib/cart.js +++ b/lib/cart.js @@ -5,40 +5,40 @@ const Consumer = require("./consumer"); const Iata = require("./iata"); module.exports = class Cart { - address(type = Address.BOTH) { - let address = Address(); + address(type = Address.BOTH) { + let address = Address(); - if ((type & Address.BILLING) === Address.BILLING) { - this.billing = address; - } - - if ((type & Address.SHIPPING) === Address.SHIPPING) { - this.shipping = [address]; - } - - return address; + if ((type & Address.BILLING) === Address.BILLING) { + this.billing = address; } - addItem(item) { - if (this.items === undefined) { - this.items = []; - } + if ((type & Address.SHIPPING) === Address.SHIPPING) { + this.shipping = [address]; + } - this.items.push(item); + return address; + } - return this; + addItem(item) { + if (this.items === undefined) { + this.items = []; } - setConsumer(name, email, cpf) { - this.consumer = new Consumer(name, email, cpf); + this.items.push(item); - return this.consumer; - } + return this; + } - setIata(code, departureTax, flight) { - this.iata = new Iata(code, departureTax); - this.iata.flight = flight; + setConsumer(name, email, cpf) { + this.consumer = new Consumer(name, email, cpf); - return this; - } + return this.consumer; + } + + setIata(code, departureTax, flight) { + this.iata = new Iata(code, departureTax); + this.iata.flight = flight; + + return this; + } }; diff --git a/lib/consumer.js b/lib/consumer.js index 0034421..5754034 100644 --- a/lib/consumer.js +++ b/lib/consumer.js @@ -3,33 +3,33 @@ const Phone = require("./phone"); module.exports = class Consumer { - constructor(name, email, cpf) { - this.name = name; - this.email = email; - this.cpf = cpf; + constructor(name, email, cpf) { + this.name = name; + this.email = email; + this.cpf = cpf; + } + + static get MALE() { + return "M"; + } + + static get FEMALE() { + return "F"; + } + + addDocument(type, number) { + if (this.documents === undefined) { + this.documents = []; } - static get MALE() { - return "M"; - } - - static get FEMALE() { - return "F"; - } + this.documents.push({ type: type, number: number }); - addDocument(type, number) { - if (this.documents === undefined) { - this.documents = []; - } + return this; + } - this.documents.push({type: type, number: number}); + setPhone(ddd, number, type = Phone.CELLPHONE) { + this.phone = new Phone(ddd, number, type); - return this; - } - - setPhone(ddd, number, type = Phone.CELLPHONE) { - this.phone = new Phone(ddd, number, type); - - return this; - } -}; \ No newline at end of file + return this; + } +}; diff --git a/lib/environment.js b/lib/environment.js index 8e056d2..97c7dca 100644 --- a/lib/environment.js +++ b/lib/environment.js @@ -5,17 +5,17 @@ const SANDBOX = "https://api.userede.com.br/desenvolvedores"; const VERSION = "v1"; module.exports = class Environment { - constructor(baseUrl, version = VERSION) { - this.ip = ""; - this.sessionId = ""; - this.endpoint = `${baseUrl}/${version}`; - } + constructor(baseUrl, version = VERSION) { + this.ip = ""; + this.sessionId = ""; + this.endpoint = `${baseUrl}/${version}`; + } - static production() { - return new Environment(PRODUCTION, VERSION); - } + static production() { + return new Environment(PRODUCTION, VERSION); + } - static sandbox() { - return new Environment(SANDBOX, VERSION) - } -}; \ No newline at end of file + static sandbox() { + return new Environment(SANDBOX, VERSION); + } +}; diff --git a/lib/erede.js b/lib/erede.js index 12e1f37..47be31b 100644 --- a/lib/erede.js +++ b/lib/erede.js @@ -6,65 +6,65 @@ const CreateTransactionService = require("./service/CreateTransactionService"); const GetTransactionService = require("./service/GetTransactionService"); module.exports = class eRede { - constructor(store) { - this.store = store; - } + constructor(store) { + this.store = store; + } - async create(transaction) { - let service = new CreateTransactionService(this.store, transaction); + async create(transaction) { + let service = new CreateTransactionService(this.store, transaction); - return service.execute(); - } + return service.execute(); + } - cancel(transaction) { - let service = new CancelTransactionService(this.store, transaction); + cancel(transaction) { + let service = new CancelTransactionService(this.store, transaction); - return service.execute(); - } + return service.execute(); + } - capture(transaction) { - let service = new CaptureTransactionService(this.store, transaction); + capture(transaction) { + let service = new CaptureTransactionService(this.store, transaction); - return service.execute(); - } + return service.execute(); + } - getByTid(tid) { - let service = new GetTransactionService(this.store); + getByTid(tid) { + let service = new GetTransactionService(this.store); - service.tid = tid; + service.tid = tid; - return service.execute(); - } + return service.execute(); + } - getByReference(reference) { - let service = new GetTransactionService(this.store); + getByReference(reference) { + let service = new GetTransactionService(this.store); - service.reference = reference; + service.reference = reference; - return service.execute(); - } + return service.execute(); + } - getRefunds(tid) { - let service = new GetTransactionService(this.store); + getRefunds(tid) { + let service = new GetTransactionService(this.store); - service.tid = tid; - service.refunds = true; + service.tid = tid; + service.refunds = true; - return service.execute(); - } + return service.execute(); + } - zero(transaction) { - let amount = transaction.amount; - let capture = transaction.capture; + zero(transaction) { + let amount = transaction.amount; + let capture = transaction.capture; - transaction.amount = 0; - transaction.capture = true; + transaction.amount = 0; + transaction.capture = true; - transaction = this.create(transaction); + transaction = this.create(transaction); - transaction.amount = amount; - transaction.capture = capture; + transaction.amount = amount; + transaction.capture = capture; - return transaction; - } -}; \ No newline at end of file + return transaction; + } +}; diff --git a/lib/exception/RedeError.js b/lib/exception/RedeError.js index 86795b0..1c11d41 100644 --- a/lib/exception/RedeError.js +++ b/lib/exception/RedeError.js @@ -1,10 +1,10 @@ "use strict"; module.exports = class RedeError extends Error { - constructor(message, code) { - super(message); + constructor(message, code) { + super(message); - this.returnCode = code; - this.returnMessage = message; - } -}; \ No newline at end of file + this.returnCode = code; + this.returnMessage = message; + } +}; diff --git a/lib/flight.js b/lib/flight.js index 0ad748c..cb2e370 100644 --- a/lib/flight.js +++ b/lib/flight.js @@ -3,20 +3,20 @@ const Passenger = require("./passenger"); module.exports = class Flight { - constructor(number, from, to, date) { - this.number = number; - this.from = from; - this.to = to; - this.date = date; - } + constructor(number, from, to, date) { + this.number = number; + this.from = from; + this.to = to; + this.date = date; + } - addPassenger(name, email, ticket) { - if (this.passenger === undefined) { - this.passenger = []; - } + addPassenger(name, email, ticket) { + if (this.passenger === undefined) { + this.passenger = []; + } - this.passenger.push(new Passenger(name, email, ticket)); + this.passenger.push(new Passenger(name, email, ticket)); - return this; - } -}; \ No newline at end of file + return this; + } +}; diff --git a/lib/iata.js b/lib/iata.js index 29e1205..7803013 100644 --- a/lib/iata.js +++ b/lib/iata.js @@ -1,8 +1,8 @@ "use strict"; module.exports = class Iata { - constructor(code, departureTax) { - this.code = code; - this.departureTax = departureTax; - } -}; \ No newline at end of file + constructor(code, departureTax) { + this.code = code; + this.departureTax = departureTax; + } +}; diff --git a/lib/item.js b/lib/item.js index 93d3fd0..a235a2f 100644 --- a/lib/item.js +++ b/lib/item.js @@ -1,25 +1,25 @@ "use strict"; module.exports = class Item { - constructor(id, quantity, type = Item.PHYSICAL) { - this.id = id; - this.quantity = quantity; - this.type = type; - } + constructor(id, quantity, type = Item.PHYSICAL) { + this.id = id; + this.quantity = quantity; + this.type = type; + } - static get PHYSICAL() { - return 1; - } + static get PHYSICAL() { + return 1; + } - static get DIGITAL() { - return 2; - } + static get DIGITAL() { + return 2; + } - static get SERVICE() { - return 3; - } + static get SERVICE() { + return 3; + } - static get AIRLINE() { - return 4; - } -}; \ No newline at end of file + static get AIRLINE() { + return 4; + } +}; diff --git a/lib/passenger.js b/lib/passenger.js index 6dfc577..ea995c0 100644 --- a/lib/passenger.js +++ b/lib/passenger.js @@ -1,9 +1,9 @@ "use strict"; module.exports = class Passenger { - constructor(name, email, ticket) { - this.name = name; - this.email = email; - this.ticket = ticket; - } -}; \ No newline at end of file + constructor(name, email, ticket) { + this.name = name; + this.email = email; + this.ticket = ticket; + } +}; diff --git a/lib/phone.js b/lib/phone.js index 317fa15..b4ee633 100644 --- a/lib/phone.js +++ b/lib/phone.js @@ -1,25 +1,25 @@ "use strict"; module.exports = class Phone { - constructor(ddd, number, type = Phone.CELLPHONE) { - this.ddd = ddd; - this.number = number; - this.type = type; - } + constructor(ddd, number, type = Phone.CELLPHONE) { + this.ddd = ddd; + this.number = number; + this.type = type; + } - static get CELLPHONE() { - return 1; - } + static get CELLPHONE() { + return 1; + } - static get HOME() { - return 2; - } + static get HOME() { + return 2; + } - static get WORK() { - return 3; - } + static get WORK() { + return 3; + } - static get OTHER() { - return 4; - } -}; \ No newline at end of file + static get OTHER() { + return 4; + } +}; diff --git a/lib/refund.js b/lib/refund.js index e8f449b..b91fe4f 100644 --- a/lib/refund.js +++ b/lib/refund.js @@ -1,21 +1,25 @@ "use strict"; module.exports = class Refund { - static fromJSON(json) { - let refund = new Refund(); + static fromJSON(json) { + let refund = new Refund(); - for (let property in json) { - if (json.hasOwnProperty(property)) { - let value = json[property]; + for (let property in json) { + if (json.hasOwnProperty(property)) { + let value = json[property]; - if (property === 'requestDateTime' || property === 'dateTime' || property === 'refundDateTime') { - value = new Date(value); - } - - refund[property] = value; - } + if ( + property === "requestDateTime" || + property === "dateTime" || + property === "refundDateTime" + ) { + value = new Date(value); } - return refund; + refund[property] = value; + } } -}; \ No newline at end of file + + return refund; + } +}; diff --git a/lib/service/CancelTransactionService.js b/lib/service/CancelTransactionService.js index 910aab0..dabbb33 100644 --- a/lib/service/CancelTransactionService.js +++ b/lib/service/CancelTransactionService.js @@ -1,19 +1,22 @@ "use strict"; -const TransactionService = require('./TransactionService'); +const TransactionService = require("./TransactionService"); module.exports = class CancelTransactionService extends TransactionService { - constructor(store, transaction) { - super(store); + constructor(store, transaction) { + super(store); - this.transaction = transaction; - } + this.transaction = transaction; + } - getUrl() { - return `${super.getUrl()}/${this.transaction.tid}/refunds`; - } + getUrl() { + return `${super.getUrl()}/${this.transaction.tid}/refunds`; + } - async execute() { - return this.sendRequest(TransactionService.POST, JSON.stringify(this.transaction)); - } -}; \ No newline at end of file + async execute() { + return this.sendRequest( + TransactionService.POST, + JSON.stringify(this.transaction) + ); + } +}; diff --git a/lib/service/CaptureTransactionService.js b/lib/service/CaptureTransactionService.js index 4d597a3..7414a41 100644 --- a/lib/service/CaptureTransactionService.js +++ b/lib/service/CaptureTransactionService.js @@ -1,19 +1,22 @@ "use strict"; -const TransactionService = require('./TransactionService'); +const TransactionService = require("./TransactionService"); module.exports = class CaptureTransactionService extends TransactionService { - constructor(store, transaction) { - super(store); + constructor(store, transaction) { + super(store); - this.transaction = transaction; - } + this.transaction = transaction; + } - getUrl() { - return `${super.getUrl()}/${this.transaction.tid}`; - } + getUrl() { + return `${super.getUrl()}/${this.transaction.tid}`; + } - execute() { - return this.sendRequest(TransactionService.PUT, JSON.stringify(this.transaction)); - } -}; \ No newline at end of file + execute() { + return this.sendRequest( + TransactionService.PUT, + JSON.stringify(this.transaction) + ); + } +}; diff --git a/lib/service/CreateTransactionService.js b/lib/service/CreateTransactionService.js index a080ac2..915b47c 100644 --- a/lib/service/CreateTransactionService.js +++ b/lib/service/CreateTransactionService.js @@ -1,15 +1,18 @@ "use strict"; -const TransactionService = require('./TransactionService'); +const TransactionService = require("./TransactionService"); module.exports = class CreateTransactionService extends TransactionService { - constructor(store, transaction) { - super(store); + constructor(store, transaction) { + super(store); - this.transaction = transaction; - } + this.transaction = transaction; + } - async execute() { - return await this.sendRequest(TransactionService.POST, JSON.stringify(this.transaction)); - } -}; \ No newline at end of file + async execute() { + return await this.sendRequest( + TransactionService.POST, + JSON.stringify(this.transaction) + ); + } +}; diff --git a/lib/service/GetTransactionService.js b/lib/service/GetTransactionService.js index 21492ad..77fb0f4 100644 --- a/lib/service/GetTransactionService.js +++ b/lib/service/GetTransactionService.js @@ -1,31 +1,31 @@ "use strict"; -const TransactionService = require('./TransactionService'); +const TransactionService = require("./TransactionService"); module.exports = class GetTransactionService extends TransactionService { - constructor(store) { - super(store); + constructor(store) { + super(store); - this.tid = undefined; - } - - getUrl() { - if (this.reference !== undefined) { - return `${super.getUrl()}?reference=${this.reference}`; - } - - if (this.tid === undefined) { - throw new Error('You need to specify one: the tid or the reference'); - } + this.tid = undefined; + } - if (this.refunds !== undefined) { - return `${super.getUrl()}/${this.tid}/refunds`; - } + getUrl() { + if (this.reference !== undefined) { + return `${super.getUrl()}?reference=${this.reference}`; + } - return `${super.getUrl()}/${this.tid}`; + if (this.tid === undefined) { + throw new Error("You need to specify one: the tid or the reference"); } - execute() { - return this.sendRequest(TransactionService.GET); + if (this.refunds !== undefined) { + return `${super.getUrl()}/${this.tid}/refunds`; } -}; \ No newline at end of file + + return `${super.getUrl()}/${this.tid}`; + } + + execute() { + return this.sendRequest(TransactionService.GET); + } +}; diff --git a/lib/service/TransactionService.js b/lib/service/TransactionService.js index c58b221..cc390b5 100644 --- a/lib/service/TransactionService.js +++ b/lib/service/TransactionService.js @@ -1,78 +1,80 @@ "use strict"; -const Transaction = require('../transaction'); -const RedeError = require('../exception/RedeError'); -const http = require('https'); -const bl = require('bl'); -const URL = require('url').URL; +const Transaction = require("../transaction"); +const RedeError = require("../exception/RedeError"); +const http = require("https"); +const bl = require("bl"); +const URL = require("url").URL; module.exports = class TransactionService { - constructor(store) { - this.store = store; - } + constructor(store) { + this.store = store; + } - static get POST() { - return 'POST'; - } + static get POST() { + return "POST"; + } - static get GET() { - return 'GET'; - } + static get GET() { + return "GET"; + } - static get PUT() { - return 'PUT'; - } + static get PUT() { + return "PUT"; + } - getUrl() { - let endpoint = this.store.environment.endpoint; + getUrl() { + let endpoint = this.store.environment.endpoint; - return `${endpoint}/transactions`; - } + return `${endpoint}/transactions`; + } - async execute() { - throw new Error('Ńão implementado'); - } + async execute() { + throw new Error("Ńão implementado"); + } - sendRequest(method, body = "") { - const url = new URL(this.getUrl()); - const options = { - hostname: url.hostname, - post: 443, - path: url.pathname, - method: method, - auth: this.store.filiation + ':' + this.store.token, - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(body) - } - }; + sendRequest(method, body = "") { + const url = new URL(this.getUrl()); + const options = { + hostname: url.hostname, + post: 443, + path: url.pathname, + method: method, + auth: this.store.filiation + ":" + this.store.token, + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body) + } + }; - return new Promise((resolve, reject) => { - let client = http.request(options, response => { - response.setEncoding('utf8'); - response.pipe(bl((error, data) => { - if (error) { - reject(error); - } + return new Promise((resolve, reject) => { + let client = http.request(options, response => { + response.setEncoding("utf8"); + response.pipe( + bl((error, data) => { + if (error) { + reject(error); + } - let json = JSON.parse(data.toString()); + let json = JSON.parse(data.toString()); - if (response.statusCode >= 400) { - if (!json || json.returnMessage === undefined) { - json = {}; - json.returnMessage = 'Alguma coisa aconteceu'; - json.returnCode = '-1'; - } + if (response.statusCode >= 400) { + if (!json || json.returnMessage === undefined) { + json = {}; + json.returnMessage = "Alguma coisa aconteceu"; + json.returnCode = "-1"; + } - reject(new RedeError(json.returnMessage, json.returnCode)); - } + reject(new RedeError(json.returnMessage, json.returnCode)); + } - resolve(Transaction.fromJSON(json)); - })); - }); + resolve(Transaction.fromJSON(json)); + }) + ); + }); - client.write(body); - client.end(); - }); - } + client.write(body); + client.end(); + }); + } }; diff --git a/lib/store.js b/lib/store.js index 39b510f..3603fb7 100644 --- a/lib/store.js +++ b/lib/store.js @@ -3,9 +3,9 @@ const Environment = require("./environment.js"); module.exports = class Store { - constructor(token, filiation, environment = Environment.production()) { - this.token = token; - this.filiation = filiation; - this.environment = environment; - } -}; \ No newline at end of file + constructor(token, filiation, environment = Environment.production()) { + this.token = token; + this.filiation = filiation; + this.environment = environment; + } +}; diff --git a/lib/submerchant.js b/lib/submerchant.js index 66d9c4f..09b4b0c 100644 --- a/lib/submerchant.js +++ b/lib/submerchant.js @@ -1,9 +1,9 @@ "use strict"; module.exports = class SubMerchant { - constructor(mcc, city, country) { - this.mcc = mcc; - this.city = city; - this.country = country; - } -}; \ No newline at end of file + constructor(mcc, city, country) { + this.mcc = mcc; + this.city = city; + this.country = country; + } +}; diff --git a/lib/threedsecure.js b/lib/threedsecure.js index b3385c7..293a2d9 100644 --- a/lib/threedsecure.js +++ b/lib/threedsecure.js @@ -1,28 +1,28 @@ "use strict"; module.exports = class ThreeDSecure { - constructor() { - this.embedded = true; - this.threeDIndicator = "1"; - } + constructor() { + this.embedded = true; + this.threeDIndicator = "1"; + } - static get CONTINUE_ON_FAILURE() { - return "continue"; - } + static get CONTINUE_ON_FAILURE() { + return "continue"; + } - static get DECLINE_ON_FAILURE() { - return "decline"; - } + static get DECLINE_ON_FAILURE() { + return "decline"; + } - static fromJSON(json) { - let threeds = new ThreeDSecure(); + static fromJSON(json) { + let threeds = new ThreeDSecure(); - for (let property in json) { - if (json.hasOwnProperty(property)) { - threeds[property] = json[property]; - } - } - - return threeds; + for (let property in json) { + if (json.hasOwnProperty(property)) { + threeds[property] = json[property]; + } } -}; \ No newline at end of file + + return threeds; + } +}; diff --git a/lib/transaction.js b/lib/transaction.js index e5a62b2..c88e792 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -8,252 +8,290 @@ const Capture = require("./capture"); const Authorization = require("./authorization"); const Additional = require("./additional"); const Antifraud = require("./antifraud"); -const Refund = require('./refund'); +const Refund = require("./refund"); module.exports = class Transaction { - constructor(amount, reference, installments) { - if (amount !== undefined) { - this.amount = amount; - } - - if (reference !== undefined) { - this.reference = reference; - } - - if (installments !== undefined) { - this.installments = installments; - } + constructor(amount, reference, installments) { + if (amount !== undefined) { + this.amount = amount; } - static get CREDIT() { - return "credit"; + if (reference !== undefined) { + this.reference = reference; } - static get DEBIT() { - return "debit"; + if (installments !== undefined) { + this.installments = installments; } - - static get ORIGIN_EREDE() { - return 1; - } - - static get ORIGIN_VISA_CHECKOUT() { - return 4; - } - - static get ORIGIN_MASTERPASS() { - return 6; - } - - static fromJSON(json) { - let transaction = new Transaction(json.amount, json.reference); - - for (let property in json) { - if (!json.hasOwnProperty(property)) { - continue; - } - - let value = json[property]; - let i = 0; - let t = 0; - - switch (property) { - case 'refunds': - transaction.refunds = []; - - for (i = 0, t = value.length; i < t; i++) { - transaction.refunds.push(Refund.fromJSON(value[i])); - } - - break; - case 'urls': - transaction.urls = []; - - for (i = 0, t = value.length; i < t; i++) { - transaction.urls.push(Url.fromJSON(value[i])); - } - - break; - case 'capture': - transaction.capture = Capture.fromJSON(value); - - break; - case 'authorization': - transaction.authorization = Authorization.fromJSON(value); - - break; - case 'additional': - transaction.additional = Additional.fromJSON(value); - - break; - case 'threeDSecure': - transaction.threeDSecure = ThreeDSecure.fromJSON(value); - - break; - case 'antifraud': - transaction.antifraud = Antifraud.fromJSON(value); - - break; - case 'requestDateTime': - case 'dateTime': - case 'refundDateTime': - transaction[property] = new Date(value); - break; - default: - transaction[property] = value; - } - } - - return transaction; - } - - /** - * - * @param gateway - * @param module - * @returns {module.Transaction} - */ - setAdditional(gateway, module) { - this.additional = new Additional(gateway, module); - - return this; - } - - /** - * - * @param url - * @param kind - * @returns {module.Transaction} - */ - addUrl(url, kind = Url.CALLBACK) { - if (this.urls === undefined) { - this.urls = []; - } - - this.urls.push(new Url(url, kind)); - - return this; - } - - /** - * - * @param environment - * @returns {module.Transaction} - */ - setAntifraud(environment) { - let cart = Cart(); - cart.environment = environment; - - this.antifraudRequired = true; - this.cart = cart; - - return this; - } - - /** - * - * @param cardNumber - * @param securityCode - * @param expirationMonth - * @param expirationYear - * @param cardHolderName - * @returns {module.Transaction} - */ - creditCard(cardNumber, securityCode, expirationMonth, expirationYear, cardHolderName) { - return this.card(cardNumber, securityCode, expirationMonth, expirationYear, cardHolderName, Transaction.CREDIT); + } + + static get CREDIT() { + return "credit"; + } + + static get DEBIT() { + return "debit"; + } + + static get ORIGIN_EREDE() { + return 1; + } + + static get ORIGIN_VISA_CHECKOUT() { + return 4; + } + + static get ORIGIN_MASTERPASS() { + return 6; + } + + static fromJSON(json) { + let transaction = new Transaction(json.amount, json.reference); + + for (let property in json) { + if (!json.hasOwnProperty(property)) { + continue; + } + + let value = json[property]; + let i = 0; + let t = 0; + + switch (property) { + case "refunds": + transaction.refunds = []; + + for (i = 0, t = value.length; i < t; i++) { + transaction.refunds.push(Refund.fromJSON(value[i])); + } + + break; + case "urls": + transaction.urls = []; + + for (i = 0, t = value.length; i < t; i++) { + transaction.urls.push(Url.fromJSON(value[i])); + } + + break; + case "capture": + transaction.capture = Capture.fromJSON(value); + + break; + case "authorization": + transaction.authorization = Authorization.fromJSON(value); + + break; + case "additional": + transaction.additional = Additional.fromJSON(value); + + break; + case "threeDSecure": + transaction.threeDSecure = ThreeDSecure.fromJSON(value); + + break; + case "antifraud": + transaction.antifraud = Antifraud.fromJSON(value); + + break; + case "requestDateTime": + case "dateTime": + case "refundDateTime": + transaction[property] = new Date(value); + break; + default: + transaction[property] = value; + } } - /** - * - * @param cardNumber - * @param securityCode - * @param expirationMonth - * @param expirationYear - * @param cardHolderName - * @returns {module.Transaction} - */ - debitCard(cardNumber, securityCode, expirationMonth, expirationYear, cardHolderName) { - return this.card(cardNumber, securityCode, expirationMonth, expirationYear, cardHolderName, Transaction.DEBIT); + return transaction; + } + + /** + * + * @param gateway + * @param module + * @returns {module.Transaction} + */ + setAdditional(gateway, module) { + this.additional = new Additional(gateway, module); + + return this; + } + + /** + * + * @param url + * @param kind + * @returns {module.Transaction} + */ + addUrl(url, kind = Url.CALLBACK) { + if (this.urls === undefined) { + this.urls = []; } - /** - * - * @param cardNumber - * @param securityCode - * @param expirationMonth - * @param expirationYear - * @param cardHolderName - * @param kind - * @returns {module.Transaction} - */ - card(cardNumber, securityCode, expirationMonth, expirationYear, cardHolderName, kind) { - this.cardNumber = cardNumber; - this.securityCode = securityCode; - this.expirationMonth = expirationMonth; - this.expirationYear = expirationYear; - this.cardHolderName = cardHolderName; - this.kind = kind; - - return this; + this.urls.push(new Url(url, kind)); + + return this; + } + + /** + * + * @param environment + * @returns {module.Transaction} + */ + setAntifraud(environment) { + let cart = Cart(); + cart.environment = environment; + + this.antifraudRequired = true; + this.cart = cart; + + return this; + } + + /** + * + * @param cardNumber + * @param securityCode + * @param expirationMonth + * @param expirationYear + * @param cardHolderName + * @returns {module.Transaction} + */ + creditCard( + cardNumber, + securityCode, + expirationMonth, + expirationYear, + cardHolderName + ) { + return this.card( + cardNumber, + securityCode, + expirationMonth, + expirationYear, + cardHolderName, + Transaction.CREDIT + ); + } + + /** + * + * @param cardNumber + * @param securityCode + * @param expirationMonth + * @param expirationYear + * @param cardHolderName + * @returns {module.Transaction} + */ + debitCard( + cardNumber, + securityCode, + expirationMonth, + expirationYear, + cardHolderName + ) { + return this.card( + cardNumber, + securityCode, + expirationMonth, + expirationYear, + cardHolderName, + Transaction.DEBIT + ); + } + + /** + * + * @param cardNumber + * @param securityCode + * @param expirationMonth + * @param expirationYear + * @param cardHolderName + * @param kind + * @returns {module.Transaction} + */ + card( + cardNumber, + securityCode, + expirationMonth, + expirationYear, + cardHolderName, + kind + ) { + this.cardNumber = cardNumber; + this.securityCode = securityCode; + this.expirationMonth = expirationMonth; + this.expirationYear = expirationYear; + this.cardHolderName = cardHolderName; + this.kind = kind; + + return this; + } + + /** + * + * @param capture + * @returns {module.Transaction} + */ + autoCapture(capture = true) { + if (!capture && this.kind === Transaction.DEBIT) { + throw new Error("Debit transactions will always be captured"); } - /** - * - * @param capture - * @returns {module.Transaction} - */ - autoCapture(capture = true) { - if (!capture && this.kind === Transaction.DEBIT) { - throw new Error("Debit transactions will always be captured"); - } - - this.capture = capture; - - return this; - } - - /** - * - * @param code - * @param departureTax - * @returns {module.Transaction} - */ - setIata(code, departureTax) { - this.iata = new Iata(code, departureTax); - - return this; - } - - /** - * - * @param softDescriptor - * @param paymentFacilitatorID - * @param subMerchant - * @returns {module.Transaction} - */ - setMcc(softDescriptor, paymentFacilitatorID, subMerchant) { - this.softDescriptor = softDescriptor; - this.paymentFacilitatorID = paymentFacilitatorID; - this.subMerchant = subMerchant; - - return this; - } - - /** - * - * @param onFailure - * @param embed - * @param directoryServerTransactionId - * @param threeDIndicator - * @returns {module.Transaction} - */ - setThreeDSecure(onFailure = ThreeDSecure.DECLINE_ON_FAILURE, embed = true, directoryServerTransactionId = "", threeDIndicator = "1") { - this.threeDSecure = new ThreeDSecure(); - this.threeDSecure.onFailure = onFailure; - this.threeDSecure.embedded = embed; - this.threeDSecure.threeDIndicator = threeDIndicator; - this.threeDSecure.DirectoryServerTransactionId = directoryServerTransactionId; - - return this; - } + this.capture = capture; + + return this; + } + + /** + * + * @param code + * @param departureTax + * @returns {module.Transaction} + */ + setIata(code, departureTax) { + this.iata = new Iata(code, departureTax); + + return this; + } + + /** + * + * @param softDescriptor + * @param paymentFacilitatorID + * @param subMerchant + * @returns {module.Transaction} + */ + setMcc(softDescriptor, paymentFacilitatorID, subMerchant) { + this.softDescriptor = softDescriptor; + this.paymentFacilitatorID = paymentFacilitatorID; + this.subMerchant = subMerchant; + + return this; + } + + /** + * + * @param onFailure + * @param embed + * @param directoryServerTransactionId + * @param threeDIndicator + * @returns {module.Transaction} + */ + setThreeDSecure( + onFailure = ThreeDSecure.DECLINE_ON_FAILURE, + embed = true, + directoryServerTransactionId = "", + threeDIndicator = "1" + ) { + this.threeDSecure = new ThreeDSecure(); + this.threeDSecure.onFailure = onFailure; + this.threeDSecure.embedded = embed; + this.threeDSecure.threeDIndicator = threeDIndicator; + this.threeDSecure.DirectoryServerTransactionId = directoryServerTransactionId; + + return this; + } }; diff --git a/lib/url.js b/lib/url.js index 614f5bf..7684d18 100644 --- a/lib/url.js +++ b/lib/url.js @@ -5,32 +5,32 @@ const THREE_D_SECURE_FAILURE = "threeDSecureFailure"; const THREE_D_SECURE_SUCCESS = "threeDSecureSuccess"; module.exports = class Url { - constructor(url, kind = Url.CALLBACK) { - this.url = url; - this.kind = kind; + constructor(url, kind = Url.CALLBACK) { + this.url = url; + this.kind = kind; + } + + static get CALLBACK() { + return CALLBACK; + } + + static get THREE_D_SECURE_FAILURE() { + return THREE_D_SECURE_FAILURE; + } + + static get THREE_D_SECURE_SUCCESS() { + return THREE_D_SECURE_SUCCESS; + } + + static fromJSON(json) { + let url = new Url(); + + for (let property in json) { + if (json.hasOwnProperty(property)) { + url[property] = json[property]; + } } - static get CALLBACK() { - return CALLBACK; - } - - static get THREE_D_SECURE_FAILURE() { - return THREE_D_SECURE_FAILURE; - } - - static get THREE_D_SECURE_SUCCESS() { - return THREE_D_SECURE_SUCCESS; - } - - static fromJSON(json) { - let url = new Url(); - - for (let property in json) { - if (json.hasOwnProperty(property)) { - url[property] = json[property]; - } - } - - return url; - } -}; \ No newline at end of file + return url; + } +}; From 28c97d6a739b15d5052bae7420e117fdf9241e2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio=20C=C3=A9sar?= Date: Thu, 10 Oct 2019 23:38:40 -0300 Subject: [PATCH 02/17] update readme adding methods --- README.md | 174 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 133 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 9d9eba3..f5c07a0 100644 --- a/README.md +++ b/README.md @@ -7,71 +7,163 @@ SDK de integração eRede ## Autorizando uma transação ```js -const eRede = require('./lib/erede'); -const Transaction = require('./lib/transaction'); -const Store = require('./lib/store'); -const Environment = require('./lib/environment'); +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); -let store = new Store('TOKEN', 'PV', Environment.sandbox()); +let store = new Store("TOKEN", "PV", Environment.sandbox()); let transaction = new Transaction(10, "ref123").creditCard( - '5448280000000007', - '235', - '12', - '2020', - 'Fulano de Tal' + "5448280000000007", + "235", + "12", + "2020", + "Fulano de Tal" ); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - } + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } }); ``` Por padrão, a transação é capturada automaticamente; caso seja necessário apenas autorizar a transação, o método `Transaction.capture()` deverá ser chamado com o parâmetro `false`: ```js -const eRede = require('./lib/erede'); -const Transaction = require('./lib/transaction'); -const Store = require('./lib/store'); -const Environment = require('./lib/environment'); +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); -let store = new Store('TOKEN', 'PV', Environment.sandbox()); -let transaction = new Transaction(10, "ref123").creditCard( - '5448280000000007', - '235', - '12', - '2020', - 'Fulano de Tal' -).autoCapture(false); +let store = new Store("TOKEN", "PV", Environment.sandbox()); +let transaction = new Transaction(10, "ref123") + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .autoCapture(false); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - } + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } }); ``` ## Autorizando uma transação com parcelamento ```js -const eRede = require('./lib/erede'); -const Transaction = require('./lib/transaction'); -const Store = require('./lib/store'); -const Environment = require('./lib/environment'); +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); -let store = new Store('TOKEN', 'PV', Environment.sandbox()); +let store = new Store("TOKEN", "PV", Environment.sandbox()); let transaction = new Transaction(10, "ref123", 2).creditCard( - '5448280000000007', - '235', - '12', - '2020', - 'Fulano de Tal' + "5448280000000007", + "235", + "12", + "2020", + "Fulano de Tal" ); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - } + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); +``` + +## Adiciona informação adicional de gateway e módulo + +```js +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); + +let store = new Store("TOKEN", "PV", Environment.sandbox()); +let transaction = new Transaction(10, "ref123", 2) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .setAdditional(1234, 56); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); +``` + +## Autorizando uma transação com MCC dinâmico + +```js +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); +const SubMerchant = require("./lib/submerchant"); + +let store = new Store("TOKEN", "PV", Environment.sandbox()); +let transaction = new Transaction(10, "ref123", 2) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .setMcc( + "COMERCIODOJOÃO", + "25416985759", + new SubMerchant(1234, "Fortaleza", "Brasil") + ); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); +``` + +## Autorizando uma transação IATA + +```js +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); + +let store = new Store("TOKEN", "PV", Environment.sandbox()); +let transaction = new Transaction(10, "ref123", 2) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .setIata("code123", "199"); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); +``` + +## Cria uma transação com Antifraude + +```js +const eRede = require("./lib/erede"); +const Transaction = require("./lib/transaction"); +const Store = require("./lib/store"); +const Environment = require("./lib/environment"); +const Consumer = require("./lib/consumer"); +const Phone = require("./lib/phone"); + +let environment = Environment.production(); +environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); + +let store = new Store("TOKEN", "PV", environment); +let transaction = new Transaction(10, "ref123", 2) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .setIata("code123", "199"); + +let antifraud = transaction.setAntifraud(environment); +antifraud + .consumer("John", "john@doe.com", "11111111111") + .setGender(Consumer.MALE) + .setPhone(new Phone("011", "111111111")); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } }); ``` From 2efb0302cee2fa85d24d6a0153d06eafa649ca62 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Mon, 28 Oct 2019 14:59:13 -0300 Subject: [PATCH 03/17] refactory and example code --- README.md | 377 ++++++++++++++++------ example/transaction.js | 19 ++ example/transaction_antifraud.js | 56 ++++ example/transaction_antifraud_area.js | 74 +++++ example/transaction_authenticated.js | 35 ++ example/transaction_cancelled.js | 16 + example/transaction_captured.js | 18 ++ example/transaction_consultingById.js | 15 + example/transaction_consulting_refunds.js | 15 + example/transaction_gateway.js | 19 ++ example/transaction_installments.js | 21 ++ lib/additional.js | 12 + lib/address.js | 54 ++++ lib/antifraud.js | 30 +- lib/authorization.js | 100 ++++++ lib/capture.js | 18 ++ lib/cart.js | 46 ++- lib/consumer.js | 6 + lib/environment.js | 12 + lib/flight.js | 4 +- lib/iata.js | 29 ++ lib/item.js | 48 +++ lib/passenger.js | 24 ++ lib/service/GetTransactionService.js | 2 + lib/transaction.js | 22 +- 25 files changed, 968 insertions(+), 104 deletions(-) create mode 100644 example/transaction.js create mode 100644 example/transaction_antifraud.js create mode 100644 example/transaction_antifraud_area.js create mode 100644 example/transaction_authenticated.js create mode 100644 example/transaction_cancelled.js create mode 100644 example/transaction_captured.js create mode 100644 example/transaction_consultingById.js create mode 100644 example/transaction_consulting_refunds.js create mode 100644 example/transaction_gateway.js create mode 100644 example/transaction_installments.js diff --git a/README.md b/README.md index f5c07a0..c021f73 100644 --- a/README.md +++ b/README.md @@ -7,37 +7,41 @@ SDK de integração eRede ## Autorizando uma transação ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); - -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123").creditCard( - "5448280000000007", - "235", - "12", - "2020", - "Fulano de Tal" +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() ); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); new eRede(store).create(transaction).then(transaction => { if (transaction.returnCode === "00") { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); + ``` Por padrão, a transação é capturada automaticamente; caso seja necessário apenas autorizar a transação, o método `Transaction.capture()` deverá ser chamado com o parâmetro `false`: ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); - -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123") +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") .autoCapture(false); @@ -46,42 +50,47 @@ new eRede(store).create(transaction).then(transaction => { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); + ``` ## Autorizando uma transação com parcelamento ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); - -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123", 2).creditCard( - "5448280000000007", - "235", - "12", - "2020", - "Fulano de Tal" +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() ); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000000)}`, 3) +.creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); new eRede(store).create(transaction).then(transaction => { if (transaction.returnCode === "00") { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); + ``` ## Adiciona informação adicional de gateway e módulo ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); - -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123", 2) +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000000)}`, 2) .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") .setAdditional(1234, 56); @@ -92,78 +101,260 @@ new eRede(store).create(transaction).then(transaction => { }); ``` -## Autorizando uma transação com MCC dinâmico +## Cria uma transação com Antifraude ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); -const SubMerchant = require("./lib/submerchant"); - -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123", 2) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") - .setMcc( - "COMERCIODOJOÃO", - "25416985759", - new SubMerchant(1234, "Fortaleza", "Brasil") - ); +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const Consumer = require("../lib/consumer"); +const Address = require("../lib/address"); + +let environment = Environment.sandbox(); +environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); -new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - } -}); +let store = new Store( + "TOKEN", + "PV", + environment +); + +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}`, + 2 +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +let antifraud = transaction.setAntifraud(environment); +antifraud + .consumer("Fulano", "fulano@mail.com", "11111111111") + .setGender(Consumer.MALE) + .setPhone("011", "999999999") + .addDocument("RG", "111111111"); + +antifraud + .address() + .setAddresseeName("Fulano") + .setAddress("Rua dos bobos") + .setNumber("125") + .setZipCode("01122123") + .setNeighbourhood("Bairro legal") + .setCity("Cidade Bonita") + .setState("UF") + .setType(Address.OTHER); + +new eRede(store) + .create(transaction) + .then(transaction => { + if (transaction.returnCode === "00") { + antifraud = transaction.getAntifraud(); + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + + console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Score: ${antifraud.score}`); + console.log(`Nível de Risco: ${antifraud.riskLevel}`); + console.log(`Recomendação: ${antifraud.recommendation}`); + } + }) + .catch(error => { + console.error(error); + }); ``` -## Autorizando uma transação IATA +## Cria uma transação com Antifraude para companhias aéreas +```js +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const Consumer = require("../lib/consumer"); +const Phone = require("../lib/phone"); +const Address = require("../lib/address"); +const Passenger = require("../lib/passenger"); +const Flight = require("../lib/flight"); + +let environment = Environment.sandbox(); +environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); + +let store = new Store( + "TOKEN", + "PV", + environment +); + +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}`, + 2 +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +let antifraud = transaction.setAntifraud(environment); +antifraud + .consumer("Fulano", "fulano@mail.com", "11111111111") + .setGender(Consumer.MALE) + .setPhone("011", "999999999") + .addDocument("RG", "111111111"); + +antifraud + .address() + .setAddresseeName("Fulano") + .setAddress("Rua dos bobos") + .setNumber("125") + .setZipCode("01122123") + .setNeighbourhood("Bairro legal") + .setCity("Cidade Bonita") + .setState("UF") + .setType(Address.OTHER); + +antifraud.setIata( + "code123", + "250", + new Flight( + "123213", + "Los Angeles", + "New York", + "2017-02-15T10:54:45-9:00" + ).addPassenger( + new Passenger("Arya Stark", "lorem@ipsum.com", "32423432432").setPhone( + new Phone("011", "912341234") + ) + ) +); +new eRede(store) + .create(transaction) + .then(transaction => { + if (transaction.returnCode === "00") { + antifraud = transaction.getAntifraud(); + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + + console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Score: ${antifraud.score}`); + console.log(`Nível de Risco: ${antifraud.riskLevel}`); + console.log(`Recomendação: ${antifraud.recommendation}`); + } + }) + .catch(error => { + console.error(error); + }); +``` + +## Capturando uma transação ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); -let store = new Store("TOKEN", "PV", Environment.sandbox()); -let transaction = new Transaction(10, "ref123", 2) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") - .setIata("code123", "199"); +new eRede(store) + .capture(new Transaction(10).setTid("10011910280828200188")) + .then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação capturada com sucesso: ${transaction.tid}`); + } + }); +``` -new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - } +## Cancelando uma transação +```js +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store) + .cancel(new Transaction(10).setTid("10011910280828200220")) + .then(transaction => { + console.log(`Transação cancelada com sucesso: ${transaction.tid}`); + }); +``` + +## Consultando uma transação pelo ID +```js +const eRede = require("../lib/erede"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store).getByTid("10011910280828200189").then(transaction => { + console.log( + `Transação consutada com sucesso: ${transaction.authorization.tid}, status: ${transaction.authorization.status}` + ); }); ``` -## Cria uma transação com Antifraude +## Consultando cancelamentos de uma transação +```js +const eRede = require("../lib/erede"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +new eRede(store).getRefunds("10011910280828200220").then(transaction => { + transaction.refunds.forEach(el => { + console.log(`Transação cancelada : ${el.refundId}`); + }); +}); +``` + +## Transação com autenticação ```js -const eRede = require("./lib/erede"); -const Transaction = require("./lib/transaction"); -const Store = require("./lib/store"); -const Environment = require("./lib/environment"); -const Consumer = require("./lib/consumer"); -const Phone = require("./lib/phone"); - -let environment = Environment.production(); -environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const ThreeDSecure = require("../lib/threedsecure"); +const Url = require("../lib/url"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); -let store = new Store("TOKEN", "PV", environment); -let transaction = new Transaction(10, "ref123", 2) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") - .setIata("code123", "199"); +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}` +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); -let antifraud = transaction.setAntifraud(environment); -antifraud - .consumer("John", "john@doe.com", "11111111111") - .setGender(Consumer.MALE) - .setPhone(new Phone("011", "111111111")); +transaction.setThreeDSecure(ThreeDSecure.DECLINE_ON_FAILURE); +transaction.addUrl( + "https://redirecturl.com/3ds/success", + Url.THREE_D_SECURE_SUCCESS +); +transaction.addUrl( + "https://redirecturl.com/3ds/failure", + Url.THREE_D_SECURE_FAILURE +); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { - console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + if (transaction.returnCode === "220") { + console.log( + `Redirecione o cliente para ${transaction.threeDSecure.url} para autenticação` + ); } }); -``` +``` \ No newline at end of file diff --git a/example/transaction.js b/example/transaction.js new file mode 100644 index 0000000..515cd73 --- /dev/null +++ b/example/transaction.js @@ -0,0 +1,19 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .autoCapture(false); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); diff --git a/example/transaction_antifraud.js b/example/transaction_antifraud.js new file mode 100644 index 0000000..d52a791 --- /dev/null +++ b/example/transaction_antifraud.js @@ -0,0 +1,56 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const Consumer = require("../lib/consumer"); +const Address = require("../lib/address"); + +let environment = Environment.sandbox(); +environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); + +let store = new Store( + "TOKEN", + "PV", + environment +); + +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}`, + 2 +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +let antifraud = transaction.setAntifraud(environment); +antifraud + .consumer("Fulano", "fulano@mail.com", "11111111111") + .setGender(Consumer.MALE) + .setPhone("011", "999999999") + .addDocument("RG", "111111111"); + +antifraud + .address() + .setAddresseeName("Fulano") + .setAddress("Rua dos bobos") + .setNumber("125") + .setZipCode("01122123") + .setNeighbourhood("Bairro legal") + .setCity("Cidade Bonita") + .setState("UF") + .setType(Address.OTHER); + +new eRede(store) + .create(transaction) + .then(transaction => { + if (transaction.returnCode === "00") { + antifraud = transaction.getAntifraud(); + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + + console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Score: ${antifraud.score}`); + console.log(`Nível de Risco: ${antifraud.riskLevel}`); + console.log(`Recomendação: ${antifraud.recommendation}`); + } + }) + .catch(error => { + console.error(error); + }); diff --git a/example/transaction_antifraud_area.js b/example/transaction_antifraud_area.js new file mode 100644 index 0000000..ddb60ca --- /dev/null +++ b/example/transaction_antifraud_area.js @@ -0,0 +1,74 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const Consumer = require("../lib/consumer"); +const Phone = require("../lib/phone"); +const Address = require("../lib/address"); +const Passenger = require("../lib/passenger"); +const Flight = require("../lib/flight"); + +let environment = Environment.sandbox(); +environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); + +let store = new Store( + "TOKEN", + "PV", + environment +); + +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}`, + 2 +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +let antifraud = transaction.setAntifraud(environment); +antifraud + .consumer("Fulano", "fulano@mail.com", "11111111111") + .setGender(Consumer.MALE) + .setPhone("011", "999999999") + .addDocument("RG", "111111111"); + +antifraud + .address() + .setAddresseeName("Fulano") + .setAddress("Rua dos bobos") + .setNumber("125") + .setZipCode("01122123") + .setNeighbourhood("Bairro legal") + .setCity("Cidade Bonita") + .setState("UF") + .setType(Address.OTHER); + +antifraud.setIata( + "code123", + "250", + new Flight( + "123213", + "Los Angeles", + "New York", + "2017-02-15T10:54:45-9:00" + ).addPassenger( + new Passenger("Arya Stark", "lorem@ipsum.com", "32423432432").setPhone( + new Phone("011", "912341234") + ) + ) +); + +new eRede(store) + .create(transaction) + .then(transaction => { + if (transaction.returnCode === "00") { + antifraud = transaction.getAntifraud(); + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + + console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Score: ${antifraud.score}`); + console.log(`Nível de Risco: ${antifraud.riskLevel}`); + console.log(`Recomendação: ${antifraud.recommendation}`); + } + }) + .catch(error => { + console.error(error); + }); diff --git a/example/transaction_authenticated.js b/example/transaction_authenticated.js new file mode 100644 index 0000000..6e511cf --- /dev/null +++ b/example/transaction_authenticated.js @@ -0,0 +1,35 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); +const ThreeDSecure = require("../lib/threedsecure"); +const Url = require("../lib/url"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}` +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +transaction.setThreeDSecure(ThreeDSecure.DECLINE_ON_FAILURE); +transaction.addUrl( + "https://redirecturl.com/3ds/success", + Url.THREE_D_SECURE_SUCCESS +); +transaction.addUrl( + "https://redirecturl.com/3ds/failure", + Url.THREE_D_SECURE_FAILURE +); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "220") { + console.log( + `Redirecione o cliente para ${transaction.threeDSecure.url} para autenticação` + ); + } +}); diff --git a/example/transaction_cancelled.js b/example/transaction_cancelled.js new file mode 100644 index 0000000..6768e0d --- /dev/null +++ b/example/transaction_cancelled.js @@ -0,0 +1,16 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store) + .cancel(new Transaction(10).setTid("10011910280828200220")) + .then(transaction => { + console.log(`Transação cancelada com sucesso: ${transaction.tid}`); + }); diff --git a/example/transaction_captured.js b/example/transaction_captured.js new file mode 100644 index 0000000..af69b31 --- /dev/null +++ b/example/transaction_captured.js @@ -0,0 +1,18 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store) + .capture(new Transaction(10).setTid("10011910280828200188")) + .then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação capturada com sucesso: ${transaction.tid}`); + } + }); diff --git a/example/transaction_consultingById.js b/example/transaction_consultingById.js new file mode 100644 index 0000000..2312d33 --- /dev/null +++ b/example/transaction_consultingById.js @@ -0,0 +1,15 @@ +const eRede = require("../lib/erede"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store).getByTid("10011910280828200189").then(transaction => { + console.log( + `Transação consutada com sucesso: ${transaction.authorization.tid}, status: ${transaction.authorization.status}` + ); +}); diff --git a/example/transaction_consulting_refunds.js b/example/transaction_consulting_refunds.js new file mode 100644 index 0000000..2980d86 --- /dev/null +++ b/example/transaction_consulting_refunds.js @@ -0,0 +1,15 @@ +const eRede = require("../lib/erede"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); + +new eRede(store).getRefunds("10011910280828200220").then(transaction => { + transaction.refunds.forEach(el => { + console.log(`Transação cancelada : ${el.refundId}`); + }); +}); diff --git a/example/transaction_gateway.js b/example/transaction_gateway.js new file mode 100644 index 0000000..e6a17fe --- /dev/null +++ b/example/transaction_gateway.js @@ -0,0 +1,19 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000000)}`, 2) + .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .setAdditional(1234, 56); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); diff --git a/example/transaction_installments.js b/example/transaction_installments.js new file mode 100644 index 0000000..4701a6d --- /dev/null +++ b/example/transaction_installments.js @@ -0,0 +1,21 @@ +const eRede = require("../lib/erede"); +const Transaction = require("../lib/transaction"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); + +let store = new Store( + "TOKEN", + "PV", + Environment.sandbox() +); +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000000)}`, + 3 +).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + +new eRede(store).create(transaction).then(transaction => { + if (transaction.returnCode === "00") { + console.log(`Transação autorizada com sucesso: ${transaction.tid}`); + } +}); diff --git a/lib/additional.js b/lib/additional.js index 16f163b..856bebf 100644 --- a/lib/additional.js +++ b/lib/additional.js @@ -17,4 +17,16 @@ module.exports = class Additional { return additional; } + + setGateway(gateway) { + this.gateway = gateway; + + return this; + } + + setModule(module) { + this.module = module; + + return this; + } }; diff --git a/lib/address.js b/lib/address.js index 22eb0be..20318b2 100644 --- a/lib/address.js +++ b/lib/address.js @@ -28,4 +28,58 @@ module.exports = class Address { static get OTHER() { return 4; } + + setAddress(address) { + this.address = address; + + return this; + } + + setAddresseeName(addresseeName) { + this.addresseeName = addresseeName; + + return this; + } + + setCity(city) { + this.city = city; + + return this; + } + + setComplement(complement) { + this.complement = complement; + + return this; + } + + setNeighbourhood(neighbourhood) { + this.neighbourhood = neighbourhood; + + return this; + } + + setNumber(number) { + this.number = number; + + return this; + } + + setState(state) { + this.state = state; + + return this; + } + + setType(type) { + this.type = type; + + return this; + } + + setZipCode(zipcode) { + this.zipCode = zipcode; + + return this; + } }; diff --git a/lib/antifraud.js b/lib/antifraud.js index 0ec2042..d3bd77f 100644 --- a/lib/antifraud.js +++ b/lib/antifraud.js @@ -6,7 +6,7 @@ module.exports = class Antifraud { } static fromJSON(json) { - let antifraud = new self(); + let antifraud = new Antifraud(); for (let property in json) { if (json.hasOwnProperty(property)) { @@ -16,4 +16,32 @@ module.exports = class Antifraud { return antifraud; } + + setRecommendation(recommendation) { + this.recommendation = recommendation; + + return this; + } + + setRiskLevel(riskLevel) { + this.riskLevel = riskLevel; + + return this; + } + + setScore(score) { + this.score = score; + + return this; + } + + setSuccess(success) { + this.success = success; + + return this; + } + + isSuccess() { + return this.success; + } }; diff --git a/lib/authorization.js b/lib/authorization.js index 791e535..0bcaa11 100644 --- a/lib/authorization.js +++ b/lib/authorization.js @@ -22,4 +22,104 @@ module.exports = class Authorization { return authorization; } + + setAffiliation(affiliation) { + this.affiliation = affiliation; + + return this; + } + + setAmount(amount) { + this.amount = amount; + + return this; + } + + setAuthorizationCode(authorizationCode) { + this.authorizationCode = authorizationCode; + + return this; + } + + setCardBin(cardBin) { + this.cardBin = cardBin; + + return this; + } + + setCardHolderName(cardHolderName) { + this.cardHolderName = cardHolderName; + + return this; + } + + setDateTime(dateTime) { + this.dateTime = new Date(dateTime); + + return this; + } + + setInstallments(installments) { + this.installments = installments; + + return this; + } + + setKind(kind) { + this.kind = kind; + + return this; + } + + setLast4(last4) { + this.last4 = last4; + + return this; + } + + setNsu(nsu) { + this.nsu = nsu; + + return this; + } + + setOrigin(origin) { + this.origin = origin; + + return this; + } + + setReference(reference) { + this.reference = reference; + } + + setReturnCode(returnCode) { + this.returnCode = returnCode; + + return this; + } + + setReturnMessage(returnMessage) { + this.returnMessage = returnMessage; + + return this; + } + + setStatus(status) { + this.status = status; + + return this; + } + + setSubscription(subscription) { + this.subscription = subscription; + + return this; + } + + setTid(tid) { + this.tid = tid; + + return this; + } }; diff --git a/lib/capture.js b/lib/capture.js index f797892..fcfe26c 100644 --- a/lib/capture.js +++ b/lib/capture.js @@ -22,4 +22,22 @@ module.exports = class Capture { return capture; } + + setAmount(amount) { + this.amount = amount; + + return this; + } + + setDateTime(dateTime) { + this.dateTime = new Date(dateTime); + + return this; + } + + setNsu(nsu) { + this.nsu = nsu; + + return this; + } }; diff --git a/lib/cart.js b/lib/cart.js index 7436c52..ee93d38 100644 --- a/lib/cart.js +++ b/lib/cart.js @@ -6,7 +6,7 @@ const Iata = require("./iata"); module.exports = class Cart { address(type = Address.BOTH) { - let address = Address(); + let address = new Address(); if ((type & Address.BILLING) === Address.BILLING) { this.billing = address; @@ -19,6 +19,18 @@ module.exports = class Cart { return address; } + setBillingAddress(address) { + this.billing = address; + + return this; + } + + setShippingAddress(address) { + this.shipping = [address]; + + return this; + } + addItem(item) { if (this.items === undefined) { this.items = []; @@ -29,15 +41,39 @@ module.exports = class Cart { return this; } - setConsumer(name, email, cpf) { - this.consumer = new Consumer(name, email, cpf); + addShippingAddress(shippingAddress) { + if (this.shipping === null) { + this.shipping = []; + } + + this.shipping.push(shippingAddress); - return this.consumer; + return this; + } + + consumer(name, email, cpf) { + let consumer = new Consumer(name, email, cpf); + + this.setConsumer(consumer); + + return consumer; + } + + setConsumer(consumer) { + this.consumer = consumer; + + return this; } setIata(code, departureTax, flight) { this.iata = new Iata(code, departureTax); - this.iata.flight = flight; + this.iata.setFlight(flight); + + return this; + } + + setEnvironment(environment) { + this.environment = environment; return this; } diff --git a/lib/consumer.js b/lib/consumer.js index 5754034..f727dc1 100644 --- a/lib/consumer.js +++ b/lib/consumer.js @@ -17,6 +17,12 @@ module.exports = class Consumer { return "F"; } + setGender(type) { + this.gender = type; + + return this; + } + addDocument(type, number) { if (this.documents === undefined) { this.documents = []; diff --git a/lib/environment.js b/lib/environment.js index 97c7dca..a13ce5b 100644 --- a/lib/environment.js +++ b/lib/environment.js @@ -18,4 +18,16 @@ module.exports = class Environment { static sandbox() { return new Environment(SANDBOX, VERSION); } + + setIp(ip) { + this.ip = ip; + + return this; + } + + setSessionId(sessionId) { + this.sessionId = sessionId; + + return this; + } }; diff --git a/lib/flight.js b/lib/flight.js index cb2e370..13841bf 100644 --- a/lib/flight.js +++ b/lib/flight.js @@ -10,12 +10,12 @@ module.exports = class Flight { this.date = date; } - addPassenger(name, email, ticket) { + addPassenger(passenger) { if (this.passenger === undefined) { this.passenger = []; } - this.passenger.push(new Passenger(name, email, ticket)); + this.passenger.push(passenger); return this; } diff --git a/lib/iata.js b/lib/iata.js index 7803013..4baecbc 100644 --- a/lib/iata.js +++ b/lib/iata.js @@ -5,4 +5,33 @@ module.exports = class Iata { this.code = code; this.departureTax = departureTax; } + + setCode(code) { + this.code = code; + + return this; + } + + setDepartureTax(departureTax) { + this.departureTax = departureTax; + + return this; + } + + setFlight(flight) { + this.flight = []; + this.addFlight(flight); + + return this; + } + + addFlight(flight) { + if (this.flight === undefined) { + this.flight = []; + } + + this.flight.push(flight); + + return this; + } }; diff --git a/lib/item.js b/lib/item.js index a235a2f..28c782e 100644 --- a/lib/item.js +++ b/lib/item.js @@ -22,4 +22,52 @@ module.exports = class Item { static get AIRLINE() { return 4; } + + setAmount(amount) { + this.amount = amount; + + return this; + } + + setDescription(description) { + this.description = description; + + return this; + } + + setDiscount(discount) { + this.discount = discount; + + return this; + } + + setFreight(freight) { + this.freight = freight; + + return this; + } + + setId(id) { + this.id = id; + + return this; + } + + setQuantity(quantity) { + this.quantity = quantity; + + return this; + } + + setShippingType(shippingType) { + this.shippingType = shippingType; + + return this; + } + + setType(type) { + this.type = type; + + return this; + } }; diff --git a/lib/passenger.js b/lib/passenger.js index ea995c0..cd2abb9 100644 --- a/lib/passenger.js +++ b/lib/passenger.js @@ -6,4 +6,28 @@ module.exports = class Passenger { this.email = email; this.ticket = ticket; } + + setEmail(email) { + this.email = email; + + return this; + } + + setName(name) { + this.name = name; + + return this; + } + + setPhone(phone) { + this.phone = phone; + + return this; + } + + setTicket(ticket) { + this.ticket = ticket; + + return this; + } }; diff --git a/lib/service/GetTransactionService.js b/lib/service/GetTransactionService.js index 77fb0f4..41f9bd6 100644 --- a/lib/service/GetTransactionService.js +++ b/lib/service/GetTransactionService.js @@ -7,6 +7,8 @@ module.exports = class GetTransactionService extends TransactionService { super(store); this.tid = undefined; + this.reference = undefined; + this.refunds = undefined; } getUrl() { diff --git a/lib/transaction.js b/lib/transaction.js index c88e792..693a3a1 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -135,19 +135,25 @@ module.exports = class Transaction { return this; } + setTid(tid) { + this.tid = tid; + + return this; + } + /** * * @param environment * @returns {module.Transaction} */ setAntifraud(environment) { - let cart = Cart(); - cart.environment = environment; + let cart = new Cart(); + cart.setEnvironment(environment); this.antifraudRequired = true; this.cart = cart; - return this; + return cart; } /** @@ -294,4 +300,14 @@ module.exports = class Transaction { return this; } + + getAntifraud() { + let antifraud = this.antifraud; + + if (antifraud === null) { + antifraud = new Antifraud(); + } + + return antifraud; + } }; From efb44cff260990bbcfacf3eaf750a9c494984061 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Tue, 29 Oct 2019 14:14:12 -0300 Subject: [PATCH 04/17] adding tests --- .env.example | 2 + .env.test.example | 2 + .gitignore | 5 +- __tests__/integration/transaction.test.js | 32 ++++ __tests__/store.js | 14 ++ example/transaction.js | 1 + jest.config.js | 188 ++++++++++++++++++++++ package.json | 13 +- transaction.test.js | 20 +++ 9 files changed, 273 insertions(+), 4 deletions(-) create mode 100644 .env.example create mode 100644 .env.test.example create mode 100644 __tests__/integration/transaction.test.js create mode 100644 __tests__/store.js create mode 100644 jest.config.js create mode 100644 transaction.test.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..bd67c29 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +REDE_PV= +REDE_TOKEN= \ No newline at end of file diff --git a/.env.test.example b/.env.test.example new file mode 100644 index 0000000..bd67c29 --- /dev/null +++ b/.env.test.example @@ -0,0 +1,2 @@ +REDE_PV= +REDE_TOKEN= \ No newline at end of file diff --git a/.gitignore b/.gitignore index e41bb60..78f86d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ .idea node_modules/ package-lock.json -yarn.lock \ No newline at end of file +yarn.lock +.env.test + +__test__/coverage \ No newline at end of file diff --git a/__tests__/integration/transaction.test.js b/__tests__/integration/transaction.test.js new file mode 100644 index 0000000..6211513 --- /dev/null +++ b/__tests__/integration/transaction.test.js @@ -0,0 +1,32 @@ +require("dotenv").config({ + path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" +}); + +const eRede = require("../../lib/erede"); +const Transaction = require("../../lib/transaction"); +const Store = require("../../lib/store"); +const Environment = require("../../lib/environment"); + +describe("Transactions", () => { + let environment = + process.env.NODE_ENV === "test" + ? Environment.sandbox() + : Environment.production(); + + let store = new Store( + process.env.REDE_TOKEN, + process.env.REDE_PV, + environment + ); + + test("if user can create a transaction", async () => { + let transaction = new Transaction( + 10, + `ref${Math.ceil(Date.now())}` + ).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + + const response = await new eRede(store).create(transaction); + + expect(response.returnCode).toBe("00"); + }); +}); diff --git a/__tests__/store.js b/__tests__/store.js new file mode 100644 index 0000000..f0191a4 --- /dev/null +++ b/__tests__/store.js @@ -0,0 +1,14 @@ +require("dotenv").config({ + path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" +}); + +const Store = require("../../lib/store"); +const Environment = require("../../lib/environment"); + +module.exports = new Store( + process.env.REDE_TOKEN, + process.env.REDE_PV, + process.env.NODE_ENV === "test" + ? Environment.sandbox() + : Environment.production() +); diff --git a/example/transaction.js b/example/transaction.js index 515cd73..2649523 100644 --- a/example/transaction.js +++ b/example/transaction.js @@ -8,6 +8,7 @@ let store = new Store( "PV", Environment.sandbox() ); + let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") .autoCapture(false); diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..49b45c4 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,188 @@ +// For a detailed explanation regarding each configuration property, visit: +// https://jestjs.io/docs/en/configuration.html + +module.exports = { + // All imported modules in your tests should be mocked automatically + // automock: false, + + // Stop running tests after `n` failures + bail: true, + + // Respect "browser" field in package.json when resolving modules + // browser: false, + + // The directory where Jest should store its cached dependency information + // cacheDirectory: "/tmp/jest_rs", + + // Automatically clear mock calls and instances between every test + clearMocks: true, + + // Indicates whether the coverage information should be collected while executing the test + // collectCoverage: false, + + // An array of glob patterns indicating a set of files for which coverage information should be collected + // collectCoverageFrom: null, + + // The directory where Jest should output its coverage files + // coverageDirectory: null, + + // An array of regexp pattern strings used to skip coverage collection + // coveragePathIgnorePatterns: [ + // "/node_modules/" + // ], + + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], + + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: null, + + // A path to a custom dependency extractor + // dependencyExtractor: null, + + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, + + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], + + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: null, + + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: null, + + // A set of global variables that need to be available in all test environments + // globals: {}, + + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", + + // An array of directory names to be searched recursively up from the requiring module's location + // moduleDirectories: [ + // "node_modules" + // ], + + // An array of file extensions your modules use + // moduleFileExtensions: [ + // "js", + // "json", + // "jsx", + // "ts", + // "tsx", + // "node" + // ], + + // A map from regular expressions to module names that allow to stub out resources with a single module + // moduleNameMapper: {}, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + modulePathIgnorePatterns: ["/lib/", "/example/"], + + // Activates notifications for test results + // notify: false, + + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", + + // A preset that is used as a base for Jest's configuration + // preset: null, + + // Run tests from one or more projects + // projects: null, + + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, + + // Automatically reset mock state between every test + // resetMocks: false, + + // Reset the module registry before running each individual test + // resetModules: false, + + // A path to a custom resolver + // resolver: null, + + // Automatically restore mock state between every test + // restoreMocks: false, + + // The root directory that Jest should scan for tests and modules within + // rootDir: null, + + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], + + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", + + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + // setupFilesAfterEnv: [], + + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], + + // The test environment that will be used for testing + testEnvironment: "node", + + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, + + // Adds a location field to test results + // testLocationInResults: false, + + // The glob patterns Jest uses to detect test files + testMatch: [ + "**/__tests__/**/*.test.js?(x)" + // "**/?(*.)+(spec|test).[tj]s?(x)" + ] + + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "/node_modules/" + // ], + + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], + + // This option allows the use of a custom results processor + // testResultsProcessor: null, + + // This option allows use of a custom test runner + // testRunner: "jasmine2", + + // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href + // testURL: "http://localhost", + + // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" + // timers: "real", + + // A map from regular expressions to paths to transformers + // transform: null, + + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // "/node_modules/" + // ], + + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, + + // Indicates whether each individual test should be reported during the run + // verbose: null, + + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], + + // Whether to use watchman for file crawling + // watchman: true, +}; diff --git a/package.json b/package.json index bb01758..0edca2b 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,9 @@ "erede", "sdk" ], + "scripts": { + "test": "NODE_ENV=test jest --config=jest.config.js" + }, "repository": { "type": "git", "url": "https://github.com/DevelopersRede/erede-node.git" @@ -22,8 +25,8 @@ }, "main": "./lib/erede.js", "dependencies": { - "semver": "^5.0.3", - "bl": "^3.0.0" + "bl": "^3.0.0", + "semver": "^5.0.3" }, "config": { "blanket": { @@ -31,5 +34,9 @@ "data-cover-never": "node_modules" } }, - "readmeFilename": "README.md" + "readmeFilename": "README.md", + "devDependencies": { + "dotenv": "^8.2.0", + "jest": "^24.9.0" + } } diff --git a/transaction.test.js b/transaction.test.js new file mode 100644 index 0000000..4ae10f3 --- /dev/null +++ b/transaction.test.js @@ -0,0 +1,20 @@ +require("dotenv").config({ + path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" +}); + +const eRede = require("../../lib/erede"); +const Transaction = require("../../lib/transaction"); +const Store = require("../../lib/store"); +const Environment = require("../../lib/environment"); + +describe("Transactions", () => { + let store; + + beforeEach(() => { + store = new Store("TOKEN", "PV", Environment.sandbox()); + }); + + test("dois mais dois é quatro", () => { + expect(2 + 2).toBe(4); + }); +}); From f7512925807e93c99170d3659cb40ef0dee2d1f2 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Thu, 31 Oct 2019 16:47:55 -0300 Subject: [PATCH 05/17] refactory store and envionment --- __tests__/integration/transaction.test.js | 14 +------------- __tests__/store.js | 15 ++++++++------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/__tests__/integration/transaction.test.js b/__tests__/integration/transaction.test.js index 6211513..d783f04 100644 --- a/__tests__/integration/transaction.test.js +++ b/__tests__/integration/transaction.test.js @@ -4,21 +4,9 @@ require("dotenv").config({ const eRede = require("../../lib/erede"); const Transaction = require("../../lib/transaction"); -const Store = require("../../lib/store"); -const Environment = require("../../lib/environment"); +const store = require("../store"); describe("Transactions", () => { - let environment = - process.env.NODE_ENV === "test" - ? Environment.sandbox() - : Environment.production(); - - let store = new Store( - process.env.REDE_TOKEN, - process.env.REDE_PV, - environment - ); - test("if user can create a transaction", async () => { let transaction = new Transaction( 10, diff --git a/__tests__/store.js b/__tests__/store.js index f0191a4..1f90a2b 100644 --- a/__tests__/store.js +++ b/__tests__/store.js @@ -2,13 +2,14 @@ require("dotenv").config({ path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" }); -const Store = require("../../lib/store"); -const Environment = require("../../lib/environment"); +const Store = require("../lib/store"); +const Environment = require("../lib/environment"); -module.exports = new Store( - process.env.REDE_TOKEN, - process.env.REDE_PV, +let environment = process.env.NODE_ENV === "test" ? Environment.sandbox() - : Environment.production() -); + : Environment.production(); + +let store = new Store(process.env.REDE_TOKEN, process.env.REDE_PV, environment); + +module.exports = store; From 1f652dd2b60fe70c92e0543a6eb7babe12da3b34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio=20C=C3=A9sar?= Date: Thu, 31 Oct 2019 19:55:28 -0300 Subject: [PATCH 06/17] configure eslint and prettier --- .eslintrc.js | 21 +++++++++++++++++++++ .prettierrc | 4 ++++ __tests__/integration/transaction.test.js | 22 +++++++++++----------- __tests__/store.js | 17 ++++++++++------- package.json | 9 ++++++++- transaction.test.js | 20 -------------------- 6 files changed, 54 insertions(+), 39 deletions(-) create mode 100644 .eslintrc.js create mode 100644 .prettierrc delete mode 100644 transaction.test.js diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..e8db9f1 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,21 @@ +module.exports = { + env: { + commonjs: true, + es6: true, + node: true + }, + extends: ['airbnb-base', 'prettier'], + plugins: ['eslint-plugin-prettier'], + parser: 'babel-eslint', + globals: { + Atomics: 'readonly', + SharedArrayBuffer: 'readonly' + }, + parserOptions: { + ecmaVersion: 2018 + }, + rules: { + 'no-undef': 'off', + 'new-cap': 'off' + } +} diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..c1a6f66 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "trailingComma": "es5" +} diff --git a/__tests__/integration/transaction.test.js b/__tests__/integration/transaction.test.js index d783f04..4c70f73 100644 --- a/__tests__/integration/transaction.test.js +++ b/__tests__/integration/transaction.test.js @@ -1,20 +1,20 @@ -require("dotenv").config({ - path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" +require('dotenv').config({ + path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env', }); -const eRede = require("../../lib/erede"); -const Transaction = require("../../lib/transaction"); -const store = require("../store"); +const eRede = require('../../lib/erede'); +const Transaction = require('../../lib/transaction'); +const store = require('../store'); -describe("Transactions", () => { - test("if user can create a transaction", async () => { - let transaction = new Transaction( +describe('Transactions', () => { + test('if user can create a transaction', async () => { + const transaction = new Transaction( 10, `ref${Math.ceil(Date.now())}` - ).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); + ).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); const response = await new eRede(store).create(transaction); - expect(response.returnCode).toBe("00"); - }); + expect(response.returnCode).toBe('00'); + }, 10000); }); diff --git a/__tests__/store.js b/__tests__/store.js index 1f90a2b..3094ace 100644 --- a/__tests__/store.js +++ b/__tests__/store.js @@ -1,15 +1,18 @@ -require("dotenv").config({ - path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" +require('dotenv').config({ + path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env', }); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); -let environment = - process.env.NODE_ENV === "test" +const environment = process.env.NODE_ENV === 'test' ? Environment.sandbox() : Environment.production(); -let store = new Store(process.env.REDE_TOKEN, process.env.REDE_PV, environment); +const store = new Store( + process.env.REDE_TOKEN, + process.env.REDE_PV, + environment, +); module.exports = store; diff --git a/package.json b/package.json index 0edca2b..206dbe5 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,14 @@ }, "readmeFilename": "README.md", "devDependencies": { + "babel-eslint": "^10.0.3", "dotenv": "^8.2.0", - "jest": "^24.9.0" + "eslint": "^6.6.0", + "eslint-config-airbnb-base": "^14.0.0", + "eslint-config-prettier": "^6.5.0", + "eslint-plugin-import": "^2.18.2", + "eslint-plugin-prettier": "^3.1.1", + "jest": "^24.9.0", + "prettier": "^1.18.2" } } diff --git a/transaction.test.js b/transaction.test.js deleted file mode 100644 index 4ae10f3..0000000 --- a/transaction.test.js +++ /dev/null @@ -1,20 +0,0 @@ -require("dotenv").config({ - path: process.env.NODE_ENV === "test" ? ".env.test" : ".env" -}); - -const eRede = require("../../lib/erede"); -const Transaction = require("../../lib/transaction"); -const Store = require("../../lib/store"); -const Environment = require("../../lib/environment"); - -describe("Transactions", () => { - let store; - - beforeEach(() => { - store = new Store("TOKEN", "PV", Environment.sandbox()); - }); - - test("dois mais dois é quatro", () => { - expect(2 + 2).toBe(4); - }); -}); From 2d7ccb4125f6049d8f66db40cf147461626359d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BAlio=20C=C3=A9sar?= Date: Wed, 13 Nov 2019 14:27:14 -0300 Subject: [PATCH 07/17] tests jest --- README.md | 314 ++++++++++------------ __tests__/integration/transaction.test.js | 67 ++++- __tests__/store.js | 5 +- __tests__/transaction.js | 7 + example/transaction_antifraud.js | 50 ++-- jest.config.js | 10 +- jest.setup.js | 1 + lib/additional.js | 6 +- lib/consumer.js | 10 +- lib/transaction.js | 60 ++--- 10 files changed, 270 insertions(+), 260 deletions(-) create mode 100644 __tests__/transaction.js create mode 100644 jest.setup.js diff --git a/README.md b/README.md index c021f73..cf9f6a1 100644 --- a/README.md +++ b/README.md @@ -7,95 +7,81 @@ SDK de integração eRede ## Autorizando uma transação ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); -let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000)}` +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); - ``` Por padrão, a transação é capturada automaticamente; caso seja necessário apenas autorizar a transação, o método `Transaction.capture()` deverá ser chamado com o parâmetro `false`: ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000)}`) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal') .autoCapture(false); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); - ``` ## Autorizando uma transação com parcelamento ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); -let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000000)}`, 3) -.creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); +let transaction = new Transaction( + 10, + `ref${parseInt(Date.now() / 1000000)}`, + 3 +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); - ``` ## Adiciona informação adicional de gateway e módulo ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); let transaction = new Transaction(10, `ref${parseInt(Date.now() / 1000000)}`, 2) - .creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal") + .creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal') .setAdditional(1234, 56); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { console.log(`Transação autorizada com sucesso: ${transaction.tid}`); } }); @@ -104,54 +90,50 @@ new eRede(store).create(transaction).then(transaction => { ## Cria uma transação com Antifraude ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); -const Consumer = require("../lib/consumer"); -const Address = require("../lib/address"); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); +const Consumer = require('../lib/consumer'); +const Address = require('../lib/address'); let environment = Environment.sandbox(); -environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); +environment.setIp('127.0.0.1').setSessionId('NomeEstabelecimento-WebSessionID'); -let store = new Store( - "TOKEN", - "PV", - environment -); +let store = new Store('TOKEN', 'PV', environment); let transaction = new Transaction( 10, `ref${parseInt(Date.now() / 1000)}`, 2 -).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); let antifraud = transaction.setAntifraud(environment); antifraud - .consumer("Fulano", "fulano@mail.com", "11111111111") + .consumer('Fulano', 'fulano@mail.com', '11111111111') .setGender(Consumer.MALE) - .setPhone("011", "999999999") - .addDocument("RG", "111111111"); + .setPhone('011', '999999999') + .addDocument('RG', '111111111'); antifraud .address() - .setAddresseeName("Fulano") - .setAddress("Rua dos bobos") - .setNumber("125") - .setZipCode("01122123") - .setNeighbourhood("Bairro legal") - .setCity("Cidade Bonita") - .setState("UF") + .setAddresseeName('Fulano') + .setAddress('Rua dos bobos') + .setNumber('125') + .setZipCode('01122123') + .setNeighbourhood('Bairro legal') + .setCity('Cidade Bonita') + .setState('UF') .setType(Address.OTHER); new eRede(store) .create(transaction) .then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { antifraud = transaction.getAntifraud(); console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Antifraude: ${antifraud.isSuccess() ? 'Sucesso' : 'Falha'}`); console.log(`Score: ${antifraud.score}`); console.log(`Nível de Risco: ${antifraud.riskLevel}`); console.log(`Recomendação: ${antifraud.recommendation}`); @@ -163,61 +145,58 @@ new eRede(store) ``` ## Cria uma transação com Antifraude para companhias aéreas + ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); -const Consumer = require("../lib/consumer"); -const Phone = require("../lib/phone"); -const Address = require("../lib/address"); -const Passenger = require("../lib/passenger"); -const Flight = require("../lib/flight"); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); +const Consumer = require('../lib/consumer'); +const Phone = require('../lib/phone'); +const Address = require('../lib/address'); +const Passenger = require('../lib/passenger'); +const Flight = require('../lib/flight'); let environment = Environment.sandbox(); -environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); +environment.setIp('127.0.0.1').setSessionId('NomeEstabelecimento-WebSessionID'); -let store = new Store( - "TOKEN", - "PV", - environment -); +let store = new Store('TOKEN', 'PV', environment); let transaction = new Transaction( 10, `ref${parseInt(Date.now() / 1000)}`, 2 -).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); let antifraud = transaction.setAntifraud(environment); antifraud - .consumer("Fulano", "fulano@mail.com", "11111111111") + .consumer('Fulano', 'fulano@mail.com', '11111111111') .setGender(Consumer.MALE) - .setPhone("011", "999999999") - .addDocument("RG", "111111111"); + .setPhone('011', '999999999') + .addDocument('RG', '111111111'); antifraud .address() - .setAddresseeName("Fulano") - .setAddress("Rua dos bobos") - .setNumber("125") - .setZipCode("01122123") - .setNeighbourhood("Bairro legal") - .setCity("Cidade Bonita") - .setState("UF") + .setAddresseeName('Fulano') + .setAddress('Rua dos bobos') + .setNumber('125') + .setZipCode('01122123') + .setNeighbourhood('Bairro legal') + .setCity('Cidade Bonita') + .setState('UF') .setType(Address.OTHER); antifraud.setIata( - "code123", - "250", + 'code123', + '250', new Flight( - "123213", - "Los Angeles", - "New York", - "2017-02-15T10:54:45-9:00" + '123213', + 'Los Angeles', + 'New York', + '2017-02-15T10:54:45-9:00' ).addPassenger( - new Passenger("Arya Stark", "lorem@ipsum.com", "32423432432").setPhone( - new Phone("011", "912341234") + new Passenger('Arya Stark', 'lorem@ipsum.com', '32423432432').setPhone( + new Phone('011', '912341234') ) ) ); @@ -225,11 +204,11 @@ antifraud.setIata( new eRede(store) .create(transaction) .then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { antifraud = transaction.getAntifraud(); console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Antifraude: ${antifraud.isSuccess() ? 'Sucesso' : 'Falha'}`); console.log(`Score: ${antifraud.score}`); console.log(`Nível de Risco: ${antifraud.riskLevel}`); console.log(`Recomendação: ${antifraud.recommendation}`); @@ -241,60 +220,51 @@ new eRede(store) ``` ## Capturando uma transação + ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); new eRede(store) - .capture(new Transaction(10).setTid("10011910280828200188")) + .capture(new Transaction(10).setTid('10011910280828200188')) .then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { console.log(`Transação capturada com sucesso: ${transaction.tid}`); } }); ``` ## Cancelando uma transação + ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); new eRede(store) - .cancel(new Transaction(10).setTid("10011910280828200220")) + .cancel(new Transaction(10).setTid('10011910280828200220')) .then(transaction => { - console.log(`Transação cancelada com sucesso: ${transaction.tid}`); + console.log(`Transação cancelada com sucesso: ${transaction.tid}`); }); ``` ## Consultando uma transação pelo ID + ```js -const eRede = require("../lib/erede"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); -new eRede(store).getByTid("10011910280828200189").then(transaction => { +new eRede(store).getByTid('10011910280828200189').then(transaction => { console.log( `Transação consutada com sucesso: ${transaction.authorization.tid}, status: ${transaction.authorization.status}` ); @@ -302,18 +272,15 @@ new eRede(store).getByTid("10011910280828200189").then(transaction => { ``` ## Consultando cancelamentos de uma transação + ```js -const eRede = require("../lib/erede"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); -new eRede(store).getRefunds("10011910280828200220").then(transaction => { +new eRede(store).getRefunds('10011910280828200220').then(transaction => { transaction.refunds.forEach(el => { console.log(`Transação cancelada : ${el.refundId}`); }); @@ -321,40 +288,37 @@ new eRede(store).getRefunds("10011910280828200220").then(transaction => { ``` ## Transação com autenticação + ```js -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); -const ThreeDSecure = require("../lib/threedsecure"); -const Url = require("../lib/url"); - -let store = new Store( - "TOKEN", - "PV", - Environment.sandbox() -); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); +const ThreeDSecure = require('../lib/threedsecure'); +const Url = require('../lib/url'); + +let store = new Store('TOKEN', 'PV', Environment.sandbox()); let transaction = new Transaction( 10, `ref${parseInt(Date.now() / 1000)}` -).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); transaction.setThreeDSecure(ThreeDSecure.DECLINE_ON_FAILURE); transaction.addUrl( - "https://redirecturl.com/3ds/success", + 'https://redirecturl.com/3ds/success', Url.THREE_D_SECURE_SUCCESS ); transaction.addUrl( - "https://redirecturl.com/3ds/failure", + 'https://redirecturl.com/3ds/failure', Url.THREE_D_SECURE_FAILURE ); new eRede(store).create(transaction).then(transaction => { - if (transaction.returnCode === "220") { + if (transaction.returnCode === '220') { console.log( `Redirecione o cliente para ${transaction.threeDSecure.url} para autenticação` ); } }); -``` \ No newline at end of file +``` diff --git a/__tests__/integration/transaction.test.js b/__tests__/integration/transaction.test.js index 4c70f73..68fd359 100644 --- a/__tests__/integration/transaction.test.js +++ b/__tests__/integration/transaction.test.js @@ -1,20 +1,67 @@ -require('dotenv').config({ - path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env', -}); - const eRede = require('../../lib/erede'); -const Transaction = require('../../lib/transaction'); const store = require('../store'); +const Environment = require('../../lib/environment'); +const Address = require('../../lib/address'); +const Consumer = require('../../lib/consumer'); +const transaction = require('../transaction'); describe('Transactions', () => { test('if user can create a transaction', async () => { - const transaction = new Transaction( - 10, - `ref${Math.ceil(Date.now())}` - ).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); + transaction.reference = `ref${Math.ceil(Date.now())}`; const response = await new eRede(store).create(transaction); expect(response.returnCode).toBe('00'); - }, 10000); + }); + + test('if user can create a transaction with installments', async () => { + transaction.reference = `ref${Math.ceil(Date.now())}`; + transaction.installments = 3; + + const response = await new eRede(store).create(transaction); + + expect(response.returnCode).toBe('00'); + expect(response.installments).toBe(3); + }); + + test('if a user can create a transaction adding infomation gateway and module', async () => { + transaction.reference = `ref${Math.ceil(Date.now())}`; + transaction.setAdditional(1234, 56); + + const response = await new eRede(store).create(transaction); + expect(response.returnCode).toBe('00'); + expect(response.additional.gateway).toBe('1234'); + expect(response.additional.module).toBe('56'); + }); + + test('if user can create a transaction with antifraud', async () => { + transaction.reference = `ref${Math.ceil(Date.now())}`; + + const environment = + process.env.NODE_ENV === 'test' + ? Environment.sandbox() + : Environment.production(); + + const antifraud = transaction.setAntifraud(environment); + antifraud + .consumer('Fulano', 'fulano@mail.com', '11111111111') + .setGender(Consumer.MALE) + .setPhone('011', '999999999') + .addDocument('RG', '111111111'); + + antifraud + .address() + .setAddresseeName('Fulano') + .setAddress('Rua dos bobos') + .setNumber('125') + .setZipCode('01122123') + .setNeighbourhood('Bairro legal') + .setCity('Cidade Bonita') + .setState('UF') + .setType(Address.OTHER); + + const response = await new eRede(store).create(transaction); + + console.log(response); + }); }); diff --git a/__tests__/store.js b/__tests__/store.js index 3094ace..2b96080 100644 --- a/__tests__/store.js +++ b/__tests__/store.js @@ -5,14 +5,15 @@ require('dotenv').config({ const Store = require('../lib/store'); const Environment = require('../lib/environment'); -const environment = process.env.NODE_ENV === 'test' +const environment = + process.env.NODE_ENV === 'test' ? Environment.sandbox() : Environment.production(); const store = new Store( process.env.REDE_TOKEN, process.env.REDE_PV, - environment, + environment ); module.exports = store; diff --git a/__tests__/transaction.js b/__tests__/transaction.js new file mode 100644 index 0000000..21724ab --- /dev/null +++ b/__tests__/transaction.js @@ -0,0 +1,7 @@ +const Transaction = require('../lib/transaction'); + +module.exports = new Transaction( + 10, + `ref${Math.ceil(Date.now())}`, + 3 +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); diff --git a/example/transaction_antifraud.js b/example/transaction_antifraud.js index d52a791..947b554 100644 --- a/example/transaction_antifraud.js +++ b/example/transaction_antifraud.js @@ -1,51 +1,47 @@ -const eRede = require("../lib/erede"); -const Transaction = require("../lib/transaction"); -const Store = require("../lib/store"); -const Environment = require("../lib/environment"); -const Consumer = require("../lib/consumer"); -const Address = require("../lib/address"); +const eRede = require('../lib/erede'); +const Transaction = require('../lib/transaction'); +const Store = require('../lib/store'); +const Environment = require('../lib/environment'); +const Consumer = require('../lib/consumer'); +const Address = require('../lib/address'); -let environment = Environment.sandbox(); -environment.setIp("127.0.0.1").setSessionId("NomeEstabelecimento-WebSessionID"); +const environment = Environment.sandbox(); +environment.setIp('127.0.0.1').setSessionId('NomeEstabelecimento-WebSessionID'); -let store = new Store( - "TOKEN", - "PV", - environment -); +const store = new Store('TOKEN', 'PV', environment); -let transaction = new Transaction( +const transaction = new Transaction( 10, `ref${parseInt(Date.now() / 1000)}`, 2 -).creditCard("5448280000000007", "235", "12", "2020", "Fulano de Tal"); +).creditCard('5448280000000007', '235', '12', '2020', 'Fulano de Tal'); let antifraud = transaction.setAntifraud(environment); antifraud - .consumer("Fulano", "fulano@mail.com", "11111111111") + .consumer('Fulano', 'fulano@mail.com', '11111111111') .setGender(Consumer.MALE) - .setPhone("011", "999999999") - .addDocument("RG", "111111111"); + .setPhone('011', '999999999') + .addDocument('RG', '111111111'); antifraud .address() - .setAddresseeName("Fulano") - .setAddress("Rua dos bobos") - .setNumber("125") - .setZipCode("01122123") - .setNeighbourhood("Bairro legal") - .setCity("Cidade Bonita") - .setState("UF") + .setAddresseeName('Fulano') + .setAddress('Rua dos bobos') + .setNumber('125') + .setZipCode('01122123') + .setNeighbourhood('Bairro legal') + .setCity('Cidade Bonita') + .setState('UF') .setType(Address.OTHER); new eRede(store) .create(transaction) .then(transaction => { - if (transaction.returnCode === "00") { + if (transaction.returnCode === '00') { antifraud = transaction.getAntifraud(); console.log(`Transação autorizada com sucesso: ${transaction.tid}`); - console.log(`Antifraude: ${antifraud.isSuccess() ? "Sucesso" : "Falha"}`); + console.log(`Antifraude: ${antifraud.isSuccess() ? 'Sucesso' : 'Falha'}`); console.log(`Score: ${antifraud.score}`); console.log(`Nível de Risco: ${antifraud.riskLevel}`); console.log(`Recomendação: ${antifraud.recommendation}`); diff --git a/jest.config.js b/jest.config.js index 49b45c4..19850b2 100644 --- a/jest.config.js +++ b/jest.config.js @@ -82,7 +82,7 @@ module.exports = { // moduleNameMapper: {}, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - modulePathIgnorePatterns: ["/lib/", "/example/"], + modulePathIgnorePatterns: ['/lib/', '/example/'], // Activates notifications for test results // notify: false, @@ -126,13 +126,13 @@ module.exports = { // setupFiles: [], // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], + setupFilesAfterEnv: ['./jest.setup.js'], // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], // The test environment that will be used for testing - testEnvironment: "node", + testEnvironment: 'node', // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, @@ -142,9 +142,9 @@ module.exports = { // The glob patterns Jest uses to detect test files testMatch: [ - "**/__tests__/**/*.test.js?(x)" + '**/__tests__/**/*.test.js?(x)', // "**/?(*.)+(spec|test).[tj]s?(x)" - ] + ], // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ diff --git a/jest.setup.js b/jest.setup.js new file mode 100644 index 0000000..a9ffd51 --- /dev/null +++ b/jest.setup.js @@ -0,0 +1 @@ +jest.setTimeout(10000); // in milliseconds diff --git a/lib/additional.js b/lib/additional.js index 856bebf..bada40a 100644 --- a/lib/additional.js +++ b/lib/additional.js @@ -1,5 +1,3 @@ -"use strict"; - module.exports = class Additional { constructor(gateway, module) { this.gateway = gateway; @@ -7,9 +5,9 @@ module.exports = class Additional { } static fromJSON(json) { - let additional = new Additional(); + const additional = new Additional(); - for (let property in json) { + for (const property in json) { if (json.hasOwnProperty(property)) { additional[property] = json[property]; } diff --git a/lib/consumer.js b/lib/consumer.js index f727dc1..6ef9c6b 100644 --- a/lib/consumer.js +++ b/lib/consumer.js @@ -1,6 +1,4 @@ -"use strict"; - -const Phone = require("./phone"); +const Phone = require('./phone'); module.exports = class Consumer { constructor(name, email, cpf) { @@ -10,11 +8,11 @@ module.exports = class Consumer { } static get MALE() { - return "M"; + return 'M'; } static get FEMALE() { - return "F"; + return 'F'; } setGender(type) { @@ -28,7 +26,7 @@ module.exports = class Consumer { this.documents = []; } - this.documents.push({ type: type, number: number }); + this.documents.push({ type, number }); return this; } diff --git a/lib/transaction.js b/lib/transaction.js index 693a3a1..1ad6a51 100644 --- a/lib/transaction.js +++ b/lib/transaction.js @@ -1,14 +1,12 @@ -"use strict"; - -const Cart = require("./cart"); -const Url = require("./url"); -const Iata = require("./iata"); -const ThreeDSecure = require("./threedsecure"); -const Capture = require("./capture"); -const Authorization = require("./authorization"); -const Additional = require("./additional"); -const Antifraud = require("./antifraud"); -const Refund = require("./refund"); +const Cart = require('./cart'); +const Url = require('./url'); +const Iata = require('./iata'); +const ThreeDSecure = require('./threedsecure'); +const Capture = require('./capture'); +const Authorization = require('./authorization'); +const Additional = require('./additional'); +const Antifraud = require('./antifraud'); +const Refund = require('./refund'); module.exports = class Transaction { constructor(amount, reference, installments) { @@ -26,11 +24,11 @@ module.exports = class Transaction { } static get CREDIT() { - return "credit"; + return 'credit'; } static get DEBIT() { - return "debit"; + return 'debit'; } static get ORIGIN_EREDE() { @@ -46,19 +44,19 @@ module.exports = class Transaction { } static fromJSON(json) { - let transaction = new Transaction(json.amount, json.reference); + const transaction = new Transaction(json.amount, json.reference); - for (let property in json) { + for (const property in json) { if (!json.hasOwnProperty(property)) { continue; } - let value = json[property]; + const value = json[property]; let i = 0; let t = 0; switch (property) { - case "refunds": + case 'refunds': transaction.refunds = []; for (i = 0, t = value.length; i < t; i++) { @@ -66,7 +64,7 @@ module.exports = class Transaction { } break; - case "urls": + case 'urls': transaction.urls = []; for (i = 0, t = value.length; i < t; i++) { @@ -74,29 +72,29 @@ module.exports = class Transaction { } break; - case "capture": + case 'capture': transaction.capture = Capture.fromJSON(value); break; - case "authorization": + case 'authorization': transaction.authorization = Authorization.fromJSON(value); break; - case "additional": + case 'additional': transaction.additional = Additional.fromJSON(value); break; - case "threeDSecure": + case 'threeDSecure': transaction.threeDSecure = ThreeDSecure.fromJSON(value); break; - case "antifraud": + case 'antifraud': transaction.antifraud = Antifraud.fromJSON(value); break; - case "requestDateTime": - case "dateTime": - case "refundDateTime": + case 'requestDateTime': + case 'dateTime': + case 'refundDateTime': transaction[property] = new Date(value); break; default: @@ -147,7 +145,7 @@ module.exports = class Transaction { * @returns {module.Transaction} */ setAntifraud(environment) { - let cart = new Cart(); + const cart = new Cart(); cart.setEnvironment(environment); this.antifraudRequired = true; @@ -243,7 +241,7 @@ module.exports = class Transaction { */ autoCapture(capture = true) { if (!capture && this.kind === Transaction.DEBIT) { - throw new Error("Debit transactions will always be captured"); + throw new Error('Debit transactions will always be captured'); } this.capture = capture; @@ -289,8 +287,8 @@ module.exports = class Transaction { setThreeDSecure( onFailure = ThreeDSecure.DECLINE_ON_FAILURE, embed = true, - directoryServerTransactionId = "", - threeDIndicator = "1" + directoryServerTransactionId = '', + threeDIndicator = '1' ) { this.threeDSecure = new ThreeDSecure(); this.threeDSecure.onFailure = onFailure; @@ -302,7 +300,7 @@ module.exports = class Transaction { } getAntifraud() { - let antifraud = this.antifraud; + let { antifraud } = this; if (antifraud === null) { antifraud = new Antifraud(); From 63988dd0f66cf7da53374e0c57d177687b74a5cc Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:07:36 -0300 Subject: [PATCH 08/17] test create transaction with antifraud --- .env.test.example | 2 -- .gitignore | 2 +- __tests__/integration/transaction.test.js | 7 ++++--- jest.config.js | 6 +++--- 4 files changed, 8 insertions(+), 9 deletions(-) delete mode 100644 .env.test.example diff --git a/.env.test.example b/.env.test.example deleted file mode 100644 index bd67c29..0000000 --- a/.env.test.example +++ /dev/null @@ -1,2 +0,0 @@ -REDE_PV= -REDE_TOKEN= \ No newline at end of file diff --git a/.gitignore b/.gitignore index 78f86d7..3c597ee 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,4 @@ package-lock.json yarn.lock .env.test -__test__/coverage \ No newline at end of file +__tests__/coverage \ No newline at end of file diff --git a/__tests__/integration/transaction.test.js b/__tests__/integration/transaction.test.js index 68fd359..39020be 100644 --- a/__tests__/integration/transaction.test.js +++ b/__tests__/integration/transaction.test.js @@ -44,7 +44,7 @@ describe('Transactions', () => { const antifraud = transaction.setAntifraud(environment); antifraud - .consumer('Fulano', 'fulano@mail.com', '11111111111') + .consumer('Fulano', 'fulano@mail.com', '09444956059') .setGender(Consumer.MALE) .setPhone('011', '999999999') .addDocument('RG', '111111111'); @@ -61,7 +61,8 @@ describe('Transactions', () => { .setType(Address.OTHER); const response = await new eRede(store).create(transaction); - - console.log(response); + expect(response.returnCode).toBe('00'); + expect(response.antifraud.success).toBe(true); + expect(response.returnMessage).toBe('Success.'); }); }); diff --git a/jest.config.js b/jest.config.js index 19850b2..6fbfaa4 100644 --- a/jest.config.js +++ b/jest.config.js @@ -18,13 +18,13 @@ module.exports = { clearMocks: true, // Indicates whether the coverage information should be collected while executing the test - // collectCoverage: false, + collectCoverage: true, // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: null, + collectCoverageFrom: ["lib/**"], // The directory where Jest should output its coverage files - // coverageDirectory: null, + coverageDirectory: "__tests__/coverage", // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ From 96569ba79e8a0a18fbf106302cb917af14169d63 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:22:07 -0300 Subject: [PATCH 09/17] add travis ci --- .travis.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..2b6453b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: node_js +node_js: + - 12 + +cache: + npm: false + yarn: true + +before_install: + - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version version-number + - export PATH="$HOME/.yarn/bin:$PATH" + +script: + - yarn install + - yarn jest From 24254626961f3a43526de12597e51327ce05453f Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:24:56 -0300 Subject: [PATCH 10/17] update travis yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2b6453b..58f7140 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,7 @@ cache: yarn: true before_install: - - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version version-number + - curl -o- -L https://yarnpkg.com/install.sh | bash -s - export PATH="$HOME/.yarn/bin:$PATH" script: From 43ecb4d372a525f31fd1b8ab4f90bf9acc333348 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:30:17 -0300 Subject: [PATCH 11/17] rempve coverage --- .travis.yml | 2 +- jest.config.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 58f7140..1007c10 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,4 +12,4 @@ before_install: script: - yarn install - - yarn jest + - yarn test diff --git a/jest.config.js b/jest.config.js index 6fbfaa4..bd1f5a8 100644 --- a/jest.config.js +++ b/jest.config.js @@ -18,13 +18,13 @@ module.exports = { clearMocks: true, // Indicates whether the coverage information should be collected while executing the test - collectCoverage: true, + // collectCoverage: true, // An array of glob patterns indicating a set of files for which coverage information should be collected - collectCoverageFrom: ["lib/**"], + // collectCoverageFrom: ["lib/**"], // The directory where Jest should output its coverage files - coverageDirectory: "__tests__/coverage", + // coverageDirectory: "__tests__/coverage", // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ From dfee8e5495d2b131e292d22c15351955ec93b922 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:34:53 -0300 Subject: [PATCH 12/17] add test rede pv and rede token --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index 1007c10..8b407a1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,10 @@ language: node_js node_js: - 12 +env: + - REDE_PV=10004605 + - REDE_TOKEN=a53ecd5be25c4069b2a21b004b9c4872 + cache: npm: false yarn: true From e7a1419501184be990ef3a91fe784e7ab096f3bb Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:46:16 -0300 Subject: [PATCH 13/17] add commento echo --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 8b407a1..264ade9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,5 +15,6 @@ before_install: - export PATH="$HOME/.yarn/bin:$PATH" script: + - echo ${REDE_PV} ${REDE_TOKEN} - yarn install - yarn test From ad6dcf7ea4bfb84f5b7627b0a5babdc3d08c593f Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 15:52:26 -0300 Subject: [PATCH 14/17] add token and pv --- .travis.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 264ade9..04f9ec3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,13 @@ language: node_js node_js: + - 8 + - 9 + - 10 + - 11 - 12 env: - - REDE_PV=10004605 - - REDE_TOKEN=a53ecd5be25c4069b2a21b004b9c4872 + - REDE_PV=10004605 REDE_TOKEN=a53ecd5be25c4069b2a21b004b9c4872 cache: npm: false From f536b8d2142cd2dd1dc7b67bb2ac85a824c6a892 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 16:03:40 -0300 Subject: [PATCH 15/17] set 15 segs to async --- .travis.yml | 1 - jest.setup.js | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 04f9ec3..9ba3484 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,5 @@ before_install: - export PATH="$HOME/.yarn/bin:$PATH" script: - - echo ${REDE_PV} ${REDE_TOKEN} - yarn install - yarn test diff --git a/jest.setup.js b/jest.setup.js index a9ffd51..ecf3cb2 100644 --- a/jest.setup.js +++ b/jest.setup.js @@ -1 +1 @@ -jest.setTimeout(10000); // in milliseconds +jest.setTimeout(15000); // in milliseconds From 76ffbe1018fc6651527af91d232c046c22f8ab39 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 16:17:43 -0300 Subject: [PATCH 16/17] remove node 9 --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9ba3484..1f4d598 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: node_js node_js: - 8 - - 9 - 10 - 11 - 12 From 784aa7cfbfb2879743cb09aee72515e8abdd09a7 Mon Sep 17 00:00:00 2001 From: Julio Cesar Date: Wed, 13 Nov 2019 16:31:00 -0300 Subject: [PATCH 17/17] add bagde travisci --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cf9f6a1..e401c98 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # SDK Node.js +[![Build Status](https://travis-ci.com/juliosouzam/erede-node.svg?branch=master)](https://travis-ci.com/juliosouzam/erede-node) SDK de integração eRede