UNPKG

forest-express

Version:

Official package for all Forest Express Lianas

81 lines (80 loc) 2.74 kB
"use strict"; var P = require('bluebird'); var logger = require('../../../services/logger'); var dataUtil = require('../../../utils/data'); function InvoicesGetter(Implementation, params, opts, integrationInfo) { var stripe = opts.integrations.stripe.stripe(opts.integrations.stripe.apiKey); var collectionModel = null; function hasPagination() { return params.page; } function getLimit() { if (hasPagination()) { return params.page.size || 10; } return 10; } function getStartingAfter() { if (hasPagination() && params.starting_after) { return params.starting_after; } return undefined; } function getEndingBefore() { if (hasPagination() && params.ending_before) { return params.ending_before; } return undefined; } function getInvoices(query) { return new P(function (resolve, reject) { stripe.invoices.list(query, function (err, invoices) { if (err) { return reject(err); } return resolve([invoices.total_count, invoices.data]); }); }); } this.perform = function () { collectionModel = integrationInfo.collection; var collectionFieldName = integrationInfo.field, embeddedPath = integrationInfo.embeddedPath; var fieldName = embeddedPath ? "".concat(collectionFieldName, ".").concat(embeddedPath) : collectionFieldName; return Implementation.Stripe.getCustomer(collectionModel, collectionFieldName, params.recordId).then(function (customer) { var query = { limit: getLimit(), starting_after: getStartingAfter(), ending_before: getEndingBefore(), 'include[]': 'total_count' }; if (customer && !!customer[collectionFieldName]) { query.customer = dataUtil.find(customer[collectionFieldName], embeddedPath); } if (customer && !query.customer) { return P.resolve([0, []]); } return getInvoices(query).spread(function (count, invoices) { return P.map(invoices, function (invoice) { if (customer) { invoice.customer = customer; } else { return Implementation.Stripe.getCustomerByUserField(collectionModel, fieldName, invoice.customer).then(function (customerFound) { invoice.customer = customerFound; return invoice; }); } return invoice; }).then(function (invoicesData) { return [count, invoicesData]; }); })["catch"](function (error) { logger.warn('Stripe invoices retrieval issue: ', error); return P.resolve([0, []]); }); }, function () { return P.resolve([0, []]); }); }; } module.exports = InvoicesGetter;