import { PaymentOptions, PaymentType, MappedPaymentOptions, SubscriptionTerm } from '../types/subscription'; import { EmptyResultError, ValidationError } from '../errors'; export function mapPaymentOptions(options: PaymentOptions) { const charges = options.offer.getAvailableCharges(options.billingCountry, options.option); const selectedPaymentTerm = charges.find(charge => charge.subscriptionCode === options.paymentTerm); if (!selectedPaymentTerm) { throw new EmptyResultError('Charge Not Found in Available Charges', { charges, term: options.paymentTerm }); } if (options.sendConfirmationEmail !== undefined && typeof options.sendConfirmationEmail !== 'boolean'){ throw new ValidationError('The value of sendConfirmationEmail must be boolean', { sendConfirmationEmail: options.sendConfirmationEmail }); } const subscriptionTerm: SubscriptionTerm = { iso8601Duration: selectedPaymentTerm.subscriptionCode, termType: options.singleTermSubscription ? 'Termed' : 'Evergreen', autoRenewTerm: options.singleTermSubscription ? false : true, }; const mapped: MappedPaymentOptions = { paymentType: options.paymentType.toUpperCase(), paymentMethodId: options.paymentMethodId, paymentGateway: options.paymentGateway, price: selectedPaymentTerm.value, currencyCode: selectedPaymentTerm.currency, subscriptionTerm: subscriptionTerm, offerId: options.offer.id, closePaymentMethod: options.closePaymentMethod, sendConfirmationEmail: typeof options.sendConfirmationEmail === 'boolean' ? options.sendConfirmationEmail : true }; // Add the extra information for PayPal if (options.paymentType === PaymentType.PAYPAL) { mapped.paypalBAID = options.paypalBAID; mapped.paypalEmail = options.paypalEmail; } // Add the extra information for Apple Pay if (options.paymentType === PaymentType.APPLEPAY) { const paymentToken = JSON.parse(options.paymentMethodId); mapped.paymentToken = paymentToken.paymentData; mapped.transactionIdentifier = paymentToken.transactionIdentifier; mapped.paymentMethodId = 'apple-pay'; } // Add trial information if the offer is a trial if (options.offer.isTrial()) { mapped.term = 'trial'; mapped.trial = { price: selectedPaymentTerm.trialValue as string, term: selectedPaymentTerm.subscriptionPaymentDue }; } // Add delivery start date and fulfilment option if (!options.offer.isEpaper() && (options.offer.isPrint() || options.offer.isBundle())) { mapped.startDate = options.startDate; } //some products (ePaper/print) require fulfilment option if (options.offer.isEpaper() || options.offer.isPrint() || options.offer.isBundle()) { mapped.option = options.option; } if (options.segmentId) { mapped.segmentId = options.segmentId; } if (options.backdatedStartDate) { mapped.backdatedStartDate = options.backdatedStartDate; } return mapped; }