Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50640 views
1
###
2
Sync remote stripe view of all users with our local via (in our database).
3
4
Should get done eventually mostly via webhooks, etc., -- but for now this is OK.
5
###
6
7
fs = require('fs')
8
async = require('async')
9
10
misc = require('smc-util/misc')
11
{defaults, required} = misc
12
13
exports.stripe_sync = (opts) ->
14
opts = defaults opts,
15
dump_only : false
16
logger : undefined
17
database : required
18
cb : undefined
19
20
dbg = (m) -> opts.logger?.debug("stripe_sync: #{m}")
21
dbg()
22
users = undefined
23
target = undefined
24
25
async.series([
26
(cb) ->
27
require('./connect').init_stripe
28
logger : opts.logger
29
database : opts.database
30
cb : cb
31
(cb) ->
32
dbg("get all customers from the database with stripe -- this is a full scan of the database and will take a while")
33
# TODO: we could make this faster by putting an index on the stripe_customer_id field.
34
opts.database._query
35
query : 'SELECT account_id, stripe_customer_id, stripe_customer FROM accounts WHERE stripe_customer_id IS NOT NULL'
36
cb : (err, x) ->
37
users = x?.rows
38
cb(err)
39
(cb) ->
40
dbg("dump stripe_customer data to file for statistical analysis")
41
target = "#{process.env.HOME}/stripe/"
42
fs.exists target, (exists) ->
43
if not exists
44
fs.mkdir(target, cb)
45
else
46
cb()
47
(cb) ->
48
dbg('actually writing customer data')
49
# NOTE: Of coure this is potentially one step out of date -- but in theory this should always be up to date
50
dump = []
51
for x in users
52
# these could all be embarassing if this backup "got out" -- remove anything about actual credit card
53
# and person's name/email.
54
y = misc.copy_with(x.stripe_customer, ['created', 'subscriptions', 'metadata'])
55
y.subscriptions = y.subscriptions?.data
56
y.metadata = y.metadata?.account_id?.slice(0,8)
57
dump.push(y)
58
fs.writeFile("#{target}/stripe_customers-#{misc.to_iso(new Date())}.json", misc.to_json(dump), cb)
59
(cb) ->
60
if opts.dump_only
61
cb()
62
return
63
dbg("got #{users.length} users with stripe info")
64
stripe = require('./connect').get_stripe()
65
f = (x, cb) ->
66
dbg("updating customer #{x.account_id} data to our local database")
67
opts.database.stripe_update_customer
68
account_id : x.account_id
69
stripe : stripe
70
customer_id : x.stripe_customer_id
71
cb : cb
72
async.mapLimit(users, 3, f, cb)
73
], (err) ->
74
if err
75
dbg("error updating customer info -- #{err}")
76
else
77
dbg("updated all customer info successfully")
78
opts.cb?(err)
79
)
80
81