Exemplo n.º 1
0
class ReplyForm(FlaskForm):
    message = TextAreaField(lazy_gettext('Message'),
                            validators=[
                                validators.DataRequired(),
                                validators.Length(min=0, max=140)
                            ])
    submit = SubmitField(lazy_gettext('Submit'))
Exemplo n.º 2
0
def close_account():
    form = CloseAccountForm()

    if form.validate_on_submit():
        if verify_password(form.password.data, current_user.password):
            Chatmessage.query.filter_by(author=current_user.id).delete()
            ChatmessageIngame.query.filter_by(author=current_user.id).delete()
            Privatemessage.query.filter_by(sender=current_user.id).delete()
            Privatemessage.query.filter_by(receiver=current_user.id).delete()
            current_user.alternative_id = current_user.id + 100000000
            current_user.username = f'DeletedUser{current_user.id}'
            current_user.email = None
            current_user.password = None
            current_user.active = False
            current_user.avatar = None

            db.session.commit()

            return redirect(url_for('generic.index'))

        else:
            form.password.errors.append(lazy_gettext('Wrong password'))

    return render_template('profile/close_account.html',
                           form=form,
                           title=lazy_gettext('Close account'))
Exemplo n.º 3
0
    def validate_name(form, field):
        if len(field.data) <= 0:
            raise ValidationError(lazy_gettext("Username required"))

        u = db.session.query(User).filter_by(name_insensitive=field.data).first()
        if u:
            raise ValidationError(lazy_gettext("Username already taken"))
Exemplo n.º 4
0
class SalesOrderLineInlineAdmin(InlineFormAdmin):
    form_args = dict(
        unit_price=dict(label=lazy_gettext('Unit Price')),
        quantity=dict(label=lazy_gettext('Quantity')),
        remark=dict(label=lazy_gettext('Remark')),
    )

    def postprocess_form(self, form):
        from flask_admin.model.fields import AjaxSelectField
        ajaxLoader = QueryAjaxModelLoader(name='product',
                                          session=service.Info.get_db().session,
                                          model=Product,
                                          fields=['name'])
        form.product = AjaxSelectField(ajaxLoader, label=lazy_gettext('Product(Can be searched by first letter)'))
        form.retail_price = DisabledStringField(label=lazy_gettext('Retail Price'))
        form.price_discount = DisabledStringField(label=lazy_gettext('Price Discount'))
        form.original_amount = DisabledStringField(label=lazy_gettext('Original Amount'))
        form.actual_amount = DisabledStringField(label=lazy_gettext('Actual Amount'))
        form.discount_amount = DisabledStringField(label=lazy_gettext('Discount Amount'))
        form.remark = None
        form.sol_shipping_line = None
        form.external_id = None
        return form

    form_columns = ('id', 'product', 'unit_price', 'quantity',)
Exemplo n.º 5
0
def general_settings():
    form = GeneralSettingsForm(request.form)
    settings = UserSettings.query.filter_by(user=current_user.id).first()

    if form.validate_on_submit():
        settings.notification_sound = True if form.notification_sound.data == 'enabled' else False
        settings.allow_challenges = True if form.allow_challenges.data == 'enabled' else False
        settings.allow_private_messages = True if form.allow_private_messages.data == 'enabled' else False
        settings.allow_friend_requests = True if form.allow_friend_requests.data == 'enabled' else False

        if settings.country != form.country.data:
            country_changed_recently = settings.last_country_change and settings.last_country_change > datetime.utcnow() - timedelta(days=30)
            if settings.country and country_changed_recently:
                cooldown_timestamp = (settings.last_country_change + timedelta(days=30)).strftime('%d.%m.%Y, %H:%M:%S')
                flash(lazy_gettext('You can only change your country setting once per month. You need to wait until: ') + cooldown_timestamp + ' UTC.', 'danger')
                return render_template('profile/general_settings.html', form=form, title=lazy_gettext('General settings'))

            settings.country = form.country.data if form.country.data and form.country.data != 'None' else None
            settings.last_country_change = datetime.utcnow()
        db.session.commit()
        flash(lazy_gettext("Settings saved."))

    form.notification_sound.data = 'enabled' if settings.notification_sound else 'disabled'
    form.allow_challenges.data = 'enabled' if settings.allow_challenges else 'disabled'
    form.allow_private_messages.data = 'enabled' if settings.allow_private_messages else 'disabled'
    form.allow_friend_requests.data = 'enabled' if settings.allow_friend_requests else 'disabled'
    form.country.data = settings.country if settings.country else None
    
    return render_template('profile/general_settings.html', form=form, title=lazy_gettext('General settings'))
Exemplo n.º 6
0
 def get(self):
     parser = reqparse.RequestParser()
     parser.add_argument(
         'evt',
         required=True,
         help=lazy_gettext("L'événement concerné doit être spécifié"))
     parser.add_argument('token',
                         required=True,
                         help=lazy_gettext("Token ?"))
     args = parser.parse_args()
     inscription = Inscription.query.filter_by(token=args['token']).first()
     evt = int(args['evt'])
     if not inscription or inscription.evenement.id != evt:
         print('ici')
         return False
     intervenant = Intervenant.query.filter_by(
         id_inscription=inscription.id).first()
     if not intervenant:
         return {
             'nom': inscription.personne.nom,
             'prenom': inscription.personne.prenom
         }
     return {
         'nom': inscription.personne.nom,
         'prenom': inscription.personne.prenom,
         'email': inscription.personne.email
     }
Exemplo n.º 7
0
def search_results(search):
    results = []
    search_string = search.search.data

    if search_string:
        import re
        search_string_list = re.sub("[^\W]", " ", search_string).split()
        qry = db.session.query(Book).filter(Book.title == search_string)
        results = qry.all()
    else:
        qry = db.session.query(Book)
        results = qry.all()

    if not results:
        flash(lazy_gettext(u'No results found!'), 'info')
        return redirect(url_for('search'))
    else:
        # display results
        table = BookResults(results)
        if current_user.has_roles('Admin'):
            table.add_column(
                'edit',
                LinkCol(lazy_gettext(u'Edit'),
                        '.edit',
                        url_kwargs=dict(id='id')))
        table.border = True
        return render_template('books/results.html', table=table, form=search)
Exemplo n.º 8
0
 def action_batch_alter(self, ids):
     try:
         if request.form['promotion_id'] is '':
             raise Exception(lazy_gettext('No new promotion ID entered.'))
         new_promotion_id = int(request.form['promotion_id'])
         new_promotion = Promotion.query.filter_by(id=new_promotion_id).one_or_none()
         if new_promotion is None:
             raise Exception(lazy_gettext('New promotion not found.'))
         
         user_promotion_ids = [(id_pair.split(',')[0], id_pair.split(',')[1]) for id_pair in ids]
         user_promotions = UserPromotion.query.filter(
                 db.or_(
                     db.and_(UserPromotion.user_id == user_id, UserPromotion.promotion_id == promotion_id)
                     for user_id, promotion_id in user_promotion_ids
                 ))
         count = 0
         for user_promotion in user_promotions.all():
             user_promotion.promotion_id = new_promotion_id
             self.session.add(user_promotion)
             count += 1
         self.session.commit()
         flash(lazy_gettext("Successfully Changed") + f" {count} " + lazy_gettext("Records"))
         logger.info(f'Batch UserPromotion change by admin {auth_get_current_username()} changed {count} UserPromotions')
     except Exception as ex:
         self.session.rollback()
         flash(lazy_gettext("Error ") + f"{str(ex)}")
         logger.exception(f'Batch UserPromotion change by admin {auth_get_current_username()} raised exception')
Exemplo n.º 9
0
 def __init__(self):
     super().__init__(Client,
                      db.session,
                      name=lazy_gettext("Clients"),
                      category=lazy_gettext("Clients"),
                      menu_icon_type="fa",
                      menu_icon_value="fa-user")
Exemplo n.º 10
0
def barcode(userid):
    import barcode
    from barcode import writer
    from io import BytesIO, StringIO

    qry = db.session.query(User).filter(User.id==userid)
    user = qry.first()

    if user:
        if userid == current_user.id:
            fp = BytesIO()
            print(userid)
            code128 = barcode.get_barcode_class('code128')
            the_code = code128(userid.hex)
            the_code.write(fp)
            encoded_output = fp.getvalue().decode()
            encoded_output = encoded_output[encoded_output.find('<svg'):]
            fp.close()
            return render_template('auth/barcode.html', encoded_output=encoded_output, username=current_user.username)

        else:
            flash(lazy_gettext(u"You don't have the rights to display: \"{user}\"'s barcode").format(user=userid.hex))
            redirect(url_for('index'))
    else:
        flash(lazy_gettext(u'ERROR: User \"{userid}\" doesn''t exist').format(userid=userid.hex))
        return redirect(url_for('index'))
Exemplo n.º 11
0
class UserTable(Table):
    classes = ['table']
    id = Col('Id')
    username = Col(lazy_gettext(u'Username'))
    roles = RoleCol(lazy_gettext(u'Roles'))
    locale = LanguageCol(lazy_gettext(u'Language'))
    edit = ButtonCol(lazy_gettext(u'Edit'), '.edit', url_kwargs=dict(userid='id'))
Exemplo n.º 12
0
def change_avatar():
    if request.method == 'POST' and 'avatar' in request.files:
        avatar_file = request.files['avatar']
        if avatar_file.filename == '':
            flash(lazy_gettext('No selected file'), 'danger')
            return redirect(request.url)
        delete_avatar()
        filename = avatars.save(avatar_file,
                                name='{}.'.format(current_user.id))
        image = os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'],
                             'avatars', filename)
        if image.split('.')[-1].lower() not in ['jpg', 'jpeg', 'gif', 'png']:
            flash(lazy_gettext('Wrong image format.'))
            return redirect(url_for('profile.change_avatar'))
        im = Image.open(image)
        rgb_im = im.convert('RGB')
        rgb_im.thumbnail((64, 64), Image.BICUBIC)
        rgb_im.save(
            os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'], 'avatars',
                         f'{current_user.id}_thumbnail.jpg'), "JPEG")
        current_user.avatar = filename
        current_user.avatar_version = int(time.time())
        db.session.commit()
        flash(lazy_gettext("Avatar saved."))
        return redirect(url_for('profile.change_avatar'))

    avatar_url = avatars.url(
        current_user.avatar) if current_user.avatar else avatars.url(
            'default.png')

    return render_template('profile/change_avatar.html',
                           avatar_url=avatar_url,
                           title=lazy_gettext('Avatar Settings'))
Exemplo n.º 13
0
class UserProfileForm(Form):
    display_name = StringField(lazy_gettext("Display name"), [Length(max=30)])
    timezone = SelectField(coerce=str, label=lazy_gettext("Timezone"), default="UTC")
    locale = SelectField(
        lazy_gettext("Locale"), default="en", choices=[["en", "English"], ["fr", "French"], ["pl", "Polish"]]
    )
    submit = SubmitField(lazy_gettext("Update profile"))
Exemplo n.º 14
0
def validate_isbn13(form, field):
    if field.data:
        if len(field.data) != 13:
            raise ValidationError(
                lazy_gettext(u'ISBN 13 must be 10 character long'))
        if not field.data.isdigit():
            raise ValidationError(
                lazy_gettext(u'ISBN 13 must contain only numeric characters'))
Exemplo n.º 15
0
def test_get_languages(app):
    """Test default language."""
    app.config.update(
        I18N_LANGUAGES=[("en", lazy_gettext("engelsk")), ("de", lazy_gettext("tysk"))], BABEL_DEFAULT_LOCALE="da"
    )
    i18n = InvenioI18N(app)
    with app.app_context():
        assert i18n.get_languages() == [("da", "dansk"), ("en", "engelsk"), ("de", "tysk")]
Exemplo n.º 16
0
class ScoreForm(FlaskForm):
    score_value = IntegerField(lazy_gettext('Score'),
                               validators=[
                                   InputRequired(),
                                   NumberRange(min=0, max=180),
                                   impossible_numbers_check
                               ])
    submit = SubmitField(lazy_gettext('Submit score'))
Exemplo n.º 17
0
class AlbumForm(Form):
    title = StringField(lazy_gettext("Title"), [Length(max=255), DataRequired()])
    description = TextAreaField(lazy_gettext("Description"))
    private = BooleanField(lazy_gettext("Private"), default=False)
    genre = StringField("Genre", [Length(max=255)])
    tags = StringField("Tags", [Length(max=1000)])

    submit = SubmitField(lazy_gettext("Save"))
Exemplo n.º 18
0
class PaymentMethodLineInlineAdmin(InlineFormAdmin):
    form_args = dict(
        account_name=dict(label=lazy_gettext('Account Name')),
        account_number=dict(label=lazy_gettext('Account Number')),
        bank_name=dict(label=lazy_gettext('Bank Name')),
        bank_branch=dict(label=lazy_gettext('Bank Branch')),
        remark=dict(label=lazy_gettext('Remark')),
    )
Exemplo n.º 19
0
def details(hashid):
    tournament, creator_name = (Tournament.query.filter_by(hashid=hashid).join(
        User, User.id == Tournament.creator).add_columns(
            User.username).first_or_404())

    if current_user in tournament.banned_players:
        flash(lazy_gettext('You were banned from this tournament.'), 'danger')
        return redirect(url_for('generic.lobby'))

    form = ChatmessageForm()
    messages = (Chatmessage.query.filter_by(tournament_hashid=hashid).filter(
        Chatmessage.timestamp > (datetime.utcnow() - timedelta(hours=24))
    ).order_by(
        Chatmessage.id.desc()).limit(100).from_self().join(User).add_columns(
            User.username).join(UserStatistic).add_columns(
                UserStatistic.average).join(UserSettings).add_columns(
                    UserSettings.country).all())

    in_tournament = tournament in current_user.tournaments

    player1 = aliased(User)
    player2 = aliased(User)
    recent_results = (GameBase.query.filter_by(tournament=hashid).filter_by(
        status='completed').order_by(
            GameBase.end.desc()).limit(10).from_self().join(
                player1, GameBase.player1 == player1.id).add_columns(
                    player1.username).join(player2,
                                           GameBase.player2 == player2.id,
                                           isouter=True).add_columns(
                                               player2.username).all())

    settings = UserSettings.query.filter_by(user=current_user.id).first()
    if not settings:
        settings = UserSettings(user=current_user.id)
        db.session.add(settings)
        db.session.commit()

    for game, _, _ in recent_results:
        if game.bo_sets > 1:
            game.p1_final_score = game.p1_sets
            game.p2_final_score = game.p2_sets
        else:
            game.p1_final_score = game.p1_legs
            game.p2_final_score = game.p2_legs

    return render_template(
        'tournament/details.html',
        tournament=tournament,
        form=form,
        messages=messages,
        in_tournament=in_tournament,
        recent_results=recent_results,
        creator_name=creator_name,
        show_average_in_chat_list=settings.show_average_in_chat_list,
        country=settings.country,
        title=lazy_gettext('Tournament details'),
    )
Exemplo n.º 20
0
def test_get_languages(app):
    """Test default language."""
    app.config.update(I18N_LANGUAGES=[('en', lazy_gettext('engelsk')),
                                      ('de', lazy_gettext('tysk'))],
                      BABEL_DEFAULT_LOCALE='da')
    i18n = InvenioI18N(app)
    with app.app_context():
        assert i18n.get_languages() == \
            [('da', 'dansk'), ('en', 'engelsk'), ('de', 'tysk')]
Exemplo n.º 21
0
class RoleAdmin(ModelViewWithAccess):

    def is_accessible(self):
        return is_super_admin()

    def get_query(self):
        if not is_super_admin():
            return exclude_super_admin_roles(self.model.name, super(RoleAdmin, self).get_query())
        return super(RoleAdmin, self).get_query()

    def get_count_query(self):
        if not is_super_admin():
            return exclude_super_admin_roles(self.model.name, super(RoleAdmin, self).get_count_query())
        return super(RoleAdmin, self).get_count_query()

    def on_model_change(self, form, model, is_created):
        """Check whether the parent role is same as child role"""
        super(RoleAdmin, self).on_model_change(form, model, is_created)
        if is_created: # All models created from UI is not system role.
            model.is_system = False
        CycleReferenceValidator.validate(form, model, object_type='Role', parent='parent',
                                         children='sub_roles', is_created=is_created)

    column_list = ('id', 'name', 'description',)

    column_searchable_list = ('name', 'description', 'parent.name', 'parent.description')

    form_extra_fields = {
        'shadow_is_system': DisabledBooleanField(label=lazy_gettext('System Role')),
        'shadow_name': ReadonlyStringField(label=lazy_gettext('Name'))
    }

    form_args = dict(
        name=dict(label=lazy_gettext('Name'),
                  description=lazy_gettext('Name will not be editable after the role been created.')),
    )

    column_labels = dict(
        id=lazy_gettext('id'),
        description=lazy_gettext('Description'),
        users=lazy_gettext('User'),
        sub_roles=lazy_gettext('Sub Roles'),
        parent=lazy_gettext('Parent Role'),
        is_system = lazy_gettext('System Role')
    )

    form_columns = ('parent', 'name', 'shadow_name','description', 'shadow_is_system', 'sub_roles', 'users')

    form_create_rules = ('parent', 'name', 'description', 'shadow_is_system', 'sub_roles', 'users')

    form_edit_rules = ('parent', 'shadow_name', 'description', 'shadow_is_system', 'sub_roles', 'users')

    column_editable_list = ('description',)

    column_sortable_list = ('id', 'name', 'description')

    column_details_list = ('id', 'name', 'description', 'is_system', 'parent', 'sub_roles', 'users')
Exemplo n.º 22
0
class GameForm(FlaskForm):
    title = TextField(lazy_gettext(u'Title'), [validators.InputRequired()])
    publisher = TextField(lazy_gettext(u'Publisher'),
                          [validators.InputRequired()])
    author = TextField(lazy_gettext(u'Author'))
    isbn10 = TextField('ISBN 10', [validate_isbn10])
    isbn13 = TextField('ISBN 13', [validate_isbn13])
    category = SelectField(lazy_gettext(u'Category'), choices=book_categories)
    submit = SubmitField(lazy_gettext(u'Save'))
Exemplo n.º 23
0
def streamable_games(api_key, tournament_hashid=None):
    form = ConfirmStreamGameForm()
    if api_key != current_app.config['API_KEY']:
        return jsonify('Wrong API key.')

    games_query = Game.query

    if tournament_hashid:
        games_query = games_query.filter_by(tournament=tournament_hashid)

    games = (games_query.filter_by(webcam=True).filter_by(
        status='started').order_by(Game.id.desc()).limit(30).all())

    streamable_games = {}
    user_names = {}
    choices = []

    for game in games:
        player1 = WebcamSettings.query.filter_by(user=game.player1).first()
        if not player1 or not player1.stream_consent:
            continue
        player2 = WebcamSettings.query.filter_by(user=game.player2).first()
        if not player2 or not player2.stream_consent:
            continue
        if game.player1 not in user_names:
            user_names[game.player1] = (User.query.with_entities(
                User.username).filter_by(id=game.player1).first_or_404()[0])
        if game.player2 and game.player1 != game.player2 and game.player2 not in user_names:
            user_names[game.player2] = (User.query.with_entities(
                User.username).filter_by(id=game.player2).first_or_404()[0])
        streamable_games[game.hashid] = game
        choices.append((game.hashid, game.hashid))

    streamed_game = StreamGame.query.filter_by(user=current_user.id).first()
    streamed_game = streamed_game.hashid if streamed_game else None
    form.games.choices = choices

    if form.validate_on_submit():
        streamed_game = StreamGame.query.filter_by(
            user=current_user.id).first()
        if not streamed_game:
            streamed_game = StreamGame(user=current_user.id)
            db.session.add(streamed_game)
        streamed_game.hashid = form.games.data
        streamed_game.jitsi_hashid = streamable_games[
            form.games.data].jitsi_hashid
        db.session.commit()
        flash(lazy_gettext('Game selected as stream game.'), 'success')

    return render_template(
        'admin/stream.html',
        games=streamable_games,
        user_names=user_names,
        form=form,
        title=lazy_gettext('Streaming'),
    )
Exemplo n.º 24
0
class EditProfileForm(FlaskForm):
    firstname = StringField(lazy_gettext('First Name'),
                            [validators.Length(min=4, max=25)])
    lastname = StringField(lazy_gettext('Last Name'),
                           [validators.Length(min=4, max=25)])
    email = StringField(lazy_gettext('Email Address'), [validators.Email()])

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError(lazy_gettext('Email is already in use.'))
Exemplo n.º 25
0
def index():
    results = Book.query.all()
    table = BookResults(results,
                        no_items=lazy_gettext(u'No books in the database'))
    if current_user.has_roles('Admin'):
        table.add_column(
            'edit',
            LinkCol(lazy_gettext(u'Edit'), '.edit', url_kwargs=dict(id='id')))
        print(table)
    return render_template('books/index.html', table=table)
Exemplo n.º 26
0
 def postprocess_form(self, form):
     form.total_amount = DisabledStringField(label=lazy_gettext('Total Amount'))
     form.remark = None
     form.pol_receiving_lines = None
     ajaxLoader = QueryAjaxModelLoader(name='product',
                                       session=service.Info.get_db().session,
                                       model=Product,
                                       fields=['name'])
     form.product = AjaxSelectField(ajaxLoader, label=lazy_gettext('Product(Can be searched by first letter)'))
     return form
Exemplo n.º 27
0
def test_get_languages(app):
    """Test default language."""
    app.config.update(
        I18N_LANGUAGES=[
            ('en', lazy_gettext('engelsk')), ('de', lazy_gettext('tysk'))],
        BABEL_DEFAULT_LOCALE='da')
    i18n = InvenioI18N(app)
    with app.app_context():
        assert i18n.get_languages() == \
            [('da', 'dansk'), ('en', 'engelsk'), ('de', 'tysk')]
Exemplo n.º 28
0
class CountryForm(Form):
    name = StringField(
        lazy_gettext('Country Name'),
        validators=[
            DataRequired(message=lazy_gettext('Country name cant empty!'))
        ])
    iso_code_2 = StringField(
        lazy_gettext('ISO Code (2)'),
        validators=[
            DataRequired(message=lazy_gettext('ISO Code (2) cant empty!'))
        ])
    iso_code_3 = StringField(
        lazy_gettext('ISO Code (3)'),
        validators=[
            DataRequired(message=lazy_gettext('ISO Code (3) cant empty!'))
        ])
    address_format = TextAreaField(lazy_gettext('Address Format'))
    postcode_required = RadioField(lazy_gettext('Postcode required'),
                                   choices=[(True, 'Yes'), (False, 'No')],
                                   validators=[InputRequired()],
                                   coerce=lambda x: x != 'False')
    status = SelectField(lazy_gettext('Status'),
                         choices=[(1, 'Enabled'), (-1, 'Disabled')],
                         coerce=int)

    def validate_name(self, filed):
        if Country.query.filter_by(name=filed.data).first():
            return ValidationError(
                lazy_gettext('Country name [%s] already exists.' % filed.data))
Exemplo n.º 29
0
class InventoryTransactionLineInlineAdmin(InlineFormAdmin):

    form_args = dict(
        id=dict(label=lazy_gettext('id')),
        product=dict(label=lazy_gettext('Product')),
        price=dict(label=lazy_gettext('Inventory Transaction Price'),
                   description=lazy_gettext('For sales, it should be sell price, '
                                            'for item lost or broken, should be purchase price plus logistic expend')),
        in_transit_quantity=dict(label=lazy_gettext('In Transit Quantity'),
                                 description=lazy_gettext('Quantity of product ordered but still on the way')),
        quantity=dict(label=lazy_gettext('Actual Quantity Change'),
                      description=lazy_gettext('This quantity should be a negative number '
                                               'for sales, item lost or item broken')),
        remark=dict(label=lazy_gettext('Remark')),
    )

    def postprocess_form(self, form):
        from psi.app.views.components import DisabledStringField
        form.total_amount = DisabledStringField(label=lazy_gettext('Total Amount'))
        form.saleable_quantity = DisabledStringField(label=lazy_gettext('Saleable Quantity')),
        ajaxLoader = QueryAjaxModelLoader(name='product',
                                          session=service.Info.get_db().session,
                                          model=Product,
                                          fields=['name'])
        form.product = AjaxSelectField(ajaxLoader, label=lazy_gettext('Product(Can be searched by first letter)'))
        form.itl_receiving_line = None
        form.remark = None
        form.itl_shipping_line = None
        form.in_transit_quantity = None
        return form
Exemplo n.º 30
0
class PreferenceAdmin(ModelViewWithAccess):
    can_create, can_delete = False, False

    form_args = dict(
        def_so_incoming_type=dict(query_factory=Incoming.type_filter),
        def_so_incoming_status=dict(query_factory=Incoming.status_filter),
        def_so_exp_status=dict(query_factory=Expense.status_filter),
        def_so_exp_type=dict(query_factory=Expense.type_filter),
        def_po_logistic_exp_status=dict(query_factory=Expense.status_filter),
        def_po_logistic_exp_type=dict(query_factory=Expense.type_filter),
        def_po_goods_exp_status=dict(query_factory=Expense.status_filter),
        def_po_goods_exp_type=dict(query_factory=Expense.type_filter),
    )
    column_list = ('def_so_incoming_type', 'def_so_incoming_status',
                   'def_so_exp_status', 'def_so_exp_type',
                   'def_po_logistic_exp_status', 'def_po_logistic_exp_type',
                   'def_po_goods_exp_status', 'def_po_goods_exp_type')
    column_labels = dict(
        def_so_incoming_type=lazy_gettext('Default Sales Order Incoming Type'),
        def_so_incoming_status=lazy_gettext(
            'Default Sale Order Incoming Status'),
        def_so_exp_status=lazy_gettext('Default Sale Order Expense Status'),
        def_so_exp_type=lazy_gettext('Default Sales Order Expense Type'),
        def_po_logistic_exp_status=lazy_gettext(
            'Default Purchase Order Logistic Expense Status'),
        def_po_logistic_exp_type=lazy_gettext(
            'Default Purchase Order Logistic Expense Type'),
        def_po_goods_exp_status=lazy_gettext(
            'Default Purchase Order Goods Expense Status'),
        def_po_goods_exp_type=lazy_gettext(
            'Default Purchase Order Goods Expense Type'),
        remark=lazy_gettext('Remark'),
    )
Exemplo n.º 31
0
class IncomingAdmin(ModelViewWithAccess):
    column_list = ('id', 'date', 'amount', 'status', 'category', 'sales_order', 'remark')
    column_editable_list = ['date', 'amount', 'remark']

    edit_modal = True
    create_modal = True

    form_args = dict(
        status=dict(query_factory=Incoming.status_filter),
        category=dict(query_factory=Incoming.type_filter),
        date=dict(default=datetime.now()),
    )
    column_sortable_list = ('id', 'date', 'amount', ('status', 'status.display'),
                            ('category', 'category.display'), 'remark')
    column_labels = {
        'id': lazy_gettext('id'),
        'amount': lazy_gettext('Amount'),
        'date': lazy_gettext('Date'),
        'category': lazy_gettext('Category'),
        'status': lazy_gettext('Status'),
        'sales_order': lazy_gettext('Related Sales Order'),
        'remark': lazy_gettext('Remark'),
        'category.display': lazy_gettext('Category'),
        'status.display': lazy_gettext('Status'),
    }

    column_searchable_list = ['category.display', 'status.display']
    column_filters = ['date', 'amount', 'category.display', 'status.display']

    form_excluded_columns = ('sales_order', 'organization')
    column_details_exclude_list = ('organization',)
    column_formatters = {
        'sales_order': sales_order_formatter,
        'date': default_date_formatter,
    }
Exemplo n.º 32
0
class ChangeCountryForm(FlaskForm):
    country = SelectField(
        lazy_gettext('Country'),
        choices=COUNTRIES,
        validators=[DataRequired()],
    )

    accept_country_cooldown = BooleanField(lazy_gettext('Accept'),
                                           validators=[DataRequired()])

    submit = SubmitField(lazy_gettext('Save'))
Exemplo n.º 33
0
class MessageForm(FlaskForm):
    recipient = SelectField(lazy_gettext('Recipient'),
                            validators=[validators.DataRequired()],
                            coerce=int)
    subject = StringField(lazy_gettext('Subject'))
    message = TextAreaField(lazy_gettext('Message'),
                            validators=[
                                validators.DataRequired(),
                                validators.Length(min=0, max=140)
                            ])
    submit = SubmitField(lazy_gettext('Submit'))
Exemplo n.º 34
0
        def test_logic():
            from psi.app.models import Receiving, EnumValues
            from psi.app.views import ReceivingAdmin
            from psi.app.service import Info
            receiving = Receiving()
            complete_status = EnumValues.get(RECEIVING_COMPLETE_STATUS_KEY)
            receiving.status = complete_status
            db_session = Info.get_db().session
            receiving_admin = ReceivingAdmin(Receiving, db_session, name=lazy_gettext("Receiving"),
                                             category=lazy_gettext('Purchase'), menu_icon_type=ICON_TYPE_GLYPH,
                                             menu_icon_value='glyphicon-import')

            self.assertRaises(ValidationError, receiving_admin.on_model_delete, receiving)
Exemplo n.º 35
0
    def scaffold_form(self):
        # Start with the standard form as provided by Flask-Admin. We've already told Flask-Admin to exclude the
        # password field from this form.
        form_class = super(UserAdmin, self).scaffold_form()

        # Add a password field, naming it "password2" and labeling it "New Password".
        # autocomplete:new-password is to disable chrome to autofill password
        # Reference: http://stackoverflow.com/questions/15738259/disabling-chrome-autofill
        form_class.password2 = PasswordField(label=lazy_gettext('New Password'),
                                             render_kw={"autocomplete": "new-password"},
                                             description=lazy_gettext('Left blank if you don\'t want to change it, '
                                                                      'input the new password to change it'))
        return form_class
Exemplo n.º 36
0
 def postprocess_form(self, form):
     form.remark = None
     form.inventory_transaction_line = None
     form.product = None
     form.transient_price = DisabledStringField(label=lazy_gettext('Receiving Price'),
                                                description=lazy_gettext('Receiving price is brought from purchase '
                                                                         'order and can not be modified in '
                                                                         'receiving line'))
     form.transient_product = DisabledStringField(label=lazy_gettext('Product'))
     form.total_amount = DisabledStringField(label=lazy_gettext('Total Amount'))
     form.price = None
     form.inventory_links = None
     return form
Exemplo n.º 37
0
 def postprocess_form(self, form):
     from psi.app.views.components import DisabledStringField
     form.total_amount = DisabledStringField(label=lazy_gettext('Total Amount'))
     form.saleable_quantity = DisabledStringField(label=lazy_gettext('Saleable Quantity')),
     ajaxLoader = QueryAjaxModelLoader(name='product',
                                       session=service.Info.get_db().session,
                                       model=Product,
                                       fields=['name'])
     form.product = AjaxSelectField(ajaxLoader, label=lazy_gettext('Product(Can be searched by first letter)'))
     form.itl_receiving_line = None
     form.remark = None
     form.itl_shipping_line = None
     form.in_transit_quantity = None
     return form
Exemplo n.º 38
0
 def sub_reports(self):
     reps = ['overall',
             'today', 'yesterday',
             'this_week', 'last_week',
             'this_month', 'last_month',
             'this_quarter', 'last_quarter',
             'this_year', 'last_year',]
     return [(x, lazy_gettext(x.replace('_',' ').title())) for x in reps]
Exemplo n.º 39
0
 def test_lazy_gettext(self):
     app = flask.Flask(__name__)
     b = babel.Babel(app, default_locale='de_DE')
     yes = lazy_gettext(u'Yes')
     with app.test_request_context():
         assert text_type(yes) == 'Ja'
     app.config['BABEL_DEFAULT_LOCALE'] = 'en_US'
     with app.test_request_context():
         assert text_type(yes) == 'Yes'
Exemplo n.º 40
0
 def test_lazy_gettext_defaultdomain(self):
     app = flask.Flask(__name__)
     domain = babel.Domain(domain='test')
     b = babel.Babel(app, default_locale='de_DE', default_domain=domain)
     first = lazy_gettext('first')
     with app.test_request_context():
         assert text_type(first) == 'erste'
     app.config['BABEL_DEFAULT_LOCALE'] = 'en_US'
     with app.test_request_context():
         assert text_type(first) == 'first'
Exemplo n.º 41
0
 def postprocess_form(self, form):
     from flask_admin.model.fields import AjaxSelectField
     ajaxLoader = QueryAjaxModelLoader(name='product',
                                       session=service.Info.get_db().session,
                                       model=Product,
                                       fields=['name'])
     form.product = AjaxSelectField(ajaxLoader, label=lazy_gettext('Product(Can be searched by first letter)'))
     form.retail_price = DisabledStringField(label=lazy_gettext('Retail Price'))
     form.price_discount = DisabledStringField(label=lazy_gettext('Price Discount'))
     form.original_amount = DisabledStringField(label=lazy_gettext('Original Amount'))
     form.actual_amount = DisabledStringField(label=lazy_gettext('Actual Amount'))
     form.discount_amount = DisabledStringField(label=lazy_gettext('Discount Amount'))
     form.remark = None
     form.sol_shipping_line = None
     form.external_id = None
     return form
Exemplo n.º 42
0
def supplier_formatter(view, context, model, name):
    try:
        s = model.supplier
    except Exception:
        s = model

    fields = (name_field,
            {'label': lazy_gettext('QQ'), 'field': 'qq'},
            {'label': lazy_gettext('Phone'), 'field': 'phone'},
            {'label': lazy_gettext('Contact'), 'field': 'contact'},
            {'label': lazy_gettext('Email'), 'field': 'email'},
            {'label': lazy_gettext('Whole Sale Req'), 'field': 'whole_sale_req'},
            {'label': lazy_gettext('Can Mixed Whole Sale'), 'field': 'can_mixed_whole_sale'},
            remark_field,)
    detail_fields = (
        {'label': '开户名', 'field': 'account_name'},
        {'label': '账户号', 'field': 'account_number'},
        {'label': '开户行', 'field': 'bank_name'},
        {'label': '分行', 'field': 'bank_branch'},
    )
    if s is not None:
        return _obj_formatter(view, context, model, value=s, model_name='supplier',
                              title=s.name, fields=fields, detail_fields=detail_fields, detail_field='paymentMethods')
    return ''
Exemplo n.º 43
0
def create_app(config_name=None):
    app = Flask(__name__,
                static_url_path='/static',
                static_folder='static',
                instance_relative_config=True)

    # Configurações
    app.config.from_object('config.default')  # Configuração basica
    app.config.from_object(config_name)  # Configuração dependente do ambiente
    app.config.from_pyfile('config.py')  # Configuração local não versionada (chaves, segredos, senhas etc.)

    # Assets
    js = Bundle('js/vendor/jquery-1.11.0.min.js',
                'js/vendor/bootstrap.min.js',
                'js/vendor/jquery-ui.min.js',
                'js/plugins.js',
                'js/main.js',
                filters='jsmin', output='js/bundle.js')

    css = Bundle('css/bootstrap.min.css',
                 'css/scielo-portal.css',
                 filters='cssmin', output='css/bundle.css')

    assets.register('js_all', js)
    assets.register('css_all', css)
    assets.init_app(app)
    # i18n
    babel.init_app(app)
    # login
    login_manager.init_app(app)
    # Toolbar
    toolbar.init_app(app)
    # Mongo
    dbmongo.init_app(app)
    # SQLAlchemy
    dbsql.init_app(app)
    # Emails
    mail.init_app(app)

    # Handler de páginas de erro
    errors.register_errorhandlers(app)

    # Interface do admin
    from .models import User
    from app.admin import views

    admin = flask_admin.Admin(
        app, 'OPAC admin',
        index_view=views.AdminIndexView(),
        template_mode='bootstrap3',
        base_template="admin/opac_base.html")

    admin.add_view(views.CollectionAdminView(Collection, name=lazy_gettext(u'Coleção')))
    admin.add_view(views.SponsorAdminView(Sponsor, name=lazy_gettext(u'Financiador')))
    admin.add_view(views.JournalAdminView(Journal, name=lazy_gettext(u'Periódico')))
    admin.add_view(views.IssueAdminView(Issue, name=lazy_gettext(u'Fascículo')))
    admin.add_view(views.ArticleAdminView(Article, name=lazy_gettext(u'Artigo')))
    admin.add_view(views.UserAdminView(User, dbsql.session, name=lazy_gettext(u'Usuário')))

    from .main import main as main_bp
    app.register_blueprint(main_bp)

    return app
Exemplo n.º 44
0
 def postprocess_form(self, form):
     form.remark = None
     form.inventory_transaction_line = None
     form.total_amount = DisabledStringField(label=lazy_gettext('Total Amount'))
     return form
Exemplo n.º 45
0
 def __init__(self, description=None, **kwagrs):
       description = description or lazy_gettext(u'repeat captcha')
       super(CaptchaField, self).__init__(validators=(ValidCaptcha(),), label=lazy_gettext(u'captcha'), description=description, **kwagrs)
       self.widget = CaptchaWidget()
Exemplo n.º 46
0
 def postprocess_form(self, form):
     form.total_amount = DisabledStringField(
         label=lazy_gettext('Total Amount'))
     form.remark = None
     form.pol_receiving_lines = None
     return form
Exemplo n.º 47
0
# coding=utf-8
from psi.app.utils import user_has_role, format_util
from flask import url_for, render_template
from flask_babelex import lazy_gettext
from markupsafe import Markup

from psi.app.views.views_mapping import get_endpoint_by_type_attr

has_invoice_field = {'label': lazy_gettext('Has Invoice'), 'field': 'has_invoice'}
goods_amount_field = {'label': lazy_gettext('Goods Amount'), 'field': 'goods_amount'}
unit_price_field = {'label': lazy_gettext('Unit Price'), 'field': 'unit_price'}
price_field = {'label': lazy_gettext('Unit Price'), 'field': 'price'}
code_field = {'label': lazy_gettext('Code'), 'field': 'code'}
lead_day_field = {'label': lazy_gettext('Lead Day'), 'field': 'lead_day'}
deliver_day_field = {'label': lazy_gettext('Deliver Day'), 'field': 'deliver_day'}
spec_link_field = {'label': lazy_gettext('Spec Link'), 'field': 'spec_link'}
distinguishing_feature_field = {'label': lazy_gettext('Distinguishing Feature'), 'field': 'distinguishing_feature'}
retail_price_field = {'label': lazy_gettext('Retail Price'), 'field': 'retail_price'}
price_discount_field = {'label': lazy_gettext('Price Discount'), 'field': 'price_discount'}
quantity_field = {"label": lazy_gettext('Quantity'), "field": 'quantity'}
in_transit_quantity_field = {"label": lazy_gettext('In Transit Quantity'), "field": 'in_transit_quantity'}
product_field = {'label': lazy_gettext('Product'), 'field': 'product'}
logistic_amount_field = {'label': lazy_gettext('Logistic Amount'), 'field': 'logistic_amount'}
actual_amount_field = {'label': lazy_gettext('Actual Amount'), 'field': 'actual_amount'}
original_amount_field = {'label': lazy_gettext('Original Amount'), 'field': 'original_amount'}
discount_amount_field = {'label': lazy_gettext('Discount Amount'), 'field': 'discount_amount'}
total_amount_field = {'label': lazy_gettext('Total Amount'), 'field': 'total_amount'}
category_field = {'label': lazy_gettext('Category'), 'field': 'category'}
remark_field = {'label': lazy_gettext('Remark'), 'field': 'remark'}
status_field = {'label': lazy_gettext('Status'), 'field': 'status'}
type_field = {'label': lazy_gettext('Type'), 'field': 'type'}
Exemplo n.º 48
0
def test_json_encoder(app):
    """Test extension initalization."""
    InvenioI18N(app)
    assert app.json_encoder().encode("test") == '"test"'
    assert app.json_encoder().encode(lazy_gettext("test")) == '"test"'
Exemplo n.º 49
0
def create_app():
    app = Flask(__name__,
                static_url_path='/static',
                static_folder='static',
                instance_relative_config=False)

    app.url_map.converters['regex'] = RegexConverter

    # Configurações
    app.config.from_object('webapp.config.default')  # Configuração basica
    app.config.from_envvar('OPAC_CONFIG', silent=True)  # configuração do ambiente
    # login
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login_view'
    login_manager.init_app(app)

    # Minificando o HTML
    if not app.config['DEBUG']:
        HTMLMIN(app)

    # Registrando os filtros
    app.jinja_env.filters['abbrmonth'] = jinja_filters.abbrmonth
    app.jinja_env.filters['trans_alpha2'] = custom_filters.trans_alpha2

    # Assets
    js = Bundle('js/vendor/jquery-1.11.0.min.js',
                'js/vendor/underscore-min.js',
                'js/vendor/bootstrap.min.js',
                'js/vendor/iframeResizer.min.js',
                'js/vendor/clipboard.js',
                'js/common.js',
                'js/main.js',
                filters='jsmin', output='js/bundle.js')

    css = Bundle('css/bootstrap.min.css',
                 'css/scielo-portal.css',
                 'css/style.css',
                 filters='cssmin', output='css/bundle.css')

    assets.register('js_all', js)
    assets.register('css_all', css)
    assets.init_app(app)
    # i18n
    babel.init_app(app)
    # Debug Toolbar
    if app.config['DEBUG']:
        # Toolbar
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(app)
    # Mongo
    dbmongo.init_app(app)
    # SQLAlchemy
    dbsql.init_app(app)
    # Emails
    mail.init_app(app)

    # Interface do admin
    from .models import User, File, Image
    # from .admin import views
    from webapp.admin import views

    admin = flask_admin.Admin(
        app, 'OPAC admin',
        index_view=views.AdminIndexView(),
        template_mode='bootstrap3',
        base_template="admin/opac_base.html")

    admin.add_view(views.CollectionAdminView(Collection, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Coleção')))
    admin.add_view(views.SponsorAdminView(Sponsor, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Financiador')))
    admin.add_view(views.JournalAdminView(Journal, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Periódico')))
    admin.add_view(views.IssueAdminView(Issue, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Fascículo')))
    admin.add_view(views.ArticleAdminView(Article, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Artigo')))
    admin.add_view(views.PressReleaseAdminView(PressRelease, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Press Release')))
    admin.add_view(views.ResourceAdminView(Resource, category=lazy_gettext(u'Catálogo'), name=lazy_gettext(u'Recursos')))
    admin.add_view(views.NewsAdminView(News, category=lazy_gettext(u'Notícias'), name=lazy_gettext(u'Notícias')))
    admin.add_view(views.FileAdminView(File, dbsql.session, category=lazy_gettext(u'Ativos')))
    admin.add_view(views.ImageAdminView(Image, dbsql.session, category=lazy_gettext(u'Ativos')))
    admin.add_view(views.PagesAdminView(Pages, category=lazy_gettext(u'Ativos'), name=lazy_gettext(u'Páginas')))
    admin.add_view(views.UserAdminView(User, dbsql.session, category=lazy_gettext(u'Gestão'), name=lazy_gettext(u'Usuário')))

    from .main import main as main_bp
    app.register_blueprint(main_bp)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
Exemplo n.º 50
0
def create_app():
    app = Flask(__name__,
                static_url_path='/static',
                static_folder='static',
                instance_relative_config=False)

    # Configurações
    app.config.from_object('webapp.config.default')  # Configuração basica
    app.config.from_envvar('OPAC_CONFIG', silent=True)  # configuração do ambiente

    # Assets
    js = Bundle('js/vendor/jquery-1.11.0.min.js',
                'js/vendor/bootstrap.min.js',
                'js/vendor/jquery-ui.min.js',
                'js/plugins.js',
                'js/main.js',
                filters='jsmin', output='js/bundle.js')

    css = Bundle('css/bootstrap.min.css',
                 'css/scielo-portal.css',
                 filters='cssmin', output='css/bundle.css')

    assets.register('js_all', js)
    assets.register('css_all', css)
    assets.init_app(app)
    # i18n
    babel.init_app(app)
    # login
    login_manager.init_app(app)

    if app.config['DEBUG']:
        # Toolbar
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(app)
    # Mongo
    dbmongo.init_app(app)
    # SQLAlchemy
    dbsql.init_app(app)
    # Emails
    mail.init_app(app)

    # Interface do admin
    from .models import User
    # from .admin import views
    from webapp.admin import views

    admin = flask_admin.Admin(
        app, 'OPAC admin',
        index_view=views.AdminIndexView(),
        template_mode='bootstrap3',
        base_template="admin/opac_base.html")

    admin.add_view(views.CollectionAdminView(Collection, name=lazy_gettext(u'Coleção')))
    admin.add_view(views.SponsorAdminView(Sponsor, name=lazy_gettext(u'Financiador')))
    admin.add_view(views.JournalAdminView(Journal, name=lazy_gettext(u'Periódico')))
    admin.add_view(views.IssueAdminView(Issue, name=lazy_gettext(u'Fascículo')))
    admin.add_view(views.ArticleAdminView(Article, name=lazy_gettext(u'Artigo')))
    admin.add_view(views.UserAdminView(User, dbsql.session, name=lazy_gettext(u'Usuário')))

    from .main import main as main_bp
    app.register_blueprint(main_bp)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app