Exemplo n.º 1
0
    def all_entries_download(self):
        schema = self.AllEntriesSchema().clone()
        form = PorInlineForm(schema)
        controls = self.request.GET.items()
        appstruct = form.validate(controls)

        header = ['cliente', 'progetto', 'request', 'user', 'data', 'descrizione', 'ore']

        rows = [
                (
                    row['customer'],
                    row['project'],
                    row['request'],
                    row['user'],
                    row['date'],
                    row['description'],
                    row['seconds']/60.0/60.0,
                )
            for row in self.search(**appstruct)['rows']
            ]

        return {
                'header': header,
                'rows': rows
                }
Exemplo n.º 2
0
    def __call__(self):
        schema = self.MyEntriesSchema(validator=validate_period).clone()\
                     .bind(yesterday=yesterday(),
                           today=datetime.date.today())
        limit = 1000
        projects = qry_active_projects().all()
        form = PorInlineForm(schema,
                             formid='my_entries',
                             method='GET',
                             buttons=[
                                 SearchButton(title=u'Search'),
                             ])

        form['project_id'].widget.values = [('', '')] + sorted([(str(p.id), ' / '.join([p.customer.name, p.name])) for p in projects],
                                                               key=lambda x: x[1].lower())

        result_table = ''
        controls = self.request.GET.items()

        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {
                    'form': e.render(),
                    'saved_query_form': render_saved_query_form(self.request),
                    'result_table': None
                    }
        
        current_uid = self.request.authenticated_user.id
        entries_by_date, entries_count = self.search(author_id=current_uid,
                                                     limit=limit,
                                                     **appstruct)

        highlight = functools.partial(webhelpers.html.tools.highlight,
                                      phrase=appstruct['searchtext'])

        delta0 = datetime.timedelta()
        delta_tot = sum([sum((e.hours for e in x[1]), delta0) for x in entries_by_date], delta0)

        human_tot = timedelta_as_human_str(delta_tot)
        days_tot = timedelta_as_work_days(delta_tot)

        result_table = render('por.dashboard:reports/templates/my_entries_results.pt',
                              {
                                  'entries_by_date': entries_by_date,
                                  'entries_count': entries_count,
                                  'highlight': highlight,
                                  'human_tot': human_tot,
                                  'days_tot': days_tot,
                                  'datetime': datetime,
                                  'ticket_url': ticket_url,
                                  'timedelta_as_human_str': timedelta_as_human_str,
                              },
                              request=self.request)

        return {
                'form': form.render(appstruct=appstruct),
                'saved_query_form': render_saved_query_form(self.request),
                'result_table': result_table,
                }
Exemplo n.º 3
0
def search(request):

    schema = SearchSchema().bind(request=request)
    form = PorInlineForm(
                schema,
                formid='search',
                method='GET',
                buttons=[SearchButton(title=u'Search'),]
            )

    tracs = searchable_tracs(request)
    form['tracs'].widget.values = [('', '')] \
                              + [(t.trac_name, t.project_name) for t in tracs]

    users = DBSession.query(User).order_by(User.fullname)
    form['authors'].widget.values = [('', '')] \
                              + [(a.email, a.fullname) for a in users]

    controls = request.GET.items()
    if not controls:
        return {'form': form.render(),
                'results':[]}
    try:
        appstruct = form.validate(controls)
    except deform.ValidationFailure as e:
        return {'form': e.render(),
                'results':[]}

    params = appstruct.copy()
    if not params['tracs']:
        params['tracs'] = [t.trac_name for t in tracs]

    fs = FullTextSearch(request=request, **params)
    results = fs.get_search_results()
    next_url = None
    previous_url = None
    docs = []

    if results:
        docs = [FullTextSearchObject(**doc) for doc in results]
        records_len = results.result.numFound
        if not fs.page_start + fs.page_size >= records_len: # end of set
            next_query = add_param(request, 'page_start', fs.page_start + fs.page_size)
            next_url = current_route_url(request, _query=next_query)

        if not fs.page_start == 0:
            previous_page = fs.page_start - fs.page_size
            if previous_page < 0:
                previous_page = 0
            previous_query = add_param(request, 'page_start', previous_page)
            previous_url = current_route_url(request, _query=previous_query)

    return {'docs': docs,
            'next': next_url,
            'form': form.render(appstruct=appstruct),
            'previous': previous_url,
            'add_param': add_param,
            'results': results}
Exemplo n.º 4
0
 def custom_json(self):
     schema = self.CustomSchema(validator=validate_period).clone()
     form = PorInlineForm(schema)
     controls = self.request.GET.items()
     appstruct = form.validate(controls)
     detail = self.search(render_links=False, **appstruct)
     result = []
     for row in detail['rows']:
         row['hours'] = timedelta_as_human_str(row['hours'])
         del row['description']
         result.append(row)
     return result
Exemplo n.º 5
0
def render_saved_query_form(request):
    current_uid = request.authenticated_user.id
    qry = DBSession.query(SavedQuery)

    # retrieve a saved query by the same user...
    qry = qry.filter(SavedQuery.author_id==current_uid)
    # ..for the current report..
    qry = qry.filter(SavedQuery.report_name==request.view_name)
    # ..with the current parameters
    qry = qry.filter(SavedQuery.query_string=='?'+request.query_string)

    # XXX what if there are two queries with the exact same parameters?

    savedqry = qry.first()
    report_name = request.view_name

    if savedqry:
        appstruct = {
                'sq_id': savedqry.id,
                'query_name': savedqry.query_name,
                'report_name': report_name,
                }
        buttons = [
                RenameButton(title=u'Rename', type='button', name='submit_edit'),
                DeleteButton(title=u'Delete', type='button', name='submit_delete'),
                ]
    else:
        appstruct = {
                'report_name': report_name,
                }
        buttons = [
                FavoriteButton(title=u'Save', type='button', name="submit_add"),
                ]


    form = PorInlineForm(SavedQuerySchema().clone(),
                         formid='saved_query_form',
                         action='save_query',
                         method='POST',
                         buttons=buttons,
                         )
    return form.render(appstruct=appstruct)
Exemplo n.º 6
0
    def custom_xls(self):
        schema = self.CustomSchema(validator=validate_period).clone()
        form = PorInlineForm(schema)
        controls = self.request.GET.items()
        appstruct = form.validate(controls)

        detail = self.search(render_links=False, **appstruct)

        columns = detail['columns']

        rows = [
                [
                    self.format_xls(row[col_key])
                    for col_key, col_title in columns
                    ] + [timedelta_as_human_str(row['hours'])]
                for row in detail['rows']
                ]

        return {
                'header': [col_title for col_key, col_title in columns] + ['Ore'],
                'rows': rows,
                }
Exemplo n.º 7
0
    def __call__(self):
        schema = self.CustomSchema(validator=validate_period).clone()
        projects = self.request.filter_viewables(qry_active_projects())

        # select customers that have some active project
        customers = self.request.filter_viewables(sorted(set(p.customer for p in projects), key=unicodelower))

        users = DBSession.query(User).order_by(User.fullname)
        users = filter_users_with_timeentries(users)
        customer_requests = self.request.filter_viewables(DBSession.query(CustomerRequest).order_by(CustomerRequest.name))

        form = PorInlineForm(schema,
                             formid='report-customer',
                             method='GET',
                             buttons=[
                                 SearchButton(title=u'Search'),
                             ])

        workflow = get_workflow(TimeEntry(), 'TimeEntry')

        all_wf_states = [
                            (state, workflow._state_data[state]['title'] or state)
                            for state in workflow._state_order
                        ]

        form['workflow_states'].widget.values = all_wf_states
        # XXX the following validator is broken
        form['workflow_states'].validator = colander.OneOf([str(ws[0]) for ws in all_wf_states])

        form['customer_id'].widget.values = [('', '')] + [(str(c.id), c.name) for c in customers]
        # don't validate as it might be an archived customer
        form['project_id'].widget.values = [('', '')] + [(str(p.id), p.name) for p in projects]
        # don't validate as it might be an archived project

        form['users'].widget.values = [(str(u.id), u.fullname) for u in users]
        # XXX the following validator is broken
        form['users'].validator = colander.OneOf([str(u.id) for u in users])

        form['customer_requests'].widget.values = [(str(c.id), c.name) for c in customer_requests]
        # XXX the following validator is broken
        form['customer_requests'].validator = colander.OneOf([str(c.id) for c in customer_requests])

        controls = self.request.GET.items()

        if not controls:
            # the form is empty
            return {
                    'form': form.render(),
                    'saved_query_form': render_saved_query_form(self.request),
		    'qs':'',
                    'result_table': None
                    }

        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {
                    'form': e.render(),
                    'saved_query_form': render_saved_query_form(self.request),
		    'qs':'',
                    'result_table': None
                    }

        detail = self.search(render_links=True, **appstruct)

        result_table = None

        if detail['rows']:
            base_link = self.request.path_url.rsplit('/', 1)[0]
            xls_link = ''.join([base_link, '/', 'custom_xls', '?', self.request.query_string])
            json_link = ''.join([base_link, '/', 'custom_json', '?', self.request.query_string])
            delta0 = datetime.timedelta()
            delta_tot = sum((row['hours'] for row in detail['rows']), delta0)
            human_tot = timedelta_as_human_str(delta_tot)

            result_table = render('por.dashboard:reports/templates/custom_results.pt',
                                  {
                                      'rows': detail['rows'],
                                      'columns': detail['columns'],
                                      'xls_link': xls_link,
                                      'json_link': json_link,
                                      'format_web': self.format_web,
                                      'human_tot': human_tot,
                                  },
                                  request=self.request)

        return {
                'form': form.render(appstruct=appstruct),
                'saved_query_form': render_saved_query_form(self.request),
                'qs': self.request.query_string,
                'result_table': result_table,
                }
Exemplo n.º 8
0
    def __call__(self):

        done_state = set()
        done_contract = set()
        errors = {}
        if self.request.POST:
            done_state, done_contract, errors = self.state_contract_change()
            if done_state:
                self.request.add_message('State changed for %d time entries.' % len(done_state))
            if done_contract:
                self.request.add_message('Contract changed for %d time entries.' % len(done_contract))

        # GET parameters for the search form

        fanstatic_resources.report_te_state_change.need()
        schema = self.StateChangeSchema(validator=validate_period).clone()
        projects = self.request.filter_viewables(qry_active_projects())

        # select customers that have some active project
        customers = self.request.filter_viewables(sorted(set(p.customer for p in projects), key=unicodelower))

        users = DBSession.query(User).order_by(User.fullname)
        users = filter_users_with_timeentries(users)
        customer_requests = self.request.filter_viewables(DBSession.query(CustomerRequest).order_by(CustomerRequest.name))

        form = PorInlineForm(schema,
                             formid='te_state_change',
                             method='GET',
                             buttons=[
                                 SearchButton(title=u'Search'),
                             ])

        workflow = get_workflow(TimeEntry(), 'TimeEntry')

        all_wf_states = [
                            (state, workflow._state_data[state]['title'] or state)
                            for state in workflow._state_order
                        ]

        form['workflow_states'].widget.values = all_wf_states
        # XXX the following validator is broken
        form['workflow_states'].validator = colander.OneOf([str(ws[0]) for ws in all_wf_states])

        form['customer_id'].widget.values = [('', '')] + [(str(c.id), c.name) for c in customers]
        # don't validate as it might be an archived customer
        form['project_id'].widget.values = [('', '')] + [(str(p.id), p.name) for p in projects]
        # don't validate as it might be an archived project

        form['users'].widget.values = [(str(u.id), u.fullname) for u in users]
        # XXX the following validator is broken
        form['users'].validator = colander.OneOf([str(u.id) for u in users])

        form['customer_requests'].widget.values = [(str(c.id), c.name) for c in customer_requests]
        # XXX the following validator is broken
        form['customer_requests'].validator = colander.OneOf([str(c.id) for c in customer_requests])

        controls = self.request.GET.items()

        if not controls:
            # the form is empty
            return {
                    'form': form.render(),
                    'saved_query_form': render_saved_query_form(self.request),
		    'qs':'',
                    'result_table': '',
                    }

        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {
                    'form': e.render(),
                    'saved_query_form': render_saved_query_form(self.request),
		    'qs':'',
                    'result_table': '',
                    }

        entries_detail = self.search(**appstruct)

        all_contracts = DBSession().query(Contract.id, Contract.name).all()

        result_table = render('por.dashboard:reports/templates/state_change.pt',
                              {
                                  'entries_tree': entries_detail['entries_tree'],
                                  'all_wf_states': all_wf_states,
                                  'all_contracts': all_contracts,
                                  'wf_state_names': dict((ws[0], ws[1]) for ws in all_wf_states),
                                  'done_state': done_state,
                                  'done_contract': done_contract,
                                  'errors': errors,
                              },
                              request=self.request)

        return {
                'form': form.render(appstruct=appstruct),
                'saved_query_form': render_saved_query_form(self.request),
		'qs': self.request.query_string,
                'result_table': result_table,
                }
Exemplo n.º 9
0
    def __call__(self):
        fanstatic_resources.report_all_entries.need()

        schema = self.AllEntriesSchema(validator=validate_period).clone()

        projects = [
                project for project in self.request.filter_viewables(qry_active_projects())
                if self.request.has_permission('reports_all_entries_for_project', project)
                ]

        # select customers that have some active project
        customers = self.request.filter_viewables(sorted(set(p.customer for p in projects), key=unicodelower))

        users = DBSession.query(User).order_by(User.fullname)
        users = filter_users_with_timeentries(users)
        customer_requests = self.request.filter_viewables(DBSession.query(CustomerRequest).order_by(CustomerRequest.name))

        form = PorInlineForm(schema,
                             formid='all_entries',
                             method='GET',
                             buttons=[
                                 SearchButton(title=u'Search'),
                             ])

        form['customer_id'].widget.values = [('', '')] + [(str(c.id), c.name) for c in customers]
        # don't validate as it might be an archived customer
        form['project_id'].widget.values = [('', '')] + [(str(p.id), p.name) for p in projects]
        # don't validate as it might be an archived project

        form['users'].widget.values = [(str(u.id), u.fullname) for u in users]
        # XXX the following validator is broken
        form['users'].validator = colander.OneOf([str(u.id) for u in users])

        form['customer_requests'].widget.values = [(str(c.id), c.name) for c in customer_requests]
        # XXX the following validator is broken
        form['customer_requests'].validator = colander.OneOf([str(c.id) for c in customer_requests])

        controls = self.request.GET.items()

        if not controls:
            # the form is empty
            return {
                    'form': form.render(),
                    'saved_query_form': render_saved_query_form(self.request),
		    'qs':'',
                    'has_results': False
                    }

        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {
                    'form': e.render(),
                    'saved_query_form': render_saved_query_form(self.request),
                    'qs': self.request.query_string,
                    'has_results': False
                    }

        entries_detail = self.search(**appstruct)

        col_headers = {
            'customer': u'Customer',
            'project': u'Project',
            'request': u'Request',
            'user': u'User',
            'date': u'Data',
        }

        columns = [
            { 'colvalue': 'time', 'groupbyrank': None, 'pivot': True, 'result': False },
        ]

        for idx, colname in enumerate(entries_detail['groupby']):
            columns.append({
                            'colvalue': colname,
                            'coltext': colname,
                            'header': col_headers[colname],
                            'groupbyrank': idx+1,
                            'pivot': False,
                            'result': False
                           })

        columns.append({'colvalue': 'description', 'coltext': 'description', 'header': 'description', 'pivot': False, 'result': False})
        columns.append({'colvalue': 'seconds', 'groupbyrank': None, 'pivot': False, 'result': True})

        sourcetable = {
                    'rows': entries_detail['rows'],
                    'columns': columns
                }

        return {
                'form': form.render(appstruct=appstruct),
                'saved_query_form': render_saved_query_form(self.request),
                'qs': self.request.query_string,
                'has_results': len(sourcetable['rows'])>0,
                'tpReport_oConf': json.dumps({
                                    'sourcetable': sourcetable,
                                    'id_tree': entries_detail['id_tree'],
                                    'groupby': entries_detail['groupby'],
                                }),
                }