async function unsubscribeMonthlyMonitorReportForUnsubscribeToken()

in src/db/tables/subscriber_email_preferences.ts [262:338]


async function unsubscribeMonthlyMonitorReportForUnsubscribeToken(
  unsubscribeToken: string,
) {
  try {
    // TODO: Remove this comment
    // Investigation: MNTOR-4326
    const sub = await getEmailPreferenceForUnsubscribeToken(unsubscribeToken);

    if (
      typeof sub?.subscriber_id === "number" &&
      sub.monthly_monitor_report_free === false
    ) {
      logger.info(
        "unsubscribe_monthly_monitor_report_for_unsubscribe_token_already_unsubscribed",
        sub.subscriber_id,
      );
    } else if (typeof sub?.subscriber_id === "number") {
      // TODO: remove after MNTOR-4343
      const subscriber = await getSubscriberById(sub.subscriber_id);
      if (!subscriber) {
        logger.error(
          "unsubscribe_monthly_monitor_report_for_unsubscribe_token_subscriber_not_found",
          { subscriberId: sub.subscriber_id },
        );

        // should throw a sentry error for further investigation
        captureMessage(
          `unsubscribe_monthly_monitor_report_for_unsubscribe_token_subscriber_not_found_updated: ${sub.subscriber_id}`,
        );

        await knex("subscriber_email_preferences")
          .where("subscriber_id", sub.subscriber_id)
          .update({
            monthly_monitor_report_free: false,
            // @ts-ignore knex.fn.now() results in it being set to a date,
            // even if it's not typed as a JS date object:
            monthly_monitor_report_free_at: knex.fn.now(),
          });

        logger.info(
          "unsubscribe_monthly_monitor_report_for_unsubscribe_token_subscriber_not_found_updated",
          {
            subscriberId: sub.subscriber_id,
          },
        );
        return;
      }
      await updateEmailPreferenceForSubscriber(sub.subscriber_id, true, {
        monthly_monitor_report_free: false,
      });
    } else {
      logger.error(
        `cannot find subscriber with unsubscribe token: ${unsubscribeToken}`,
        {
          unsubscribeToken,
        },
      );
      throw new Error(
        `cannot find subscriber with unsubscribe token: ${unsubscribeToken}`,
      );
    }
  } catch (e) {
    // TODO: Remove this comment
    // Investigation: MNTOR-4326
    // This is getting logged intermittenly
    logger.error(
      "error_unsubscribe_monthly_monitor_report_for_unsubscribe_token",
      {
        message: (e as Error).message,
        stack_trace: (e as Error).stack,
        unsubscribeToken,
      },
    );
    captureException(e);
    throw e;
  }
}