"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRequestErrorRetryable = exports.filterObjectListByMatchFields = exports.buildConstituentActionDataFromPayload = exports.buildGiftDataFromPayload = exports.buildConstituentPayloadFromPayload = exports.splitConstituentPayload = exports.augmentFieldsWithConstituentFields = exports.dateStringToFuzzyDate = void 0;
const createOrUpdateIndividualConstituent_1 = require("../createOrUpdateIndividualConstituent");
const dateStringToFuzzyDate = (dateString) => {
    const date = new Date((dateString + '').split('T')[0]);
    if (isNaN(date.getTime())) {
        return false;
    }
    else {
        return {
            d: date.getUTCDate().toString(),
            m: (date.getUTCMonth() + 1).toString(),
            y: date.getUTCFullYear().toString()
        };
    }
};
exports.dateStringToFuzzyDate = dateStringToFuzzyDate;
const augmentFieldsWithConstituentFields = (fields) => {
    Object.keys(createOrUpdateIndividualConstituent_1.fields).forEach((key) => {
        let fieldKey = 'constituent_' + key;
        let fieldLabel = 'Constituent ' + createOrUpdateIndividualConstituent_1.fields[key].label;
        if (key === 'constituent_id') {
            fieldKey = key;
            fieldLabel = createOrUpdateIndividualConstituent_1.fields[key].label;
        }
        fields[fieldKey] = {
            ...createOrUpdateIndividualConstituent_1.fields[key],
            label: fieldLabel
        };
    });
    return fields;
};
exports.augmentFieldsWithConstituentFields = augmentFieldsWithConstituentFields;
const splitConstituentPayload = (payload) => {
    const constituentData = {
        birthplace: payload.birthplace,
        ethnicity: payload.ethnicity,
        first: payload.first,
        former_name: payload.former_name,
        gender: payload.gender,
        gives_anonymously: payload.gives_anonymously,
        income: payload.income,
        industry: payload.industry,
        last: payload.last,
        lookup_id: payload.lookup_id,
        marital_status: payload.marital_status,
        preferred_name: payload.preferred_name,
        religion: payload.religion,
        suffix: payload.suffix,
        suffix_2: payload.suffix_2,
        title: payload.title,
        title_2: payload.title_2
    };
    Object.keys(constituentData).forEach((key) => {
        if (!constituentData[key]) {
            delete constituentData[key];
        }
    });
    if (payload.birthdate) {
        const birthdateFuzzyDate = (0, exports.dateStringToFuzzyDate)(payload.birthdate);
        if (birthdateFuzzyDate) {
            constituentData.birthdate = birthdateFuzzyDate;
        }
    }
    let addressData = {};
    if (payload.address &&
        (payload.address.address_lines ||
            payload.address.city ||
            payload.address.country ||
            payload.address.postal_code ||
            payload.address.state) &&
        payload.address.type) {
        addressData = payload.address;
    }
    let emailData = {};
    if (payload.email && payload.email.address && payload.email.type) {
        emailData = payload.email;
    }
    let onlinePresenceData = {};
    if (payload.online_presence && payload.online_presence.address && payload.online_presence.type) {
        onlinePresenceData = payload.online_presence;
    }
    let phoneData = {};
    if (payload.phone && payload.phone.number && payload.phone.type) {
        phoneData = payload.phone;
    }
    return [constituentData, addressData, emailData, onlinePresenceData, phoneData];
};
exports.splitConstituentPayload = splitConstituentPayload;
const buildConstituentPayloadFromPayload = (payload) => {
    const constituentPayload = {};
    Object.keys(payload).forEach((key) => {
        if (key.startsWith('constituent_')) {
            if (payload[key] &&
                (typeof payload[key] !== 'object' ||
                    (Object.keys(payload[key]).length > 0 && Object.values(payload[key]).every((x) => !!x)))) {
                let constituentPayloadKey = key.substring('constituent_'.length);
                if (key === 'constituent_id') {
                    constituentPayloadKey = key;
                }
                constituentPayload[constituentPayloadKey] = payload[key];
            }
        }
    });
    return constituentPayload;
};
exports.buildConstituentPayloadFromPayload = buildConstituentPayloadFromPayload;
const buildGiftDataFromPayload = (constituentId, payload) => {
    const giftData = {
        amount: {
            value: payload.amount
        },
        constituency: payload.constituency,
        constituent_id: constituentId,
        date: payload.date,
        default_fundraiser_credits: payload.default_fundraiser_credits,
        default_soft_credits: payload.default_soft_credits,
        gift_code: payload.gift_code,
        gift_status: payload.gift_status,
        is_anonymous: payload.is_anonymous,
        is_manual: true,
        lookup_id: payload.lookup_id,
        post_date: payload.post_date,
        post_status: payload.post_status,
        reference: payload.reference,
        subtype: payload.subtype,
        type: payload.type
    };
    Object.keys(giftData).forEach((key) => {
        if (!giftData[key]) {
            delete giftData[key];
        }
    });
    if (payload.batch_number) {
        giftData.batch_number = payload.batch_number;
        giftData.batch_prefix = payload.batch_prefix || 'API';
    }
    giftData.date = giftData.date || new Date().toISOString();
    if (payload.acknowledgement) {
        const acknowledgementData = {
            status: payload.acknowledgement.status || 'NEEDSACKNOWLEDGEMENT'
        };
        if (acknowledgementData.status !== 'NEEDSACKNOWLEDGEMENT' &&
            acknowledgementData.status !== 'DONOTACKNOWLEDGE' &&
            payload.acknowledgement.date) {
            acknowledgementData.date = payload.acknowledgement.date;
        }
        giftData.acknowledgements = [acknowledgementData];
    }
    giftData.gift_splits = [
        {
            amount: {
                value: payload.amount
            },
            fund_id: payload.fund_id
        }
    ];
    giftData.payments = [
        {
            payment_method: payload.payment_method
        }
    ];
    if (giftData.payments[0].payment_method === 'PersonalCheck') {
        giftData.payments[0].check_number = payload.check_number;
        if (payload.check_date) {
            const checkDateFuzzyDate = (0, exports.dateStringToFuzzyDate)(payload.check_date);
            if (checkDateFuzzyDate) {
                giftData.payments[0].check_date = checkDateFuzzyDate;
            }
        }
    }
    if ((giftData.post_status === 'NotPosted' || giftData.post_status === 'Posted') && !giftData.post_date) {
        giftData.post_date = payload.date;
    }
    if (payload.receipt) {
        const receiptData = {
            status: payload.receipt.status || 'NEEDSRECEIPT'
        };
        if (receiptData.status === 'RECEIPTED' && payload.receipt.date) {
            receiptData.date = payload.receipt.date;
        }
        giftData.receipts = [receiptData];
    }
    if (giftData.type === 'RecurringGift') {
        if (payload.recurring_gift_schedule) {
            giftData.recurring_gift_schedule = {
                end_date: payload.recurring_gift_schedule.end_date,
                frequency: payload.recurring_gift_schedule.frequency || '',
                start_date: payload.recurring_gift_schedule.start_date || ''
            };
        }
    }
    else if (giftData.type === 'RecurringGiftPayment' && payload.linked_gifts) {
        giftData.linked_gifts = payload.linked_gifts;
    }
    return giftData;
};
exports.buildGiftDataFromPayload = buildGiftDataFromPayload;
const buildConstituentActionDataFromPayload = (constituentId, payload) => {
    const constituentActionData = {
        constituent_id: constituentId,
        date: payload.date,
        category: payload.category,
        completed: payload.completed,
        completed_date: payload.completed_date,
        description: payload.description,
        direction: payload.direction,
        end_time: payload.end_time,
        fundraisers: payload.fundraisers,
        location: payload.location,
        opportunity_id: payload.opportunity_id,
        outcome: payload.outcome,
        priority: payload.priority,
        start_time: payload.start_time,
        status: payload.status,
        summary: payload.summary,
        type: payload.type,
        author: payload.author
    };
    Object.keys(constituentActionData).forEach((key) => {
        if (!constituentActionData[key]) {
            delete constituentActionData[key];
        }
    });
    return constituentActionData;
};
exports.buildConstituentActionDataFromPayload = buildConstituentActionDataFromPayload;
const filterObjectListByMatchFields = (list, data, matchFields) => {
    return list.find((item) => {
        let isMatch = undefined;
        matchFields.forEach((field) => {
            if (isMatch !== false) {
                let fieldName = field;
                if (field.startsWith('int:')) {
                    fieldName = field.split('int:')[1];
                }
                let itemValue = item[fieldName] ? item[fieldName].toLowerCase() : '';
                let dataValue = data[fieldName] ? data[fieldName].toLowerCase() : '';
                if (field.startsWith('int:')) {
                    itemValue = itemValue.replace(/\D/g, '');
                    dataValue = dataValue.replace(/\D/g, '');
                }
                isMatch = itemValue === dataValue;
            }
        });
        return isMatch;
    });
};
exports.filterObjectListByMatchFields = filterObjectListByMatchFields;
const isRequestErrorRetryable = (statusCode) => {
    return statusCode === 429 || statusCode >= 500;
};
exports.isRequestErrorRetryable = isRequestErrorRetryable;
//# sourceMappingURL=index.js.map