def test_get_departement_code_for_mainland_France(self): # given postal_code = PostalCode(postalCode="75012") # when departement_code = postal_code.get_departement_code() # then assert departement_code == "75"
def test_get_departement_code_for_overseas_France(self): # given postal_code = PostalCode(postalCode="97440") # when departement_code = postal_code.get_departement_code() # then assert departement_code == "974"
def create_industrial_user_offerers(users_by_name, offerers_by_name): logger.info("create_industrial_user_offerers") user_offerers_by_name = {} # special validation user = users_by_name["pro93 real-validation"] offerer = offerers_by_name["414819409 lat:48.8 lon:1.48"] user_offerers_by_name["pro93 real-validation / 414819409 lat:48.8 lon:1.48"] = create_user_offerer( offerer=offerer, user=user ) # loop on users for (user_name, user) in users_by_name.items(): for (offerer_name, offerer) in offerers_by_name.items(): if ( PostalCode(offerer.postalCode).get_departement_code() != user.departementCode or "real-validation" in user_name ): continue user_offerers_by_name["{} / {}".format(user_name, offerer_name)] = create_user_offerer( offerer=offerer, user=user ) repository.save(*user_offerers_by_name.values()) logger.info("created %d user_offerers", len(user_offerers_by_name)) return user_offerers_by_name
def make_validation_email_object( offerer: Offerer, user_offerer: UserOfferer, get_by_siren=api_entreprises.get_by_offerer ) -> dict: vars_obj_user = vars(user_offerer.user) vars_obj_user.pop("clearTextPassword", None) api_entreprise = get_by_siren(offerer) offerer_departement_code = PostalCode(offerer.postalCode).get_departement_code() email_html = render_template( "mails/internal_validation_email.html", user_offerer=user_offerer, user_vars=pformat(vars_obj_user), offerer=offerer, offerer_vars_user_offerer=pformat(vars(user_offerer.offerer)), offerer_vars=pformat(vars(offerer)), offerer_pro_link=build_pc_pro_offerer_link(offerer), offerer_summary=pformat(_summarize_offerer_vars(offerer, api_entreprise)), user_summary=pformat(_summarize_user_vars(user_offerer)), api_entreprise=pformat(api_entreprise), api_url=settings.API_URL, ) return { "FromName": "pass Culture", "Subject": "%s - inscription / rattachement PRO à valider : %s" % (offerer_departement_code, offerer.name), "Html-part": email_html, }
def update_user_information_from_external_source( user: User, data: Union[fraud_models.DMSContent, fraud_models.JouveContent, fraud_models.EduconnectContent], commit=False, ) -> User: if isinstance(data, fraud_models.DMSContent): # FIXME: the following function does not override user.dateOfBirth, we should do it user = create_beneficiary_from_application(data, user) elif isinstance(data, fraud_models.JouveContent): if data.activity: user.activity = data.activity if data.address: user.address = data.address if data.city: user.city = data.city if data.gender: user.civility = "Mme" if data.gender == "F" else "M." if data.birthDateTxt: user.dateOfBirth = data.birthDateTxt if data.firstName: user.firstName = data.firstName if data.lastName: user.lastName = data.lastName if data.postalCode and not user.postalCode: user.postalCode = data.postalCode user.departementCode = PostalCode(data.postalCode).get_departement_code() if data.firstName and data.lastName: user.publicName = f"{user.firstName} {user.lastName}" if data.bodyPieceNumber: items = ( fraud_api.validate_id_piece_number_format_fraud_item(data.bodyPieceNumber), fraud_api._duplicate_id_piece_number_fraud_item(data.bodyPieceNumber), ) if all((item.status == fraud_models.FraudStatus.OK) for item in items): user.idPieceNumber = data.bodyPieceNumber if not FeatureToggle.ENABLE_PHONE_VALIDATION.is_active(): if not user.phoneNumber and data.phoneNumber: user.phoneNumber = data.phoneNumber elif isinstance(data, fraud_models.EduconnectContent): user.firstName = data.first_name user.lastName = data.last_name user.dateOfBirth = datetime.combine(data.birth_date, time(0, 0)) user.ineHash = data.ine_hash # update user fields to be correctly initialized user.hasSeenTutorials = False user.remove_admin_role() db.session.add(user) db.session.flush() if commit: db.session.commit() return user
def _set_offerer_departement_code(new_user: User, offerer: Offerer) -> User: if settings.IS_INTEGRATION: new_user.departementCode = "00" elif offerer.postalCode is not None: new_user.departementCode = PostalCode(offerer.postalCode).get_departement_code() else: new_user.departementCode = "XX" # We don't want to trigger an error on this: # we want the error on user return new_user
def build_expired_bookings_recap_email_data_for_offerer( offerer: Offerer, bookings: typing.List[Booking] ) -> typing.Dict: return { "Mj-TemplateID": 1952508, "Mj-TemplateLanguage": True, "Vars": { "bookings": _extract_bookings_information_from_bookings_list(bookings), "department": PostalCode(offerer.postalCode).get_departement_code(), }, }
def _serialize_date_with_timezone(date_without_timezone: datetime, booking: AbstractKeyedTuple) -> datetime: if booking.venueDepartmentCode: return _apply_departement_timezone( naive_datetime=date_without_timezone, departement_code=booking.venueDepartmentCode) offerer_department_code = PostalCode( booking.offererPostalCode).get_departement_code() return _apply_departement_timezone( naive_datetime=date_without_timezone, departement_code=offerer_department_code)
def fill_pro_department_code_with_offerer_postal_code() -> None: pro_user_to_update = (User.query.join(UserOfferer).join(Offerer).filter( Offerer.postalCode.startswith("75")).filter( User.departementCode == "93").options(joinedload( User.offerers)).all()) for pro_user in pro_user_to_update: offerer = _get_user_initial_linked_offerer(pro_user) pro_user.departementCode = PostalCode( offerer.postalCode).get_departement_code() repository.save(*pro_user_to_update)
def build_expired_bookings_recap_email_data_for_offerer( offerer: Offerer, bookings: list[Booking], withdrawal_period) -> dict: return { "Mj-TemplateID": 3095184, "Mj-TemplateLanguage": True, "Vars": { "bookings": _extract_bookings_information_from_bookings_list(bookings), "department": PostalCode(offerer.postalCode).get_departement_code(), "withdrawal_period": withdrawal_period, }, }
def build_expired_bookings_recap_email_data_for_offerer( offerer: Offerer, recipients: str, bookings: typing.List[Booking] ) -> typing.Dict: return { "FromEmail": settings.SUPPORT_EMAIL_ADDRESS, "Mj-TemplateID": 1952508, "Mj-TemplateLanguage": True, "To": recipients if feature_send_mail_to_users_enabled() else settings.DEV_EMAIL_ADDRESS, "Vars": { "bookings": _extract_bookings_information_from_bookings_list(bookings), "department": PostalCode(offerer.postalCode).get_departement_code(), "env": format_environment_for_email(), }, }
def format_phone_number_with_country_code(user: User) -> str: if not user.phoneNumber: raise UserWithoutPhoneNumberException() if not user.postalCode or ( PostalCode(user.postalCode)._is_overseas_departement() and user.departementCode not in PHONE_PREFIX_BY_DEPARTEMENT_CODE ): logger.warning( "Unknown phone prefix for user %s", user, extra={"departementCode": user.departementCode, "postalCode": user.postalCode}, ) return build_internationalized_phone_number(user, user.phoneNumber)
def create_pro_user(pro_user: ProUserCreationBodyModel) -> User: new_pro_user = User(from_dict=pro_user.dict(by_alias=True)) new_pro_user.email = sanitize_email(new_pro_user.email) new_pro_user.notificationSubscriptions = asdict(NotificationSubscriptions(marketing_email=pro_user.contact_ok)) new_pro_user.remove_admin_role() new_pro_user.remove_beneficiary_role() new_pro_user.needsToFillCulturalSurvey = False new_pro_user.generate_validation_token() if pro_user.postal_code: new_pro_user.departementCode = PostalCode(pro_user.postal_code).get_departement_code() if settings.IS_INTEGRATION: new_pro_user.add_beneficiary_role() deposit = payment_api.create_deposit(new_pro_user, "integration_signup") new_pro_user.deposits = [deposit] return new_pro_user
def test_get_departement_code_for_overseas_France(self): # given la_reunion_postal_code = PostalCode(postalCode="97440") polynesie_francaise_postal_code = PostalCode(postalCode="98700") # when la_reunion_departement_code = la_reunion_postal_code.get_departement_code( ) polynesie_francaise__departement_code = polynesie_francaise_postal_code.get_departement_code( ) # then assert la_reunion_departement_code == "974" assert polynesie_francaise__departement_code == "987"
def update_beneficiary_mandatory_information( user: User, address: str, city: str, postal_code: str, activity: str, phone_number: Optional[str] = None ) -> None: user_initial_roles = user.roles update_payload = { "address": address, "city": city, "postalCode": postal_code, "departementCode": PostalCode(postal_code).get_departement_code(), "activity": activity, "hasCompletedIdCheck": True, } if not FeatureToggle.ENABLE_PHONE_VALIDATION.is_active() and not user.phoneNumber and phone_number: update_payload["phoneNumber"] = phone_number with transaction(): User.query.filter(User.id == user.id).update(update_payload) db.session.refresh(user) if ( not steps_to_become_beneficiary(user) and fraud_api.has_user_passed_fraud_checks(user) and not fraud_api.is_user_fraudster(user) ): subscription_api.check_and_activate_beneficiary(user.id) else: update_external_user(user) new_user_roles = user.roles underage_user_has_been_activated = ( UserRole.UNDERAGE_BENEFICIARY in new_user_roles and UserRole.UNDERAGE_BENEFICIARY not in user_initial_roles ) logger.info( "User id check profile updated", extra={"user": user.id, "has_been_activated": user.has_beneficiary_role or underage_user_has_been_activated}, )
def create_account( email: str, password: str, birthdate: date, marketing_email_subscription: bool = False, is_email_validated: bool = False, send_activation_mail: bool = True, remote_updates: bool = True, postal_code: str = None, phone_number: str = None, apps_flyer_user_id: str = None, apps_flyer_platform: str = None, ) -> User: email = sanitize_email(email) if find_user_by_email(email): raise exceptions.UserAlreadyExistsException() departement_code = PostalCode(postal_code).get_departement_code() if postal_code else None user = User( email=email, dateOfBirth=datetime.combine(birthdate, datetime.min.time()), isEmailValidated=is_email_validated, publicName=VOID_PUBLIC_NAME, # Required because model validation requires 3+ chars hasSeenTutorials=False, notificationSubscriptions=asdict(NotificationSubscriptions(marketing_email=marketing_email_subscription)), postalCode=postal_code, departementCode=departement_code, phoneNumber=phone_number, lastConnectionDate=datetime.now(), ) if not user.age or user.age < constants.ACCOUNT_CREATION_MINIMUM_AGE: raise exceptions.UnderAgeUserException() return initialize_account( user, password, apps_flyer_user_id, apps_flyer_platform, send_activation_mail, remote_updates )
def department_code(self) -> str: return PostalCode(self.postal_code).get_departement_code()
def get_postal_code_timezone(postal_code: str) -> str: return get_department_timezone( PostalCode(postal_code).get_departement_code())
def _set_offerer_departement_code(new_user: User, offerer: Offerer) -> User: if offerer.postalCode is not None: new_user.departementCode = PostalCode(offerer.postalCode).get_departement_code() else: new_user.departementCode = None return new_user
def store_departement_code(self): self.departementCode = PostalCode( self.postalCode).get_departement_code()