2020-08-12 11:18:30 +03:00
|
|
|
const _ = require('lodash');
|
|
|
|
const uuid = require('uuid');
|
|
|
|
const ObjectId = require('bson-objectid');
|
|
|
|
const moment = require('moment-timezone');
|
|
|
|
const errors = require('@tryghost/errors');
|
2021-06-15 19:01:22 +03:00
|
|
|
const debug = require('@tryghost/debug')('importer:members');
|
2020-08-12 11:18:30 +03:00
|
|
|
const membersService = require('../index');
|
2020-08-18 15:39:45 +03:00
|
|
|
const models = require('../../../models');
|
2021-05-03 19:29:44 +03:00
|
|
|
const i18n = require('../../../../shared/i18n');
|
2021-06-15 17:36:27 +03:00
|
|
|
const logging = require('@tryghost/logging');
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
const handleUnrecognizedError = (error) => {
|
|
|
|
if (!errors.utils.isIgnitionError(error)) {
|
|
|
|
return new errors.DataImportError({
|
|
|
|
message: error.message,
|
|
|
|
context: error.context,
|
|
|
|
err: error
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
};
|
2020-08-18 15:39:45 +03:00
|
|
|
|
2020-08-27 12:47:00 +03:00
|
|
|
const doImport = async ({members, labels, importSetLabels, createdBy}) => {
|
|
|
|
debug(`Importing members: ${members.length}, labels: ${labels.length}, import lables: ${importSetLabels.length}, createdBy: ${createdBy}`);
|
2020-08-18 15:39:45 +03:00
|
|
|
|
2020-08-20 08:41:47 +03:00
|
|
|
let {
|
2020-08-18 15:39:45 +03:00
|
|
|
invalidMembers,
|
|
|
|
membersToInsert,
|
|
|
|
stripeCustomersToFetch,
|
|
|
|
stripeCustomersToCreate,
|
|
|
|
labelAssociationsToInsert
|
2020-08-27 12:47:00 +03:00
|
|
|
} = getMemberData({members, labels, importSetLabels, createdBy});
|
2020-08-18 15:39:45 +03:00
|
|
|
|
2020-08-20 08:41:47 +03:00
|
|
|
// NOTE: member insertion has to happen before the rest of insertions to handle validation
|
|
|
|
// errors - remove failed members from label/stripe sets
|
2020-08-20 11:24:05 +03:00
|
|
|
debug(`Starting insert of ${membersToInsert.length} members`);
|
2020-08-20 08:41:47 +03:00
|
|
|
const insertedMembers = await models.Member.bulkAdd(membersToInsert).then((insertResult) => {
|
2020-08-20 11:24:05 +03:00
|
|
|
if (insertResult.unsuccessfulRecords.length) {
|
|
|
|
const unsuccessfulIds = insertResult.unsuccessfulRecords.map(r => r.id);
|
|
|
|
|
2020-08-20 08:41:47 +03:00
|
|
|
labelAssociationsToInsert = labelAssociationsToInsert
|
2020-08-20 11:24:05 +03:00
|
|
|
.filter(la => !unsuccessfulIds.includes(la.member_id));
|
2020-08-20 08:41:47 +03:00
|
|
|
|
|
|
|
stripeCustomersToFetch = stripeCustomersToFetch
|
2020-08-20 11:24:05 +03:00
|
|
|
.filter(sc => !unsuccessfulIds.includes(sc.member_id));
|
2020-08-20 08:41:47 +03:00
|
|
|
|
|
|
|
stripeCustomersToCreate = stripeCustomersToCreate
|
2020-08-20 11:24:05 +03:00
|
|
|
.filter(sc => !unsuccessfulIds.includes(sc.member_id));
|
|
|
|
}
|
|
|
|
|
|
|
|
debug(`Finished inserting members with ${insertResult.errors.length} errors`);
|
|
|
|
if (insertResult.errors.length) {
|
|
|
|
insertResult.errors = insertResult.errors.map((error) => {
|
|
|
|
if (error.code === 'ER_DUP_ENTRY') {
|
|
|
|
return new errors.ValidationError({
|
|
|
|
message: i18n.t('errors.models.member.memberAlreadyExists.message'),
|
2020-09-10 07:03:57 +03:00
|
|
|
context: i18n.t('errors.models.member.memberAlreadyExists.context', {
|
|
|
|
action: 'add'
|
|
|
|
}),
|
2020-08-20 11:24:05 +03:00
|
|
|
err: error
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return handleUnrecognizedError(error);
|
|
|
|
}
|
|
|
|
});
|
2020-08-20 08:41:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return insertResult;
|
|
|
|
});
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const fetchedStripeCustomersPromise = fetchStripeCustomers(stripeCustomersToFetch);
|
|
|
|
const createdStripeCustomersPromise = createStripeCustomers(stripeCustomersToCreate);
|
2020-08-20 11:24:05 +03:00
|
|
|
|
|
|
|
debug(`Starting insert of ${labelAssociationsToInsert.length} label associations`);
|
|
|
|
const insertedLabelsPromise = models.Base.Model.bulkAdd(labelAssociationsToInsert, 'members_labels')
|
|
|
|
.then((insertResult) => {
|
|
|
|
debug(`Finished inserting member label associations with ${insertResult.errors.length} errors`);
|
|
|
|
return insertResult;
|
|
|
|
});
|
2020-08-18 15:39:45 +03:00
|
|
|
|
|
|
|
const insertedCustomersPromise = Promise.all([
|
|
|
|
fetchedStripeCustomersPromise,
|
2020-08-20 08:41:47 +03:00
|
|
|
createdStripeCustomersPromise
|
2020-08-18 15:39:45 +03:00
|
|
|
]).then(
|
2020-08-20 08:41:47 +03:00
|
|
|
([fetchedStripeCustomers, createdStripeCustomers]) => {
|
2020-08-20 11:24:05 +03:00
|
|
|
const stripeCustomersToInsert = fetchedStripeCustomers.customersToInsert.concat(createdStripeCustomers.customersToInsert);
|
|
|
|
|
|
|
|
debug(`Starting insert of ${stripeCustomersToInsert.length} stripe customers`);
|
|
|
|
return models.MemberStripeCustomer.bulkAdd(stripeCustomersToInsert).then((insertResult) => {
|
|
|
|
debug(`Finished inserting stripe customers with ${insertResult.errors.length} errors`);
|
|
|
|
|
|
|
|
if (insertResult.errors.length) {
|
|
|
|
insertResult.errors = insertResult.errors.map((error) => {
|
|
|
|
if (error.code === 'ER_DUP_ENTRY') {
|
|
|
|
return new errors.ValidationError({
|
|
|
|
message: i18n.t('errors.models.member_stripe_customer.customerAlreadyExists.message'),
|
|
|
|
context: i18n.t('errors.models.member_stripe_customer.customerAlreadyExists.context'),
|
|
|
|
err: error
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return handleUnrecognizedError(error);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return insertResult;
|
|
|
|
});
|
2020-08-20 08:41:47 +03:00
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
);
|
|
|
|
|
|
|
|
const insertedSubscriptionsPromise = Promise.all([
|
|
|
|
fetchedStripeCustomersPromise,
|
|
|
|
createdStripeCustomersPromise,
|
|
|
|
insertedCustomersPromise
|
|
|
|
]).then(
|
2020-08-20 11:24:05 +03:00
|
|
|
([fetchedStripeCustomers, createdStripeCustomers, insertedCustomersResult]) => {
|
|
|
|
let subscriptionsToInsert = fetchedStripeCustomers.subscriptionsToInsert.concat(createdStripeCustomers.subscriptionsToInsert);
|
|
|
|
|
|
|
|
if (insertedCustomersResult.unsuccessfulRecords.length) {
|
|
|
|
const unsuccessfulCustomerIds = insertedCustomersResult.unsuccessfulRecords.map(r => r.customer_id);
|
|
|
|
subscriptionsToInsert = subscriptionsToInsert.filter(s => !unsuccessfulCustomerIds.includes(s.customer_id));
|
|
|
|
}
|
|
|
|
|
|
|
|
debug(`Starting insert of ${subscriptionsToInsert.length} stripe customer subscriptions`);
|
|
|
|
return models.StripeCustomerSubscription.bulkAdd(subscriptionsToInsert)
|
|
|
|
.then((insertResult) => {
|
|
|
|
debug(`Finished inserting stripe customer subscriptions with ${insertResult.errors.length} errors`);
|
|
|
|
|
|
|
|
if (insertResult.errors.length) {
|
|
|
|
insertResult.errors = insertResult.errors.map((error) => {
|
|
|
|
if (error.code === 'ER_DUP_ENTRY') {
|
|
|
|
return new errors.ValidationError({
|
|
|
|
message: i18n.t('errors.models.stripe_customer_subscription.subscriptionAlreadyExists.message'),
|
|
|
|
context: i18n.t('errors.models.stripe_customer_subscription.subscriptionAlreadyExists.context'),
|
|
|
|
err: error
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return handleUnrecognizedError(error);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return insertResult;
|
|
|
|
});
|
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
);
|
|
|
|
|
|
|
|
const deletedMembersPromise = Promise.all([
|
|
|
|
fetchedStripeCustomersPromise,
|
2020-08-20 11:24:05 +03:00
|
|
|
createdStripeCustomersPromise,
|
|
|
|
insertedCustomersPromise,
|
|
|
|
insertedSubscriptionsPromise
|
2020-08-18 15:39:45 +03:00
|
|
|
]).then(
|
2020-08-20 11:24:05 +03:00
|
|
|
([fetchedStripeCustomers, createdStripeCustomers, insertedStripeCustomers, insertedStripeSubscriptions]) => {
|
|
|
|
const memberIds = [
|
|
|
|
...fetchedStripeCustomers.membersToDelete,
|
|
|
|
...createdStripeCustomers.membersToDelete,
|
|
|
|
...insertedStripeCustomers.unsuccessfulRecords.map(r => r.member_id),
|
|
|
|
...insertedStripeSubscriptions.unsuccessfulRecords.map(r => r.member_id)
|
|
|
|
];
|
|
|
|
|
|
|
|
return models.Member.bulkDestroy(memberIds);
|
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
);
|
|
|
|
|
|
|
|
// This looks sequential, but at the point insertedCustomersPromise has resolved so have all the others
|
|
|
|
const insertedSubscriptions = await insertedSubscriptionsPromise;
|
|
|
|
const insertedCustomers = await insertedCustomersPromise;
|
|
|
|
const deletedMembers = await deletedMembersPromise;
|
|
|
|
const fetchedCustomers = await fetchedStripeCustomersPromise;
|
|
|
|
const insertedLabels = await insertedLabelsPromise;
|
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
const allErrors = [
|
|
|
|
...insertedMembers.errors,
|
|
|
|
...insertedCustomers.errors,
|
|
|
|
...insertedSubscriptions.errors,
|
|
|
|
...insertedLabels.errors,
|
|
|
|
...fetchedCustomers.errors
|
|
|
|
];
|
|
|
|
const importedCount = insertedMembers.successful - deletedMembers.successful;
|
|
|
|
const invalidCount = insertedMembers.unsuccessful + invalidMembers.length + deletedMembers.successful + deletedMembers.unsuccessful;
|
|
|
|
|
|
|
|
debug(`Finished members import with ${importedCount} imported, ${invalidCount} invalid and ${allErrors.length} errors`);
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const result = {
|
|
|
|
imported: {
|
2020-08-20 11:24:05 +03:00
|
|
|
count: importedCount
|
2020-08-18 15:39:45 +03:00
|
|
|
},
|
|
|
|
invalid: {
|
2020-08-20 11:24:05 +03:00
|
|
|
count: invalidCount,
|
|
|
|
errors: allErrors
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
// Allow logging to happen outside of the request cycle
|
|
|
|
process.nextTick(() => {
|
|
|
|
result.invalid.errors.forEach(err => logging.error(err));
|
2020-08-20 11:24:05 +03:00
|
|
|
deletedMembers.errors.forEach(err => logging.error(err));
|
|
|
|
insertedLabels.errors.forEach(err => logging.error(err));
|
2020-08-18 15:39:45 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
return result;
|
2020-08-12 11:18:30 +03:00
|
|
|
};
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
function serializeMemberLabels(labels) {
|
|
|
|
return labels.reduce((labelsAcc, label) => {
|
|
|
|
if (!label) {
|
|
|
|
return labels;
|
|
|
|
}
|
|
|
|
if (typeof label !== 'string') {
|
|
|
|
return labelsAcc.concat(label.name);
|
|
|
|
}
|
2020-08-20 07:43:42 +03:00
|
|
|
return labelsAcc.concat(label.trim());
|
|
|
|
}, []);
|
2020-08-18 15:39:45 +03:00
|
|
|
}
|
|
|
|
|
2020-08-27 12:47:00 +03:00
|
|
|
function getMemberData({members, labels, importSetLabels, createdBy}) {
|
|
|
|
const labelIdLookup = labels.reduce(function (labelIdLookupAcc, labelModel) {
|
2020-08-18 15:39:45 +03:00
|
|
|
return Object.assign(labelIdLookupAcc, {
|
2020-08-27 08:27:15 +03:00
|
|
|
[labelModel.name]: labelModel.id
|
2020-08-18 15:39:45 +03:00
|
|
|
});
|
|
|
|
}, {});
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const importedLabels = importSetLabels.map(label => label.name);
|
|
|
|
|
|
|
|
const invalidMembers = [];
|
|
|
|
const membersToInsert = [];
|
|
|
|
const stripeCustomersToFetch = [];
|
|
|
|
const stripeCustomersToCreate = [];
|
|
|
|
const labelAssociationsToInsert = [];
|
|
|
|
|
|
|
|
members.forEach(function (member) {
|
|
|
|
// @TODO This is expensive, maybe we can just error if we get shoddy data?
|
|
|
|
for (let key in member) {
|
|
|
|
if (member[key] === 'undefined') {
|
|
|
|
delete member[key];
|
|
|
|
}
|
|
|
|
}
|
2020-08-12 11:18:30 +03:00
|
|
|
|
|
|
|
let subscribed;
|
|
|
|
if (_.isUndefined(member.subscribed_to_emails)) {
|
2020-08-19 14:42:48 +03:00
|
|
|
// Member's model default
|
|
|
|
subscribed = true;
|
2020-08-12 11:18:30 +03:00
|
|
|
} else {
|
|
|
|
subscribed = (String(member.subscribed_to_emails).toLowerCase() !== 'false');
|
|
|
|
}
|
|
|
|
|
|
|
|
let createdAt = member.created_at === '' ? undefined : member.created_at;
|
|
|
|
|
2020-11-20 04:09:02 +03:00
|
|
|
// fixes a formatting issue where inserted dates are showing up as ints and not date times...
|
|
|
|
const dateFormat = 'YYYY-MM-DD HH:mm:ss';
|
|
|
|
|
2020-08-12 11:18:30 +03:00
|
|
|
if (createdAt) {
|
2020-11-20 04:09:02 +03:00
|
|
|
createdAt = moment(createdAt).format(dateFormat);
|
2020-08-12 11:18:30 +03:00
|
|
|
} else {
|
2020-11-20 04:09:02 +03:00
|
|
|
createdAt = moment().format(dateFormat);
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const memberToInsert = {
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-12 11:18:30 +03:00
|
|
|
uuid: uuid.v4(), // member model default
|
|
|
|
email: member.email,
|
|
|
|
name: member.name,
|
|
|
|
note: member.note,
|
|
|
|
subscribed: subscribed,
|
|
|
|
created_at: createdAt,
|
|
|
|
created_by: createdBy
|
2020-08-18 15:39:45 +03:00
|
|
|
};
|
|
|
|
membersToInsert.push(memberToInsert);
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-20 07:43:42 +03:00
|
|
|
const memberLabels = member.labels
|
|
|
|
? serializeMemberLabels((member.labels || '').split(','))
|
|
|
|
: [];
|
2020-08-18 15:39:45 +03:00
|
|
|
const allLabels = _.union(memberLabels, importedLabels);
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const memberLabelAssociationsToInsert = allLabels.map((label, index) => {
|
|
|
|
return {
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-18 15:39:45 +03:00
|
|
|
member_id: memberToInsert.id,
|
|
|
|
label_id: labelIdLookup[label],
|
|
|
|
sort_order: index
|
|
|
|
};
|
|
|
|
});
|
|
|
|
labelAssociationsToInsert.push(...memberLabelAssociationsToInsert);
|
2020-08-12 11:18:30 +03:00
|
|
|
|
|
|
|
if (member.stripe_customer_id) {
|
2020-08-18 15:39:45 +03:00
|
|
|
const stripeCustomerToFetch = {
|
|
|
|
customer_id: member.stripe_customer_id,
|
|
|
|
member_id: memberToInsert.id
|
|
|
|
};
|
|
|
|
stripeCustomersToFetch.push(stripeCustomerToFetch);
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
if (String(member.complimentary_plan).toLowerCase() === 'true') {
|
|
|
|
const stripeCustomerToCreate = {
|
|
|
|
member_id: memberToInsert.id,
|
|
|
|
name: memberToInsert.name,
|
|
|
|
email: memberToInsert.email
|
|
|
|
};
|
|
|
|
stripeCustomersToCreate.push(stripeCustomerToCreate);
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
return {
|
|
|
|
invalidMembers,
|
|
|
|
membersToInsert,
|
|
|
|
stripeCustomersToFetch,
|
|
|
|
stripeCustomersToCreate,
|
|
|
|
labelAssociationsToInsert
|
|
|
|
};
|
|
|
|
}
|
2020-08-13 11:31:11 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
async function createStripeCustomers(stripeCustomersToCreate) {
|
|
|
|
const result = {
|
|
|
|
errors: [],
|
|
|
|
customersToInsert: [],
|
|
|
|
subscriptionsToInsert: [],
|
|
|
|
membersToDelete: []
|
|
|
|
};
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
debug(`Creating Stripe customers for ${stripeCustomersToCreate.length} records`);
|
2020-08-18 15:39:45 +03:00
|
|
|
await Promise.all(stripeCustomersToCreate.map(async function createStripeCustomer(customerToCreate) {
|
|
|
|
try {
|
|
|
|
const customer = await membersService.api.members.createStripeCustomer({
|
|
|
|
email: customerToCreate.email,
|
|
|
|
name: customerToCreate.name
|
|
|
|
});
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
result.customersToInsert.push({
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-18 15:39:45 +03:00
|
|
|
member_id: customerToCreate.member_id,
|
|
|
|
customer_id: customer.id,
|
|
|
|
email: customer.email,
|
|
|
|
name: customer.name,
|
|
|
|
created_at: new Date(),
|
|
|
|
updated_at: new Date(),
|
|
|
|
created_by: 1,
|
|
|
|
updated_by: 1
|
|
|
|
});
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
const subscription = await membersService.api.members.createComplimentarySubscription(customer);
|
|
|
|
|
|
|
|
const payment = subscription.default_payment_method;
|
|
|
|
result.subscriptionsToInsert.push({
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-18 15:39:45 +03:00
|
|
|
customer_id: customer.id,
|
|
|
|
subscription_id: subscription.id,
|
|
|
|
plan_id: subscription.plan.id,
|
|
|
|
status: subscription.status,
|
|
|
|
cancel_at_period_end: subscription.cancel_at_period_end,
|
|
|
|
current_period_end: new Date(subscription.current_period_end * 1000),
|
|
|
|
start_date: new Date(subscription.start_date * 1000),
|
|
|
|
default_payment_card_last4: payment && payment.card && payment.card.last4 || null,
|
|
|
|
plan_nickname: subscription.plan.nickname || '',
|
|
|
|
plan_interval: subscription.plan.interval,
|
|
|
|
plan_amount: subscription.plan.amount,
|
|
|
|
plan_currency: subscription.plan.currency,
|
|
|
|
created_at: new Date(),
|
|
|
|
updated_at: new Date(),
|
|
|
|
created_by: 1,
|
|
|
|
updated_by: 1
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
if (error.message.indexOf('customer') && error.code === 'resource_missing') {
|
2020-08-20 11:24:05 +03:00
|
|
|
result.errors.push(new errors.NotFoundError({
|
|
|
|
message: `Member not imported. ${error.message}`,
|
|
|
|
context: i18n.t('errors.api.members.stripeCustomerNotFound.context'),
|
|
|
|
help: i18n.t('errors.api.members.stripeCustomerNotFound.help'),
|
|
|
|
err: error,
|
|
|
|
errorDetails: JSON.stringify(customerToCreate)
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
result.errors.push(handleUnrecognizedError(error));
|
2020-08-18 15:39:45 +03:00
|
|
|
}
|
2020-08-20 11:24:05 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
result.membersToDelete.push(customerToCreate.member_id);
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
}));
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
debug(`Finished creating Stripe customers with ${result.errors.length} errors`);
|
2020-08-18 15:39:45 +03:00
|
|
|
return result;
|
|
|
|
}
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
async function fetchStripeCustomers(stripeCustomersToInsert) {
|
|
|
|
const result = {
|
|
|
|
errors: [],
|
|
|
|
customersToInsert: [],
|
|
|
|
subscriptionsToInsert: [],
|
|
|
|
membersToDelete: []
|
|
|
|
};
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
debug(`Fetching Stripe customers for ${stripeCustomersToInsert.length} records`);
|
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
await Promise.all(stripeCustomersToInsert.map(async function fetchStripeCustomer(customer) {
|
|
|
|
try {
|
|
|
|
const fetchedCustomer = await membersService.api.members.getStripeCustomer(customer.customer_id, {
|
|
|
|
expand: ['subscriptions', 'subscriptions.data.default_payment_method']
|
|
|
|
});
|
2020-08-12 11:18:30 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
result.customersToInsert.push({
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-18 15:39:45 +03:00
|
|
|
member_id: customer.member_id,
|
|
|
|
customer_id: customer.customer_id,
|
|
|
|
email: fetchedCustomer.email,
|
|
|
|
name: fetchedCustomer.name,
|
|
|
|
created_at: new Date(),
|
|
|
|
updated_at: new Date(),
|
|
|
|
created_by: 1,
|
|
|
|
updated_by: 1
|
|
|
|
});
|
|
|
|
|
|
|
|
fetchedCustomer.subscriptions.data.forEach((subscription) => {
|
|
|
|
const payment = subscription.default_payment_method;
|
|
|
|
result.subscriptionsToInsert.push({
|
2021-04-21 18:02:02 +03:00
|
|
|
id: ObjectId().toHexString(),
|
2020-08-18 15:39:45 +03:00
|
|
|
customer_id: customer.customer_id,
|
|
|
|
subscription_id: subscription.id,
|
|
|
|
plan_id: subscription.plan.id,
|
|
|
|
status: subscription.status,
|
|
|
|
cancel_at_period_end: subscription.cancel_at_period_end,
|
|
|
|
current_period_end: new Date(subscription.current_period_end * 1000),
|
|
|
|
start_date: new Date(subscription.start_date * 1000),
|
|
|
|
default_payment_card_last4: payment && payment.card && payment.card.last4 || null,
|
|
|
|
plan_nickname: subscription.plan.nickname || '',
|
|
|
|
plan_interval: subscription.plan.interval,
|
|
|
|
plan_amount: subscription.plan.amount,
|
|
|
|
plan_currency: subscription.plan.currency,
|
|
|
|
created_at: new Date(),
|
|
|
|
updated_at: new Date(),
|
|
|
|
created_by: 1,
|
|
|
|
updated_by: 1
|
2020-08-12 11:18:30 +03:00
|
|
|
});
|
2020-08-18 15:39:45 +03:00
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
if (error.message.indexOf('customer') && error.code === 'resource_missing') {
|
2020-08-20 11:24:05 +03:00
|
|
|
result.errors.push(new errors.NotFoundError({
|
|
|
|
message: `Member not imported. ${error.message}`,
|
|
|
|
context: i18n.t('errors.api.members.stripeCustomerNotFound.context'),
|
|
|
|
help: i18n.t('errors.api.members.stripeCustomerNotFound.help'),
|
|
|
|
err: error,
|
|
|
|
errorDetails: JSON.stringify(customer)
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
result.errors.push(handleUnrecognizedError(error));
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
2020-08-20 11:24:05 +03:00
|
|
|
|
2020-08-18 15:39:45 +03:00
|
|
|
result.membersToDelete.push(customer.member_id);
|
2020-08-12 11:18:30 +03:00
|
|
|
}
|
2020-08-18 15:39:45 +03:00
|
|
|
}));
|
|
|
|
|
2020-08-20 11:24:05 +03:00
|
|
|
debug(`Finished fetching Stripe customers with ${result.errors.length} errors`);
|
2020-08-18 15:39:45 +03:00
|
|
|
return result;
|
|
|
|
}
|
2020-08-12 11:18:30 +03:00
|
|
|
|
|
|
|
module.exports = doImport;
|