ticketvr
Version:
check your ticketVR balance in the command line - Brazilian tickets only
218 lines (167 loc) • 5.99 kB
text/coffeescript
ticketVR = require 'commander'
request = require 'request'
fs = require 'fs'
userhome = require 'userhome'
clc = require 'cli-color'
updateNotifier = require 'update-notifier'
Insight = require 'insight'
pkg = require '../package.json'
#ANALYTICS CONFIG
insight = new Insight
packageName : pkg.name
packageVersion: pkg.version
trackingCode : 'UA-5427757-46'
if insight.optOut == undefined
return insight.askPermission()
#CLEAN CARDS
String::clean = ->
@.replace /[ -.]/g, ''
#DEFAULTS
defaults =
base : "http://www.ticket.com.br/portal-web/consult-card"
random: () ->
Math.random()
url : (type, card) ->
"#{@base}/balance/json?chkProduto=TR&card=#{card}&rand=#{@random}"
tUrl : (card, token, rows) ->
"#{@base}/release/json?txtOperacao=lancamentos&token=#{token}&card=#{card}&rows=#{rows}&rand=#{@random}"
list : ['Ticket Restaurante', 'Ticket Alimentação']
types: ['TR', 'TA']
file : userhome '.ticketVR.json'
#MAIN FUNCTIONS OF THE PROGRAM
ticketVR
.version(pkg.version)
.option('-r, --remove', 'Remover os cartões salvos')
.option('-l, --list [value]', 'Listar últimas transações. Ex: ticketVR -l 10', parseInt)
.parse(process.argv)
#NOTIFY IF HAS ANY UPDATE
notifier = updateNotifier
packagePath: '../package'
if notifier.update
notifier.notify()
#MAKE REQUEST
makeRequest = (type, card, callback) ->
#generate the url
options =
headers:
"Host" : "www.ticket.com.br"
"Referer" : "http://www.ticket.com.br/portal/portalcorporativo/home/home.htm"
"X-Requested-With": "XMLHttpRequest"
"Accept" : "application/json, text/javascript, */*; q=0.01"
url: defaults.url type, card
request options, (err, res, body) ->
if !err and res.statusCode == 200
#parse result
result = JSON.parse body
if err or !result.status
showError(result.messageError, card)
else
showResult(type, clc.blue(result.card.balance.value))
if ticketVR.list
val = if typeof ticketVR.list == 'number' then ticketVR.list else 6
getTransactionList(card, result.token, val)
showScheduling result.card.scheduling
#if has a callback execute
if typeof callback == "function"
callback()
else
console.log '----------------------------------'
console.log clc.red("Não foi possível conectar com o servidor :(\nVerifique sua conexão com a internet.")
console.log '----------------------------------'
process.stdin.destroy()
#GET TRANSACTION LIST
getTransactionList = (card, token, rows) ->
options =
headers:
"Host" : "www.ticket.com.br"
"Referer" : "http://www.ticket.com.br/portal/portalcorporativo/usuario/consulte-seu-saldo/consulte-seu-saldo.htm?card=#{card}&token=#{token}"
"X-Requested-With": "XMLHttpRequest"
"Accept" : "application/json, text/javascript, */*; q=0.01"
url: defaults.tUrl card, token, rows
request options, (err, res, body) ->
#parse result
result = JSON.parse body
if err or !result.status
showError(result.messageError, token)
else
showTransactionList result.card.release
#GET USER CARDS
checkCards = (type, file, callback) ->
if fs.existsSync file
data = fs.readFileSync file, 'utf8'
json = JSON.parse data
if !!json[type]
defaults.cards = json[type]
callback true
else
callback false
else
callback false
#SHOW TRANSACTION LIST
showTransactionList = (itens) ->
if itens.length > 0
console.log "Últimas transações:"
itens.forEach (iten) ->
console.log " • #{iten.date} | %s | #{iten.description}", clc.red("R$" + iten.value)
console.log '----------------------------------'
#SHOW SCHEDULING
showScheduling = (itens) ->
if itens.length > 0
itens.forEach (iten) ->
console.log "Próximo depósito no dia %s no valor de R$ %s", clc.blue(iten.date), clc.blue(iten.value)
console.log "Motivo: #{iten.description}"
console.log '----------------------------------'
#SHOW RESULT OF REQUEST
showResult = (type, value) ->
console.log '----------------------------------'
console.log ' O saldo do seu %s é R$ %s', type, value
console.log '----------------------------------'
#terminate the process
process.stdin.destroy()
#SHOW ERROR
showError = (err, card) ->
console.log clc.red('ERRO')
console.log clc.red('%s: %s'), err, card
insight.track 'error', 'err'
#terminate the process
process.stdin.destroy()
#WRITE THE FILE
writeFile = (file, type, card) ->
if fs.existsSync file
data = fs.readFileSync file, 'utf8'
json = JSON.parse data
else
json = {}
json[type] = card.clean()
fs.writeFileSync file, JSON.stringify(json, null, 4)
console.log "Seu cartão foi salvo com sucesso!\nPara apagar use o comando 'ticketVR -r'\n----------------------------------"
#track cards saved
insight.track 'cards', 'saved'
#START THE PROGRAM
console.log '----------------------------------'
console.log "Escolha o tipo de cartão:"
#remove saved cards with argument -r
if ticketVR.remove
fs.unlinkSync defaults.file
#track card deleted
insight.track 'cards', 'deleted'
#choose type of card
ticketVR.choose defaults.list, (i) ->
type = defaults.types[i]
list = defaults.list[i]
#track type of card
if ticketVR.list
insight.track 'cards', 'list', 'type', type
else
insight.track 'cards', 'type', type
#check the card
checkCards type, defaults.file, (exist) ->
#if you have a card saved
if exist
makeRequest type, defaults.cards.clean()
#else ask for the card number
else
ticketVR.prompt "Número do #{list}: ", /\b(?:\d[ -.]*?){16}\b/, (card) ->
#make the request
makeRequest type, card.clean(), ->
writeFile defaults.file, type, card