Ejemplo n.º 1
0
def index():
    """Return the start dashboard."""
    if not current_user.has_role('Startseite'):
        # User does not have privileges to read the start page => redirect to the first he can or implicitly to 403 by trying to access start
        for rdict in RoleURLs:
            if current_user.has_role(rdict['name']):
                return redirect(rdict['url'])
    return catchall('start')
Ejemplo n.º 2
0
def item_list():
    if current_user.item_list_locked:
        return render_template('locked_item_list.html', item_ranks=current_user.item_list.items)
    else:
        if current_user.has_role('initiate'):
            return edit_list_route(current_user, current_user, as_user_type='initiate')
        return edit_list_route(current_user, current_user)
Ejemplo n.º 3
0
def export(history_id, status_id):
    history = UploadHistoryModel.find_by_id(history_id)
    if history.user.id != current_user.id and current_user.has_role('Vendor'):
        return render_template('errors/404.html'), 404

    # 1 - Validated
    # 2 - Validation-err
    # 3 - Unvalidated
    status = ""

    if status_id.startswith('1'):
        status = 'validated'
    elif status_id.startswith('2'):
        status = 'validation-error'
    elif status_id.startswith('3'):
        status = 'unvalidated'

    file = s3.get_object(Bucket=current_app.config['S3_BUCKET'],
                         Key='{}/{}.csv'.format(status, history_id))

    return Response(
        file['Body'].read(),
        mimetype='application/csv',
        headers={
            "Content-Disposition":
            "attachment;filename=export_raw_data_{}.csv".format(history_id)
        })
Ejemplo n.º 4
0
def delete_post(ticket_id, post_id):
    # check user is authorised to delete posts. Only admin can do this.
    if not current_user.has_role('admin'):
        flash('You are not authorised to delete posts', category='warning')

    ticket = FlicketTicket.query.filter_by(id=ticket_id).first()
    post = FlicketPost.query.filter_by(id=post_id).first()

    if request.method == "POST":

        # delete images from database and folder
        images = FlicketUploads.query.filter_by(posts_id=post_id)
        for i in images:
            # delete files
            os.remove(
                os.path.join(
                    os.getcwd(),
                    app.config['ticket_upload_folder'] + '/' + i.file_name))
            # remove from database
            db.session.delete(i)

        db.session.delete(post)
        # commit changes
        db.session.commit()
        flash('post deleted', category='success')
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    return render_template('flicket/flicket_deletepost.html',
                           post=post,
                           title='Flicket - Delete post')
Ejemplo n.º 5
0
def result():
    id = request.args.get('id', type=int)
    history = UploadHistoryModel.find_by_id(id)
    if history.user.id != current_user.id and current_user.has_role('Vendor'):
        return render_template('errors/404.html'), 404
    # stdout = ""
    # stderr = ""
    # base_folder = current_app.config['UPLOAD_FOLDER']
    # folder = "{}/{}_vendor/{}/".format(base_folder, current_user.id, id)
    # if not os.path.exists(os.path.realpath(os.path.dirname(folder))):
    #     folder = "{}/{}_{}/{}/".format(base_folder, current_user.id, current_user.short_name, id)
    # file_dir = os.path.realpath(os.path.dirname(folder))
    # print(file_dir)
    # print(os.path.join(file_dir, "stdout"))
    # if os.path.isfile(os.path.join(file_dir, "stdout")):
    #     with open(os.path.join(file_dir, "stdout"), 'r') as file1:
    #         stdout = file1.read()
    #         file1.close()
    #     with open(os.path.join(file_dir, "stderr"), 'r') as file2:
    #         stderr = file2.read()
    #         stderr = stderr.replace("%", "")
    #         stderr = stderr.replace('\n', "<br/>")
    #         file2.close()

    return render_template('result.html', title='Job Result', history=history)
Ejemplo n.º 6
0
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False

        if current_user.has_role('Admin'):
            return True

        return False
Ejemplo n.º 7
0
def index():
    if current_user.is_authenticated:
        if current_user.has_role('Admin'):
            return redirect(url_for('admin.index'))
        else:
            return redirect(url_for('main.welcome'))
    else:
        return redirect(url_for('user.login'))
Ejemplo n.º 8
0
    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return True

        if current_user.has_role(['admin', 'gestor']):
            return True

        return True
Ejemplo n.º 9
0
 def index(self):
     if not current_user.is_active or not current_user.is_authenticated:
         return redirect(url_for('user.login'))
     else:
         if current_user.has_role('Admin'):
             return self.render('admin/myhome.html')
         else:
             return self.render('errors/404.html'), 404
Ejemplo n.º 10
0
def access():
    rooms = Room.query.all()
    if request.method == 'POST':
        room_post = request.form.get('rooms')
        dt_access = request.form.get('dt_access')
        hour_access = request.form.get('hour_access')

        date_access = dt_access + ' ' + hour_access
        date_time_access = datetime.strptime(date_access, '%d/%m/%Y %H:%M:%S')

        print(date_time_access)

        list_access = db.session.query(HourRegister, Room, User, Hours).join(
            Room, Room.id == HourRegister.room_id).join(
                User, User.id == HourRegister.user_id).join(
                    Hours, Hours.id == HourRegister.hours_id).filter(
                        Room.id == room_post,
                        User.id == session["user_id"],
                        HourRegister.datetime_start_access <= date_time_access,
                        HourRegister.datetime_end_access >= date_time_access,
                    ).all()

        if len(list_access) > 0 or current_user.has_role(['admin']) == True:
            flash([1, 'Access released.'], category='info')

            new_log = LogAccess(room_id=room_post,
                                user_id=session["user_id"],
                                date_access=date_access)

            db.session.add(new_log)
            db.session.commit()

            # Print query
            # for tt in list_access:
            #     print(tt[1].room,
            #         type(tt[0].dt_start_access),
            #         tt[2].name,
            #         tt[0].dt_access,
            #         tt[3].hour_start,
            #         tt[3].hour_end,
            #         tt[0].description)

            # Colocar aqui o RASP

            LED_PIN = 32
            GPIO.setmode(GPIO.BOARD)
            GPIO.setup(LED_PIN, GPIO.OUT)
            GPIO.output(LED_PIN, 1)
            time.sleep(3)
            GPIO.output(LED_PIN, 0)

        else:
            flash([0, 'Access denied.'], category='info')

    return render_template('access.html', rooms=rooms)


# ---------------------- End Access Room
Ejemplo n.º 11
0
def index():
  ## ensure that the login_next_url is none
  session['login_next_url'] = None
  if not current_user.is_authenticated:
    return redirect(url_for('user.login'))
  admin=False
  if current_user.has_role("admin"):
    admin=True

  return render_template('index.html', title="Home", admin=admin)
def before_request():
    lang = get_locale()
    lang = lang if lang else app.config['BABEL_DEFAULT_LOCALE']
    set_lang(lang)

    if request.path.startswith('/admin'):
        if current_user.is_authenticated:
            if not current_user.has_role("admin"):
                return redirect(url_for('user.logout'))
        else:
            return redirect(url_for('user.login'))
Ejemplo n.º 13
0
def close_status(ticket_id):
    ticket = FlicketTicket.query.filter_by(id=ticket_id).first()
    new_status = FlicketStatus.query.filter_by(status="Closed").first()

    print(request.referrer.split('/')[-4])

    # Check to see if user is authorised to close ticket.
    edit = False
    if ticket.user == current_user:
        edit = True
    if ticket.assigned == current_user:
        edit = True
    if current_user.has_role('admin'):
        edit = True

    if not edit:
        flash(
            'Only the person to which the ticket has been assigned, creator or Admin can close this ticket.',
            category='warning')
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    # Check to see if the ticket is already closed.
    if ticket.current_status.status == 'Closed':
        flash('Ticket is already closed.', category='warning')
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    f_mail = FlicketMail()
    f_mail.close_ticket(ticket)

    # add action record
    add_action(action='close', ticket=ticket)

    resolution = TicketResolution.query.filter_by(
        id=request.form['resolution']).first()

    ticket.current_status = new_status
    ticket.resolution = resolution
    ticket.resolved_by = current_user
    ticket.date_resolved = datetime.datetime.now()
    db.session.commit()

    flash('Ticket {} closed.'.format(str(ticket_id).zfill(5)),
          category='success')

    return redirect(url_for('ticket_view', ticket_id=ticket.id))
Ejemplo n.º 14
0
def master_upload():
    if current_app.config['ZINC_MODE']:
        form = MasterUploadForm()
        formats = FileFormatModel.find_all()
        if not current_user.company and not current_user.has_role('Admin'):
            flash('Permission denied', category='warning')
            return render_template('master_upload.html', title='Upload File', form=form, formats=formats)
        else:
            if request.method == 'POST' and form.validate_on_submit():
                return_msg = validate(form.file.data, form)
                return jsonify(return_msg)
            # else:
            #     # return_msg = validate(form)
            #     return jsonify(return_msg)
            return render_template('master_upload.html', title='Upload File', form=form, formats=formats)
    else:
        if request.method == 'POST':
            return jsonify(excel_validation(request))
        return render_template('master_upload.html', title='Upload File')
Ejemplo n.º 15
0
def delete_department(department_id=False):
    if department_id:

        # check user is authorised to delete departments. Only admin can do this.
        if not current_user.has_role('admin'):
            flash('You are not authorised to delete departments.',
                  category='warning')

        form = ConfirmPassword()

        #
        departments = FlicketCategory.query.filter_by(
            department_id=department_id)
        department = FlicketDepartment.query.filter_by(
            id=department_id).first()

        # we can't delete any departments associated with categories.
        if departments.count() > 0:
            flash(
                'Department has categories linked to it. Department can not be deleted unless the categories are removed.',
                category="danger")
            return redirect(url_for('departments'))

        if form.validate_on_submit():
            # delete category from database
            department = FlicketDepartment.query.filter_by(
                id=department_id).first()

            db.session.delete(department)
            # commit changes
            db.session.commit()
            flash('Department {} deleted.'.format(department.department),
                  category='success')
            return redirect(url_for('departments'))

        notification = "You are trying to delete department <span class=\"label label-default\">{}</span>.".format(
            department.department)

        return render_template('flicket_delete.html',
                               form=form,
                               notification=notification,
                               title='Flicket - Delete')
Ejemplo n.º 16
0
def welcome():
    user = UserModel.find_by_email(current_user.email)
    if current_user.has_role("Admin"):
        return redirect(url_for('admin_views.upload_report'))
    else:
        user_upload_count = get_user_job_count()
        latest_history = UploadHistoryModel.get_last_by_user_id(
            user_id=user.id)
        if latest_history:
            catalog_type = CATALOG_TYPE.get(latest_history.catalog_type)
            status = JOB_STATUS.get(latest_history.status_id)
            return render_template('welcome.html',
                                   user=user,
                                   title='Welcome',
                                   latest_history=latest_history,
                                   catalog_type=catalog_type,
                                   status=status,
                                   user_upload_count=user_upload_count)
        else:
            return render_template('welcome.html', user=user, title='Welcome')
Ejemplo n.º 17
0
def release(ticket_id=False):

    if ticket_id:

        ticket = FlicketTicket.query.filter_by(id=ticket_id).first()

        if ticket.current_status.status == 'Closed':
            flash('Ticket is closed.', category='warning')
            return redirect(url_for('ticket_view', ticket_id=ticket.id))

        # is ticket assigned.
        if not ticket.assigned:
            flash('Ticket has not been assigned')
            return redirect(url_for('ticket_view', ticket_id=ticket_id))

        # check ticket is owned by user or user is admin
        if (ticket.assigned.id !=
                current_user.id) and (not current_user.has_role('admin')):
            flash('You can not release a ticket you are not working on.')
            return redirect(url_for('ticket_view', ticket_id=ticket_id))

        # set status to open
        status = FlicketStatus.query.filter_by(status='Open').first()
        ticket.current_status = status
        ticket.assigned = None
        db.session.commit()

        # add action record
        add_action(action='release', ticket=ticket)

        # send email to state ticket has been released.
        f_mail = FlicketMail()
        f_mail.release_ticket(ticket)

        flash('You released ticket: {}'.format(ticket.id))
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    return redirect(url_for('tickets'))
Ejemplo n.º 18
0
def delete_category(category_id=False):
    if category_id:

        # check user is authorised to delete categories. Only admin can do this.
        if not current_user.has_role('admin'):
            flash('You are not authorised to delete categories.',
                  category='warning')

        form = ConfirmPassword()

        categories = FlicketTicket.query.filter_by(category_id=category_id)
        category = FlicketCategory.query.filter_by(id=category_id).first()

        # stop the deletion of categories assigned to tickets.
        if categories.count() > 0:
            flash(
                'Category is linked to posts. Category can not be deleted unless link is removed.',
                category="danger")
            return redirect(url_for('departments'))

        if form.validate_on_submit():
            # delete category from database
            category = FlicketCategory.query.filter_by(id=category_id).first()

            db.session.delete(category)
            # commit changes
            db.session.commit()
            flash('Category deleted', category='success')
            return redirect(url_for('departments'))

        notification = "You are trying to delete category <span class=\"label label-default\">{}</span> that belongs to department <span class=\"label label-default\">{}</span>.".format(
            category.category, category.department.department)

        return render_template('flicket/flicket_delete.html',
                               form=form,
                               notification=notification,
                               title='Flicket - Delete')
Ejemplo n.º 19
0
def open_status(ticket_id):

    ticket = FlicketTicket.query.filter_by(id=ticket_id).first()
    new_status = FlicketStatus.query.filter_by(status="Open").first()

    # Check to see if user is authorised to close ticket.
    edit = False
    if ticket.user == current_user:
        edit = True
    if ticket.assigned == current_user:
        edit = True
    if current_user.has_role('admin'):
        edit = True

    if not edit:
        flash(
            'Only the person to which the ticket has been assigned, creator or Admin can open this ticket.',
            category='warning')
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    f_mail = FlicketMail()
    f_mail.reopen_ticket(ticket)

    # add action record
    add_action(action='reopen', ticket=ticket)

    ticket.current_status = new_status
    ticket.resolution = None
    ticket.resolved_by = None
    ticket.date_resolved = None
    db.session.commit()

    flash('Ticket {} reopened.'.format(str(ticket_id).zfill(5)),
          category='success')

    return redirect(url_for('ticket_view', ticket_id=ticket.id))
Ejemplo n.º 20
0
 def is_accessible(self):
     if not is_authenticated():
         return False
     if not current_user.has_role(*self.get_accessible_roles()):
         return False
     return True
Ejemplo n.º 21
0
def edit_post(post_id):

    form = EditReplyForm(post_id=post_id)

    post = FlicketPost.query.filter_by(id=post_id).first()

    if not post:
        flash('Could not find post.', category='warning')
        return redirect(url_for('flicket_main'))

    # check to see if topic is closed. ticket can't be edited once it's closed.
    if post.ticket.current_status.status == "Closed":
        return redirect(url_for('ticket_view', ticket_id=post.ticket.id))

    # check user is authorised to edit post. Only author or admin can do this.
    not_authorised = True
    if post.user == current_user or current_user.has_role('admin'):
        not_authorised = False
    if not_authorised:
        flash('You are not authorised to edit this post.', category='warning')
        return redirect(url_for('ticket_view', ticket_id=post.ticket_id))

    if form.validate_on_submit():

        # before we make any changes store the original post content in the history table if it has changed.
        if post.modified_id:
            history_id = post.modified_id
        else:
            history_id = post.user_id
        if post.content != form.content.data:
            history = FlicketHistory(original_content=post.content,
                                     post=post,
                                     date_modified=datetime.datetime.now(),
                                     user_id=history_id)
            db.session.add(history)

        # loop through the selected uploads for deletion.
        if len(form.uploads.data) > 0:
            for i in form.uploads.data:
                # get the upload document information from the database.
                query = FlicketUploads.query.filter_by(id=i).first()
                # define the full uploaded filename
                the_file = os.path.join(app.config['ticket_upload_folder'],
                                        query.filename)

                if os.path.isfile(the_file):
                    # delete the file from the folder
                    os.remove(the_file)

                db.session.delete(query)

        post.content = form.content.data
        post.modified = current_user
        post.date_modified = datetime.datetime.now()

        files = request.files.getlist("file")
        upload_attachments = UploadAttachment(files)
        if upload_attachments.are_attachements():
            upload_attachments.upload_files()

        # add files to database.
        upload_attachments.populate_db(post)

        db.session.commit()
        flash('Post successfully edited.', category='success')

        return redirect(url_for('ticket_view', ticket_id=post.ticket_id))

    form.content.data = post.content

    return render_template('flicket/flicket_editpost.html',
                           title='Edit Post',
                           form=form)
Ejemplo n.º 22
0
 def is_accessible(self):
     if not current_user.is_authenticated:
         return False
     return current_user.has_role('admin', 'manager')
Ejemplo n.º 23
0
 def decorated_function(*args, **kwargs):
     if not current_user.is_authenticated or not current_user.has_role('admin'):
        return current_app.login_manager.unauthorized()
     return f(*args, **kwargs)
Ejemplo n.º 24
0
def user_role():
    # user_roles = any(role.name for role in current_user.roles if role.name in ['aluno','professor'])
    checked_role = current_user.has_role(['admin'])
    return str(checked_role)
Ejemplo n.º 25
0
def has_edit_permission():
    if not current_user.is_authenticated:
        return False
    return current_user.has_role('admin', 'manager')
Ejemplo n.º 26
0
 def is_accessible(self):
     if current_user.is_authenticated and current_user.has_role('admin'):
         return True
     return False
Ejemplo n.º 27
0
def edit_ticket(ticket_id, siteid=None):
    form = EditTicketForm(ticket_id=ticket_id)

    ticket = FlicketTicket.query.filter_by(id=ticket_id).first()

    if not ticket:
        flash('Could not find ticket.', category='warning')
        return redirect(url_for('tickets'))

    siteid = siteid

    site = Site.query.filter_by(id=ticket.site_id).one()

    if ticket.project_id != None:
        project = Project.query.filter_by(id=ticket.project_id).first()
    else:
        project = None

    if site != None:
        projects = Project.query.filter_by(site_id=site.id).all()
    else:
        projects = None
    app.logger.info(site.name)
    site_list = Site.query.all()

    if ticket.current_status.status == 'Closed':
        flash('Cannot edit closed ticket.', category='warning')
        return redirect(url_for('ticket_view', ticket_id=ticket.id))

    if ticket.current_status == None:
        ticket_status = FlicketStatus.query.filter_by(status='Open').first()
        ticket.current_status = ticket_status
        db.session.commit()

    # check user is authorised to edit ticket. Currently, only admin or author can do this.
    not_authorised = True
    if ticket.user == current_user or current_user.has_role(
            'admin') or ticket.assigned == current_user:
        not_authorised = False

    if not_authorised:
        flash('You are not authorised to edit this ticket.',
              category='warning')
        return redirect(url_for('ticket_view', ticket_id=ticket_id))

    if form.validate_on_submit():

        ticket.component = TicketComponent.query.filter_by(
            id=request.form['Component']).first()
        if request.form['date_due'] != " " and request.form['date_due'] != None:
            ticket.date_due = request.form['date_due']
        site = Site.query.filter_by(name=request.form['sitename']).one()
        ticket.site_id = site.id
        project = Project.query.filter_by(id=request.form['project']).first()
        ticket.project_id = project.id

        db.session.commit()

        # before we make any changes store the original post content in the history table if it has changed.
        if ticket.modified_id:
            history_id = ticket.modified_id
        else:
            history_id = ticket.started_id
        if ticket.description != form.content.data:
            history = FlicketHistory(original_content=ticket.description,
                                     topic=ticket,
                                     date_modified=datetime.datetime.now(),
                                     user_id=history_id)
            db.session.add(history)

        # loop through the selected uploads for deletion.
        if len(form.uploads.data) > 0:
            for i in form.uploads.data:
                # get the upload document information from the database.
                query = FlicketUploads.query.filter_by(id=i).first()
                # define the full uploaded filename
                the_file = os.path.join(app.config['ticket_upload_folder'],
                                        query.filename)

                if os.path.isfile(the_file):
                    # delete the file from the folder
                    os.remove(the_file)

                db.session.delete(query)

        ticket_status = FlicketStatus.query.filter_by(status='open').first()
        ticket_priority = FlicketPriority.query.filter_by(
            id=int(form.priority.data)).first()
        ticket_category = FlicketCategory.query.filter_by(
            id=int(form.category.data)).first()

        ticket.description = form.content.data
        ticket.ticket_name = form.title.data
        ticket.modified = current_user
        ticket.date_modified = datetime.datetime.now()
        ticket.current_status = ticket_status
        ticket.ticket_priority = ticket_priority
        ticket.category = ticket_category

        files = request.files.getlist("file")
        upload_attachments = UploadAttachment(files)
        if upload_attachments.are_attachements():
            upload_attachments.upload_files()

        # add files to database.
        upload_attachments.populate_db(ticket)

        db.session.commit()
        flash('Ticket successfully edited.', category='success')
        return redirect(url_for('ticket_view', ticket_id=ticket_id))

    form.content.data = ticket.description
    form.priority.data = ticket.ticket_priority_id
    form.title.data = ticket.ticket_name
    form.category.data = ticket.category_id

    components = TicketComponent.query.all()

    app.logger.info('edit ticket for site ' + site.name)
    return render_template('flicket/flicket_edittopic.html',
                           title='Edit Ticket',
                           form=form,
                           site=site,
                           sites=site_list,
                           siteid=siteid,
                           project=project,
                           projects=projects,
                           components=components,
                           ticket=ticket)
Ejemplo n.º 28
0
def filter_tickets():

    PER_PAGE = 5
    if request.args.get('page') == None:
        page = 1
    else:
        page = int(request.args.get('page'))

    siteid = request.args.get('site')

    access_allowed = check_valid_site(siteid)

    if id != None and access_allowed:
        site = Site.query.filter_by(id=siteid).first()
        tickets = FlicketTicket.query.filter_by(site_id=site.id)
    elif current_user.has_role('admin'):
        tickets = FlicketTicket.query
    else:
        tickets = []
        #get all the tickets for a particular user
        for user_site in current_user.sites:
            tickets += FlicketTicket.query.filter_by(site_id=user_site.id)
        site = None

    name = request.args.get('name', None)
    if name == "":
        tickets = tickets
    else:
        tickets = tickets.filter(FlicketTicket.ticket_name.contains(name))
    priority = request.args.get('priority', None)
    if priority == "all":
        tickets = tickets
    else:
        priority = FlicketPriority.query.filter_by(priority=priority).first()
        tickets = tickets.filter_by(ticket_priority_id=priority.id)
    category = request.args.get('category', None)
    if category == "all":
        tickets = tickets
    else:
        category = FlicketCategory.query.filter_by(category=category).first()
        tickets = tickets.filter_by(category_id=category.id)
    status = request.args.get('status', None)
    if status == "all":
        tickets = tickets
    else:
        status = FlicketStatus.query.filter_by(status=status).first()
        tickets = tickets.filter_by(status_id=status.id)
    tickets = tickets.order_by(FlicketTicket.date_added.desc()).paginate(
        page, PER_PAGE, False)
    previous_page = tickets.has_prev
    next_page = tickets.has_next
    pages = tickets.pages
    print(page)
    print(pages)
    return jsonify({
        "results":
        render_template('flicket/ticket_table_template.html', tickets=tickets),
        "page":
        page,
        "next":
        next_page,
        "previous":
        previous_page,
        "pages":
        pages
    })
Ejemplo n.º 29
0
 def decorated_function(*args, **kwargs):
     if not current_user.is_authenticated or not current_user.has_role(
             'admin'):
         return current_app.login_manager.unauthorized()
     return f(*args, **kwargs)
Ejemplo n.º 30
0
def ticket_create(siteid=None,
                  projectname=None,
                  component=None,
                  priority=None,
                  category=None):

    form = CreateTicketForm(title=request.args.get('ticket_description'),
                            priority=request.args.get('priority'))

    if form.validate_on_submit():

        # this is a new post so ticket status is 'open'
        ticket_status = FlicketStatus.query.filter_by(status='Open').first()
        ticket_priority = FlicketPriority.query.filter_by(
            id=int(form.priority.data)).first()
        ticket_category = FlicketCategory.query.filter_by(
            id=int(form.category.data)).first()
        ticket_component = TicketComponent.query.filter_by(
            id=request.form['Component']).first()

        if request.form['date_due'] != " " and request.form['date_due'] != None:
            date_due = request.form['date_due']
        else:
            date_due = None
        siteid = request.form['siteid']

        site = Site.query.filter_by(id=siteid).one()
        app.logger.info('new ticket for ' + siteid)
        app.logger.info('new ticket for ' + str(site.id))

        project_id = request.form['project']
        print(project_id)
        if project_id != "":
            project = Project.query.filter_by(id=project_id).first()
            project_id = project.id
        else:
            project_id = None
        print(project_id)

        files = request.files.getlist("file")
        upload_attachments = UploadAttachment(files)
        if upload_attachments.are_attachements():
            upload_attachments.upload_files()

        app.logger.info(str(site.name) + ' ' + str(site.id))
        # submit ticket data to database
        new_ticket = FlicketTicket(ticket_name=form.title.data,
                                   date_added=datetime.datetime.now(),
                                   user=current_user,
                                   current_status=ticket_status,
                                   description=form.content.data,
                                   ticket_priority=ticket_priority,
                                   category=ticket_category,
                                   component=ticket_component,
                                   site_id=site.id,
                                   project_id=project_id,
                                   date_due=date_due)
        db.session.add(new_ticket)

        # add attachments to the dataabase.
        upload_attachments.populate_db(new_ticket)
        # subscribe user to ticket
        subscribe = FlicketSubscription(user=current_user, ticket=new_ticket)
        db.session.add(subscribe)

        # commit changes to the database
        db.session.commit()

        flash('New Ticket created.', category='success')

        return redirect(url_for('ticket_view', ticket_id=new_ticket.id))

    print(request.args.get('site_id'))

    if siteid != None:
        site = Site.query.filter_by(id=siteid).first()
        sites = None
        if projectname != None:
            project = Project.query.filter_by(name=projectname).first()
        else:
            project = None
        projects = Project.query.filter_by(site_id=site.id).all()
    else:
        if current_user.has_role('admin'):
            sites = Site.query.all()
        else:
            sites = current_user.sites
        site = None
        project = None
        #Needs to be removed once ticket model has been updated
        projects = Project.query.all()

    components = TicketComponent.query.all()

    print(request.referrer.split('/')[-1])

    return render_template('flicket/flicket_create.html',
                           title='Create Ticket',
                           form=form,
                           sites=sites,
                           site=site,
                           project=project,
                           projects=projects,
                           components=components)
Ejemplo n.º 31
0
 def is_accessible(self):
     return current_user.has_role('Admin')
Ejemplo n.º 32
0
 def inaccessible_callback(self, name, **kwargs):
     if not is_authenticated():
         return current_app.user_manager.unauthenticated_view_function()
     if not current_user.has_role(*self.get_accessible_roles()):
         return current_app.user_manager.unauthorized_view_function()
Ejemplo n.º 33
0
 def is_accessible(self):
     return (
         not current_user.is_anonymous) and current_user.has_role('admin')
Ejemplo n.º 34
0
def tickets(siteid=None):

    access_allowed = check_valid_site(siteid)
    PER_PAGE = 5
    if request.args.get('page') == None:
        page = 1
    else:
        page = int(request.args.get('page'))

    if siteid != None and access_allowed:
        site = Site.query.filter_by(id=siteid).first()
        tickets = FlicketTicket.query.filter_by(site_id=site.id).order_by(
            FlicketTicket.date_added.desc()).paginate(page, PER_PAGE, False)
    elif current_user.has_role('admin'):
        site = None
        tickets = FlicketTicket.query.order_by(
            FlicketTicket.date_added.desc()).paginate(page, PER_PAGE, False)
    else:
        tickets = []
        #get all the tickets for a particular user
        tickets = FlicketTicket.query.filter(
            FlicketTicket.site_id.in_(
                [user_site.id for user_site in current_user.sites]))
        tickets = tickets.order_by(FlicketTicket.date_added.desc()).paginate(
            page, PER_PAGE, False)
        site = None

    print(tickets)

    form = SearchTicketForm()

    # get request arguments from the url
    status = request.args.get('status')
    department = request.args.get('department')
    category = request.args.get('category')
    content = request.args.get('content')
    user_id = request.args.get('user_id')

    if form.validate_on_submit():

        department = ''
        category = ''
        status = ''

        user = User.query.filter_by(email=form.email.data).first()
        if user:
            user_id = user.id

        # convert form inputs to it's table title
        if form.department.data:
            department = FlicketDepartment.query.filter_by(
                id=form.department.data).first().department
        if form.category.data:
            category = FlicketCategory.query.filter_by(
                id=form.category.data).first().category
        if form.status.data:
            status = FlicketStatus.query.filter_by(
                id=form.status.data).first().status

        return redirect(
            url_for(
                'tickets',
                content=form.content.data,
                page=page,
                department=department,
                category=category,
                status=status,
                user_id=user_id,
            ))

    number_results = len(tickets.items)
    all_status = FlicketStatus.query.all()
    all_priority = FlicketPriority.query.all()
    all_category = FlicketCategory.query.all()

    return render_template('flicket/flicket_tickets.html',
                           title='Tickets',
                           form=form,
                           tickets=tickets,
                           page=page,
                           number_results=number_results,
                           status=status,
                           department=department,
                           category=category,
                           user_id=user_id,
                           site=site,
                           all_status=all_status,
                           all_priority=all_priority,
                           all_category=all_category)