예제 #1
0
    def setUp(self):
        portal = self.layer['portal']
        setRoles(portal, TEST_USER_ID, ('Manager', ))

        portal.invokeFactory('emc.bokeh.fearture',
                             'fearture1',
                             title="fearture1",
                             description="demo fearture",
                             source="reference")
        item = portal['fearture1']

        portal.invokeFactory('File', 'file')
        file = portal['file']

        data = getFile('data_template.csv').read()

        file.file = namedfile.NamedBlobFile(data,
                                            filename=u"data_template.csv")
        intids = component.getUtility(IIntIds)
        #         file.file = NamedFile()
        file_id = intids.getId(file)
        #         b.rel = RelationValue(file_id)
        item.reference = RelationValue(file_id)
        #         import pdb
        #         pdb.set_trace()

        self.portal = portal
예제 #2
0
    def _annex_file_content(_path):
        if not os.path.isfile(_path):
            logger.info("Le fichier %s n'a pas ete trouve." % _path)
            return None

        with open(_path, "r") as annex_file:
            name = safe_unicode(os.path.basename(_path))

            annex_read = annex_file.read()
            annex_blob = namedfile.NamedBlobFile(annex_read, filename=name)
            return annex_blob
예제 #3
0
    def setUp(self):
        portal = self.layer['portal']
        setRoles(portal, TEST_USER_ID, ('Manager',))

        portal.invokeFactory('emc.bokeh.fearture', 'fearture1',
                            title="fearture1",
                            description="demo fearture",
                            source="upload")     
        data = getFile('data_template.csv').read()

    
        item = portal['fearture1']

        item.upload = namedfile.NamedBlobFile(data,filename=u"data_template.csv")            
        self.portal = portal     
예제 #4
0
    def create(title=None, description=None, doc_data=None, doc_name=None, step=None):
        folder = utils.get_folder_unrestricted('resources/documents')
        id = utils.create_id('staticdocument')
        item = _createObjectByType('staticdocument', folder, id)

        item.title = title
        item.description = description
        item.file = namedfile.NamedBlobFile(
            utils.base64decode(doc_data),
            filename=doc_name.decode('utf-8', 'ignore')
        )
        item.wcc_user = False

        intids = component.getUtility(IIntIds)
        step_id = intids.getId(step)
        item.doc_in_step = [RelationValue(step_id)]
        notify(ObjectModifiedEvent(item))

        return item
예제 #5
0
    def create_thumb(item):
        if not item.file:
            return

        if item.file.contentType != 'application/pdf':
            if item.file_thumb is not None:
                item.file_thumb = None
            return

        source = item.file.open()
        (fd, filename) = tempfile.mkstemp()
        dest_filename = filename + '.png'

        try:
            tmp_source = os.fdopen(fd, 'wb')
            tmp_source.write(source.read())
            tmp_source.close()

            command = "convert -quality 95 -thumbnail '307x' -crop '307x168+0+0' +repage {source}[0] {output}".format(
                source=filename,
                output=dest_filename
            )
            proc = subprocess.Popen(command, shell=True,
                stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            )
            proc.communicate()[0]

            tmp_dest = open(dest_filename, 'rb')

            item.file_thumb = namedfile.NamedBlobFile(
                tmp_dest.read(),
                filename=os.path.basename(dest_filename.decode('utf-8', 'ignore'))
            )
            tmp_dest.close()
        except:
            pass
        finally:
            try:
                os.remove(filename)
                os.remove(dest_filename)
            except:
                pass
예제 #6
0
def addedOrModifiedArticle(obj, event):

    ownerId = obj.owner_info()['id']
    currentUserId = api.user.get_current().getId()
    if ownerId != currentUserId and 'Site Administrator' not in api.user.get_roles(
            username=currentUserId):
        return
    """
    reviewResults = 0
    if obj.acceptOrReject1 is not None:
        reviewResults += 1
    if obj.acceptOrReject2 is not None:
        reviewResults += 1
    if obj.acceptOrReject3 is not None:
        reviewResults += 1
    if reviewResults > 1:
        attachFile, obj.attachFile = obj.attachFile, None
        with api.env.adopt_roles(['Manager']):
            if attachFile is None:
                return
            fileObj = api.content.create(
                container=obj,
                type='File',
                title='AttachFile%s' % DateTime().strftime('%Y%m%d'),
                file=attachFile,
            )
        return
    """

    if (api.content.get_state(obj) not in [
            'draft', 'modifyThenReview'
    ]) and ('Site Administrator' not in api.user.get_roles()):
        api.portal.show_message(
            message=_(u"Can not modify the contents of the period for review"),
            request=obj.REQUEST,
            type='warning')
        raise
    if obj.attachFile is None:
        return

    attachFile, obj.attachFile = obj.attachFile, None
    with api.env.adopt_roles(['Manager']):
        if attachFile is None:
            return
        fileObj = api.content.create(
            container=obj,
            type='File',
            title='AttachFile%s' % DateTime().strftime('%Y%m%d'),
            file=attachFile,
        )

    if fileObj.file.filename[-4:] == u"docx":
        filename = '/tmp/utaipei_temp.docx'
    else:
        filename = '/tmp/utaipei_temp.doc'

    fileObj = fileObj.file.open()
    with open(filename, 'w') as tempFile:
        data = fileObj.read()
        tempFile.write(data)

    os.popen('cd /tmp; lowriter --convert-to pdf %s' % filename)

    with open('/tmp/utaipei_temp.pdf') as tempFile:
        pdfFile = tempFile.read()

    with api.env.adopt_roles(['Manager']):
        pdf_file = api.content.create(
            container=obj,
            type='File',
            title='AttachPdfFile%s' % DateTime().strftime('%Y%m%d'),
            file=namedfile.NamedBlobFile(data=pdfFile,
                                         filename=u'AttachPdfFile.pdf'))
    return
    def test_ws_getItemInfosWithAnnexesRequest(self):
        """
          Test that getting an item with a given UID returns valuable informations and linked annexes
        """
        cfg = self.meetingConfig
        self.changeUser('pmCreator1')
        self.failUnless(
            len(self.portal.portal_catalog(portal_type='MeetingItemPga')) == 0)
        # prepare data for a default item
        req = self._prepareCreationData()
        # add one annex
        data = {
            'title': 'My annex 1',
            'filename': 'smallTestFile.pdf',
            'file': 'smallTestFile.pdf'
        }
        req._creationData._annexes = [self._prepareAnnexInfo(**data)]
        # create the item
        newItem, reponse = self._createItem(req)
        newItemUID = newItem.UID()
        # get informations about the item, by default 'showAnnexes' is False
        resp = self._getItemInfos(newItemUID)
        expected = """<ns1:getItemInfosResponse xmlns:ns1="http://ws4pm.imio.be" """ \
            """xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" """ \
            """xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" """ \
            """xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" """ \
            """xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <itemInfo xsi:type="ns1:ItemInfo">
    <UID>{0}</UID>
    <id>{1}</id>
    <title>My new item title</title>
    <creator>pmCreator1</creator>
    <creation_date>{2}</creation_date>
    <modification_date>{3}</modification_date>
    <category>development</category>
    <description>&lt;p&gt;Description&lt;/p&gt;</description>
    <detailedDescription>&lt;p&gt;Detailed description&lt;/p&gt;</detailedDescription>
    <decision>&lt;p&gt;Décision&lt;/p&gt;</decision>
    <preferredMeeting/>
    <preferred_meeting_date>1950-01-01T00:00:00.006Z</preferred_meeting_date>
    <review_state>itemcreated</review_state>
    <meeting_date>1950-01-01T00:00:00.006Z</meeting_date>
    <absolute_url>http://nohost/plone/Members/pmCreator1/mymeetings/plonegov-assembly/{4}</absolute_url>
    <externalIdentifier/>
    <extraInfos/>
  </itemInfo>
</ns1:getItemInfosResponse>
""".format(newItemUID,
                newItem.getId(),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.created())),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.modified())),
                newItem.getId())
        # annexes are not shown by default
        self.assertEqual(expected, resp)
        # now with 'showAnnexes=True'
        financial_annex_type_id = calculate_category_id(
            cfg.annexes_types.item_annexes.get('financial-analysis'))
        item_annex_type_id = calculate_category_id(
            cfg.annexes_types.item_annexes.get('item-annex'))
        resp = self._getItemInfos(newItemUID, showAnnexes=True)
        expected = """<ns1:getItemInfosResponse xmlns:ns1="http://ws4pm.imio.be" """ \
            """xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" """ \
            """xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" """ \
            """xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" """ \
            """xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <itemInfo xsi:type="ns1:ItemInfo">
    <UID>{0}</UID>
    <id>{1}</id>
    <title>My new item title</title>
    <creator>pmCreator1</creator>
    <creation_date>{2}</creation_date>
    <modification_date>{3}</modification_date>
    <category>development</category>
    <description>&lt;p&gt;Description&lt;/p&gt;</description>
    <detailedDescription>&lt;p&gt;Detailed description&lt;/p&gt;</detailedDescription>
    <decision>&lt;p&gt;Décision&lt;/p&gt;</decision>
    <preferredMeeting/>
    <preferred_meeting_date>1950-01-01T00:00:00.006Z</preferred_meeting_date>
    <review_state>itemcreated</review_state>
    <meeting_date>1950-01-01T00:00:00.006Z</meeting_date>
    <absolute_url>http://nohost/plone/Members/pmCreator1/mymeetings/plonegov-assembly/{4}</absolute_url>
    <externalIdentifier/>
    <extraInfos/>
    <annexes xsi:type="ns1:AnnexInfo">
      <id>smalltestfile.pdf</id>
      <title>My annex 1</title>
      <annexTypeId>{5}</annexTypeId>
      <filename>smallTestFile.pdf</filename>
      <file>
{6}</file>
    </annexes>
  </itemInfo>
</ns1:getItemInfosResponse>
""".format(newItemUID,
                newItem.getId(),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.created())),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.modified())),
                newItem.getId(),
                financial_annex_type_id,
                base64.encodestring(get_annexes(newItem)[0].file.data))
        # one annex is shown
        self.assertEqual(expected, resp)
        # now check with several (2) annexes...
        afile = open(
            os.path.join(os.path.dirname(__file__), 'mediumTestFile.odt'))
        annex_file = afile.read()
        afile.close()
        api.content.create(
            title='My BeautifulTestFile title',
            type='annex',
            file=namedfile.NamedBlobFile(
                annex_file, filename=safe_unicode(u'myBeautifulTestFile.odt')),
            container=newItem,
            content_category=item_annex_type_id,
            to_print=False,
            confidential=False)

        resp = self._getItemInfos(newItemUID, showAnnexes=True)
        expected = """<ns1:getItemInfosResponse xmlns:ns1="http://ws4pm.imio.be" """ \
            """xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" """ \
            """xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" """ \
            """xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" """ \
            """xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <itemInfo xsi:type="ns1:ItemInfo">
    <UID>{0}</UID>
    <id>{1}</id>
    <title>My new item title</title>
    <creator>pmCreator1</creator>
    <creation_date>{2}</creation_date>
    <modification_date>{3}</modification_date>
    <category>development</category>
    <description>&lt;p&gt;Description&lt;/p&gt;</description>
    <detailedDescription>&lt;p&gt;Detailed description&lt;/p&gt;</detailedDescription>
    <decision>&lt;p&gt;Décision&lt;/p&gt;</decision>
    <preferredMeeting/>
    <preferred_meeting_date>1950-01-01T00:00:00.006Z</preferred_meeting_date>
    <review_state>itemcreated</review_state>
    <meeting_date>1950-01-01T00:00:00.006Z</meeting_date>
    <absolute_url>http://nohost/plone/Members/pmCreator1/mymeetings/plonegov-assembly/{4}</absolute_url>
    <externalIdentifier/>
    <extraInfos/>
    <annexes xsi:type="ns1:AnnexInfo">
      <id>{5}</id>
      <title>My annex 1</title>
      <annexTypeId>{6}</annexTypeId>
      <filename>smallTestFile.pdf</filename>
      <file>
{7}</file>
    </annexes>
    <annexes xsi:type="ns1:AnnexInfo">
      <id>{8}</id>
      <title>My BeautifulTestFile title</title>
      <annexTypeId>{9}</annexTypeId>
      <filename>myBeautifulTestFile.odt</filename>
      <file>
{10}</file>
    </annexes>
  </itemInfo>
</ns1:getItemInfosResponse>
""".format(newItemUID,
                newItem.getId(),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.created())),
                gDateTime.get_formatted_content(gDateTime(), localtime(newItem.modified())),
                newItem.getId(),
                get_annexes(newItem)[0].id,
                financial_annex_type_id,
                base64.encodestring(get_annexes(newItem)[0].file.data),
                get_annexes(newItem)[1].id,
                item_annex_type_id,
                base64.encodestring(get_annexes(newItem)[1].file.data))
        # 2 annexes are shown
        self.assertEqual(expected, resp)
예제 #8
0
def handlerCreatedPlan(self, event):

    plant = self.plan_type
    # userid = api.user.get_current().id
    # import pdb; pdb.set_trace()
    # Be carefull with this
    # if userid == 'admin':
    try:
        userid = self.Login()
    except Exception:
        userid = self.id

    if plant == 'plantext':

        plantext = self.text

        if plantext:

            tex_title = self.title
            tex_author = ""
            tex_institution = "IM - UNAM"
            tex_phone = ""
            tex_email = ""
            tex_homepage = ""
            tex_date = ""

            catalog = getToolByName(getSite(), 'portal_catalog')
            query = {'portal_type': 'FSDPerson', 'id': userid}
            brains = catalog.searchResults(query)
            if brains:
                obj = brains[0].getObject()
                tex_author = obj.Title().decode('utf-8', 'ignore')
                tex_phone = getattr(obj, 'officePhone', '')
                tex_email = obj.getEmail()
                websites = obj.getWebsites()
                if websites:
                    tex_homepage = websites[0]
                # tex_date = "13 de Octubre de 2016"
            # title_plan = 'foo.tex'
            title_plan = "%s.tex" % (userid)
            mainTex = '% !TEX encoding = UTF-8 Unicode\n'
            mainTex += PLAN_LATEX_TEMPLATE % (
                tex_title,
                tex_author,
                tex_institution,
                tex_phone,
                tex_email,
                tex_homepage,
                tex_date,
                plantext,
            )
            try:
                # fileTex = unicode(mainTex, "utf-8", errors="ignore")
                fileTex = mainTex.encode('utf-8', 'ignore')
                tempdir = tempfile.mkdtemp()
                file_path = os.path.join(tempdir, title_plan)
                file_os = open(file_path, 'wb')
                file_os.write(fileTex)
                file_os.close()
                os.system(
                    "cd {0}; pdflatex -interaction=nonstopmode {1}".format(
                        tempdir, file_path))
                os.system(
                    "cd {0}; gs -o page1.png -sDEVICE=pngalpha -dLastPage=1 {1}"
                    .format(tempdir, file_path.replace('.tex', '.pdf')))
            except:
                pass

            pdfname = file_path.replace('.tex', '.pdf')
            new_file = open(pdfname, "rb")
            self.textfile = namedfile.NamedBlobFile(new_file.read(),
                                                    filename=u"plan.pdf")

            image_path = os.path.join(tempdir, 'page1.png')
            thumb_file = open(image_path, 'r')

            self.thumbpdf = namedfile.NamedBlobImage(data=thumb_file.read(),
                                                     contentType='image/png',
                                                     filename=u'page1.png')

            try:
                shutil.rmtree(tempdir)  # remove tempdir
            except:
                pass

        else:
            self.textfile = None
            self.thumbpdf = None
            self.text = ''

    else:

        self.textfile = None
        self.text = ''
        if self.file:
            try:

                tempdir = tempfile.mkdtemp()
                file_path = os.path.join(tempdir, 'plan.pdf')
                file_os = open(file_path, 'wb')
                file_os.write(self.file.data)
                file_os.close()
                os.system(
                    "cd {0}; gs -o page1.png -sDEVICE=pngalpha -dLastPage=1 {1}"
                    .format(tempdir, file_path))
                image_path = os.path.join(tempdir, 'page1.png')
                thumb_file = open(image_path, 'r')

                self.thumbpdf = namedfile.NamedBlobImage(
                    data=thumb_file.read(),
                    contentType='image/png',
                    filename=u'page1.png')
            except:
                self.thumbpdf = None

            try:
                shutil.rmtree(tempdir)  # remove tempdir
            except:
                pass

        else:
            self.thumbpdf = None
예제 #9
0
def handlerModifiedPlan(self, event):

    if self.REQUEST.get('orig_template', '') == 'folder_contents':
        return

    plant = self.plan_type
    userid = api.user.get_current().id
    # Be carefull with this
    if userid == 'admin':
        # userid = self.Login()
        try:
            userid = self.Login()
        except Exception:
            userid = self.id

    if plant == 'plantext':

        # plantext = self.text
        plantext = self.REQUEST.get('form.widgets.text', '')

        if plantext:

            tex_title = self.title
            tex_author = ""
            tex_institution = "IM - UNAM"
            tex_phone = ""
            tex_email = ""
            tex_homepage = ""
            tex_date = ""

            text_conferences = "\n\n"
            conferences = self.conferences
            for conference in conferences:
                text_conferences += 'En %s si se dan las condicones necesarias, planeo organizar %s, con sede en %s. \n' % (
                    conference['conference_month'],
                    conference['conference_title'],
                    conference['conference_institution'])

            plantext += text_conferences

            catalog = getToolByName(getSite(), 'portal_catalog')
            query = {'portal_type': 'FSDPerson', 'id': userid}
            brains = catalog.searchResults(query)
            if brains:
                obj = brains[0].getObject()
                tex_author = obj.Title().decode('utf-8', 'ignore')
                tex_phone = getattr(obj, 'officePhone', '')
                tex_email = obj.getEmail()
                websites = obj.getWebsites()
                if websites:
                    tex_homepage = websites[0]
            # title_plan = 'foo.tex'
            title_plan = "%s.tex" % (userid)
            mainTex = '% !TEX encoding = UTF-8 Unicode\n'
            mainTex += PLAN_LATEX_TEMPLATE % (
                tex_title,
                tex_author,
                tex_institution,
                tex_phone,
                tex_email,
                tex_homepage,
                tex_date,
                plantext,
            )

            # mainTex += PLAN_LATEX_TEMPLATE % (plantext,)
            try:
                # fileTex = unicode(mainTex, "utf-8", errors="ignore")
                fileTex = mainTex.encode('utf-8', 'ignore')
                tempdir = tempfile.mkdtemp()
                file_path = os.path.join(tempdir, title_plan)
                file_os = open(file_path, 'wb')
                file_os.write(fileTex)
                file_os.close()
                os.system(
                    "cd {0}; pdflatex -interaction=nonstopmode {1}".format(
                        tempdir, file_path))
                os.system(
                    "cd {0}; gs -o page1.png -sDEVICE=pngalpha -dLastPage=1 {1}"
                    .format(tempdir, file_path.replace('.tex', '.pdf')))
            except:
                pass

            pdfname = file_path.replace('.tex', '.pdf')
            new_file = open(pdfname, "rb")
            self.textfile = namedfile.NamedBlobFile(new_file.read(),
                                                    filename=u"plan.pdf")

            image_path = os.path.join(tempdir, 'page1.png')
            thumb_file = open(image_path, 'r')

            self.thumbpdf = namedfile.NamedBlobImage(data=thumb_file.read(),
                                                     contentType='image/png',
                                                     filename=u'page1.png')

            try:
                shutil.rmtree(tempdir)  # remove tempdir
            except:
                pass
        else:
            self.textfile = None
            self.thumbpdf = None
            self.text = ''
    else:

        self.textfile = None
        self.text = ''
        if self.file:
            try:

                tempdir = tempfile.mkdtemp()
                file_path = os.path.join(tempdir, 'plan.pdf')
                file_os = open(file_path, 'wb')
                file_os.write(self.file.data)
                file_os.close()
                os.system(
                    "cd {0}; gs -o page1.png -sDEVICE=pngalpha -dLastPage=1 {1}"
                    .format(tempdir, file_path))
                image_path = os.path.join(tempdir, 'page1.png')
                thumb_file = open(image_path, 'r')

                self.thumbpdf = namedfile.NamedBlobImage(
                    data=thumb_file.read(),
                    contentType='image/png',
                    filename=u'page1.png')
            except:
                self.thumbpdf = None

            try:
                shutil.rmtree(tempdir)  # remove tempdir
            except:
                pass

        else:
            self.thumbpdf = None
예제 #10
0
def addDemoData(context):
    ''' '''
    if isNotMeetingCommunesDemoProfile(context):
        return

    site = context.getSite()
    tool = api.portal.get_tool('portal_plonemeeting')
    cfg = tool.objectValues('MeetingConfig')[0]
    wfTool = api.portal.get_tool('portal_workflow')
    pTool = api.portal.get_tool('plone_utils')
    mTool = api.portal.get_tool('portal_membership')
    # first we need to be sure that our IPoneMeetingLayer is set correctly
    # https://dev.plone.org/ticket/11673
    from zope.event import notify
    from zope.traversing.interfaces import BeforeTraverseEvent
    notify(BeforeTraverseEvent(site, site.REQUEST))
    # we will create elements for some users, make sure their personal
    # area is correctly configured
    # first make sure the 'Members' folder exists
    members = mTool.getMembersFolder()
    if members is None:
        _createObjectByType('Folder', site, id='Members')
    mTool.createMemberArea('agentPers')
    mTool.createMemberArea('agentInfo')
    mTool.createMemberArea('agentCompta')
    # create 5 meetings : 2 passed, 1 current and 2 future
    today = datetime.now()
    dates = [
        today - timedelta(days=13), today - timedelta(days=6),
        today + timedelta(days=1), today + timedelta(days=8),
        today + timedelta(days=15)
    ]

    # items dict here : the key is the user we will create the item for
    # we use item templates so content is created for the demo
    items = {
        'agentPers': (
            {
                'templateId': 'template3',
                'title': u'Engagement temporaire d\'un informaticien',
                'budgetRelated': True,
                'review_state': 'validated',
            },
            {
                'templateId': 'template2',
                'title': u'Contrôle médical de Mr Antonio',
                'budgetRelated': False,
                'review_state': 'proposed',
            },
            {
                'templateId': 'template2',
                'title': u'Contrôle médical de Mlle Debbeus',
                'budgetRelated': False,
                'review_state': 'proposed',
            },
            {
                'templateId': 'template2',
                'title': u'Contrôle médical de Mme Hanck',
                'budgetRelated': False,
                'review_state': 'validated',
            },
            {
                'templateId': 'template4',
                'title':
                u'Prestation réduite Mme Untelle, instritutrice maternelle',
                'budgetRelated': False,
                'review_state': 'validated',
            },
        ),
        'agentInfo': (
            {
                'templateId': 'template5',
                'title': u'Achat nouveaux serveurs',
                'budgetRelated': True,
                'review_state': 'validated',
            },
            {
                'templateId': 'template5',
                'title': u'Marché public, contestation entreprise Untelle SA',
                'budgetRelated': False,
                'review_state': 'validated',
            },
        ),
        'agentCompta': (
            {
                'templateId': 'template5',
                'title': u'Présentation budget 2014',
                'budgetRelated': True,
                'review_state': 'validated',
            },
            {
                'templateId': 'template5',
                'title': u'Plainte de Mme Daise, taxe immondice',
                'budgetRelated': False,
                'review_state': 'validated',
            },
            {
                'templateId': 'template5',
                'title': u'Plainte de Mme Uneautre, taxe piscine',
                'budgetRelated': False,
                'review_state': 'proposed',
            },
        ),
        'dgen': (
            {
                'templateId': 'template1',
                'title': u'Tutelle CPAS : point 1 BP du 15 juin',
                'budgetRelated': False,
                'review_state': 'created',
            },
            {
                'templateId': 'template5',
                'title': u'Tutelle CPAS : point 2 BP du 15 juin',
                'budgetRelated': False,
                'review_state': 'proposed',
            },
            {
                'templateId': 'template5',
                'title': u'Tutelle CPAS : point 16 BP du 15 juin',
                'budgetRelated': True,
                'review_state': 'validated',
            },
        ),
    }
    # login as 'dgen'
    mTool.createMemberArea('dgen')

    for cfg in tool.objectValues('MeetingConfig'):
        # cleanMemoize so ToolPloneMeeting.getMeetingConfig returns the correct MeetingConfig
        cleanMemoize(site)
        secrFolder = tool.getPloneMeetingFolder(cfg.getId(), 'dgen')
        # build attendees and signatories passed to Meeting._doUpdateContacts
        # attendees OrderedDict([('uid1', 'attendee'), ('uid2', 'attendee'), ('uid3', 'absent')])
        # signatories {'uid1': '1'}
        attendees = OrderedDict()
        signatories = {}
        for hp_uid in cfg.getOrderedContacts():
            attendees[hp_uid] = 'attendee'
        signatories = {attendees.keys()[1]: '1', attendees.keys()[0]: '2'}
        # create meetings
        for date in dates:
            meetingId = secrFolder.invokeFactory(cfg.getMeetingTypeName(),
                                                 id=date.strftime('%Y%m%d'),
                                                 date=date)
            meeting = getattr(secrFolder, meetingId)
            pTool.changeOwnershipOf(meeting, 'dgen')
            meeting._do_update_contacts(attendees=attendees,
                                        signatories=signatories)
            # -13 meeting is closed
            if date == today - timedelta(days=13):
                wfTool.doActionFor(meeting, 'freeze')
                wfTool.doActionFor(meeting, 'decide')
                wfTool.doActionFor(meeting, 'close')
            # -6 meeting is frozen
            if date == today - timedelta(days=6):
                wfTool.doActionFor(meeting, 'freeze')
                wfTool.doActionFor(meeting, 'decide')
            meeting.reindexObject()

            for item in meeting.get_items():
                pTool.changeOwnershipOf(item, 'dgen')

        # create items
        for userId in items:
            userFolder = tool.getPloneMeetingFolder(cfg.getId(), userId)
            for item in items[userId]:
                # get the template then clone it
                template = getattr(
                    tool.getMeetingConfig(userFolder).itemtemplates,
                    item['templateId'])
                with api.env.adopt_user(username=userId):
                    tool.invalidateAllCache()
                    newItem = template.clone(
                        newOwnerId=userId,
                        destFolder=userFolder,
                        newPortalType=cfg.getItemTypeName())
                    newItem.setTitle(item['title'])
                    newItem.setBudgetRelated(item['budgetRelated'])
                    if item['review_state'] == 'proposed':
                        wfTool.doActionFor(newItem, 'propose')

                if item['review_state'] == 'validated':
                    wfTool.doActionFor(newItem, 'validate')
                # add annexe and advice for one item in College
                if item['templateId'] == 'template3' and cfg.id == 'meeting-config-college':
                    cpt = 1
                    annexes_config_root = get_config_root(newItem)
                    for annexType in ('annexe', 'annexe', 'annexeBudget',
                                      'annexeCahier'):
                        annex_title = u'CV Informaticien N°2016-%s' % (cpt)
                        annex_file = namedfile.NamedBlobFile(
                            'Je suis le contenu du fichier',
                            filename=u'CV-0%s.txt' % (cpt))
                        annexTypeId = calculate_category_id(
                            annexes_config_root.get(annexType))
                        annex_id = normalize_name(site.REQUEST, annex_title)
                        api.content.create(container=newItem,
                                           id=annex_id,
                                           type='annex',
                                           title=annex_title,
                                           file=annex_file,
                                           content_category=annexTypeId,
                                           to_print=False,
                                           confidential=False)
                        cpt += 1
                    newItem.setOptionalAdvisers(
                        ('{0}__rowid__unique_id_003'.format(
                            org_id_to_uid('dirfin')),
                         org_id_to_uid('informatique')))
                    newItem.at_post_create_script()
                    createContentInContainer(
                        newItem, 'meetingadvice', **{
                            'advice_group': org_id_to_uid('informatique'),
                            'advice_type': u'positive',
                            'advice_comment': RichTextValue(SAMPLE_TEXT),
                            'advice_observations': RichTextValue()
                        })
                if item['templateId'] == 'template5' and cfg.id == 'meeting-config-college':
                    newItem.setOptionalAdvisers((org_id_to_uid('dirgen'), ))
                    newItem.at_post_create_script()
                    createContentInContainer(
                        newItem, 'meetingadvice', **{
                            'advice_group': org_id_to_uid('dirgen'),
                            'advice_type': u'negative',
                            'advice_comment': RichTextValue(SAMPLE_TEXT),
                            'advice_observations': RichTextValue(SAMPLE_TEXT)
                        })

                newItem.reindexObject()

        # adapt some parameters for config
        cfg.setAnnexToPrintMode('enabled_for_info')
예제 #11
0
def batchcreatannualreport(context):
    """批量创建缺失的年检报告,仅限于市本级,仅用于2014年度年检"""
    from plone import namedfile
    import datetime
    catalog = getToolByName(context, "portal_catalog")
    wf = getToolByName(context, "portal_workflow")
    hege = [
        "湘潭市科技情报学会",
        "湘潭市建设工程造价管理协会",
        "湘潭市金融学会",
        "湘潭市餐饮行业协会",
        "江南工业集团有限公司职工技术协会",
        "湘潭钢铁集团有限公司职工技术协会",
        "湘乡铝厂职工技术协会",
        "湘潭电厂职工技术协会",
        "湘潭市土木建筑学会",
        "湘潭市体育总会",
        "湘潭公路管理局职工技术协会",
        "江麓机电科技有限公司职工技术协会",
        "湘潭市消费者委员会",
        "湘潭市基督教三自爱国运动委员会",
        "湘潭市天主教爱国会",
        "湘潭市佛教协会",
        "湘潭市职工文化协会",
        "湘潭市道教协会",
        "湘潭市外来投资企业协会",
        "湘潭市电机工程学会",
        "湘潭市作家协会",
        "湘潭市翻译工作者协会",
        "湘潭市老年书画家协会",
        "湘潭市检察学会",
        "湘潭市房地产业协会",
        "湘潭市杂文学会",
        "湘潭市农村经济学会",
        "湘潭市档案学会",
        "湘潭市税务学会",
        "湘潭市护理学会",
        "湘潭市烟草学会",
        "湘潭市医学会",
        "湘潭市中医药学会",
        "湘潭市药学会",
        "湘潭市粮食经济科技学会",
        "湘潭市预防医学会",
        "湘潭市林学会",
        "湘潭市民俗文化学会",
        "湘潭市统计学会",
        "湘潭市农学会",
        "湘潭市诗词协会",
        "湘潭市集邮协会",
        "湘潭市书法家协会",
        "湘潭市基层卫生协会",
        "湘潭市戏剧家协会",
        "湘潭市金融会计学会",
        "湘潭市青年文学艺术家协会",
        "湘潭市足球协会",
        "湘潭市图书馆学会",
        "湘潭市企事业文学艺术界联合会",
        "湘潭市人民对外友好协会",
        "湘潭市汽车维修协会",
        "湘潭市机械化自动化学会",
        "湘潭市礼友经发联谊会",
        "湘潭市学会工作研究会",
        "湘潭齐白石研究会",
        "湘潭市钱币学会",
        "湘潭市人民代表大会制度研究会",
        "湘潭市注册会计师协会",
        "湘潭市少年儿童文学艺术家协会",
        "湘潭市接待服务协会",
        "湘潭市延安精神研究会",
        "湘潭市纪检监察学会",
        "湘潭市海外交流协会",
        "湘潭市个体劳动者私营企业协会",
        "湘潭市楹联家协会",
        "湘潭市摄影家协会",
        "湘潭市音乐家协会",
        "湘潭市警察协会",
        "湘潭市见义勇为奖励促进会",
        "湘潭市刑法学会",
        "湘潭市企业信用促进会",
        "湘潭市妇女人才联谊会",
        "湘潭银行业协会",
        "湘潭市旅游协会",
        "湘潭市民间商会",
        "湘潭保险行业协会",
        "湘潭市机械工程学会",
        "湘潭市农业机械学会",
        "湘潭市犯罪学研究会",
        "湘潭雨湖诗社",
        "湘潭市反邪教协会",
        "湘潭市茶叶行业协会",
        "湘潭市文明单位工作协会",
        "湘潭市民间文艺家协会",
        "湘潭市文学研究会",
        "湘潭市医疗保险学会",
        "湘潭市文艺评论家协会",
        "湘潭市再生资源行业协会",
        "湘潭市棋类协会",
        "湘潭市服务业促进会",
        "湘潭市气象学会",
        "湘潭市风景园林协会",
        "湘潭市收藏协会",
        "湘潭高新区消费者协会",
        "湘潭市电力行业协会",
        "湘潭市学生体育协会",
        "湘潭市机动车驾驶员培训协会",
        "湘潭市曲艺家协会",
        "湘潭市职业安全健康协会",
        "湘潭市道路运输协会",
        "湘潭市京剧票友协会",
        "湘潭市武术协会",
        "湘潭市游泳协会",
        "湘潭市金属材料商会",
        "湘潭市国库工作研究会",
        "湘潭市直机关书画家协会",
        "湘潭市妇幼保健与优生优育协会",
        "湘潭市花鸟画家协会",
        "湘潭市汽车商会",
        "湘潭市矿山装备行业协会",
        "湘潭市粮食行业协会",
        "湘潭市不动产业商会",
        "湘潭市电子信息行业协会",
        "湘潭市家用电器商会",
        "湘潭市老年保健协会",
        "湘潭市经纪人协会",
        "湘潭市计量测试检定所职工技术协会",
        "湘潭市狩猎协会",
        "湘潭市眼镜商会",
        "湘潭市龙舟协会",
        "湘潭市莲城书画研究会",
        "湘潭市农业机械流通行业协会",
        "湘潭市关心下一代爱心助学协会",
        "湘潭市少数民族联谊会",
        "湘潭市物流与采购联合会",
        "湘潭市五金机电商会",
        "湘潭市女作家协会",
        "湘潭离心机有限公司职工技术协会",
        "湘潭市国际税收研究会",
        "湘潭市基层法律服务工作者协会",
        "湘潭市侨商投资企业协会",
        "湘潭市人民政协理论研究会",
        "湘潭市宝庆商会",
        "湘潭市食品行业协会",
        "湘潭市城乡规划协会",
        "湘潭市禁毒协会",
        "湘潭市咨询业协会",
        "湘潭市鸟类爱好者协会",
        "湘潭市浙江商会",
        "湘潭市自行车运动协会",
        "湘潭市家政服务协会",
        "湘潭市九华慈善会",
        "湘潭市传统文化研究会",
        "湘潭市民间艺术研究会",
        "湘潭市商务联合会",
        "湘潭市汽车行业协会",
        "湘潭市福建商会",
        "湘潭市物业服务协会",
        "湘潭市医院协会",
        "湘潭市冬泳协会",
        "湘潭市羽毛球协会",
        "湘潭市汽车用品商会",
        "湘潭市残疾人企业家协会",
        "湘潭市义工联合会",
        "湘潭市衡阳商会",
        "湘潭市建筑器材租赁商会",
        "湘潭市出租汽车行业协会",
        "湘潭市电子商务协会",
        "湘潭市国学研究会",
        "湘潭市体育舞蹈协会",
        "湘潭市青山桥乡土文化研究会",
        "湘潭市水文职工技术协会",
        "湘潭市林业产业协会",
        "湘潭市浏阳商会",
        "湘潭市市容环境卫生协会",
        "湘潭市石料行业协会",
        "湘潭市经济技术开发区(九华)消费者协会",
        "湘潭市育婴师协会",
        "湘潭市留学归国人员联谊会",
        "湘潭市江西商会",
        "湘潭市巫家拳协会",
        "湘潭市油画学会",
        "湘潭市空竹运动协会",
        "湘潭市地方金融行业协会",
        "湘潭市数据学会",
        "湘潭市中小微企业金融促进会",
        "湘潭市肾病互助协会",
        "湘潭市《周易》文化研究会",
        "湘潭市企业联合会",
        "湘潭市企业家协会",
        "湘潭市花卉盆景协会",
        "湘潭市律师协会",
        "湘潭市广播电视学会",
        "湘潭市科技模型运动协会",
        "湘潭市统一战线理论研究会",
        "湘潭市珠算协会",
        "湘潭市财政会计学会",
        "湘潭市计算机学会",
        "湘潭市国土资源学会",
        "湘潭市莲城清风义工协会",
        "湘潭市老科技工作者协会",
        "湘潭市蔬菜协会",
        "湘潭市家具行业协会",
        "湘潭市青年企业家协会",
        "湘潭市希望工程促进会",
        "湘潭市志愿者协会",
        "湘潭市建筑业协会",
        "湘潭市抗癌协会",
        "湘潭市当代音乐促进会",
        "湘潭市政法系统文学艺术工作者联合会",
        "湘潭市渣土行业协会",
        "湘潭市孝亲敬老志愿者协会",
        "湘潭市社会福利事务管理协会",
        "湘潭市慈善总会",
        "湘潭市室内装饰行业协会",
        "湘潭环境保护协会",
        "湘潭市家居装饰材料商会",
        "湘潭市钢材深加工产业协会",
        "湘潭市思想政治工作研究会",
        "湘潭市莲城志愿者协会",
        "湘潭市柔力球协会",
        "湘潭市卫生经济学会",
        "湘潭海外联谊会",
        "湘潭市知识分子联谊会",
        "湘潭市质量协会",
        "湘潭市九华示范区个体劳动者私营企业协会",
        "湘潭市门球协会",
        "湘潭市燃气燃烧器具行业协会",
        "湘潭市糖尿病中医中药临床研究中心",
        "湘潭市世纪风职业培训学校",
        "湘潭市红十字建春医院",
        "湘潭天英职业技能培训学校",
        "湘潭易道馆跆拳道培训中心",
        "湘潭市工商适应技术学校",
        "湘潭市飞扬跆拳道培训中心",
        "湘潭市童心幼儿园",
        "湘潭市雨湖区九华杉山幼儿园",
        "湘潭市雨湖区九华红旗好贝贝幼儿园",
        "湘潭有色二十三冶医院",
        "湘潭市雨湖区九华小星星幼儿园",
        "湘潭市雨湖区九华启明星幼儿园",
        "湘潭市雨湖区九华爱贝斯幼儿园",
        "湘潭市雨湖区九华晨光幼儿园(杉山园)",
        "湘潭市创益扶困咨询中心",
        "湘潭市易家湾南天幼儿园",
        "湘潭爱民医院",
        "湘潭文理专修学院",
        "湘潭市泽民中医类风湿病研究中心",
        "湘潭新华电脑学校",
        "湘潭市精益眼视光研究所",
        "湘潭佳程涉外职业培训学校",
        "湘潭市红十字湘仁医院",
        "湘潭市华顺职业培训中心",
        "湘潭市同升国济职业技能培训学校",
        "湘潭千里马职业教育培训中心",
        "湖南吉利汽车职业技术学院",
        "湖南软件职业学院",
        "湖南汽车工程师专修学院",
        "湘潭新时代医院",
        "湘潭市银海职业技能培训学校",
        "湘潭市人力资源培训学校",
        "湘潭市中凯人机速记职业培训中心",
        "湘潭市阳光青少年俱乐部",
        "湘潭德盛职业技能培训学校",
        "湘潭市昭山示范区童之园幼儿园",
        "湘潭市江南悦意残疾人托养服务中心",
        "湘潭市岳塘区高新第一幼儿园",
        "湘潭市红太阳艺术团",
        "湘潭市金康白癜风中医中药临床治疗研究中心",
        "湘潭市恒企职业技能培训学校",
        "湘潭市荆鹏职业教育培训中心",
        "湘潭市昭山示范区健康幼儿园",
    ]
    jibenhege = [
        "湘潭市民营企业家协会", "湘潭市科技成果与技术市场协会", "湘潭市伊斯兰教协会", "湘潭高新区个体劳动者私营企业协会",
        "湘潭市勘察设计协会", "湘潭市水利学会", "湘潭市工商行政管理学会", "湘潭市房地产开发协会", "湘潭市互联网上网服务协会",
        "湘潭市司法鉴定协会", "湘潭市爱立方志愿者协会", "湘潭市德孝文化研究会", "湘潭市商标广告协会",
        "湘潭市建设工程质量安全监督协会", "湘潭市建设监理协会", "湘潭市网球协会", "湘潭市桥牌协会", "湘潭市演讲与口才协会",
        "湘潭市登山协会", "湘潭市女检察官协会", "湘潭市印刷行业协会", "湘潭市户外运动协会", "湘潭市干部教育研究会",
        "湘潭市青年书法家协会", "湘潭市美术家协会", "湘潭市审计学会", "湘潭市职工技术协会", "湘潭市设计艺术家协会",
        "湘潭市湘沪商务促进会", "湘潭市岳阳商会", "湘潭市舞蹈家协会", "湘潭市隐山湖湘文化源研究会", "湘潭市民办教育协会",
        "湘潭市发明协会", "湘潭市内部审计师协会", "湘潭市摩托车商会", "湘潭市养猪协会", "湘潭市外贸企业协会",
        "湘潭市红色文化研究会", "湘潭市百货业商会", "湘潭市导游协会", "湘潭市社会组织促进会", "湘潭市体育健康服务指导中心",
        "湘潭市俊丝美容职业技能培训学校", "湘潭市旅游职业培训中心", "湘潭市少儿特长启蒙学校", "湘潭市益智实验中学",
        "湘潭湘商文化研究中心", "湘潭市飞翔职业技能培训中心", "湘潭市金梦园养老服务中心", "湘潭厨师、服务师培训中心",
        "湘潭市永胜工程机械培训学校", "湘潭融城设计艺术职业学校"
    ]
    buhege = [
        "湘潭市新闻工作者协会", "湘潭市就业促进会", "湘潭市预算会计学会", "湘潭海峡两岸经贸发展促进会", "湘潭市职工困难互助会",
        "湘潭市专业技术人员奖励工作促进会", "湘潭市市场发展促进会", "湘潭市建设教育协会", "湘潭金桥公路职工技术协会",
        "湘潭市消防协会", "湘潭市环境科学学会", "湘潭市建设工程招标投标协会", "湘潭市法官协会", "湘潭市饲料行业协会",
        "湘潭市酒业协会", "湘潭市性病艾滋病防治协会", "湘潭市诚信协会", "湘潭市法制新闻协会", "湘潭市心理学会",
        "湘潭市机关党建研究会", "湘潭市瑾源文化研究会", "湘潭市住房和城乡建设局职工技术协会", "湘潭市建设有中国特色社会主义理论研究会",
        "湘潭市毛泽东思想研究会", "湘潭市价格协会", "湘潭市秘书学会", "湘潭市社区发展协会", "湘潭市革命老区经济开发促进会",
        "湘潭市教育学会", "湘潭市青少年科技教育协会", "湘潭市交通学会", "湘潭市畜牧水产学会", "湘潭市社会科学学会工作研究会",
        "湘潭市政策科学研究会", "湘潭市民商法学会", "湘潭市艺术收藏家协会", "湘潭市红木文化鉴赏协会", "湘潭市农产品流通行业协会",
        "湘潭市自驾游协会", "湘潭市文化产业协会", "湘潭市民生社区综合服务中心", "湘潭市美术创作中心",
        "湘潭市雨湖区九华晨光幼儿园(科大园)"
    ]

    query = {
        "object_provides": IOrgnization.__identifier__,
        "orgnization_belondtoArea": "xiangtanshi"
    }
    #             "orgnization_orgnizationType":"minfei"}
    bns = catalog(query)

    for i in bns:
        title = i.Title
        brains = catalog({
            'path':
            i.getPath(),
            'id':
            '2014',
            'object_provides':
            IOrgnization_annual_survey.__identifier__
        })
        num = len(brains)
        #            import pdb
        #            pdb.set_trace()
        if num == 0:
            newid = "2014"
            #                import pdb
            #                pdb.set_trace()
            #                if not isinstance(newid, unicode):
            #                    newid = unicode(newid, 'utf-8')
            #                surveyid = IUserPreferredFileNameNormalizer(self.request).normalize(newid)
            item = createContentInContainer(
                i.getObject(),
                "my315ok.socialorgnization.orgnizationsurvey",
                checkConstraints=False,
                id=newid)
            item.title = title
            if title in jibenhege:
                item.annual_survey = "jibenhege"
                item.sponsor_comments = item.agent_comments = u"基本合格"

            elif title in hege:
                item.annual_survey = "hege"
                item.sponsor_comments = item.agent_comments = u"合格"
            elif title in buhege:
                item.annual_survey = "buhege"
                item.sponsor_comments = item.agent_comments = u"不合格"
            else:
                continue
            item.year = "2014"
            item.sponsor_audit_date = datetime.datetime.today(
            ) + datetime.timedelta(-20)
            item.agent_audit_date = datetime.datetime.today(
            ) + datetime.timedelta(-15)
            #                import pdb
            #                pdb.set_trace()
            item.report = namedfile.NamedBlobFile(u'已提交纸质年检报告',
                                                  filename=u"2014report.doc")
            wf.doActionFor(item, 'publish', comment="publish")
            item.reindexObject()
    return "pass"
예제 #12
0
def _create_demo_setup(portal, context):
    """
    Create demo content for operun CRM.
    """

    profile_id = 'operun.crm:demo'
    profile_context = context._getImportContext(profile_id)
    profile_path = profile_context._profile_path
    offer_path = profile_path + '/files/offer.pdf'
    invoice_path = profile_path + '/files/invoice.pdf'
    logo_path = profile_path + '/files/logo.jpg'
    businesscard_path = profile_path + '/files/businesscard.jpg'

    # Setup Contacts
    contacts = api.content.create(
        type='Contacts',
        container=portal,
        id='contacts',
        title=u'Kontakte',
        description=
        u'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',  # noqa
    )
    api.content.transition(obj=contacts, transition='publish')

    # Setup Accounts
    accounts = api.content.create(
        type='Accounts',
        container=portal,
        id='accounts',
        title=u'Kunden',
        description=
        u'Ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',  # noqa
    )
    api.content.transition(obj=accounts, transition='publish')

    # Create Account
    account = api.content.create(
        type='Account',
        container=accounts,
        id='musterfirma-gmbh',
        title=u'Musterfirma GmbH',
        logo=NamedBlobImage(open(logo_path, 'r').read(), filename=u'logo.jpg'),
        ceo=u'Max Mustermann',
        email=u'*****@*****.**',
        phone=u'+49 89 123456-0',
        fax=u'+49 89 123456-99',
        website=u'https://www.musterfirma.de',
        project_reference=u'https://support.example.com/projects/1000',
        address=u'Musterstraße',
        zip=u'12345',
        city=u'Musterstadt',
        billing_email=u'*****@*****.**',
        text=RichTextValue(
            u'Sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores.',
            'text/plain', 'text/html'),  # noqa
    )
    api.content.transition(obj=account, transition='publish')

    # RelationValue
    intids = getUtility(IIntIds)

    # Create Contact
    contact = api.content.create(
        type='Contact',
        container=contacts,
        id='max-mustermann',
        title=u'Max Mustermann',
        firstname=u'Max',
        lastname=u'Mustermann',
        account=RelationValue(intids.getId(account)),
        phone=u'+49 89 123456-78',
        mobile=u'+49 170 1234567',
        email=u'*****@*****.**',
        businesscard=NamedBlobImage(open(businesscard_path, 'r').read(),
                                    filename=u'businesscard.jpg'),  # noqa
        notes=RichTextValue(
            u'Sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores.',
            'text/plain', 'text/html'),  # noqa
    )
    api.content.transition(obj=contact, transition='publish')

    # Create Invoice & Offer

    invoice = api.content.create(
        type='Invoice',
        container=account,
        id='invoice-2017-04-21',
        title=u'Invoice 2017-04-21',
        description=
        u'Invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.',  # noqa
        file=namedfile.NamedBlobFile(open(invoice_path, 'r').read(),
                                     filename=u'invoice.pdf'),
    )
    api.content.transition(obj=invoice, transition='publish')

    offer = api.content.create(
        type='Offer',
        container=account,
        id='offer-2017-04-21',
        title=u'Offer 2017-04-21',
        description=
        u'Invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.',  # noqa
        file=namedfile.NamedFile(data=open(offer_path, 'r').read(),
                                 filename=u'offer.pdf'),
    )
    api.content.transition(obj=offer, transition='publish')
예제 #13
0
 def _annex_file_content(self, annexFile=None):
     current_path = os.path.dirname(__file__)
     annexFile = annexFile or self.annexFile
     f = open(os.path.join(current_path, annexFile), 'r')
     annex_file = namedfile.NamedBlobFile(f.read(), filename=annexFile)
     return annex_file
    def __iter__(self):
        for item in self.previous:
            keys = item.keys()
            typekey = self.typekey(*keys)[0]
            pathkey = self.pathkey(*keys)[0]

            if not (typekey and pathkey):
                logger.warn('Not enough info for item: {0}'.format(item))
                yield item
                continue

            type_, path = item[typekey], item[pathkey]  # noqa

            obj = self.context.unrestrictedTraverse(
                str(item[pathkey]).lstrip('/'), None)

            if not obj:
                yield item
                continue
            if getattr(obj, 'text', None):
                raw_text = obj.text.raw
                if '@@download' in raw_text:
                    fixed_text = re.sub(r'(/@@download/.*?)"', r'"', raw_text)
                    setattr(
                        obj, 'text',
                        RichTextValue(raw=fixed_text,
                                      outputMimeType='text/x-html-safe',
                                      mimeType=u'text/html'))

            # da scommentare in caso di migrazione di subsite
            # if type_ == 'Folder' and item['is_rer_subsite']:
            #     if not IRERSubsiteEnabled.providedBy(obj):
            #         alsoProvides(obj, IRERSubsiteEnabled)
            #         obj.reindexObject(idxs=['object_provides'])
            #         obj.subsite_color = item.get('subsite_color', None)
            #
            #         if item.get('_datafield_image', None):
            #             image_params = item['_datafield_image']
            #             image_data = urllib2.urlopen(
            #                 image_params['data_uri']
            #             ).read()
            #             obj.image = namedfile.NamedBlobImage(
            #                 image_data,
            #                 contentType=image_params['content_type'],
            #                 filename=image_params['filename']
            #             )

            if type_ == 'SchedaER':
                links_info = [
                    'toDeepen', 'rulesAndActs', 'modules', 'ongoingProjects',
                    'initiatives', 'publications', 'usefulLinks', 'seeOther'
                ]
                for el in links_info:
                    if item.get(el, ''):
                        link_data = '<ul>'
                        for line in item.get(el):
                            if line['link'].startswith('http'):
                                link_data += '<li><a href="' \
                                    + line['link'] \
                                    + '" data-linktype="external" data-val="' \
                                    + line['link'] + '">' \
                                    + line['title'] \
                                    + '</a></li>'
                            else:
                                link_data += '<li><a href="../resolveuid/' \
                                    + line['uid'] \
                                    + '" data-linktype="internal" data-val="' \
                                    + line['uid'] \
                                    + '">' \
                                    + line['title'] \
                                    + '</a></li>'
                        link_data += '</ul>'
                        if link_data == '<ul></ul>':
                            link_data = ''
                        tmp_text = RichTextValue(
                            link_data, 'text/html',
                            'text/x-plone-outputfilters-html')
                        setattr(obj, el, tmp_text)
                        del item[el]

            if type_ == 'LinkNormativa':
                if getattr(obj, 'lawType', None):
                    setattr(obj, 'lawType', item.get('lawType'))
                logger.info('Fired event to setup remoteUrl for: {0}'.format(
                    obj.absolute_url()))
                notify(ObjectAddedEvent(obj))

            if type_ == 'Pubblicazione':
                if item['publicationDate']:
                    obj.publicationDate = DateTime(
                        item['publicationDate']).asdatetime()
                auth = item.get('_auth_info')
                if item.get('_datafield_image', None):
                    image_params = item['_datafield_image']
                    image_data = self.get_file_data(image_params, auth)
                    obj.image = namedfile.NamedBlobImage(
                        image_data,
                        contentType=image_params['content_type'],
                        filename=image_params['filename'])
                if item.get('_datafield_file', None):
                    file_params = item['_datafield_file']
                    file_data = self.get_file_data(file_params, auth)
                    obj.publicationFile = namedfile.NamedBlobFile(
                        file_data, filename=file_params['filename'])

            if type_ == 'Circolare':
                if getattr(obj, 'file1') and obj.file1.getSize() == 0:
                    del obj.file1
                if getattr(obj, 'file2') and obj.file2.getSize() == 0:
                    del obj.file2
                if getattr(obj, 'file3') and obj.file3.getSize() == 0:
                    del obj.file3

            # bisogna prendere solo le immagini all'interno degli annunci del
            # mercatino
            if type_ == 'Image' and \
                    (obj.aq_parent.portal_type == 'Advertisement' or
                     obj.aq_parent.portal_type == 'BookCrossing'):
                if item.get('_datafield_image', None):
                    image_params = item['_datafield_image']

                    request = urllib2.Request(image_params['data_uri'])
                    base64string = base64.encodestring('{0}:{1}'.format(
                        self.remote_username,
                        self.remote_password)).replace('\n', '')
                    request.add_header('Authorization',
                                       'Basic {0}'.format(base64string))

                    image_data = urllib2.urlopen(request).read()
                    obj.image = namedfile.NamedBlobImage(
                        image_data,
                        contentType=image_params['content_type'],
                        filename=image_params['filename'])

            if type_ == 'Venue':
                from plone.formwidget.geolocation.geolocation import Geolocation
                geo = Geolocation(item['latitude'], item['longitude'])
                setattr(obj, 'geolocation', geo)

            yield item
예제 #15
0
    def setUp(self):
        portal = self.layer['portal']
        setRoles(portal, TEST_USER_ID, ('Manager', ))
        login(portal, TEST_USER_NAME)
        wf = getToolByName(portal, "portal_workflow")
        portal.invokeFactory('dexterity.membrane.memberfolder',
                             'memberfolder1')
        # 社团经手人账号
        portal['memberfolder1'].invokeFactory(
            'dexterity.membrane.organizationmember',
            'member1',
            email="*****@*****.**",
            last_name=u"唐",
            first_name=u"岳军",
            title=u"tangyuejun",
            password="******",
            confirm_password="******",
            orgname="orgnization1",
            homepae='http://315ok.org/',
            bonus=10,
            description="I am member1")
        # 监管单位经手人账号
        portal['memberfolder1'].invokeFactory(
            'dexterity.membrane.sponsormember',
            '100',
            email="*****@*****.**",
            last_name=u"唐",
            first_name=u"岳军",
            title=u"tangyuejun",
            password="******",
            confirm_password="******",
            orgname=u"government1",
            homepae='http://315ok.org/',
            bonus=10,
            description="I am member1")
        # 民政局经手人账号
        portal['memberfolder1'].invokeFactory(
            'dexterity.membrane.sponsormember',
            '200',
            email="*****@*****.**",
            last_name=u"唐",
            first_name=u"岳军",
            title=u"tangyuejun",
            password="******",
            confirm_password="******",
            orgname=u"minzhengju",
            homepae='http://315ok.org/',
            bonus=10,
            description="I am member1")

        portal.invokeFactory('my315ok.socialorgnization.orgnizationfolder',
                             'orgnizationfolder1',
                             title="productfolder1",
                             description="demo productfolder")

        # 社会组织
        portal['orgnizationfolder1'].invokeFactory(
            'my315ok.socialorgnization.orgnization',
            'orgnization1',
            title=u"宝庆商会",
            description=u"运输业",
            address=u"建设北路",
            register_code="8341",
            supervisor=u"交通局",
            organization_type="minfei",
            legal_person=u"张建明",
            passDate=datetime.datetime.today(),
            belondto_area='yuhuqu',
        )
        #建立监管单位   :交通局 government1
        portal['orgnizationfolder1'].invokeFactory(
            'my315ok.socialorgnization.governmentorgnization',
            'government1',
            title=u"交通局",
            description=u"运输业",
            operator="*****@*****.**",
        )

        #建民政局    id hard code as:‘minzhengju’                                               )
        portal['orgnizationfolder1'].invokeFactory(
            'my315ok.socialorgnization.governmentorgnization',
            'minzhengju',
            title=u"民政局",
            description=u"民政局",
            operator="*****@*****.**",
        )

        #        logout()
        #        login(portal, '*****@*****.**')
        portal['orgnizationfolder1']['orgnization1'].invokeFactory(
            'my315ok.socialorgnization.orgnizationsurvey',
            'survey1',
            title=u"宝庆商会",
            description=u"运输业",
            annual_survey="hege",
            year="2013",
        )

        data = getFile('demo.txt').read()
        item = portal['orgnizationfolder1']['orgnization1']['survey1']
        item.image = NamedImage(data, 'image/gif', u'image.gif')
        item.report = namedfile.NamedBlobFile(data, filename=u"demo.txt")

        self.portal = portal
        self.wf = wf
        import transaction
        transaction.commit()