Example #1
0
 def set_selects(self, filter_noship=False):
     countries = Country.query.all()
     if filter_noship:
         self.country.choices = (
             [(c.alpha3, c.name) for c in countries if not c.noship]
         )
     else:
         self.country.choices = (
             [(c.alpha3, c.name) for c in countries]
         )
     usa = Country.get(alpha3='USA')
     self.usa_state.choices = (
         [(s.abbreviation, s.name) for s in usa.states]
     )
     self.usa_state.choices.insert(0, ('0', 'Select a state:'))
     can = Country.get(alpha3='CAN')
     self.can_state.choices = (
         [(s.abbreviation, s.name) for s in can.states]
     )
     self.can_state.choices.insert(0, ('0', 'Select a province:'))
     aus = Country.get(alpha3='AUS')
     self.aus_state.choices = (
         [(s.abbreviation, s.name) for s in aus.states]
     )
     self.aus_state.choices.insert(0, ('0', 'Select a state:'))
Example #2
0
    def populate_address(self, address):
        """Populate an `Address` with data from `AddressForm`.

        Args:
            address: the `Address` instance to populate.
        """
        address.first_name = self.first_name.data
        address.last_name = self.last_name.data
        address.business_name = self.business_name.data
        address.address_line1 = self.address_line1.data
        address.address_line2 = self.address_line2.data
        address.city = self.city.data
        address.postalcode = self.postalcode.data
        address.country = Country.get(alpha3=self.country.data)
        address.email = self.email.data
        address.phone = self.phone.data
        address.fax = self.fax.data
        if self.country.data == 'USA':
            address.state = address.country.get_state(
                abbreviation=self.usa_state.data
            )
        elif self.country.data == 'CAN':
            address.state = address.country.get_state(
                abbreviation=self.can_state.data
            )
        elif self.country.data == 'AUS':
            address.state = address.country.get_state(
                abbreviation=self.aus_state.data
            )
        else:
            address.unlisted_state = self.unlisted_state.data
Example #3
0
def add_country():
    form = CountryForm()

    if form.validate_on_submit():
        try:
            country = Country(name=form.name.data)

            db.session.add(country)
            db.session.commit()

            return redirect('/add-country')
        except:
            db.session.rollback()

    return render_template('add_country.html', form=form)
Example #4
0
def resetdb(fast=False):
    """Erase db and/or create a new one with an admin account."""
    from pycountry import countries
    from app.auth import models as auth_models
    from app.seeds import models as seeds_models
    from app.shop import models as shop_models
    from app.shop.models import Country, State
    resp = input(
        'WARNNG: This will erase existing database and create a new one! '
        'Proceed anyway? y/N: '
    )
    if 'y' in resp.lower():
        print('Erasing existing database if present...')
        db.session.rollback()
        db.session.remove()
        if db.engine.dialect.name == 'postgresql':
            db.engine.execute('drop schema if exists public cascade')
            db.engine.execute('create schema public')
        db.drop_all()
        print('Configuring mappers...')
        db.configure_mappers()
        print('Creating new database...')
        db.create_all()
        db.session.commit()
        admin = User()
        db.session.add(admin)
        print('Populating countries table...')
        db.session.add_all(
            sorted(
                Country.generate_from_alpha3s(c.alpha3 for c in countries),
                key=lambda x: x.name
            )
        )
        db.session.flush()
        print('Setting safe to ship countries...')
        stsfile = Path(
            app.config['JSON_FOLDER'], 
            'safe_to_ship_countries.json'
        )
        try:
            with stsfile.open('r', encoding='utf-8') as ifile:
                sts = json.loads(ifile.read())
                for c in sts:
                    if isinstance(c, str):
                        alpha3 = c
                        thresh = None
                    else:
                        alpha3 = c[0]
                        thresh = c[1]
                    country = Country.get(alpha3=alpha3)
                    if thresh:
                        country.at_own_risk_threshold = thresh
                    country.safe_to_ship = True
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}". This file should be a JSON list '
                'containing alpha3 country codes for countries we can safely '
                'ship to, including ones that become at own risk above a '
                'certain cost total, which should be 2 value lists formatted '
                '["<alpha3", <int or decimal cost above which is at own '
                'risk>], e.g.: [... , "JPN", "NLD", ["NOR", 50], "PRI", '
                '"ESP", ...]'.format(stsfile.absolute())
            )
        print('Setting noship countries...')
        ncfile = Path(app.config['JSON_FOLDER'], 'noship_countries.json')
        try:
            with ncfile.open('r', encoding='utf-8') as ifile:
                a3s = json.loads(ifile.read())
                for alpha3 in a3s:
                    country = Country.get(alpha3=alpha3)
                    country.noship = True
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}"! This file should be a JSON list '
                'containing alpha3 country codes for countries we cannot '
                'ship to. e.g.: ["BGD", "BRA", "CHN", ... ]'
                .format(ncfile.absolute())
            )
        print('Populating States/Provinces/etc...')
        try:
            sfile = Path(app.config['JSON_FOLDER'], 'states.json')
            with sfile.open('r', encoding='utf-8') as ifile:
                d = json.loads(ifile.read())
                db.session.add_all(
                    State.generate_from_dict(d)
                )
                db.session.flush()
        except FileNotFoundError:
            db.session.rollback()
            raise FileNotFoundError(
                'Could not find file "{}"! If it does not exist, it should '
                'be created and contain a JSON object formatted: { "<country '
                'alpha3 code>": { "<state abbreviation>": "<state name>", '
                '... }, ... } e.g. {"USA": {"AL": "Alabama", "AK": '
                '"Alaska", ... }, "CAN": {"AB": "Alberta", "BC": '
                '"British Columbia", ... }, ... }'.format(sfile.absolute())
            )
        print('Setting California sales tax...')
        rfile = Path(app.config['JSON_FOLDER'], 'rates.json')
        try:
            with rfile.open('r', encoding='utf-8') as ifile:
                rates = json.loads(ifile.read())
            ca = State.get(
                country=Country.get(alpha3='USA'), abbreviation='CA'
            )
            ca.tax = Decimal(str(rates['sales tax']['USA']['CA']))
            db.session.flush()
        except FileNotFoundError:
            raise FileNotFoundError(
                'Could not find file "{}"! It should contain a JSON object '
                'including: { "sales tax": {"USA": {"CA":<tax rate>i, ... }, '
                '... }, ... }'.format(rfile.absolute())
            )
        print('Creating first administrator account...')
        if fast:
            admin.name = 'admin'
            admin.email = 'admin@localhost'
            admin.set_password('sgsadmin')  # Very secure!
        else:
            admin.name = input('Enter name for admin account: ')
            admin.email = input('Enter email address for admin account: ')
            while True:
                pw = getpass('Enter new password: '******'Confirm new password: '******'Passwords do not match! Please try again.')
                else:
                    break
            admin.set_password(pw)
        admin.grant_permission(Permission.MANAGE_SEEDS)
        admin.grant_permission(Permission.MANAGE_USERS)
        admin.confirmed = True
        print('Admin account "{}" created!'.format(admin.name))
        db.session.commit()
        print('Database was successfully created!')
    else:
        print('Aborted.')