Untitled

mail@pastecode.io avatar
unknown
javascript
3 years ago
7.1 kB
1
Indexable
Never
    const campaign = await campaignRepository.findByCode(value.campaign_code);
    if (!campaign) {
        throw new InvalidCampaignException(`Invalid campaign code '${value.campaign_code}'`);
    }

    validateCampaignDate(campaign);
    validateCampaignStatus(campaign);

    // Registration form effective date and status validation
    const registrationForm = await registrationFormRepository.findBySalesforceId(value.registration.form_name)
    if (!registrationForm) {
        throw new InvalidRegistrationFormException(`Registration form not found with name '${value.registration.form_name}'.\n${JSON.stringify(value)}'`);
    }

    validateRegistrationFormDate(registrationForm);
    validateRegistrationFormStatus(registrationForm);

    const registrationFormFields = await registrationFormFieldRepository.findByRegistrationFormId(registrationForm.id);
    if (registrationFormFields.length <= 0) {
        throw new InvalidRegistrationFormFieldsException(`No form fields found for registration form.\n${JSON.stringify(registrationForm)}`);
    }

    // Question code existent validation
    const registrationFormFieldsQuestions = [];
    registrationFormFields.forEach((item) => {
        if (item.code) {
            registrationFormFieldsQuestions.push(item.code);
        }
    });

    for (const item of value.registration.submissions.answers) {
        if (!registrationFormFieldsQuestions.includes(item.question_code)) {
            throw new InvalidRegistrationFormException(`Invalid or non-exist or is deleted question code: ${item.question_code}.\n${JSON.stringify(value)}`);
        }
    }

    // Validate if the submitted answers are applicable for the form questions
    const questions = {};
    salesforcePayload.registration.submissions.answers = [];

    for (const ans of value.registration.submissions.answers) {
        questions[ans.question_code] = ans.answer;
    }

    for (const field of registrationFormFields) {
        if (field.code in questions) {
            // If there is a set of accepted answers in 'options' then verify if the submitting answer is accepted
            if (field.options) {
                let allPossibleAnswers = field.options.split(';');

                if (!allPossibleAnswers.includes(questions[field.code])) {
                    if (field.is_mandatory || questions[field.code]) {
                        throw new InvalidAnswerException(`Invalid answer(s) for question code: ${field.code}.\n${JSON.stringify(value)}`);
                    }
                }
            }
            else {
                // If the question is mandatory but user submitted an empty answer
                if (field.is_mandatory && questions[field.code] === '') {
                    throw new InvalidAnswerException(`Answer is mandatory for question code: ${field.code}.\n${JSON.stringify(value)}`);
                }
            }

            salesforcePayload.registration.submissions.answers.push({
                registration_form_fields_salesforce_id: field.salesforce_id,
                answer: questions[field.code]
            });
        }
    }

    // Save response answer response to db
    const registrationFormResponse = await registrationFormResponseRepository.insert({
        registration_form_id: registrationForm.id,
        registrant_name: value.registration.submissions.registrant_name || '',
        marketing_consent: value.registration.submissions.marketing_consent || '',
        pii_email_token: !value.registration.submissions.email ? '' : cryptoService.md5(value.registration.submissions.email.toLowerCase()),
        pii_phone_token: !value.registration.submissions.phone_no ? '' : cryptoService.md5(value.registration.submissions.phone_no),
        pii_id_token: !value.registration.submissions.identification_num ? '' : cryptoService.md5(value.registration.submissions.identification_num),
        pii_data_clear: cryptoService.encrypt(JSON.stringify({
            registrant_name: value.registration.submissions.registrant_name || '',
            phone_no: value.registration.submissions.phone_no || '',
            email: value.registration.submissions.email || '',
            identification_num: value.registration.submissions.identification_num || '',
            marketing_consent: value.registration.submissions.marketing_consent || '',
        })),
        source: value.registration.submissions.source || '',
        answers: JSON.stringify(value.registration.submissions.answers),
        is_deleted: false,
        sync_to_salesforce: 'pending'
    });
    salesforcePayload.registration.registration_form_response_id = registrationFormResponse.id;

    const queueArray = [];
    let queue;

    // Send to Integration queue
    if (registrationForm.integration) {
        queue = queueService.sendToQueue(
            JSON.stringify({
                email: value.registration.submissions.email || '',
                registrantName: value.registration.submissions.registrant_name || '',
                registrationFormId: registrationForm.id,
                registrationFormResponseId: registrationFormResponse.id,
                registrationFormIntegrations: registrationForm.integration,
                marketingConsent: value.registration.submissions.marketing_consent,
                source: value.registration.submissions.source,
                campaign: JSON.stringify(campaign),
                messageId: uuidv4()
            }),
            'integration',
            config.integration_queue.queueUrl,
            config.integration_queue.delaySeconds
        );

        queueArray.push(queue);
    }

    // Send message to Reward Campaign queue
    queue = queueService.sendToQueue(
        JSON.stringify({
            campaignId: campaign.id,
            registrationFormSalesforceId: value.registration.form_name,
            name: value.registration.submissions.registrant_name || '',
            email: value.registration.submissions.email ? value.registration.submissions.email.toLowerCase() : '',
            phone: value.registration.submissions.phone_no || '',
            id: value.registration.submissions.identification_num || '',
            piiEmailToken: !value.registration.submissions.email ? '' : cryptoService.md5(value.registration.submissions.email.toLowerCase()),
            piiPhoneToken: !value.registration.submissions.phone_no ? '' : cryptoService.md5(value.registration.submissions.phone_no),
            piiIdToken: !value.registration.submissions.identification_num ? '' : cryptoService.md5(value.registration.submissions.identification_num),
            userQuestionsAndAnswers: value.registration.submissions.answers,
            registrationFormResponseId: registrationFormResponse.id,
            salesforcePayload,
            messageId: uuidv4()
        }),
        'reward_campaign_assessment',
        config.reward_campaign_queue.queueUrl,
        config.reward_campaign_queue.delaySeconds
    );
    queueArray.push(queue);

    await Promise.all(queueArray);

    return true;