This repository has been archived by the owner on Oct 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
crm.coffee
56 lines (49 loc) · 1.77 KB
/
crm.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# create 'Case' objects in CRM when we see
# device failures
#
through = require('through')
salesforce = require("node-salesforce")
redis = require('./configure').createRedisClient()
RATE_LIMIT = parseInt(process.env.RATE_LIMIT || 60)
cols = (name) ->
sf = new salesforce.Connection()
sf.login process.env.CRM_USERNAME, process.env.CRM_PASSWORD, (err, sub) ->
sf.sobject(name).describe (err, meta) ->
console.log field.name for field in meta.fields
decode = (code) ->
if message = process.env["CODE_#{code}"]
message
else
'Sensor Failed'
with_the_force = (cb) ->
sf = new salesforce.Connection()
sf.login process.env.CRM_USERNAME,
process.env.CRM_PASSWORD,
(err, user) -> cb err, sf
rate_limit = (key, callback) ->
redis.get key, (err, value) ->
callback() unless value
redis.setex key, RATE_LIMIT, (new Date()).getTime(), redis.print
open_case = (data) ->
return unless data.failure
open_the_case = ->
with_the_force (err, sf) ->
console.log(err) if err
sf.sobject('Case').create
Type: data.type || 'Electrical'
OwnerId: process.env.OWNER_ID || "005i0000000dHa7"
Reason: decode(data.code)
ContactId: process.env.CONTACT_ID || '003i0000008BypF'
Device_Id__c: data.device_id
Product__c: "#{data.device_type || 'Virtual'} Thermostat"
Sensor_Location__Latitude__s: data.lat || 42
Sensor_Location__Longitude__s: data.long || 42
Error_Code__c: data.code,
(err, ret) ->
console.log(err) if err
console.log("success=#{ret.success} case_id=#{ret.id}") unless err
key = "#{data.device_id}:#{data.code}"
rate_limit(key, open_the_case)
exports.log_drain = (req, res) ->
req.body.pipe(through(open_case)) if req.body
res.send('OK')