2015-03-19 18:02:45 -04:00
|
|
|
mongoose = require 'mongoose'
|
2015-03-21 21:49:32 -04:00
|
|
|
config = require '../../server_config'
|
|
|
|
PrepaidSchema = new mongoose.Schema {}, {strict: false, minimize: false,read:config.mongo.readpref}
|
2015-03-19 18:02:45 -04:00
|
|
|
|
2015-09-25 13:03:44 -04:00
|
|
|
PrepaidSchema.index({code: 1}, { unique: true })
|
2015-11-02 16:35:47 -05:00
|
|
|
PrepaidSchema.index({'redeemers.userID': 1})
|
2015-09-25 13:03:44 -04:00
|
|
|
|
2015-06-05 09:48:09 -04:00
|
|
|
PrepaidSchema.statics.generateNewCode = (done) ->
|
|
|
|
tryCode = ->
|
2015-10-07 17:06:09 -04:00
|
|
|
code = _.sample("abcdefghijklmnopqrstuvwxyz0123456789", 8).join('')
|
2015-06-05 09:48:09 -04:00
|
|
|
Prepaid.findOne code: code, (err, prepaid) ->
|
|
|
|
return done() if err
|
|
|
|
return done(code) unless prepaid
|
|
|
|
tryCode()
|
|
|
|
tryCode()
|
2015-11-02 16:06:58 -05:00
|
|
|
|
|
|
|
PrepaidSchema.pre('save', (next) ->
|
|
|
|
@set('exhausted', @get('maxRedeemers') <= _.size(@get('redeemers')))
|
|
|
|
next()
|
|
|
|
)
|
2015-06-05 09:48:09 -04:00
|
|
|
|
2015-11-10 14:27:46 -05:00
|
|
|
PrepaidSchema.post 'init', (doc) ->
|
|
|
|
doc.set('maxRedeemers', parseInt(doc.get('maxRedeemers')))
|
|
|
|
|
2015-03-19 18:02:45 -04:00
|
|
|
module.exports = Prepaid = mongoose.model('prepaid', PrepaidSchema)
|