All pastes #1757591 Raw Edit

clueless

public text v1 · immutable
#1757591 ·published 2010-01-19 16:09 UTC
rendered paste body
#!/usr/bin/env python# -*- coding: utf-8 -*-# Copyright (C) 2010, Mathieu PASQUET <mpa@makina-corpus.com># All rights reserved.## Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions are met:## 1. Redistributions of source code must retain the above copyright notice,#    this list of conditions and the following disclaimer.# 2. Redistributions in binary form must reproduce the above copyright#    notice, this list of conditions and the following disclaimer in the#    documentation and/or other materials provided with the distribution.# 3. Neither the name of the <ORGANIZATION> nor the names of its#    contributors may be used to endorse or promote products derived from#    this software without specific prior written permission.## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE# POSSIBILITY OF SUCH DAMAGE.__docformat__ = 'restructuredtext en'import osimport transactionfrom Testing.makerequest import makerequestimport AccessControlfrom Products.CMFCore.tests.base.security import PermissiveSecurityPolicyfrom zope.interface import implements, Interfacefrom zope.component import getMultiAdapterfrom Acquisition import aq_base, aq_innerfrom Products.CMFCore.utils import getToolByNamefrom Products.CMFPlone import utilsfrom Products.Five.browser import BrowserView ADMIN_USER='admin'PLONE_ID='z'ORGA_ID='organigramme'INSTALL_PATH = '/%s/%s' % (PLONE_ID, ORGA_ID)ORGA_TITLE = 'Organigramme'ORGAITEMSCOLS = {    'orga-direction': [u'Conseil scientifique et technique',                       u'Conseil d\'administration',                       u'Directeur général',                      ],    'orga-assdir': [u'Agence comptable',                    u'Conseiller du directeur général',                    u'Délégation a la qualite',                   ],    'orga-departement': [u'Eaux',                         u'Ecotechnologie',                         u'Territoires',                        ],    'orga-ri':  [u'Directeur Scientifique (pi)',                 u'Direction de la Stragegie et de la recherche (DSR)',                 u'Direction de la prospection et de la veille technologique (DPV)',                 u'Direction des partenariats industriels et de l\'appui aux politiques publiques (DPIA)',                 u'Direction des relations internationnalles (DRI)',                 u'Direction à l\'évaluation (DEV)',                 u'Direction à l\'évaluation et au transfert (DVT)',],    'orga-soutien': [u'Secretaire général',                     u'Directeur de la communication et des relations publiques (DCRP)',                     u'directeur des ressources humaines (DRH)',                     u'Direction juridique et des achats (DJA)',                     u'Direction des affaires financières (DAF)',                     u'Délégation à la sécurité au patrimoine et à l\'environnment (DSPE)',                     u'Déléguation aux systèmes d\'information (DSI)',                    ] ,    'orga-centre': [u'Antony',                    u'Aix-en-provence',                    u'Bordeaux',                    u'Clermont-Ferrand',                    u'Grenoble',                    u'Lyon',                    u'Nogent sur Vernission',                    u'Montpellier',                    u'Rennes',                   ],}LISTED_ORDER = ['orga-direction', 'orga-assdir', 'orga-departement', 'orga-ri', 'orga-soutien', 'orga-centre']def su(plone, username):    """ Change to named user in a plone portal.    """    user = plone.acl_users.getUser(ADMIN_USER).__of__(plone.acl_users)    AccessControl.SecurityManagement.newSecurityManager(None, user)    print 'User changed to %s.' % username    return AccessControl.SecurityManagement.getSecurityManager().getUser()def get_app(app=None):    if not app:        # log in with full rights, hacky isnt it.        AccessControl.SecurityManagement.newSecurityManager(None, AccessControl.User.system)        #limited system user, we loggued better into the plone later        AccessControl.SecurityManager.setSecurityPolicy(PermissiveSecurityPolicy())        globs = globals()        app = globs['app']        app = makerequest(app)     return appdef create_orga(    install_path=None,    orga_title=None,    orgaitemscols=None,    listed=None,    app=None):    if not install_path: install_path = INSTALL_PATH    if not orga_title: orga_title = ORGA_TITLE    if not orgaitemscols: orgaitemscols=ORGAITEMCOLS    if not listed: listed=LISTED_ORDER    app = get_app()    plone = app[PLONE_ID]    admin = su(plone, ADMIN_USER)    orga = None    cat = plone.portal_catalog    wft = plone.portal_workflow    pm = plone.portal_membership    try:        orga = app.restrictedTraverse(install_path)    except:        parent, id = os.path.split(install_path)        orgaid = app.restrictedTraverse(parent).invokeFactory('CFolder', id, title=orga_title)        orga = app.unrestrictedTraverse(install_path)        transaction.commit()    for iorgaitemcol in orgaitemscols:        orgaitemscol = orgaitemscols[iorgaitemcol]        for i, title in enumerate(orgaitemscol):            id = '%s-%s' % (iorgaitemcol, i)            item = getattr(orga, id, None)            if not item:                orga.invokeFactory('CDocument', id=id)                item = getattr(orga, id)            item.setTitle(title)            item.reindexObject()    orga.setTitle(ORGA_TITLE)    orga.reindexObject()    if not orga.hasProperty('layout'):        orga.manage_addProperty('layout', 'cemagref_organigramme', 'string')    else:         orga.manage_changeProperties(**{'layout': 'cemagref_organigramme'})    transaction.commit()          brains = cat.search({'path': INSTALL_PATH})    for brain in brains:        obj = brain.getObject()        if 'publish' in [a['id'] for a in wft.getActionsFor(obj)]:            wft.doActionFor(                obj, 'publish',                 comment='publised programmatically',                 wf_id="content_extranet_base_postmoderation_workflow"            )    transaction.commit()          print "organigramme installed"    if 'CREATEORGA' in os.environ:    app[PLONE_ID].manage_delObjects([ORGA_ID])    create_orga(INSTALL_PATH, ORGA_TITLE, ORGAITEMSCOLS, LISTED_ORDER)class IOrgaView(Interface):    """IOrgaView."""    def getSections():        """getItems"""     def getItems():        """getItems"""class OrgaView(BrowserView):    """OrgaView."""    def getItems(self):        cat = getToolByName(self.context, 'portal_catalog')        brains = cat.searchResults(**{"portal_type": "CDocument",                                      "path": "/".join(self.context.getPhysicalPath())})        items = {}        for key in LISTED_ORDER: items[key] = []        for brain in brains:            for key in LISTED_ORDER:                if key in brain.id:                    items[key].append(brain)                    break        import pdb;pdb.set_trace()  ## Breakpoint ##        return items    def getSections(self):        """getItems"""          return LISTED_ORDER# vim:set et sts=4 ts=4 tw=80: