示例#1
0
 def getCSSClasses(self, item):
     css = self.cssClasses.copy()
     value = self.getValue(item)
     if value and value != self.ignored_value:
         if getProjectSpace(self.context).colorize_project_rows and 'interne' in item.categories[0]:
             css.update({'tr': 'volet_interne'})
     return css
示例#2
0
def manage_fields(the_form, portal_type, mode):
    """
        Remove, reorder and restrict fields
    """

    fields_schemas = getattr(getProjectSpace(the_form.context),
                             '{}_fields'.format(portal_type), [])
    if not fields_schemas:
        return
    to_input = []
    to_display = []

    for fields_schema in reversed(fields_schemas):
        field_name = fields_schema['field_name']
        read_condition = fields_schema.get('read_tal_condition') or ""
        write_condition = fields_schema.get('write_tal_condition') or ""
        if _evaluateExpression(the_form.context, expression=read_condition):
            to_display.append(field_name)
        if _evaluateExpression(the_form.context, expression=write_condition):
            to_input.append(field_name)

        field = remove(the_form, field_name)
        if field is not None and field_name in to_display:
            add(the_form, field, index=0)
            if mode != 'view' and field_name not in to_input:
                field.mode = "display"

    for group in [the_form] + the_form.groups:
        for field_name in group.fields:
            if field_name == 'reference_number' and mode != 'view':
                continue
            if field_name not in to_display:
                group.fields = group.fields.omit(field_name)
示例#3
0
def update_reference_number(
        self,
        ptypes='strategicobjective|operationalobjective|pstaction',
        doit=''):
    """
        Correct reference numbers
    """
    if not check_zope_admin():
        return "You must be a zope manager to run this script"
    out = []
    # search regarding context
    types = ptypes.split('|')
    ps = getProjectSpace(self)
    out.append("Working on projectspace {}".format(ps))
    out.append('Searching on context {} for types {}'.format(self, types))
    brains = api.content.find(context=self, portal_type=types, sort_on='path')
    nref = ps.last_reference_number
    for brain in brains:
        nref += 1
        obj = brain.getObject()
        out.append("Changing ref from '{}' to {} on '{}'".format(
            obj.reference_number, nref, brain.getPath()))
        if doit == '1':
            obj.reference_number = nref
            obj.reindexObject()

    if doit == '1':
        ps.last_reference_number = nref
    return '\n'.join(out)
示例#4
0
 def href(self):
     pst = getProjectSpace(self.context)
     if IProject.providedBy(
             self.context):  # TODO: test if context is descendant of pst ?
         return "{0}/sitemap?came_from={1}".format(
             pst.absolute_url(),
             self.context.UID(),
         )
     else:
         return "{0}/sitemap".format(pst.absolute_url(), )
示例#5
0
 def __call__(self, context):
     """"""
     projectspace = getProjectSpace(context)
     terms = []
     for plan in projectspace.plan_values or []:
         terms.append(SimpleTerm(
             plan['key'],
             plan['key'],
             plan['label'],
         ))
     return SimpleVocabulary(terms)
示例#6
0
 def __call__(self, context):
     """"""
     projectspace = getProjectSpace(context)
     terms = []
     for priority in projectspace.priority_values:
         terms.append(
             SimpleTerm(
                 priority['key'],
                 priority['key'],
                 priority['label'],
             ))
     return SimpleVocabulary(terms)
示例#7
0
 def __call__(self, context):
     """"""
     projectspace = getProjectSpace(context)
     terms = []
     for category in projectspace.categories_values:
         terms.append(
             SimpleTerm(
                 category['key'],
                 category['key'],
                 category['label'],
             ))
     return SimpleVocabulary(terms)
示例#8
0
 def __call__(self, context):
     """"""
     projectspace = getProjectSpace(None)
     terms = []
     budget_types = projectspace.budget_types
     for budget_type in budget_types:
         terms.append(
             SimpleTerm(
                 budget_type['key'],
                 budget_type['key'],
                 budget_type['label'],
             ))
     return SimpleVocabulary(terms)
示例#9
0
def default_year(context):
    """
      defaultFactory for the field IBudgetSchema.year
    """
    years = getProjectSpace(None).budget_years or []
    year = datetime.date.today().year
    if year in years:
        return year
    elif year + 1 in years:
        return year + 1
    elif years:
        return years[-1]
    else:
        return None
示例#10
0
    def init_hv(self):
        """ init method to be called in document """

        def _cleanup_fields(field_schemas):
            """Handle some cases like IDublinCore.title to just keep title"""
            return [field_schema['field_name'].split('.')[-1] for field_schema in field_schemas]

        projectspace = getProjectSpace(self.real_context)
        self.activated_fields = {
            'so': _cleanup_fields(projectspace.strategicobjective_fields),
            'oo': _cleanup_fields(projectspace.operationalobjective_fields),
            'ac': _cleanup_fields(projectspace.pstaction_fields),
            'sb': _cleanup_fields(projectspace.pstsubaction_fields),
        }
示例#11
0
def onAddProject(obj, event):
    """
      Handler when a project is added
    """
    # compute reference number
    if not base_hasattr(obj, 'symbolic_link'):
        projectspace = getProjectSpace(obj)
        projectspace.last_reference_number += 1
        obj.reference_number = projectspace.last_reference_number
        obj.reindexObject(['reference_number'])
    # refresh budget split lines
    if base_hasattr(obj, 'budget_split'):
        update_budget_splits(obj, event)
    # Update field data on every parents
    pw = obj.portal_workflow
    workflows = pw.getWorkflowsFor(obj)
    if not workflows or pw.getInfoFor(
            obj, 'review_state') in get_budget_states(obj):
        _updateSummarizedFields(obj)
示例#12
0
 def getGlobalBudgetByYear(self):
     """
         Return a dictionary containing globalized budgets per year
     """
     # initialize the dictionary in the year range defined by the project space
     fixed_years = [y for y in getProjectSpace(self.real_context).budget_years or []]
     budget_by_year = {year: 0 for year in fixed_years}
     # get the persistent dict
     annotations = IAnnotations(self.real_context)
     # get the children budget amounts
     if CBIAK in annotations:
         globalised_budget = annotations[CBIAK]
         for child in globalised_budget:
             for budget in globalised_budget[child]:
                 if budget['year'] in fixed_years:
                     budget_by_year[budget['year']] += budget['amount']
     # get the current element budget amounts
     for budget in self.real_context.budget:
         if budget['year'] in fixed_years:
             budget_by_year[budget['year']] += budget['amount']
     return budget_by_year
示例#13
0
def get_criteria_holder(context):
    pst = getProjectSpace(context)
    if IProjectSpace.providedBy(context):
        return pst.strategicobjectives
    elif context.portal_type == 'strategicobjective':
        return pst.operationalobjectives
    elif context.portal_type == 'operationalobjective':
        return pst.pstactions
    elif context.portal_type == 'pstaction':
        if context.listFolderContents({'portal_type': 'pstsubaction'}):
            context.REQUEST.set('has_subaction', True)
            return pst.pstactions
        else:
            context.REQUEST.set('has_subaction', False)
            return pst.tasks
    elif context.portal_type == 'pstsubaction':
        return pst.tasks
    elif not IFacetedNavigable.providedBy(context):
        return pst

    return context
示例#14
0
    def perform_reference_number(self):
        """
        Add or update the reference_number index
        compute the reference_number per projectspace
        store the last_reference_number in projectspace
        update catalog
        """
        logger.info('Perform reference number ...')
        addOrUpdateIndexes(self.context, {'reference_number': ('FieldIndex', {})})
        catalog = api.portal.get_tool('portal_catalog')
        projectspaces = catalog(object_provides=IProjectSpace.__identifier__)
        for projectspace in projectspaces:
            path = '/'.join(self.portal.getPhysicalPath()) + '/' + projectspace.id
            brains = catalog(object_provides=IProject.__identifier__, path={'query': path, 'depth': 3}, sort_on='created')
            for num, brain in enumerate(brains):
                obj = brain.getObject()
                if obj.reference_number == 0:
                    obj.reference_number = num + 1
                    obj.reindexObject()
                    projectspace = getProjectSpace(obj)
                    projectspace.last_reference_number = num + 1

        logger.info('Done.')
示例#15
0
 def Title(self):
     if getattr(getProjectSpace(self), 'use_ref_number', True):
         return '%s (OS.%s)' % (self.title.encode('utf8'),
                                self.reference_number)
     else:
         return self.title.encode('utf8')
示例#16
0
 def __call__(self, context):
     """"""
     years = getProjectSpace(None).budget_years or []
     return SimpleVocabulary([SimpleTerm(y) for y in years])
示例#17
0
    def prepareBudgetInfosForDisplay(self,
                                     only_used_years=False,
                                     only_used_budget_types=False):
        """
          Compute budget infos so it can be easily displayed by 'budgetinfos_datagridfield_display.pt'
          We need totals by budget_type and year to display something like :
          [budget_type/years][Global][2010][2011][2012][2013][2014][2015][2016]
          [budget_type_1    ][     5][   0][   0][   5][   -][   -][   -][   -]
          [budget_type_2    ][     5][   0][   0][   5][   -][   -][   -][   -]
          [budget_type_3    ][     5][   0][   0][   5][   -][   -][   -][   -]
          [budget_type_4    ][     5][   0][   0][   5][   -][   -][   -][   -]
          [budget_type_5    ][     5][   0][   0][   5][   -][   -][   -][   -]
          [budget_type_6    ][     7][   0][   2][   5][   -][   -][   -][   -]
          [budget_type_7    ][     8][   1][   2][   5][   -][   -][   -][   -]
          [TOTAL            ][    40][   1][   4][  35][   -][   -][   -][   -]

          We will return 5 values :
          - list of years sorted (years)
          - budget_types sorted (budget_types) : {'budget_type_id1': 'Budget type 1 title',
                                                  'budget_type_id2': 'Budget type 2 title',}
          - total_by_year : {2010: 125,
                             2011: 258,}
          -total_by_budget_type : {'budget_type1': 258,
                                   'budget_type1': 885,}
          - a dict that will appear like this :
          {2010: {'budget_type1': 125,
                  'budget_type2': 250,
                  'total': 375},
           2011: {'budget_type1': 50,
                  'budget_type2': 1222,
                  'total': 1272},
           'total_years': 1647
          }

          If p_only_used_years is True, we will return only years that were
          used not a fixed list of years, same if p_only_used_budget_types is True,
          we will only return used budget_types, not every existing one.
        """
        annotations = IAnnotations(self.context)
        if not CHILDREN_BUDGET_INFOS_ANNOTATION_KEY in annotations:
            return {}
        # get budget_types vocabulary so we can have a value to display as saved data is the key
        factory = queryUtility(
            IVocabularyFactory,
            u'imio.project.core.content.project.budget_type_vocabulary')
        budgetTypesVocab = factory(self.context)
        fixed_years = [
            str(y) for y in getProjectSpace(self.context).budget_years or []
        ]
        res = {}
        years = only_used_years and [] or fixed_years
        budget_types = only_used_budget_types and {} or budgetTypesVocab.by_value
        total_by_year = {}
        total_by_budget_type = {}
        for datagridfieldrecord in annotations[
                CHILDREN_BUDGET_INFOS_ANNOTATION_KEY].itervalues():
            for line in datagridfieldrecord:
                year = str(line['year'])
                budget_type = line['budget_type']
                amount = line['amount']
                # manage used years
                if only_used_years and not year in years:
                    years.append(year)
                # manage used budget_types
                if only_used_budget_types and not budget_type in budget_types:
                    budget_types[budget_type] = budgetTypesVocab.getTerm(
                        budget_type)
                # manage total by year/budget_type
                if not year in res:
                    res[year] = {}
                if not budget_type in res[year]:
                    res[year][budget_type] = 0
                res[year][budget_type] = res[year][budget_type] + amount
                # manage total by year
                if not year in total_by_year:
                    total_by_year[year] = 0
                total_by_year[year] = total_by_year[year] + amount
                # manage total by budget_type
                if not budget_type in total_by_budget_type:
                    total_by_budget_type[budget_type] = 0
                total_by_budget_type[
                    budget_type] = total_by_budget_type[budget_type] + amount
        # make sure with have a result for every year if we use fixed_years
        for year in years:
            if not year in res:
                res[year] = {}
                for budget_type in budget_types:
                    res[year][budget_type] = '-'
        # make sure we have each budget_type for each year
        for line in res.itervalues():
            for budget_type in budget_types:
                if not budget_type in line:
                    line[budget_type] = '-'
        # make sure we have each total for each budget_type in total_by_budget_type
        for budget_type in budget_types:
            if not budget_type in total_by_budget_type:
                total_by_budget_type[budget_type] = '-'
        # compute super total, meaning total of total_by_years
        # (that is the same than total of total_by_budget_types)
        super_total = 0
        for total in total_by_year.values():
            super_total = super_total + total

        return years, budget_types, res, total_by_year, total_by_budget_type, super_total
示例#18
0
 def budget_years(self):
     return [
         str(y) for y in getProjectSpace(self.context).budget_years or []
     ]