Exemplo n.º 1
0
    def test_ticket_creation(self):
        with self.app.app_context():
            self.db.session.add(self.user)
            tt = TicketType.query.filter_by(fixed_id=0).one()
            ticket = Ticket(type=tt, user_id=self.user.id)
            self.db.session.add(ticket)
            self.db.session.commit()

            # A ticket without a payment isn't sold...
            assert sum(TicketType.get_ticket_sales().values()) == 0
            assert ticket.id is not None

            ticket.paid = True
            self.db.session.flush()
            # ... but a paid one is
            assert sum(TicketType.get_ticket_sales().values()) == 1

            ticket.expires = datetime.utcnow() - timedelta(minutes=1)
            self.db.session.flush()
            # Expired tickets still count towards capacity
            assert sum(TicketType.get_ticket_sales().values()) == 1

            ticket.paid = False
            self.db.session.flush()
            assert sum(TicketType.get_ticket_sales().values()) == 0
Exemplo n.º 2
0
def cPanelClienteG():
    if "ID" in session and session["Tipo"] == 6:
        if request.method == 'GET':
            objEmpresa = Empresa()
            objEmpresa.setIdTipo(1)
            empresas = objEmpresa.ListarEmpresasXTipo()
            return render_template('clienteG/cPanelClienteG.html',
                                   avatar=session["Avatar"],
                                   empresas=empresas,
                                   ID=session['ID'])
        elif request.method == 'POST':
            titulo = request.form['titulo']
            detalle = request.form['detalle']
            urgencia = request.form['urgencia']
            empresa = request.form['empresa']

            objTicket = Ticket()
            objTicket.setTicket(titulo, detalle, empresa,
                                int(session['Empresa']), int(session['ID']),
                                urgencia)
            if objTicket.agregarTicket():
                return "Exito"
            else:
                return "Error"
        else:
            return redirect(url_for('index'))
    else:
        return redirect(url_for('index'))
Exemplo n.º 3
0
def cPanelAsignador():
    if "ID" in session and session['Tipo'] == 3:
        objTicket = Ticket()
        objDep = Departamento()
        deps = objDep.ListarDepartamentosXEstado(1)
        tickets = objTicket.ListarTicketsXAsignar(int(session['Empresa']))
        return render_template('asignador/cPanelAsignador.html', avatar=session["Avatar"], tickets=tickets, departamentos=deps, ID=session['ID'])
    else:
        return redirect(url_for('index'))
Exemplo n.º 4
0
def cPanelEmpleado():
    if "ID" in session and session['Tipo'] == 4:
        objTicket = Ticket()
        tickets = objTicket.ListarTicketsXEmpresaDep(session['Empresa'],
                                                     session['Departamento'],
                                                     1)
        ticketsUsario = objTicket.ListarTicketsXEmpleado(2, int(session['ID']))
        return render_template('empleado/cPanelEmpleado.html',
                               avatar=session["Avatar"],
                               tickets=tickets,
                               ID=session['ID'])
    else:
        return redirect(url_for('index'))
Exemplo n.º 5
0
def cerrarTicket():
        if "ID" in session and session['Tipo'] == 4:
            if request.method == 'POST':
                objTicket = Ticket()
                objEmail = Email()
                objUsuario = Usuario()
                IdTicket = int(request.form['IdTicket'])
                Resolucion = request.form['res']

                objTicket.setID(IdTicket)
                objTicket.setResolucion(Resolucion)
                ticket = objTicket.consultarID()
                objUsuario.setID(int(ticket[0].IdCreador))
                usuario = objUsuario.consultarID()
                
                if len(ticket) > 0:
                    if objTicket.cerrarTicket():

                        if len(usuario) > 0:
                            email = usuario[0].Email
                            objEmail.emailActualizacionTicket(email,2,ticket[0].Titulo,0)
                        else:
                            return "Error"

                        return "Exito"
                    else:
                        return "Error"
        else:
            return redirect(url_for('inicio.index'))
Exemplo n.º 6
0
def _q_index(request):
    user = request.user
    if user:
        list_type = request.get_form_var("list_type", "invited")

        n_invited = user.n_open_invited
        n_participated = user.n_open_participated
        n_yours = user.n_user_open_submit_pull_requests
        counts = [n_invited, n_participated, n_yours, None]
        tab_info = []
        for tab, count in zip(MY_PULL_REQUESTS_TAB_INFO, counts):
            tab.update(count=count)
            tab_info.append(tab)

        if list_type == "participated":
            tickets = user.get_participated_pull_requests()
        elif list_type == "yours":
            tickets = user.get_user_submit_pull_requests()
        elif list_type == "explore":
            from models.ticket import Ticket

            tickets = Ticket.gets_all_opened()
            ticket_total_len = len(tickets)
            shuffle(tickets)
        else:
            tickets = user.get_invited_pull_requests()
        is_closed_tab = False
        ticket_total_len = len(tickets)
        return st("my_pull_requests.html", **locals())
Exemplo n.º 7
0
def run_app():
    print("""
    Witaj w systemie losowania!
    Co chcesz zrobić?
    1 - Dodaj nowego gracza
    2 - Zmień liczby gracza
    3 - Losuj / nowa gra
    4 - Tabela zwycięzców
    5 - Zamknij program
    """)
    while True:
        choice = input()
        if choice == "1":
            new_ticket()
        elif choice == "2":
            change_numbers()
        elif choice == "3":
            comp_w = compare_winners()
            result = new_lottery(comp_w)
            if result:
                winner = Ticket.load_ticket_by_id(cursor, result)
                print("Zwycięzcą jest: ", winner.first_name, winner.last_name)
        elif choice == "4":
            table_of_winners()
        elif choice == "5":
            break
        else:
            print("Co dalej? Wprowadź poprawną operację.")
    def depositar_vehiculo(self, matricula, tipo):
        depositado = False


        if(tipo.lower() == "turismo"):
            if(len(parking_servicio.plazas_libres_turismo()) > 0):
                plaza_asignada = parking_servicio.plazas_libres_turismo()[0]
                parking_servicio.plazas_libres_turismo()[0].ocupada = True
                depositado = True

        elif(tipo.lower() == "motocicleta"):
            if(len(parking_servicio.plazas_libres_moto()) > 0):
                plaza_asignada = parking_servicio.plazas_libres_moto()[0]
                parking_servicio.plazas_libres_moto()[0].ocupada = True
                depositado = True

        elif(tipo.lower() == "movilidad reducida"):
            if(len(parking_servicio.plazas_libres_movreducida()) > 0):
                plaza_asignada = parking_servicio.plazas_libres_movreducida()[0]
                parking_servicio.plazas_libres_movreducida()[0].ocupada = True
                depositado = True

        if(depositado):
            pin = randint(111111,999999)

            ticket = Ticket(matricula, datetime.now(), plaza_asignada.id, pin)
            ticket_servicio.save(ticket)


        else:
            raise DatosErroneos

        return depositado
Exemplo n.º 9
0
 def create_ticket(cls, data):
     """Create a new ticket."""
     highest_ticket_id = cls._get_highest_ticket_id() + 1
     new_ticket = Ticket(ticket_id=highest_ticket_id,
                         name=data["name"],
                         status=data["status"])
     cls._tickets.append(new_ticket)
     return new_ticket
Exemplo n.º 10
0
 def open_pulls(self):
     from models.ticket import Ticket
     from models.pull import PullRequest
     pulls = [PullRequest.get_by_proj_and_ticket(self.id,
                                                 t.ticket_id)
              for t in Ticket.gets_by_proj(self.id,
                                           limit=9999)]
     return pulls
Exemplo n.º 11
0
def create_new_ticket():
    new_ticket = Ticket(name=api.payload['name'],
                        price=api.payload['price'],
                        description=api.payload['description'],
                        image=api.payload['image'],
                        user_id=get_jwt_identity())
    db.session.add(new_ticket)
    db.session.commit()
Exemplo n.º 12
0
 def create_ticket(cls, data):
     """Create a new ticket."""
     new_ticket = Ticket(
         ticket_id=cls.get_highest_ticket_id() + 1,
         name=data["name"]
     )
     cls._tickets.append(new_ticket)
     return new_ticket
Exemplo n.º 13
0
def create_basket():
    user_id = current_user.id
    items, total = get_basket_and_total()

    basket = [Ticket(type=tt, user_id=user_id) for tt in items]
    app.logger.debug('Added tickets to db for basket %s with total %s', basket,
                     total)
    return basket, total
Exemplo n.º 14
0
def get_basket():
    basket = []
    for code in session.get('basket', []):
        basket.append(Ticket(code=code))

    total = sum(t.type.get_price(get_user_currency()) for t in basket)

    app.logger.debug('Got basket %s with total %s', basket, total)
    return basket, total
Exemplo n.º 15
0
 def delete(self, _id=-1):
     if _id == -1:
         return {"msg": "Bad request!"}, 401
     current_user_id = get_jwt_identity()
     ticket = Ticket.find_by_id(_id, current_user_id)
     if not ticket:
         return {'msg': "Ticket doesn't exist!"}, 404
     db.session.delete(ticket)
     db.session.commit()
     return {'msg': "Ticket successfully deleted!"}, 200
Exemplo n.º 16
0
def ticket_choice_prompt(cinema, movie: MovieSchema, projection, movie_hall,
                         ticket_count: int):
    """
    Prompt the user to choose the seats for each ticket he wants to buy
    :param cinema: An object of class Cinema
    :param movie: A MovieSchema object for a movie from the Movie DB table
    :param projection: A ProjectionSchema object for a projection from the Projections DB table
    :param movie_hall: A 11x11 matrix representing the free seats in the movie hall
    :param ticket_count: The count of tickets the user wants to buy
    :return: A dictionary type: {ticket_idx:a Ticket object}
    """
    to_give_up = False
    tickets = {}  # type: {int:Ticket}
    for i in range(ticket_count):
        # loop until the user chooses a valid ticket
        while True:
            print("Please pick a spot for ticket #{}".format(i + 1))
            print_movie_hall(movie_hall)

            # Get the row/col for a seat and validate them
            row = input("Choose a row: (1-10): ")
            while not is_valid_row_or_col(row):
                if row == 'give up':
                    to_give_up = True
                    return None, to_give_up
                print('The row you entered is invalid.')
                row = input("Choose a row: (1-10): ")
            row = int(row)

            col = input("Choose a cow: (1-10): ")
            while not is_valid_row_or_col(col):
                if col == 'give up':
                    to_give_up = True
                    return None, to_give_up
                print('The col you entered is invalid.')
                col = input("Choose a col: (1-10): ")
            col = int(col)

            if movie_hall[row][col] == 'X':
                print('The spot you chose is taken!')
            else:
                # take the seat and add the ticket
                movie_hall[row][col] = 'X'
                ticket = Ticket(row,
                                col,
                                movie_name=movie.name,
                                projection_id=projection.id_,
                                proj_type=projection.type,
                                date=projection.proj_date,
                                hour=projection.time,
                                owner_id=cinema.user.id_)
                tickets[i + 1] = ticket
                break

    return tickets, to_give_up
Exemplo n.º 17
0
def get_basket():
    types = [TicketType.query.get(code) for code in session.get('basket', [])]

    total = sum(tt.get_price(get_user_currency()) for tt in types)

    basket = []
    for tt in types:
        basket.append(Ticket(type=tt))

    app.logger.debug('Got basket %s with total %s', basket, total)
    return basket, total
Exemplo n.º 18
0
	def get( self ):
		""" Handles HTTP GET requests. """
		query = Ticket.all()
		query.filter('financial_order_state =', 'CHARGEABLE')
		query.filter('production =', self.is_prod())
		query.order('-timestamp')
		active_tickets = query.fetch(250)
		
		query = Ticket.all()
		query.filter('financial_order_state !=', 'CHARGEABLE')
		query.filter('production =', self.is_prod())
		query.order('-financial_order_state')
		reviewing_tickets = query.fetch(250)
		
		options = self.get_options()
		options["active_tickets"] = active_tickets
		options["reviewing_tickets"] = reviewing_tickets
		options["logout_url"] = users.create_logout_url('/')
		options["content"] = self.render( "admin/tickets.html", options )
		self.response.out.write( self.render( "admin.html", options ) )
def compare_winners():
    with open('models/zadanie.json') as js:
        data = json.load(js)

    numbers_quantity = data["numbers-quantity"]
    numbers_range = data["numbers-range"]
    numbers_range_min = numbers_range["min"]
    numbers_range_max = numbers_range["max"]

    global lottery_results
    lottery_results = lottery_engine(numbers_quantity, numbers_range_min,
                                     numbers_range_max)

    ticket = Ticket()
    all_tickets = ticket.load_all_tickets(cursor)
    winners = []
    winners_list = []
    ticket_list = []

    for ticket in all_tickets:
        tickets_from_db = ticket.selected_numbers[1:-1].split(", ")
        tickets_to_load = (list(tickets_from_db))
        player_dict = {}
        for numb in tickets_to_load:
            if int(numb) in lottery_results:
                winners.append(ticket)
                player_dict[ticket.id] = 1
                dict_to_add = player_dict
                if dict_to_add in ticket_list:
                    ticket_list.remove(dict_to_add)
                    player_dict[ticket.id] += 1
                    dict_to_change = player_dict
                    ticket_list.append(dict_to_change)
                else:
                    ticket_list.append(dict_to_add)
        if winners is not None:
            for person in winners:
                if person.id not in winners_list:
                    winners_list.append(person.id)

        return ticket_list
Exemplo n.º 20
0
	def post(self, status = '', lang = '', output = 'html'):
		ticket = Ticket()

		user = users.get_current_user()
		if not user:
			self.redirect('/')

		ticket.author = user

		ticket.status = StatusService.getById(self.request.get('status'))
		ticket.severity = SeverityService.getById(self.request.get('severity'))
		if self.request.get('assignedUser'):
			ticket.assignedUser = users.User(self.request.get('assignedUser'))
		ticket.description = self.request.get('description')
		ticket.summary = self.request.get('summary')
		ticket.put()
		self.redirect('/')
Exemplo n.º 21
0
def trabajarTicket():
    if "ID" in session and session['Tipo'] == 4:
        if request.method == 'POST':
            objTicket = Ticket()
            objEmail = Email()
            objUsuario = Usuario()
            IdTicket = int(request.form['IdTicket'])

            objTicket.setID(IdTicket)
            ticket = objTicket.consultarID()
            objUsuario.setID(int(ticket[0].IdCreador))
            usuario = objUsuario.consultarID()

            if ticket[0].IdSolucionador != None:
                return "TicketTrabajando"
            else:            
                if objTicket.trabjarTicket():
                    if len(usuario) > 0:
                        email = usuario[0].Email
                        objEmail.emailActualizacionTicket(email,1,ticket[0].Titulo,0)
                    else:
                        return "Error"

                    return "Exito"
                else:
                    return "Error"
        else:
            return redirect(url_for('inicio.index'))
Exemplo n.º 22
0
 def open_parent_pulls(self):
     from models.ticket import Ticket
     from models.pull import PullRequest
     pulls = []
     parent = self.get_forked_from()
     if parent:
         pulls = [PullRequest.get_by_proj_and_ticket(parent.id,
                                                     t.ticket_id)
                  for t in Ticket.gets_by_proj(parent.id,
                                               limit=9999)]
         pulls = [p for p in pulls
                  if p and p.from_proj and p.from_proj.id == self.id]
     return pulls
Exemplo n.º 23
0
 def open_network_pulls(self):
     from models.ticket import Ticket
     from models.pull import PullRequest
     pulls = []
     projects = self.get_fork_network()
     for project in projects:
         ps = [PullRequest.get_by_proj_and_ticket(project.id,
                                                  t.ticket_id)
               for t in Ticket.gets_by_proj(project.id,
                                            limit=9999)]
         pulls.extend([p for p in ps
                       if p and p.from_proj and p.from_proj.id == self.id])
     return pulls + self.open_pulls
Exemplo n.º 24
0
 def put(self, _id=-1):
     if _id == -1:
         return {"msg": "Bad request!"}, 401
     current_user_id = get_jwt_identity()
     ticket = Ticket.find_by_id(_id, current_user_id)
     if not ticket:
         return {'msg': 'No such Ticket.'}, 404
     ticket.name = api.payload['name']
     ticket.price = api.payload['price']
     ticket.description = api.payload['description']
     ticket.image = api.payload['image']
     ticket.user_id = get_jwt_identity()
     db.session.commit()
     return {'msg': ticket.json()}
Exemplo n.º 25
0
def tickets_receipt(receipt):
    if current_user.admin:
        return redirect(url_for('admin_receipt', receipt=receipt))

    try:
        user = User.filter_by(receipt=receipt).one()
        tickets = list(user.tickets)
    except NoResultFound, e:
        try:
            ticket = Ticket.filter_by(receipt=receipt).one()
            tickets = [ticket]
            user = ticket.user
        except NoResultFound, e:
            return ('', 404)
Exemplo n.º 26
0
    def get(self):
        user_id = request.environ['USER_ID']
        tickets = Ticket.query(Ticket.user_id == user_id)
        ticket_list = []
        for ticket in tickets:
            show = ticket.show_id.get()
            event_name = show.event_id.get().name
            total_price = ticket.total_price
            seats = ticket.seats
            ticket_list.append({
                'show_name': event_name,
                'total_price': total_price,
                'seats': seats
            })

        return jsonify(ticket_list)
Exemplo n.º 27
0
def parse_response_to_tickets(query):
    print('\n🎟  Grabbing ticket info 🎟')

    tickets = []

    ticket_response = make_ticket_request(query)['issues']
    for ticket in ticket_response:
        issue = ticket['key']
        title = ticket['fields']['summary']
        labels = ticket['fields']['labels']
        created = ticket['fields']['created']
        ticket = Ticket(issue, title, labels, created)
        tickets.append(ticket)
        pprint.pprint(vars(ticket))

    return tickets
Exemplo n.º 28
0
def __parse_ticket_from_issue(issue, cloudBase):
    # Parse Reporter
    reporter = User(issue['fields']['reporter']['displayName'])

    # Parse Assignee
    assignee = User("Not Assigned")
    try:
        assignee.username = issue['fields']['assignee']['displayName']
    except:
        pass

    # Parse Key
    key = issue['key']

    link = JIRA_USER_TICKET.replace(JIRA_USER_BASE_REPLACE, cloudBase)
    link = link.replace(JIRA_USER_TICKET_REPLACE, key)

    # Parse Id
    issueId = issue['id']

    # Parse Summary
    summary = issue['fields']['summary']

    # Parse created At
    createdAt = issue['fields']['created']
    createdAt = datetime.datetime.strptime(createdAt, '%Y-%m-%dT%H:%M:%S.%f%z')

    # Parse Labels
    labels = issue['fields']['labels']

    # Parse Status
    status = Status(issue['fields']['status']['statusCategory']['name'],
                    issue['fields']['status']['statusCategory']['colorName'])

    # Parse subtasks out
    subtasks = []
    for subtask in issue['fields']['subtasks']:
        subtasks.append(Subtask(subtask['key']))

    # Parse type
    ticket_type = issue['fields']['issuetype']['name']

    ticket = Ticket(issueId, key, summary, key, labels, createdAt, reporter,
                    assignee, subtasks, link, status, ticket_type)

    return ticket
Exemplo n.º 29
0
def calificarTicket():
    if "ID" in session and session['Tipo'] == 6:
        if request.method == 'POST':
            calificacion = int(request.form['cal'])
            idTicket = int(request.form['idTicket'])

            objTicket = Ticket()
            objTicket.setCalificacion(calificacion)
            objTicket.setID(idTicket)

            if objTicket.calificarTicket():
                return "Exito"
            else:
                return "Error"
        else:
            return redirect(url_for('index'))
Exemplo n.º 30
0
 def after_create(self, extra_args):
     from models.ticket import Ticket
     comment = self
     TicketNode.add_comment(comment)
     content = extra_args
     bdb.set(BDB_TICKET_COMMENT_CONTENT_KEY % self.id, content)
     ticket = Ticket.get(self.ticket_id)
     # TODO: 将Feed全部迁移到新的系统后,取消signal发送
     codereview_signal.send(comment,
                            content=content,
                            ticket=ticket,
                            author=self.author,
                            comment=comment)
     dispatch('codereview', data={
         'comment': comment,
         'ticket': ticket,
         'sender': self.author,
     })
Exemplo n.º 31
0
def tickets_receipt(receipt):
    if current_user.admin:
        return redirect(url_for('admin_receipt', receipt=receipt))

    try:
        user = User.filter_by(receipt=receipt).one()
        tickets = list(user.tickets)
    except NoResultFound:
        try:
            ticket = Ticket.filter_by(receipt=receipt).one()
            tickets = [ticket]
            user = ticket.user
        except NoResultFound:
            return ('', 404)

    if current_user != user:
        return ('', 404)

    return render_template('tickets-receipt.htm', user=user, tickets=tickets)
Exemplo n.º 32
0
def tickets_receipt(receipt):
    if current_user.admin:
        return redirect(url_for('admin_receipt', receipt=receipt))

    try:
        user = User.filter_by(receipt=receipt).one()
        tickets = list(user.tickets)
    except NoResultFound:
        try:
            ticket = Ticket.filter_by(receipt=receipt).one()
            tickets = [ticket]
            user = ticket.user
        except NoResultFound:
            return ('', 404)

    if current_user != user:
        return ('', 404)

    return render_template('tickets-receipt.htm', user=user, tickets=tickets)
Exemplo n.º 33
0
def eliminarTicket():
    if request.method != 'POST':
        return redirect(url_for('inicio.index'))
    else:
        if "ID" in session:
            IdTicket = int(request.form['IdTicket'])
            objTicket = Ticket()
            objTicket.setID(IdTicket)
            if len(objTicket.consultarID()) > 0:
                if objTicket.eliminarTicket():
                    return "Exito"
            else:
                return "ticketPrevElim"

    return "Error"
Exemplo n.º 34
0
 def add(cls, target_id, from_sha, to_sha,
         old_path, new_path, from_oid, to_oid, old_linenum, new_linenum,
         author, content):
     # TODO: dispatch 放到 view 里
     from models.ticket import Ticket
     from libs.signals import codereview_signal
     from dispatches import dispatch
     comment = super(PullLineComment, cls).add(
         target_id, from_sha, to_sha, old_path, new_path, from_oid,
         to_oid, old_linenum, new_linenum, author, content)
     ticket = Ticket.get(target_id)
     # TODO: 重构feed之后取消signal发送
     if ticket:
         codereview_signal.send(comment, content=content,
                                ticket=ticket,
                                author=author, comment=comment)
         dispatch('codereview', data={
                  'comment': comment,
                  'ticket': ticket,
                  'sender': author,
                  })
     return comment
Exemplo n.º 35
0
    def lista_tickets(self, lista_tickets):
        self.__lista_tickets = lista_tickets

    def save(self, ticket):
        self.lista_tickets.append(ticket)

    def find_all(self):
        return self.lista_tickets

    def find_by_pin(self, pin):
        for ticket in self.lista_tickets:
            if (ticket.pin == pin):
                return ticket

    def find_by_matricula(self, matricula):
        for ticket in self.lista_tickets:
            if (ticket.matricula == matricula):
                return ticket


lista_tickets = [
    Ticket("1234BBB", datetime(2020, 12, 10, 15, 30), 6, 111111,
           datetime(2020, 12, 10, 17, 30), 5),
    Ticket("1234JJJ", datetime(2020, 12, 12, 15, 30), 6, 111111,
           datetime(2020, 12, 12, 17, 30), 5.50),
    Ticket("1234FFF", datetime(2020, 12, 14, 15, 30), 6, 111111,
           datetime(2020, 12, 14, 17, 30), 6)
]

ticket_repositorio = TicketRepositorio(lista_tickets)
Exemplo n.º 36
0
def _q_lookup(request, uid):
    if uid.isdigit():
        ticket = Ticket.get(uid)
        if ticket:
            return TicketUI(ticket)
    raise TraversalError
Exemplo n.º 37
0
 def target(self):
     from models.ticket import Ticket
     return Ticket.get(self.target_id)
Exemplo n.º 38
0
 def n_open_tickets(self):
     from models.ticket import Ticket
     return Ticket.get_count_by_proj(self.id)
Exemplo n.º 39
0
def tickets_choose_free(user_id=None):
    has_price = TicketPrice.query.filter(TicketPrice.price_int > 0)

    free_tts = TicketType.query.filter(
        ~has_price.filter(TicketPrice.type.expression).exists(),
    ).order_by(TicketType.order).all()

    if user_id is None:
        form = FreeTicketsNewUserForm()
        user = None
        new_user = True
    else:
        form = FreeTicketsForm()
        user = User.query.get_or_404(user_id)
        new_user = False

    if request.method != 'POST':
        for tt in free_tts:
            form.types.append_entry()
            form.types[-1].type_id.data = tt.id

    tts = {tt.id: tt for tt in free_tts}
    for f in form.types:
        f._type = tts[f.type_id.data]
        # TODO: apply per-user limits
        values = range(f._type.personal_limit + 1)
        f.amount.values = values
        f._any = any(values)

    if form.validate_on_submit():
        if new_user:
            app.logger.info('Creating new user with email %s and name %s',
                            form.email.data, form.name.data)
            user = User(form.email.data, form.name.data)
            flash('Created account for %s' % form.email.data)

        tickets = []
        for f in form.types:
            if f.amount.data:
                tt = f._type
                for i in range(f.amount.data):
                    t = Ticket(type=tt, user_id=user_id)
                    t.paid = True
                    user.tickets.append(t)
                    tickets.append(t)

                app.logger.info('Allocated %s %s tickets to user', f.amount.data, tt.name)

        db.session.add(user)
        db.session.commit()

        code = user.login_code(app.config['SECRET_KEY'])
        msg = Message('Your complimentary tickets to EMF',
                      sender=app.config['TICKETS_EMAIL'],
                      recipients=[user.email])

        msg.body = render_template('emails/tickets-free.txt',
                            user=user, code=code, tickets=tickets,
                            new_user=new_user)

        if feature_enabled('ISSUE_TICKETS'):
            attach_tickets(msg, user)

        mail.send(msg)

        flash('Allocated %s ticket(s)' % len(tickets))
        return redirect(url_for('.tickets_choose_free'))

    if new_user:
        users = User.query.order_by(User.id).all()
    else:
        users = None

    return render_template('admin/tickets-choose-free.html',
                           form=form, tts=free_tts, user=user, users=users)
Exemplo n.º 40
0
if p2_id:
    store.execute("delete from pullreq where from_project=%s", p2_id)
store.commit()


def setup2repos(proj1, proj2):
    path = proj1.git_real_path
    with clone(path) as workdir:
        with open(join(workdir, 'origin'), 'w') as f:
            f.write('origin')

    path = proj2.git_real_path
    with clone(path) as workdir:
        with open(join(workdir, 'origin'), 'w') as f:
            f.write('modified')

project = Project.add(
    p1_name, owner_id="testuser", summary="test", product="")
assert project
project_fork = Project.add(
    p2_name, owner_id="testuser", summary="test", product="",
    fork_from=project.id)

setup2repos(project, project_fork)

pullreq1 = PullRequest.open(project_fork, 'master', project, 'master')
ticket1 = Ticket.add(project.id, 'title', 'content', 'testuser')
pullreq1.insert(ticket1.ticket_number)

print "PR has been built at: %s" % (DOMAIN + ticket1.url)
Exemplo n.º 41
0
 def create_ticket_from_json(self, json=None):
     birth_date = str(time.strptime(json['birthDate'], "%Y-%m-%d")[:3])
     birth_date = re.sub(',\s', '-', birth_date)
     birth_date = re.sub('(\(|\))', '', birth_date)
     ticket = Ticket()
     ticket.first_name = json['firstName']
     ticket.last_name = json['lastName']
     ticket.birth_date = birth_date
     ticket.email = json['email']
     ticket.postal_code = json['zipCode'].replace(' ', '')
     ticket.residence = json['residence']
     ticket.city = json['city']
     ticket.purchase_date = time.strftime("%Y-%m-%d")
     ticket.paid = True
     ticket.price = self.get_ticket_price(ticket)
     db.session.add(ticket)
     db.session.commit()
     self.orders.append(ticket.ticket_id)
Exemplo n.º 42
0
	def getById(id):
		k = db.Key.from_path('Ticket', int(id))
		return Ticket.get(k)
Exemplo n.º 43
0
def tickets_choose_free(user_id=None):
    has_price = TicketPrice.query.filter(TicketPrice.price_int > 0)

    free_tts = TicketType.query.filter(
        ~has_price.filter(TicketPrice.type.expression).exists(), ).order_by(
            TicketType.order).all()

    if user_id is None:
        form = FreeTicketsNewUserForm()
        user = None
        new_user = True
    else:
        form = FreeTicketsForm()
        user = User.query.get_or_404(user_id)
        new_user = False

    if request.method != 'POST':
        for tt in free_tts:
            form.types.append_entry()
            form.types[-1].type_id.data = tt.id

    tts = {tt.id: tt for tt in free_tts}
    for f in form.types:
        f._type = tts[f.type_id.data]
        # TODO: apply per-user limits
        values = range(f._type.personal_limit + 1)
        f.amount.values = values
        f._any = any(values)

    if form.validate_on_submit():
        if new_user:
            app.logger.info('Creating new user with email %s and name %s',
                            form.email.data, form.name.data)
            user = User(form.email.data, form.name.data)
            flash('Created account for %s' % form.email.data)

        tickets = []
        for f in form.types:
            if f.amount.data:
                tt = f._type
                for i in range(f.amount.data):
                    t = Ticket(type=tt, user_id=user_id)
                    t.paid = True
                    user.tickets.append(t)
                    tickets.append(t)

                app.logger.info('Allocated %s %s tickets to user',
                                f.amount.data, tt.name)

        db.session.add(user)
        db.session.commit()

        code = user.login_code(app.config['SECRET_KEY'])
        send_template_email('Your complimentary tickets to EMF',
                            user.email,
                            app.config['CONTACT_EMAIL'],
                            'emails/tickets-free.txt',
                            user=user,
                            code=code,
                            tickets=tickets,
                            new_user=new_user)

        flash('Allocated %s ticket(s)' % len(tickets))
        return redirect(url_for('.tickets_choose_free'))

    if new_user:
        users = User.query.order_by(User.id).all()
    else:
        users = None

    return render_template('admin/tickets-choose-free.html',
                           form=form,
                           tts=free_tts,
                           user=user,
                           users=users)
Exemplo n.º 44
0
def buscarTickets():
    if request.method == "POST" and "ID" in session:
        plantilla = ""
        objTicket = Ticket()
        objTicket.setIdEmpresa(int(session['Empresa']))
        objTicket.setIDDepartamento(session['Departamento']) if session['Departamento'] != None else 0
        filtro = request.form['filtro']

        resultado = objTicket.buscarTickets(filtro,int(session['Tipo']),int(session['ID']))
        if len(resultado) > 0:
            for r in resultado:
                Asignador = r.Asignador if (r.Asignador != None) else 'Vacio'
                Solucionador = r.Solucionador if (r.Solucionador != None) else 'Vacio'
                Departamento = r.Departamento if (r.Departamento != None) else 'Vacio'
                FechaHoraResolucion = r.FechaHoraResolucion if (r.FechaHoraResolucion != None) else 'Vacio'
                Calificacion = r.Calificacion if (r.Calificacion != None) else 'Vacio'
                Resolucion = r.Resolucion if (r.Resolucion != None) else 'Vacio'
                Prioridad = r.Prioridad if (r.Prioridad != None) else 'Vacio'

                boton1 = "<button class='btn btn-success mt-1 mr-3' style='width: 120px !important;' detallesTicket>Ver</button>"
                boton2 = "<button data-toggle='modal' data-target='#asignarTicketModal' class='btn btn-warning mt-1' style='width: 120px !important;' IdTicketAs='"+str(r.IdTicket)+"'>Asignar</button>"

                if r.Estado == "Resuelto" and (session['Tipo'] == 1 or session['Tipo'] == 2):
                    boton2 = "<button class='btn btn-danger mt-1' style='width: 120px !important;' IdTicketElim="+str(r.IdTicket)+">Eliminar</button>"
                elif (r.Estado == "Pendiente" or r.Estado == "Trabajando") and (session['Tipo'] == 1 or session['Tipo'] == 2):
                    boton2 = ""
                elif r.Estado == "Pendiente" and session['Tipo'] == 3:
                    boton1 = "<button data-toggle='modal' data-target='#asignarTicketModal' class='btn btn-warning mt-1 mr-3' style='width: 120px !important;' IdTicketAs='"+str(r.IdTicket)+"'>Asignar</button>"
                    boton2 = "<button class='btn btn-danger mt-1' style='width: 120px !important;' IdTicketElim="+str(r.IdTicket)+">Eliminar</button>"
                elif r.Estado == "Pendiente" and session['Tipo'] == 4:
                    boton2 = "<button class='btn btn-primary mt-1' style='width: 120px !important;' IdTicketTrabajar='"+str(r.IdTicket)+"'>Trabajar</button>"
                elif r.Estado == "Trabajando" and session['Tipo'] == 4:
                    boton2 = "<button data-toggle='modal' data-target='#resolucionTicket' class='btn btn-primary mt-1' style='width: 120px !important;' IdTicketCerrar='"+str(r.IdTicket)+"'>Cerrar</button>"
                elif r.Estado == "Resuelto" and session['Tipo'] == 4:
                    boton2 = ""
                elif session['Tipo'] == 5:
                    boton2 = ""
                elif (r.Estado == "Trabajando" or r.Estado == "Pendiente") and session['Tipo'] == 6:
                    boton2 = ""
                elif r.Estado == "Resuelto" and session['Tipo'] == 6:
                    if r.Calificacion == None:
                        boton2 = "<button data-toggle='modal' data-target='#calificarTicketModal' class='btn btn-warning mt-1' style='width: 120px !important;' IdTicketCalificar='"+str(r.IdTicket)+"'>Calificar</button>"
                    else:
                        boton2 = ""

                botones = boton1+boton2

                plantilla += """<div class='card mb-3' style='max-width: 100%;'>
                <div class='row no-gutters'>
                <div class='col-12'>
                <div class='card-body'>
                <h5 class='card-title'>"""+r.Titulo+"""</h5>
                <p class='card-text'>"""+r.Detalle+"""</p>
                <p class='card-text'><small class='text-muted'>"""+str(r.FechaHoraCreacion)+"""</small></p>
                <div class='card-footer' style='display: none;'>
                    <p class='card-text'>Creador: """+r.Creador+"""</p>
                    <p class='card-text'>Asignador: """+Asignador+"""</p>
                    <p class='card-text'>Encargado: """+Solucionador+"""</p>
                    <p class='card-text'>Departamento: """+Departamento+"""</p>
                    <p class='card-text'>Prioridad: """+Prioridad+"""</p>
                    <p class='card-text'>Urgencia: """+str(r.Urgencia)+"""</p>
                    <p class='card-text'>Resuelto: """+str(FechaHoraResolucion)+"""</p>
                    <p class='card-text'>Estado: """+r.Estado+"""</p>
                    <p class='card-text'>Calificacion: """+str(Calificacion)+"""</p>
                    <p class='card-text'>Resolucion: """+str(Resolucion)+"""</p>
                    </div>"""+botones+"""
                </div>
                </div>
                </div>
                </div>"""

        else:
            plantilla += "<h4 class='text-center' style='text-transform:capitalize'>No hay resultados para tu busqueda</h4>"

        return plantilla

    return redirect(url_for('inicio.index'))
Exemplo n.º 45
0
def cargarTickets():
    if request.method == "POST" and "ID" in session:
        plantilla = ""
        idFiltro = request.form["idFiltro"]
        objTicket = Ticket()
        if session['Tipo'] == 1:
            tickets = objTicket.ListarTicketsXEstado(idFiltro)
        elif session['Tipo'] == 2:
            tickets = objTicket.ListarTicketsXEmpresaDep(session['Empresa'],session['Departamento'],idFiltro)
        elif session['Tipo'] == 4 and int(idFiltro) == 1:
            tickets = objTicket.ListarTicketsXEmpresaDep(session['Empresa'],session['Departamento'],idFiltro)
        elif session['Tipo'] == 4 and int(idFiltro) != 1:
            tickets = objTicket.ListarTicketsXEmpleado(idFiltro,session['ID'])
        elif session['Tipo'] == 3:
            tickets = objTicket.ListarTicketsXAsignar(session['Empresa'])
        elif session['Tipo'] == 5:
            tickets = objTicket.ListarTicketsXEmpresaCliente(session['Empresa'],idFiltro)
        elif session['Tipo'] == 6:
            tickets = objTicket.ListarTicketsXCliente(idFiltro,session['ID'])

        if len(tickets) > 0:
            for ticket in tickets:
                Asignador = ticket.Asignador if (ticket.Asignador != None) else 'Vacio'
                Solucionador = ticket.Solucionador if (ticket.Solucionador != None) else 'Vacio'
                Departamento = ticket.Departamento if (ticket.Departamento != None) else 'Vacio'
                FechaHoraResolucion = ticket.FechaHoraResolucion if (ticket.FechaHoraResolucion != None) else 'Vacio'
                Calificacion = ticket.Calificacion if (ticket.Calificacion != None) else 'Vacio'
                Resolucion = ticket.Resolucion if (ticket.Resolucion != None) else 'Vacio'
                Prioridad = ticket.Prioridad if (ticket.Prioridad != None) else 'Vacio'

                boton1 = "<button class='btn btn-success mt-1 mr-3' style='width: 120px !important;' detallesTicket>Ver</button>"
                boton2 = "<button data-toggle='modal' data-target='#asignarTicketModal' class='btn btn-warning mt-1' style='width: 120px !important;' IdTicketAs='"+str(ticket.IdTicket)+"'>Asignar</button>"

                if ticket.Estado == "Resuelto" and (session['Tipo'] == 1 or session['Tipo'] == 2):
                    boton2 = "<button class='btn btn-danger mt-1' style='width: 120px !important;' IdTicketElim="+str(ticket.IdTicket)+">Eliminar</button>"
                elif (ticket.Estado == "Pendiente" or ticket.Estado == "Trabajando") and (session['Tipo'] == 1 or session['Tipo'] == 2):
                    boton2 = ""
                elif ticket.Estado == "Pendiente" and session['Tipo'] == 3:
                    boton1 = "<button data-toggle='modal' data-target='#asignarTicketModal' class='btn btn-warning mt-1 mr-3' style='width: 120px !important;' IdTicketAs='"+str(ticket.IdTicket)+"'>Asignar</button>"
                    boton2 = "<button class='btn btn-danger mt-1' style='width: 120px !important;' IdTicketElim="+str(ticket.IdTicket)+">Eliminar</button>"
                elif ticket.Estado == "Pendiente" and session['Tipo'] == 4:
                    boton2 = "<button class='btn btn-primary mt-1' style='width: 120px !important;' IdTicketTrabajar='"+str(ticket.IdTicket)+"'>Trabajar</button>"
                elif ticket.Estado == "Trabajando" and session['Tipo'] == 4:
                    boton2 = "<button data-toggle='modal' data-target='#resolucionTicket' class='btn btn-primary mt-1' style='width: 120px !important;' IdTicketCerrar='"+str(ticket.IdTicket)+"'>Cerrar</button>"
                elif ticket.Estado == "Resuelto" and session['Tipo'] == 4:
                    boton2 = ""
                elif session['Tipo'] == 5:
                    boton2 = ""
                elif (ticket.Estado == "Trabajando" or ticket.Estado == "Pendiente") and session['Tipo'] == 6:
                    boton2 = ""
                elif ticket.Estado == "Resuelto" and session['Tipo'] == 6:
                    if ticket.Calificacion == None:
                        boton2 = "<button data-toggle='modal' data-target='#calificarTicketModal' class='btn btn-warning mt-1' style='width: 120px !important;' IdTicketCalificar='"+str(ticket.IdTicket)+"'>Calificar</button>"
                    else:
                        boton2 = ""

                botones = boton1+boton2

                plantilla += """<div class='card mb-3' style='max-width: 100%;'>
                <div class='row no-gutters'>
                <div class='col-12'>
                <div class='card-body'>
                <h5 class='card-title'>"""+ticket.Titulo+"""</h5>
                <p class='card-text'>"""+ticket.Detalle+"""</p>
                <p class='card-text'><small class='text-muted'>"""+str(ticket.FechaHoraCreacion)+"""</small></p>
                <div class='card-footer' style='display: none;'>
                    <p class='card-text'>Creador: """+ticket.Creador+"""</p>
                    <p class='card-text'>Asignador: """+Asignador+"""</p>
                    <p class='card-text'>Encargado: """+Solucionador+"""</p>
                    <p class='card-text'>Departamento: """+Departamento+"""</p>
                    <p class='card-text'>Prioridad: """+Prioridad+"""</p>
                    <p class='card-text'>Urgencia: """+str(ticket.Urgencia)+"""</p>
                    <p class='card-text'>Resuelto: """+str(FechaHoraResolucion)+"""</p>
                    <p class='card-text'>Estado: """+ticket.Estado+"""</p>
                    <p class='card-text'>Calificacion: """+str(Calificacion)+"""</p>
                    <p class='card-text'>Resolucion: """+str(Resolucion)+"""</p>
                    </div>"""+botones+"""
                </div>
                </div>
            </div>
            </div>"""


            return plantilla
        else:
            if session['Tipo'] == 3:
                return "<h4 class='text-center' style='text-transform:capitalize'>No hay tickets pendientes de asignacion</h4>"
            elif session['Tipo'] == 4 and int(idFiltro) != 1:
                return "<h4 class='text-center' style='text-transform:capitalize'>No posees tickets con este filtro</h4>"
            elif session['Tipo'] == 4:
                return "<h4 class='text-center' style='text-transform:capitalize;'>No hay tickets pendientes</h4>"

            return "<h4 class='text-center' style='text-transform:capitalize'>No existen tickets con este filtro</h4>"
    else:
        return redirect(url_for('inicio.index'))
Exemplo n.º 46
0
def asignarTicket():
    if "ID" in session and session['Tipo'] == 3:
        if request.method == 'POST':
            objTicket = Ticket()
            objEmail = Email()
            objUsuario = Usuario()
            IdTicket = int(request.form['IdT'])
            IdDep = int(request.form['IdDep'])
            IdUsuario = int(request.form['User'])
            Prioridad = int(request.form['Prio'])

            objTicket.setID(IdTicket)
            objTicket.setPrioridad(Prioridad)
            objTicket.setIDDepartamento(IdDep)
            objTicket.setIDSolucionador(IdUsuario)

            ticket = objTicket.consultarID()
            objUsuario.setID(IdUsuario) if IdUsuario != None else objUsuario.setID(0)
            usuario = objUsuario.consultarID()

            if ticket[0].IdDepartamento == None: 
                if objTicket.asignarTicket():

                    if len(usuario) > 0:
                        email = usuario[0].Email
                        objEmail.emailActualizacionTicket(email,3,ticket[0].Titulo,Prioridad)

                    return "Exito"
                else:
                    return "Error"
            else:
                return "Ticket Ya Asignado"
        else:
            return redirect(url_for('index'))