<commit_before>/*
* @Author: mike
* @Date:   2016-04-10 11:33:11
* @Last Modified 2016-04-16
* @Last Modified time: 2016-04-16 20:54:03
*/

'use strict';

import Subscription from './models/subscription.js'

import stripe from 'stripe'

export default class Stripe {
  constructor(app) {
    this.app = app;
    this.opts = this.app.config.stripe
    
    let defaultConfig = {
      privateKey: "",
      publicKey: "",
      template: "page"
    }
    
    app.writeDefaultConfig('stripe', defaultConfig)

    this._setupModels()
    this._setupMiddleware()
    this._setupRoutes()
    this._setupTemplates()
    this._setupStripe()

    app.get('stripe').use(this).respond('applyCoupon')
  }

  _setupTemplates() {
    this.app.get('templater').templateDir(__dirname+"/../templates/pages", this.opts.template)
    this.app.get('templater').templateDir(__dirname+"/../templates/partials")
    this.app.get('templater').templateDir(__dirname+"/../templates/emails")
  }

  _setupStripe() {
    this.stripe = stripe(this.opts.privateKey)
  }

  _setupModels() {
    this.app.get('storage').model(Subscription)
    this.app.get('storage').on('model.create.user', (identity, record) => {
      this.app.get('storage').getModel('subscription').then((Subscription) => {
        return Subscription.create({user: record})
      })
    })
  }

  _setupMiddleware() {
    this.app.get('router').middleware((req, res, next) => {
      if(!req.user) return next()
      return this.app.get('storage').getModel('subscription').then((Subscription) => {
        return Subscription.findOne().where({user: req.user.id}).then((subscription) => {
          if(subscription) req.subscription = subscription
          next()
        })
      })
    })
  }

  _setupRoutes() {
    let router = this.app.get('router')
    router.route("post", "/payment/process/:id", this._process.bind(this))
    router.route("/payment/:id", this._payment.bind(this))
    router.route("/profile/subscription", this._subscription.bind(this))
    router.route("/profile/subscription/change", this._subscriptionChange.bind(this))
    router.route("/profile/subscription/cancel", this._subscriptionCancel.bind(this))
    router.route("/profile/billing", this._billing.bind(this))
    router.route("post", "/profile/subscription/save", this._subscriptionSave.bind(this))
    router.route("post", "/profile/subscription/cancel", this._subscriptionCancelSave.bind(this))
    router.route("post", "/profile/billing/update/:id", this._billingUpdate.bind(this))

    router.route('post', '/stripe/webhook', this._processWebhook.bind(this))
  }

  applyCoupon(subscription, coupon) {
    if(!subscription || !coupon) throw new Error('Subscription or coupon not valid')
    let models = {}
    return this.app.get('storage').getModels('subscription').then((Subscription) => {
      models.Subscription = Subscription
      return this.stripe.customers.updateSubscription(subscription.customer.id, subscription.customer.subscriptions.data[0].id, {
        coupon: coupon
      })
    }).then((sub) => {
      subscription.customer.subscriptions.data[0] = sub
      return models.Subscription.update({user: subscription.user}, subscription)
    });
  }

  _processWebhook(req, res) {
    var promise
    let eventRaw = req.body
    this.app.log.debug('Strip Webhook received', eventRaw)
    if(eventRaw.livemode)<commit_msg>Fixed bug with saving stripe subscription<commit_after>/*
* @Author: mike
* @Date:   2016-04-10 11:33:11
* @Last Modified 2016-04-16
* @Last Modified time: 2016-04-16 20:55:49
*/

'use strict';

import Subscription from './models/subscription.js'

import stripe from 'stripe'

export default class Stripe {
  constructor(app) {
    this.app = app;
    this.opts = this.app.config.stripe
    
    let defaultConfig = {
      privateKey: "",
      publicKey: "",
      template: "page"
    }
    
    app.writeDefaultConfig('stripe', defaultConfig)

    this._setupModels()
    this._setupMiddleware()
    this._setupRoutes()
    this._setupTemplates()
    this._setupStripe()

    app.get('stripe').use(this).respond('applyCoupon')
  }

  _setupTemplates() {
    this.app.get('templater').templateDir(__dirname+"/../templates/pages", this.opts.template)
    this.app.get('templater').templateDir(__dirname+"/../templates/partials")
    this.app.get('templater').templateDir(__dirname+"/../templates/emails")
  }

  _setupStripe() {
    this.stripe = stripe(this.opts.privateKey)
  }

  _setupModels() {
    this.app.get('storage').model(Subscription)
    this.app.get('storage').on('model.create.user', (identity, record) => {
      this.app.get('storage').getModel('subscription').then((Subscription) => {
        return Subscription.create({user: record})
      })
    })
  }

  _setupMiddleware() {
    this.app.get('router').middleware((req, res, next) => {
      if(!req.user) return next()
      return this.app.get('storage').getModel('subscription').then((Subscription) => {
        return Subscription.findOne().where({user: req.user.id}).then((subscription) => {
          if(subscription) req.subscription = subscription
          next()
        })
      })
    })
  }

  _setupRoutes() {
    let router = this.app.get('router')
    router.route("post", "/payment/process/:id", this._process.bind(this))
    router.route("/payment/:id", this._payment.bind(this))
    router.route("/profile/subscription", this._subscription.bind(this))
    router.route("/profile/subscription/change", this._subscriptionChange.bind(this))
    router.route("/profile/subscription/cancel", this._subscriptionCancel.bind(this))
    router.route("/profile/billing", this._billing.bind(this))
    router.route("post", "/profile/subscription/save", this._subscriptionSave.bind(this))
    router.route("post", "/profile/subscription/cancel", this._subscriptionCancelSave.bind(this))
    router.route("post", "/profile/billing/update/:id", this._billingUpdate.bind(this))

    router.route('post', '/stripe/webhook', this._processWebhook.bind(this))
  }

  applyCoupon(subscription, coupon) {
    if(!subscription || !coupon) throw new Error('Subscription or coupon not valid')
    let models = {}
    return this.app.get('storage').getModel('subscription').then((Subscription) => {
      models.Subscription = Subscription
      return this.stripe.customers.updateSubscription(subscription.customer.id, subscription.customer.subscriptions.data[0].id, {
        coupon: coupon
      })
    }).then((sub) => {
      subscription.customer.subscriptions.data[0] = sub
      return models.Subscription.update({user: subscription.user}, subscription)
    });
  }

  _processWebhook(req, res) {
    var promise
    let eventRaw = req.body
    this.app.log.debug('Strip Webhook received', eventRaw)
    if(eventRaw.livemode)
{'fraction_non_alphanumeric': 0.16437951896119227, 'fraction_numerical': 0.011214401652648665, 'mean_word_length': 3.680939226519337, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '597702', 'n_tokens_mistral': 2113, 'n_tokens_neox': 2098, 'n_words': 304}