示例#1
0
def send_payments_details(payments: List[Payment],
                          recipients: List[str]) -> None:
    if not recipients:
        raise Exception(
            "[BATCH][PAYMENTS] Missing PASS_CULTURE_PAYMENTS_DETAILS_RECIPIENTS in environment variables"
        )

    if all(
            map(lambda x: x.currentStatus.status == TransactionStatus.ERROR,
                payments)):
        logger.warning(
            "[BATCH][PAYMENTS] Not sending payments details as all payments have an ERROR status"
        )
    else:
        details = create_all_payments_details(payments)
        csv = generate_payment_details_csv(details)
        logger.info("[BATCH][PAYMENTS] Sending %s details of %s payments",
                    len(details), len(payments))
        logger.info("[BATCH][PAYMENTS] Recipients of email : %s", recipients)
        try:
            send_payment_details_email(csv, recipients)
        except MailServiceException as exception:
            logger.exception(
                "[BATCH][PAYMENTS] Error while sending payment details email to MailJet: %s",
                exception)
示例#2
0
    def _send(self, recipients: Iterable[str], data: dict) -> MailResult:
        data["To"] = ", ".join(recipients)

        if settings.MAILJET_TEMPLATE_DEBUGGING:
            messages_data = data.get("Messages")
            if messages_data:
                for message_data in messages_data:
                    _add_template_debugging(message_data)
            else:
                _add_template_debugging(data)

        try:
            response = self.mailjet_client.send.create(
                data=data, timeout=settings.MAILJET_HTTP_TIMEOUT)
        except Exception as exc:  # pylint: disable=broad-except
            logger.exception("Error trying to send e-mail with Mailjet: %s",
                             exc)
            return MailResult(
                sent_data=data,
                successful=False,
            )

        successful = response.status_code == 200
        if not successful:
            logger.warning("Got %d return code from Mailjet: content=%s",
                           response.status_code, response.content)

        return MailResult(
            sent_data=data,
            successful=successful,
        )
示例#3
0
    def is_accessible(self):
        authorized = current_user.is_authenticated and current_user.isAdmin

        if authorized:
            logger.info("[ADMIN] Accès autorisé à l'interface d'administation pour %s", current_user)
        else:
            logger.warning("[ADMIN] Tentative d'accès non autorisé à l'interface d'administation par %s", current_user)

        return authorized
示例#4
0
def _process_rejection(information: Dict, procedure_id: int) -> None:
    save_beneficiary_import_with_status(
        ImportStatus.REJECTED,
        information["application_id"],
        source=BeneficiaryImportSources.demarches_simplifiees,
        source_id=procedure_id,
        detail="Compte existant avec cet email",
    )
    logger.warning(
        "[BATCH][REMOTE IMPORT BENEFICIARIES] Rejected application %s because of already existing email - Procedure %s",
        information["application_id"],
        procedure_id,
    )
示例#5
0
def _process_duplication(duplicate_users: List[User],
                         error_messages: List[str], information: Dict,
                         procedure_id: int) -> None:
    number_of_beneficiaries = len(duplicate_users)
    duplicate_ids = ", ".join([str(u.id) for u in duplicate_users])
    message = f"{number_of_beneficiaries} utilisateur(s) en doublon {duplicate_ids} pour le dossier {information['application_id']}"
    logger.warning(
        "[BATCH][REMOTE IMPORT BENEFICIARIES] Duplicate beneficiaries found : %s - Procedure %s",
        message, procedure_id)
    error_messages.append(message)
    save_beneficiary_import_with_status(
        ImportStatus.DUPLICATE,
        information["application_id"],
        source=BeneficiaryImportSources.demarches_simplifiees,
        source_id=procedure_id,
        detail=f"Utilisateur en doublon : {duplicate_ids}",
    )
def _process_creation(
    error_messages: List[str],
    information: Dict,
    new_beneficiaries: List[User],
    procedure_id: int,
    user: Optional[User] = None,
) -> None:
    new_beneficiary = create_beneficiary_from_application(information,
                                                          user=user)
    try:
        repository.save(new_beneficiary)
    except ApiErrors as api_errors:
        logger.warning(
            "[BATCH][REMOTE IMPORT BENEFICIARIES] Could not save application %s, because of error: %s - Procedure %s",
            information["application_id"],
            api_errors,
            procedure_id,
        )
        error_messages.append(str(api_errors))
    else:
        logger.info(
            "[BATCH][REMOTE IMPORT BENEFICIARIES] Successfully created user for application %s - Procedure %s",
            information["application_id"],
            procedure_id,
        )
        save_beneficiary_import_with_status(
            ImportStatus.CREATED,
            information["application_id"],
            source=BeneficiaryImportSources.demarches_simplifiees,
            source_id=procedure_id,
            user=new_beneficiary,
        )
        new_beneficiaries.append(new_beneficiary)
        try:
            if user is None:
                send_activation_email(new_beneficiary)
            else:
                send_accepted_as_beneficiary_email(new_beneficiary)
        except MailServiceException as mail_service_exception:
            logger.exception(
                "Email send_activation_email failure for application %s - Procedure %s : %s",
                information["application_id"],
                procedure_id,
                mail_service_exception,
            )
示例#7
0
            dsn=settings.SENTRY_DSN,
            integrations=[
                RedisIntegration(),
                RqIntegration(),
                SqlalchemyIntegration()
            ],
            release=read_version_from_file(),
            environment=settings.ENV,
            traces_sample_rate=settings.SENTRY_SAMPLE_RATE,
        )
        logger.info("Worker : connection to sentry OK")

    while True:
        try:
            with app.app_context():
                # This sessions removals are meant to prevent open db connection
                # to spread through forked children and cause bugs in the jobs
                # https://python-rq.org/docs/workers/#the-worker-lifecycle
                # https://docs.sqlalchemy.org/en/13/core/connections.html?highlight=dispose#engine-disposal
                db.session.remove()
                db.session.close()
                db.engine.dispose()
            with Connection(conn):
                worker = Worker(list(map(Queue, listen)),
                                exception_handlers=[log_worker_error])
                worker.work()

        except redis.ConnectionError:
            logger.warning("Worker connection error. Restarting in 5 seconds")
            time.sleep(5)