def load_all_accounts(): page_number = 1 total_pages = 1 validate_url = URLValidator() crm_account_model = apps.get_model('suitecrm', 'CrmAccount') address_model = apps.get_model('profiles', 'Address') while page_number <= total_pages: response = si.get_all_accounts_by_page(page_number) total_pages = response.get('meta', {}).get('total-pages', 1) data = response.get('data', []) for item in data: account_id = item.get('id') attr = item.get('attributes', {}) website = attr.get('website', '') name = attr.get('name', '') support_plan = attr.get('support_plan_c', '') line_1 = attr.get('billing_address_street', '') line_2 = attr.get('billing_address_street_2', '') city = attr.get('billing_address_city', '') state = attr.get('billing_address_state', '') zip_code = attr.get('billing_address_postalcode', '') country = attr.get('billing_address_country', '')[:2] if not account_id: continue if not support_plan: support_plan = 'community' elif not support_plan == 'partner': support_plan = 'vip-' + support_plan account, _ = crm_account_model.objects.get_or_create( crm_id=account_id) account.name = name account.plan = support_plan has_address = (bool(line_1) or bool(line_2) or bool(city) or bool(state) or bool(zip_code) or bool(country)) if has_address: if account.address: address = account.address address.line_1 = line_1 address.line_2 = line_2 address.city = city address.state = state address.country = Country(code=country) address.save() else: address, _ = address_model.objects.get_or_create( line_1=line_1, line_2=line_2, city=city, state=state, zip_code=zip_code, country=Country(code=country)) account.address = address try: validate_url(website) account.website = website except ValidationError: pass account.save() page_number += 1
def clean(self, value, previous_values): if value and not Country(value).numeric: raise ValidationError(_("Please enter a valid country code.")) return value
def __init__(self, *args, **kwargs): self.event = event = kwargs.pop('event') self.request = kwargs.pop('request', None) self.validate_vat_id = kwargs.pop('validate_vat_id') self.all_optional = kwargs.pop('all_optional', False) kwargs.setdefault('initial', {}) if not kwargs.get('instance') or not kwargs['instance'].country: # Try to guess the initial country from either the country of the merchant # or the locale. This will hopefully save at least some users some scrolling :) locale = get_language() country = event.settings.invoice_address_from_country if not country: valid_countries = countries.countries if '-' in locale: parts = locale.split('-') if parts[1].upper() in valid_countries: country = Country(parts[1].upper()) elif parts[0].upper() in valid_countries: country = Country(parts[0].upper()) else: if locale in valid_countries: country = Country(locale.upper()) kwargs['initial']['country'] = country super().__init__(*args, **kwargs) if not event.settings.invoice_address_vatid: del self.fields['vat_id'] c = [('', pgettext_lazy('address', 'Select state'))] fprefix = self.prefix + '-' if self.prefix else '' cc = None if fprefix + 'country' in self.data: cc = str(self.data[fprefix + 'country']) elif 'country' in self.initial: cc = str(self.initial['country']) elif self.instance and self.instance.country: cc = str(self.instance.country) if cc and cc in COUNTRIES_WITH_STATE_IN_ADDRESS: types, form = COUNTRIES_WITH_STATE_IN_ADDRESS[cc] statelist = [ s for s in pycountry.subdivisions.get(country_code=cc) if s.type in types ] c += sorted([(s.code[3:], s.name) for s in statelist], key=lambda s: s[1]) elif fprefix + 'state' in self.data: self.data = self.data.copy() del self.data[fprefix + 'state'] self.fields['state'] = forms.ChoiceField(label=pgettext_lazy( 'address', 'State'), required=False, choices=c) self.fields['state'].widget.is_required = True if not event.settings.invoice_address_required or self.all_optional: for k, f in self.fields.items(): f.required = False f.widget.is_required = False if 'required' in f.widget.attrs: del f.widget.attrs['required'] elif event.settings.invoice_address_company_required and not self.all_optional: self.initial['is_business'] = True self.fields['is_business'].widget = BusinessBooleanRadio( require_business=True) self.fields['company'].required = True self.fields['company'].widget.is_required = True self.fields['company'].widget.attrs['required'] = 'required' del self.fields['company'].widget.attrs['data-display-dependency'] if 'vat_id' in self.fields: del self.fields['vat_id'].widget.attrs[ 'data-display-dependency'] self.fields['name_parts'] = NamePartsFormField( max_length=255, required=event.settings.invoice_name_required and not self.all_optional, scheme=event.settings.name_scheme, titles=event.settings.name_scheme_titles, label=_('Name'), initial=(self.instance.name_parts if self.instance else self.instance.name_parts), ) if event.settings.invoice_address_required and not event.settings.invoice_address_company_required and not self.all_optional: self.fields['name_parts'].widget.attrs[ 'data-required-if'] = '#id_is_business_0' self.fields['name_parts'].widget.attrs[ 'data-no-required-attr'] = '1' self.fields['company'].widget.attrs[ 'data-required-if'] = '#id_is_business_1' if not event.settings.invoice_address_beneficiary: del self.fields['beneficiary']
def login_user(request): logger.info('function_call login_user(request) ->') message = "" username = password = '' msg = "" error = "" MYLANGUAGES = [] MYLANGUAGES.append(Country("DE")) MYLANGUAGES.append(Country("GB")) if settings.SERVICE == False: if request.user.is_anonymous(): if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) logger.debug( "User Authentication: [%s] successfully logged in" % username) if len(UserProfile.objects.all().filter( user=user)) == 0: profile = UserProfile( user=user, startday=settings.USER_STARTDAY, endday=settings.USER_ENDDAY, steps=settings.USER_STEPS, min_hours=settings.USER_MIN_HOUR, max_hours=settings.USER_MAX_HOUR, hourly_rate=settings.USER_HOURLY_RATE, vacation_days=settings.USER_VACATION_DAYS, acquisition=settings.USER_ACQUISITION) profile.save() if len(Customer.objects.all().filter( name='Intern')) == 0: customer = Customer(name='Intern', street='-', postcode='-', city='-', status=0) customer.save() if len(Project.objects.all().filter( name='Vacation')) == 0: project = Project( name='Vacation', description='Vacation', responsible=user, budget=0, billing=0, hourly_rate=0, status=0, customer=Customer.objects.get(name='Intern')) project.save() if len(Project.objects.all().filter(name='Ill')) == 0: project = Project( name='Ill', description='Ill', responsible=user, budget=0, billing=0, hourly_rate=0, status=0, customer=Customer.objects.get(name='Intern')) project.save() return HttpResponseRedirect(reverse('acquisition')) else: error = _("Deactivated Account") logger.debug( "User Authentication: [%s] account inactive" % username) else: error = _("Incorrect Login") logger.debug( "User Authentication: [%s] username and/or password incorrect" % username) else: logger.debug("User Authentication: [%s] already logged in" % username) return HttpResponseRedirect(reverse('acquisition')) else: if request.user.is_anonymous(): if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_superuser: login(request, user) return HttpResponseRedirect(reverse('acquisition')) error = _("Site is under maintenance") message = "error" c = { 'msg': msg, 'error': error, 'user': request.user, 'message': message, 'SITENAME': settings.SITENAME, 'management': request.user.has_perm('auth.management'), 'SSL': settings.SSL_ENABLED, 'request': request, 'languages': MYLANGUAGES } c.update(csrf(request)) return render_to_response('login.html', c, context_instance=RequestContext(request))
def test_compare_addresses_with_country_object(address): copied_address = address.get_copy() copied_address.country = Country("PL") copied_address.save() assert address == copied_address
def test_is_valid_shipping_method_shipping_outside_the_shipping_zone( mock_clear_shipping_method, vatlayer): cart = Mock(shipping_address=Mock(country=Country('PL')), shipping_method=Mock(shipping_zone=Mock(countries=['DE']))) assert not is_valid_shipping_method(cart, vatlayer, None) mock_clear_shipping_method.assert_called_once_with(cart)
def test_get_taxes_for_country(vatlayer, compare_taxes): taxes = get_taxes_for_country(Country("PL")) compare_taxes(taxes, vatlayer)
def test_payments_query( payment_txn_captured, permission_manage_orders, staff_api_client ): query = """ { payments(first: 20) { edges { node { id gateway capturedAmount { amount currency } total { amount currency } actions chargeStatus billingAddress { country { code country } firstName lastName cityArea countryArea city companyName streetAddress1 streetAddress2 postalCode } transactions { amount { currency amount } } creditCard { expMonth expYear brand firstDigits lastDigits } } } } } """ response = staff_api_client.post_graphql( query, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["payments"]["edges"][0]["node"] pay = payment_txn_captured assert data["gateway"] == pay.gateway amount = str(data["capturedAmount"]["amount"]) assert Decimal(amount) == pay.captured_amount assert data["capturedAmount"]["currency"] == pay.currency total = str(data["total"]["amount"]) assert Decimal(total) == pay.total assert data["total"]["currency"] == pay.currency assert data["chargeStatus"] == PaymentChargeStatusEnum.FULLY_CHARGED.name assert data["billingAddress"] == { "firstName": pay.billing_first_name, "lastName": pay.billing_last_name, "city": pay.billing_city, "cityArea": pay.billing_city_area, "countryArea": pay.billing_country_area, "companyName": pay.billing_company_name, "streetAddress1": pay.billing_address_1, "streetAddress2": pay.billing_address_2, "postalCode": pay.billing_postal_code, "country": { "code": pay.billing_country_code, "country": Country(pay.billing_country_code).name, }, } assert data["actions"] == [OrderAction.REFUND.name] txn = pay.transactions.get() assert data["transactions"] == [ {"amount": {"currency": pay.currency, "amount": float(str(txn.amount))}} ] assert data["creditCard"] == { "expMonth": pay.cc_exp_month, "expYear": pay.cc_exp_year, "brand": pay.cc_brand, "firstDigits": pay.cc_first_digits, "lastDigits": pay.cc_last_digits, }
def country(self, obj): return Country(obj.name).name if len(obj.name) == 2 else "-"
def test_compare_addresses_different_country(billing_address): copied_address = billing_address.get_copy() copied_address.country = Country('FR') copied_address.save() assert billing_address != copied_address
def get_country(code): return Country(code=code)
def test_compare_addresses_with_country_object(billing_address): copied_address = billing_address.get_copy() copied_address.country = Country('PL') copied_address.save() assert billing_address == copied_address
def process_request(self, request): client_ip = get_client_ip(request) if client_ip: request.country = get_country_by_ip(client_ip) if not request.country: request.country = Country(settings.DEFAULT_COUNTRY)
def setUp(self): self.tricko = UserPropertyKey.objects.create(key_name='Veľkosť trička') self.topanka = UserPropertyKey.objects.create( key_name='Veľkosť topánky') self.mobil = UserPropertyKey.objects.create(key_name='Mobil') self.telefon = UserPropertyKey.objects.create(key_name='Telefon') self.op = UserPropertyKey.objects.create(key_name='OP') self.address = Address.objects.create(street='Jablková 47', town='Dolný Kubín', postal_code='94742', country=Country('SK')) rnd = Round.objects.create( semester=Semester.objects.create( competition=Competition.objects.create( name='Test competition'), name='test', number=74, year=2024, ), number=2, visible=False, solutions_visible=False, ) self.target_user = _create_random_user( first_name='Jozef', last_name='Novak', email='*****@*****.**', gender='M', graduation=2017, ) self.source_user = _create_random_user( first_name='Jozef', last_name='Novak', email='*****@*****.**', gender='M', graduation=2015, home_address=self.address, ) UserProperty.objects.create(user=self.target_user, key=self.tricko, value='L') UserProperty.objects.create(user=self.target_user, key=self.topanka, value='47') UserProperty.objects.create(user=self.target_user, key=self.mobil, value='+421908123456') UserProperty.objects.create(user=self.source_user, key=self.tricko, value='M') UserProperty.objects.create(user=self.source_user, key=self.topanka, value='42') UserProperty.objects.create(user=self.source_user, key=self.telefon, value='+421212345678') UserProperty.objects.create(user=self.source_user, key=self.op, value='EA000444') task = Task.objects.create( name='Test task', round=rnd, number=3, description_points=0, source_points=0, has_source=False, has_description=False, ) task.assign_person(self.source_user, contests_constants.TASK_ROLE_REVIEWER)
def test_get_discount_for_checkout_shipping_voucher( shipping_cost, shipping_country_code, discount_value, discount_type, countries, expected_value, monkeypatch, channel_USD, shipping_method, shipping_method_data, ): manager = get_plugins_manager() subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD")) monkeypatch.setattr( "saleor.checkout.utils.calculations.checkout_subtotal", lambda manager, checkout_info, lines, address, discounts: subtotal, ) monkeypatch.setattr( "saleor.discount.utils.calculations.checkout_subtotal", lambda manager, checkout_info, lines, address, discounts: subtotal, ) monkeypatch.setattr("saleor.checkout.utils.is_shipping_required", lambda lines: True) shipping_total = Money(shipping_cost, "USD") checkout = Mock( spec=Checkout, is_shipping_required=Mock(return_value=True), channel_id=channel_USD.id, channel=channel_USD, shipping_method=shipping_method, get_shipping_price=Mock(return_value=shipping_total), shipping_address=Mock(country=Country(shipping_country_code)), ) voucher = Voucher.objects.create( code="unique", type=VoucherType.SHIPPING, discount_value_type=discount_type, countries=countries, ) VoucherChannelListing.objects.create( voucher=voucher, channel=channel_USD, discount=Money(discount_value, channel_USD.currency_code), ) shipping_address = Mock(spec=Address, country=Mock(code="PL")) checkout_info = CheckoutInfo( checkout=checkout, shipping_address=shipping_address, delivery_method_info=get_delivery_method_info(shipping_method_data, shipping_address), billing_address=None, channel=channel_USD, user=None, valid_pick_up_points=[], all_shipping_methods=[], ) discount = get_voucher_discount_for_checkout(manager, voucher, checkout_info, [], None, None) assert discount == Money(expected_value, "USD")
def __str__(self): if len(self.name) != 2: return self.name return format_html('{country_code} – {country_name}', country_code=self.name, country_name=Country(self.name).name)
def dispatch(self, request, *args, **kwargs): self.country_code = self.kwargs['country_code'] self.country = Country(self.country_code) self.in_book = {'0': False, '1': True, None: True}[kwargs['in_book']] self.invalid_emails = kwargs['email'] return super().dispatch(request, *args, **kwargs)
def setUp(self): self.tricko = UserPropertyKey.objects.create(key_name="Veľkosť trička") self.topanka = UserPropertyKey.objects.create( key_name="Veľkosť topánky") self.mobil = UserPropertyKey.objects.create(key_name="Mobil") self.telefon = UserPropertyKey.objects.create(key_name="Telefon") self.op = UserPropertyKey.objects.create(key_name="OP") self.address = Address.objects.create(street="Jablková 47", town="Dolný Kubín", postal_code="94742", country=Country("SK")) rnd = Round.objects.create( semester=Semester.objects.create( competition=Competition.objects.create( name="Test competition"), name="test", number=74, year=2024, ), number=2, visible=False, solutions_visible=False, ) self.target_user = _create_random_user( first_name="Jozef", last_name="Novak", email="*****@*****.**", gender="M", graduation=2017, ) self.source_user = _create_random_user( first_name="Jozef", last_name="Novak", email="*****@*****.**", gender="M", graduation=2015, home_address=self.address, ) UserProperty.objects.create(user=self.target_user, key=self.tricko, value="L") UserProperty.objects.create(user=self.target_user, key=self.topanka, value="47") UserProperty.objects.create(user=self.target_user, key=self.mobil, value="+421908123456") UserProperty.objects.create(user=self.source_user, key=self.tricko, value="M") UserProperty.objects.create(user=self.source_user, key=self.topanka, value="42") UserProperty.objects.create(user=self.source_user, key=self.telefon, value="+421212345678") UserProperty.objects.create(user=self.source_user, key=self.op, value="EA000444") task = Task.objects.create( name="Test task", round=rnd, number=3, description_points=0, source_points=0, has_source=False, has_description=False, ) task.assign_person(self.source_user, contests_constants.TASK_ROLE_REVIEWER)
def to_internal_value(self, data): return {self.field_name: Country(data)}
def create_orders(how_many=10): taxes = get_taxes_for_country(Country(settings.DEFAULT_COUNTRY)) discounts = fetch_discounts(timezone.now()) for dummy in range(how_many): order = create_fake_order(discounts, taxes) yield "Order: %s" % (order, )
(None, "127.0.0.1"), ], ) def test_get_client_ip(ip_address, expected_ip): """Test providing a valid IP in X-Forwarded-For returns the valid IP. Otherwise, if no valid IP were found, returns the requester's IP. """ expected_ip = expected_ip headers = {"HTTP_X_FORWARDED_FOR": ip_address} if ip_address else {} request = RequestFactory(**headers).get("/") assert get_client_ip(request) == expected_ip @pytest.mark.parametrize( "country, expected_currency", [(Country("PL"), "PLN"), (Country("US"), "USD"), (Country("GB"), "GBP")], ) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country.code) assert currency == expected_currency def test_create_superuser(db, client, media_root): credentials = {"email": "*****@*****.**", "password": "******"} # Test admin creation assert User.objects.all().count() == 0 create_superuser(credentials) assert User.objects.all().count() == 1 admin = User.objects.all().first() assert admin.is_superuser assert not admin.avatar
def test_multi_deserialize_save(self): serializer = MultiCountrySerializer(data={"countries": ["NZ", "AU"]}) self.assertTrue(serializer.is_valid()) saved = serializer.save() loaded = MultiCountry.objects.get(pk=saved.pk) self.assertEqual(loaded.countries, [Country("NZ"), Country("AU")])
def build_preview_invoice_pdf(event): locale = event.settings.invoice_language if not locale or locale == '__user__': locale = event.settings.locale with rolledback_transaction(), language(locale, event.settings.region): order = event.orders.create(status=Order.STATUS_PENDING, datetime=timezone.now(), expires=timezone.now(), code="PREVIEW", total=100 * event.tax_rules.count()) invoice = Invoice(order=order, event=event, invoice_no="PREVIEW", date=timezone.now().date(), locale=locale, organizer=event.organizer) invoice.invoice_from = event.settings.get('invoice_address_from') invoice.invoice_from_name = invoice.event.settings.get( 'invoice_address_from_name') invoice.invoice_from_zipcode = invoice.event.settings.get( 'invoice_address_from_zipcode') invoice.invoice_from_city = invoice.event.settings.get( 'invoice_address_from_city') invoice.invoice_from_country = invoice.event.settings.get( 'invoice_address_from_country') invoice.invoice_from_tax_id = invoice.event.settings.get( 'invoice_address_from_tax_id') invoice.invoice_from_vat_id = invoice.event.settings.get( 'invoice_address_from_vat_id') introductory = event.settings.get('invoice_introductory_text', as_type=LazyI18nString) additional = event.settings.get('invoice_additional_text', as_type=LazyI18nString) footer = event.settings.get('invoice_footer_text', as_type=LazyI18nString) payment = _("A payment provider specific text might appear here.") invoice.introductory_text = str(introductory).replace('\n', '<br />') invoice.additional_text = str(additional).replace('\n', '<br />') invoice.footer_text = str(footer) invoice.payment_provider_text = str(payment).replace('\n', '<br />') invoice.invoice_to_name = _("John Doe") invoice.invoice_to_street = _("214th Example Street") invoice.invoice_to_zipcode = _("012345") invoice.invoice_to_city = _('Sample city') invoice.invoice_to_country = Country('DE') invoice.invoice_to = '{}\n{}\n{} {}'.format(invoice.invoice_to_name, invoice.invoice_to_street, invoice.invoice_to_zipcode, invoice.invoice_to_city) invoice.invoice_to_beneficiary = '' invoice.file = None invoice.save() invoice.lines.all().delete() if event.tax_rules.exists(): for i, tr in enumerate(event.tax_rules.all()): tax = tr.tax(Decimal('100.00'), base_price_is='gross') InvoiceLine.objects.create( invoice=invoice, description=_("Sample product {}").format(i + 1), gross_value=tax.gross, tax_value=tax.tax, tax_rate=tax.rate) else: InvoiceLine.objects.create(invoice=invoice, description=_("Sample product A"), gross_value=100, tax_value=0, tax_rate=0) return event.invoice_renderer.generate(invoice)
def __init__(self, *args, **kwargs): self.event = event = kwargs.pop('event') self.request = kwargs.pop('request', None) self.validate_vat_id = kwargs.pop('validate_vat_id') self.all_optional = kwargs.pop('all_optional', False) kwargs.setdefault('initial', {}) if not kwargs.get('instance') or not kwargs['instance'].country: # Try to guess the initial country from either the country of the merchant # or the locale. This will hopefully save at least some users some scrolling :) locale = get_language() country = event.settings.invoice_address_from_country if not country: valid_countries = countries.countries if '-' in locale: parts = locale.split('-') if parts[1].upper() in valid_countries: country = Country(parts[1].upper()) elif parts[0].upper() in valid_countries: country = Country(parts[0].upper()) else: if locale in valid_countries: country = Country(locale.upper()) kwargs['initial']['country'] = country super().__init__(*args, **kwargs) if not event.settings.invoice_address_vatid: del self.fields['vat_id'] if not event.settings.invoice_address_required or self.all_optional: for k, f in self.fields.items(): f.required = False f.widget.is_required = False if 'required' in f.widget.attrs: del f.widget.attrs['required'] elif event.settings.invoice_address_company_required and not self.all_optional: self.initial['is_business'] = True self.fields['is_business'].widget = BusinessBooleanRadio( require_business=True) self.fields['company'].required = True self.fields['company'].widget.is_required = True self.fields['company'].widget.attrs['required'] = 'required' del self.fields['company'].widget.attrs['data-display-dependency'] if 'vat_id' in self.fields: del self.fields['vat_id'].widget.attrs[ 'data-display-dependency'] self.fields['name_parts'] = NamePartsFormField( max_length=255, required=event.settings.invoice_name_required and not self.all_optional, scheme=event.settings.name_scheme, titles=event.settings.name_scheme_titles, label=_('Name'), initial=(self.instance.name_parts if self.instance else self.instance.name_parts), ) if event.settings.invoice_address_required and not event.settings.invoice_address_company_required and not self.all_optional: self.fields['name_parts'].widget.attrs[ 'data-required-if'] = '#id_is_business_0' self.fields['name_parts'].widget.attrs[ 'data-no-required-attr'] = '1' self.fields['company'].widget.attrs[ 'data-required-if'] = '#id_is_business_1' if not event.settings.invoice_address_beneficiary: del self.fields['beneficiary']
def test_compare_addresses_different_country(address): copied_address = address.get_copy() copied_address.country = Country("FR") copied_address.save() assert address != copied_address
def test_multi_deserialize_save(self): serializer = MultiCountrySerializer(data={'countries': ['NZ', 'AU']}) self.assertTrue(serializer.is_valid()) saved = serializer.save() loaded = MultiCountry.objects.get(pk=saved.pk) self.assertEqual(loaded.countries, [Country('NZ'), Country('AU')])
def get_country_by_ip(ip_address): geo_data = georeader.get(ip_address) if geo_data and 'country' in geo_data and 'iso_code' in geo_data['country']: country_iso_code = geo_data['country']['iso_code'] if country_iso_code in countries: return Country(country_iso_code)
def supervisor_of(self, code=False): countries = (Country(g.name) for g in self.user.groups.all() if len(g.name) == 2) return countries if code else [c.name for c in countries]
def test_manager_get_tax_rate_percentage_value(plugins, amount, product): country = Country("PL") tax_rate_value = ExtensionsManager( plugins=plugins).get_tax_rate_percentage_value(product, country) assert tax_rate_value == Decimal(amount)
def load_all_contacts(): page_number = 1 total_pages = 1 validate_email = EmailValidator() crm_contact_model = apps.get_model('suitecrm', 'CrmContact') crm_account_model = apps.get_model('suitecrm', 'CrmAccount') crm_email_model = apps.get_model('suitecrm', 'CrmEmail') address_model = apps.get_model('profiles', 'Address') while page_number <= total_pages: response = si.get_all_contacts_by_page(page_number) total_pages = response.get('meta', {}).get('total-pages', 1) data = response.get('data', []) for item in data: contact_id = item.get('id') attr = item.get('attributes', {}) first_name = attr.get('first_name', '') last_name = attr.get('last_name', '') line_1 = attr.get('primary_address_street', '') line_2 = attr.get('primary_address_street_2', '') city = attr.get('primary_address_city', '') state = attr.get('primary_address_state', '') zip_code = attr.get('primary_address_postalcode', '') country = attr.get('primary_address_country', '')[:2] email_1 = attr.get('email1', '') email_2 = attr.get('email2', '') account_id = attr.get('account_id', '') if not contact_id or not account_id: continue try: account = crm_account_model.objects.get(crm_id=account_id) except crm_account_model.DoesNotExist: continue contact, _ = crm_contact_model.objects.get_or_create( crm_id=contact_id) contact.first_name = first_name contact.last_name = last_name contact.account = account has_address = (bool(line_1) or bool(line_2) or bool(city) or bool(state) or bool(zip_code) or bool(country)) if has_address: if contact.address: address = contact.address address.line_1 = line_1 address.line_2 = line_2 address.city = city address.state = state address.country = Country(code=country) address.save() else: address, _ = address_model.objects.get_or_create( line_1=line_1, line_2=line_2, city=city, state=state, zip_code=zip_code, country=Country(code=country)) contact.address = address contact.save() try: validate_email(email_1) crm_email_model.objects.get_or_create(contact=contact, email=email_1) except ValidationError: pass try: validate_email(email_2) crm_email_model.objects.get_or_create(contact=contact, email=email_2) except ValidationError: pass page_number += 1