"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "SurveyCompletionNotifierProcessor", {
    enumerable: true,
    get: function() {
        return SurveyCompletionNotifierProcessor;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _tasks = require("@tamanu/shared/tasks");
const _logging = require("@tamanu/shared/services/logging");
const _sequelize = require("sequelize");
const _constants = require("@tamanu/constants");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let SurveyCompletionNotifierProcessor = class SurveyCompletionNotifierProcessor extends _tasks.ScheduledTask {
    getName() {
        return 'SurveyCompletionNotifierProcessor';
    }
    async countQueue() {
        return null;
    }
    async run() {
        const surveyResponses = await this.context.store.models.SurveyResponse.findAll({
            limit: this.config.limit ?? 100,
            where: {
                endTime: {
                    [_sequelize.Op.not]: null
                },
                notified: false
            },
            include: [
                {
                    model: this.context.store.models.Encounter,
                    as: 'encounter',
                    include: [
                        {
                            model: this.context.store.models.Patient,
                            as: 'patient'
                        }
                    ]
                },
                {
                    model: this.context.store.models.Survey,
                    as: 'survey',
                    where: {
                        notifiable: true,
                        notifyEmailAddresses: {
                            [_sequelize.Op.ne]: []
                        }
                    }
                }
            ]
        });
        const getTranslation = await this.context.store.models.TranslatedString?.getTranslationFunction(_config.default.language, [
            'surveyCompletionNotifier'
        ]);
        for (const surveyResponse of surveyResponses){
            const result = await this.context.emailService.sendEmail({
                from: _config.default.mailgun.from,
                to: surveyResponse.survey.notifyEmailAddresses,
                subject: getTranslation('surveyCompletionNotifier.emailSubject', `Notification of :surveyName form submission in Tamanu`, {
                    replacements: {
                        surveyName: surveyResponse.survey.name
                    }
                }),
                html: getTranslation('surveyCompletionNotifier.emailBody', `A form has been submitted in Tamanu that may require your attention! This is an automated email to notify you that a response to a form has been submitted in Tamanu. Please login to Tamanu desktop to view details of this form response. Do not respond to this email. <br />
            Form: :surveyName<br />
            Date/Time: :endTime<br />
            Patient: :patientDisplayId<br />`, {
                    replacements: {
                        surveyName: surveyResponse.survey.name,
                        endTime: surveyResponse.endTime,
                        patientDisplayId: surveyResponse.encounter.patient.displayId
                    }
                })
            });
            if (result.status === _constants.COMMUNICATION_STATUSES.SENT) {
                surveyResponse.notified = true;
                await surveyResponse.save();
                continue;
            }
            _logging.log.error('Failed to send email notification', {
                error: result.error
            });
        }
    }
    /**
   *
   * @param {import('../ApplicationContext').ApplicationContext} context
   */ constructor(context){
        const conf = _config.default.schedules.surveyCompletionNotifierProcessor ?? {
            enabled: true,
            // every 30seconds /!\
            schedule: '*/30 * * * * *',
            limit: 100
        };
        const { schedule, jitterTime, enabled } = conf;
        super(schedule, _logging.log, jitterTime, enabled);
        this.config = conf;
        /** @type {import('../ApplicationContext').ApplicationContext} */ this.context = context;
    }
};

//# sourceMappingURL=SurveyCompletionNotifierProcessor.js.map