Exemplo n.º 1
0
    def add_order(self, ordernumber, memberid, service):
        props = {'id'     :ordernumber,
                 'title'  :ordernumber,
                 'userid' :memberid}
        createContentInContainer(
            self.orders,
            'emas.app.order',
            False,
            **props
        )
        order = self.orders._getOb(ordernumber)

        order.fullname = 'test user'
        order.phone = '999999999999'
        order.shipping_address = ''
        order.payment_method = 'eft'

        item_id = 'orderitem.%s' %service.getId()
        relation = create_relation(service.getPhysicalPath())
        props = {'id'           :item_id,
                 'title'        :service.Title(),
                 'related_item' :relation,
                 'quantity'     :1}
        createContentInContainer(
            order,
            'emas.app.orderitem',
            False,
            **props
        )
        return order
Exemplo n.º 2
0
    def update(self):
        registry = queryUtility(IRegistry)
        self.settings = registry.forInterface(IEmasSettings)
        self.mode = SERVICE_SELECTION
        self.selected_services = []

        if self.request.get('purchase.form.submitted'):
            order_items = self.request.form.get('order')
            if order_items is None or len(order_items) < 1:
                # no items selected, show the selection UI
                self.mode = SERVICE_SELECTION
           
            # set local variables for use in the template
            self.mode = SELECTION_CONFIRMATION
            self.selected_services = order_items
            
        elif self.request.get('purchase.confirmed'):
            # create member service objects
            portal_state = self.context.restrictedTraverse(
                '@@plone_portal_state'
            )
            portal = portal_state.portal()
            member = portal_state.member()
            memberid = member.getId()
            member_orders = portal['orders']
            products_and_services = portal['products_and_services']
        
            order_items = self.request.form.get('order')
            if order_items is None or len(order_items) < 1:
                # no items selected, show the selection UI
                self.mode = SERVICE_SELECTION
            
            ordernumber = self.settings.order_sequence_number + 1
            self.settings.order_sequence_number = ordernumber
            self.ordernumber = '%04d' % ordernumber
            member_orders.invokeFactory(
                type_name='emas.app.order',
                id=self.ordernumber,
                title=self.ordernumber,
                userid=memberid
            )
            self.order = member_orders._getOb(self.ordernumber)

            for sid, quantity in order_items.items():
                service = products_and_services[sid]
                relation = create_relation(service.getPhysicalPath())
                item_id = self.order.generateUniqueId(type_name='orderitem')
                self.order.invokeFactory(
                    type_name='emas.app.orderitem',
                    id=item_id,
                    title=item_id,
                    related_item=relation,
                    quantity=quantity,
                )
            
            self.request.response.redirect(
                '@@paymentdetails/?orderid=%s' %self.order.getId())
Exemplo n.º 3
0
 def test_references_dx_to_at(self):
     at = create(Builder('page').titled('AT'))
     dx = create(Builder('example dx type').titled(u'DX'))
     at_relation = create_relation('/'.join(at.getPhysicalPath()))
     IRelatedItems(dx).relatedItems = [at_relation]
     _setRelation(dx, 'relatedItems', at_relation)
     self.assertEquals(
         [at],
         list(get_state(dx).get_references())
     )
Exemplo n.º 4
0
    def _createQuestion(self):
        container = self.portal.questions
        new_id = container.generateId('question')
        rel = create_relation(container.getPhysicalPath())

        container.invokeFactory('siyavula.what.question',
                                id=new_id,
                                relatedContent=rel,
                                text='test question 01')
        question = container._getOb(new_id)
        return question
Exemplo n.º 5
0
    def _createQuestion(self):
        container = self.portal.questions
        new_id = container.generateId('question')
        rel = create_relation(container.getPhysicalPath())

        container.invokeFactory('collective.answers.question',
                                id=new_id,
                                relatedContent=rel,
                                text='test question 01')
        question = container._getOb(new_id)
        return question
Exemplo n.º 6
0
    def test_references_dx_to_dx(self):
        foo = create(Builder('example dx type').titled(u'Foo'))
        bar = create(Builder('example dx type').titled(u'Bar'))

        foo_relation = create_relation('/'.join(foo.getPhysicalPath()))
        IRelatedItems(bar).relatedItems = [foo_relation]
        _setRelation(bar, 'relatedItems', foo_relation)
        self.assertEquals(
            [foo],
            list(get_state(bar).get_references())
        )
 def _createContentRefs(self, sections):
     for number, section in enumerate(sections):
         id = self.portal.invokeFactory('File',
                                        'file%s' % number,
                                        title=u'File %s' % number)
         file = self.portal._getOb(id)
         id = section.invokeFactory('rhaptos.compilation.contentreference',
                                    'contentref%s' % number,
                                    title=u"Content reference %s" % number)
         contentref = section._getOb(id)
         relation = create_relation(file.getPhysicalPath())
         contentref.relatedContent = relation
         contentref.reindexObject(
             idxs=['compilationUID', 'relatedContentUID'])
 def _createContentRefs(self, sections):
     for number, section in enumerate(sections):
         id = self.portal.invokeFactory(
             'File',
             'file%s' %number,
             title=u'File %s' %number)
         file = self.portal._getOb(id)
         id = section.invokeFactory(
             'rhaptos.compilation.contentreference',
             'contentref%s' %number,
             title=u"Content reference %s" %number)
         contentref = section._getOb(id)
         relation = create_relation(file.getPhysicalPath())
         contentref.relatedContent = relation
         contentref.reindexObject(idxs=['compilationUID', 'relatedContentUID'])
Exemplo n.º 9
0
 def createMemberService(self, service):
     mstitle = '%s for %s' % (service.title, TEST_USER_ID)
     related_service = create_relation(service.getPhysicalPath())
     props = {'title': mstitle,
              'userid': TEST_USER_ID,
              'related_service': related_service,
              'service_type': service.service_type
              }
     ms = createContentInContainer(
         self.memberservices,
         'emas.app.memberservice',
         False,
         **props
     )
     ms.manage_setLocalRoles(TEST_USER_ID, ('Owner',))
     now = datetime.now().date()
     ms.expiry_date = now + timedelta(service.subscription_period)
     return ms
Exemplo n.º 10
0
    def addQuestion(self):
        request = self.request
        context = self.context

        question_text = request.get('question', '')
        if not question_text:
            return

        portal = context.restrictedTraverse('@@plone_portal_state').portal()
        questions = portal._getOb('questions')
        new_id = questions.generateId('question')
        relation = create_relation(context.getPhysicalPath())

        questions.invokeFactory('collective.answers.question',
                                id=new_id,
                                relatedContent=relation,
                                text=question_text.decode('utf-8'))
        
        question = questions._getOb(new_id)
        return question
Exemplo n.º 11
0
    def addQuestion(self):
        request = self.request
        context = self.context

        question_text = request.get('question', '')
        if not question_text:
            return

        portal = context.restrictedTraverse('@@plone_portal_state').portal()
        questions = portal._getOb('questions')
        new_id = questions.generateId('question')
        relation = create_relation(context.getPhysicalPath())

        questions.invokeFactory('siyavula.what.question',
                                id=new_id,
                                relatedContent=relation,
                                text=question_text.decode('utf-8'))

        question = questions._getOb(new_id)
        return question
Exemplo n.º 12
0
def create_news_items(context, app, section, i):
    seq = i + 1
    item = api.content.create(
        container=app,
        type='News Item',
        title=LOREMIPSUM_TITLES[i],
    )
    item.section = create_relation(section.getPhysicalPath())
    item.description = ' '.join(loremipsum.get_sentences(2))
    item.text = RichTextValue(raw="\n\n".join(loremipsum.get_paragraphs(3)),
                              mimeType='text/plain',
                              outputMimeType='text/x-html-safe')
    img_name = '{:02d}.jpg'.format(seq)
    img_path = os.path.join('images', img_name)
    img_data = context.openDataFile(img_path).read()
    item.image = NamedBlobImage(data=img_data,
                                filename=img_name.decode('utf-8'))
    if i % 2:
        item.must_read = True
    item.setEffectiveDate('2016/09/{:02d}'.format(seq))
    api.content.transition(item, 'publish')
    item.reindexObject()
Exemplo n.º 13
0
def move_all_newsitems_to_app(*args):
    app = api.portal.get().news
    section = app.sections()[0]
    app_path = '/'.join(app.getPhysicalPath())
    catalog = api.portal.get_tool('portal_catalog')
    items = [
        x for x in catalog(portal_type='News Item')
        if not x.getPath().startswith(app_path)
    ]
    i = 0
    j = 0
    for item in items:
        log.info("Moving legacy news item: %s", item.getPath())
        try:
            moved = api.content.move(item.getObject(), app)
            moved.section = create_relation(section.getPhysicalPath())
            moved.reindexObject()
            i += 1
        except Exception:  # https://github.com/quaive/ploneintranet/issues/950
            log.error("Could not move legacy news item: %s", item.getPath())
            j += 1
    log.info("Moved %s legacy news items into app.", i)
    if j:
        log.error("Failed to move %s news items.", j)
Exemplo n.º 14
0
    def contact(self, contact):
        self.arguments.update(contact=create_relation(contact.getPhysicalPath()))

        return self
Exemplo n.º 15
0
    def update(self):
        self.portal_state = self.context.restrictedTraverse(
            '@@plone_portal_state'
        )
        self.portal = self.portal_state.portal()
        self.member = self.portal_state.member()
        self.memberid = self.member.getId()
        self.orders = self.portal['orders']
        self.products_and_services = self.portal['products_and_services']

        registry = queryUtility(IRegistry)
        self.settings = registry.forInterface(IEmasSettings)

        self.subjects = self.request.get('subjects')
        self.service_ordered = self._service_ordered()

        self.ordernumber = ordernumber = self.request.get('ordernumber', '')

        if self.ordersubmitted():

            if self.request.has_key('confirm_back_button'):
                return self.context.restrictedTraverse('@@order')

            if ordernumber:
                self.order = self.orders._getOb(self.ordernumber)
                self.order.manage_delObjects(self.order.objectIds()) 
            else:
                tmpnumber = self.settings.order_sequence_number + 1
                self.settings.order_sequence_number = tmpnumber
                self.ordernumber = '%04d' % tmpnumber
                props = {'id'     :self.ordernumber,
                         'title'  :self.ordernumber,
                         'userid' :self.memberid}
                createContentInContainer(
                    self.orders,
                    'emas.app.order',
                    False,
                    **props
                )
                self.order = self.orders._getOb(self.ordernumber)

            self.order.fullname = self.request.get('fullname', '')
            self.order.phone = self.request.get('phone', '')
            self.order.shipping_address = self.request.get('shipping_address', '')
            self.order.payment_method = self.prod_payment()

            ordered_service_ids = []

            # mobile order
            if self.request.get('service') == 'monthly-practice':
                sid = '%s-%s-monthly-practice' % (
                    self.subjects.lower(),
                    self.request.get('grade')
                    )
                ordered_service_ids.append(sid)

            # web order
            else:
                maths_service_ids = [
                    'maths-grade8-practice',
                    'maths-grade9-practice',
                    'maths-grade10-practice',
                    'maths-grade11-practice',
                    'maths-grade12-practice',
                ]
                science_service_ids = [
                    'science-grade10-practice',
                    'science-grade11-practice',
                    'science-grade12-practice',
                ]
                if self.subjects in ('Maths', 'Maths,Science'):
                    ordered_service_ids.extend(maths_service_ids)
                if self.subjects in ('Science', 'Maths,Science'):
                    ordered_service_ids.extend(science_service_ids)
                # add discount if both subjects were ordered
                if self.subjects == 'Maths,Science':
                    ordered_service_ids.append('maths-and-science-discount')

            for sid in ordered_service_ids:
                service = self.products_and_services[sid]
                item_id = 'orderitem.%s' %service.getId()
                relation = create_relation(service.getPhysicalPath())
                quantity = 1
                props = {'id': item_id,
                         'title': service.Title(),
                         'related_item': relation,
                         'quantity': quantity}
                createContentInContainer(
                    self.order,
                    'emas.app.orderitem',
                    False,
                    **props
                )

            self.totalcost = "R %.2f" % self.order.total()
            
            # Now we do the payment bit. Since it can be one of several ways we
            # wrap the lot in a seperate method.
            self.prepPaymentDetails(self.order, self.request)

            # We can only send an invoice if we have somewhere to send it to.
            if self.member.getProperty('email'):
                self.send_invoice(self.order)
Exemplo n.º 16
0
    def handleApply(self, action):

        data, errors = self.extractData()
        add_status_msg = IStatusMessage(self.request).add

        if errors:
            self.status = self.formErrorsMessage
            return

        cat = api.portal.get_tool("portal_catalog")

        user = api.user.get_current()
        username = user.getId()

        self.session = \
            self.context.session_data_manager.getSessionData(create=True)
        plan_id = self.session.get("tch_register_plan")

        plan_brain = cat(portal_type="totav.stripe.plan", id=plan_id)
        if not plan_brain:
            self.status = "could not locate plan."
            return
        plan_brain = plan_brain[0]
            
        domain_brain = cat(portal_type="totav.stripe.domain")
        if not domain_brain:
            self.status = "could not locate stripe domain"
            return 
        domain = domain_brain[0].getObject()

        customer_brain = cat(
            portal_type="totav.stripe.customer",
            id=username,
        )
        if customer_brain:
            customer = customer_brain.getObject()
        else:
            customer = createContentInContainer(
                domain,
                "totav.stripe.customer",
                id=username,
                title=username,
                email=user.getProperty("email"),
                checkConstraints=False,
            )
    
        api.user.grant_roles(
            username=username,
            obj=customer,
            roles=["Reader",]
        )

        add_status_msg("created customer %s" % username)
    
        card = createContentInContainer(
            customer,
            "totav.stripe.card",
            title=data["nickname"],
            number=data["number"],
            name_on_card=data["name_on_card"],
            exp_month=data["exp_month"],
            exp_year=data["exp_year"],
            cvc=data["cvc"],
            checkConstraints=False,
        )
        add_status_msg("added card %s" % data["nickname"])
    
        subscription = createContentInContainer(
                customer,
                "totav.stripe.subscription",
                plan=create_relation(plan_brain.getPath()),
            )
        add_status_msg("subscribed to plan %s" % plan_brain.Title)
    
        api.group.add_user(groupname="members", username=username)
    
        url = api.portal.get().absolute_url()
        self.request.response.redirect(url)
Exemplo n.º 17
0
    def update(self):
        pps = self.context.restrictedTraverse('@@plone_portal_state')
        self.products_and_services = pps.portal()._getOb('products_and_services')
        self.navroot = pps.navigation_root()
        self.base_url = 'http://billing.internal.mxit.com/Transaction/PaymentRequest'
        self.action = self.context.absolute_url() + '/@@mxitpaymentrequest'

        pmt = getToolByName(self.context, 'portal_membership')
        memberid = member_id(
            self.request.get(USER_ID_TOKEN.lower(),
                             self.request.get(USER_ID_TOKEN)
                            )
        )
        if not memberid:
            raise ValueError('No member id supplied.')
        member = pmt.getMemberById(memberid)
        if not member:
            password = password_hash(self.context, memberid)
            pmt.addMember(memberid, password, 'Member', '')
            member = pmt.getMemberById(memberid)
            # login as new member
            newSecurityManager(self.request, member)

        registry = queryUtility(IRegistry)
        self.emas_settings = registry.forInterface(IEmasSettings)
        self.transaction_reference = self.emas_settings.order_sequence_number +1
        self.emas_settings.order_sequence_number = self.transaction_reference
        self.transaction_reference = '%04d' % self.transaction_reference

        self.product_id = self.request.get('productId')
        try:
            self.product = self.products_and_services._getOb(self.product_id)
        except AttributeError:
            raise AttributeError(
                'Product with id %s not found' % self.product_id
                )
            
        self.product_name = self.product.title
        self.product_description = self.product.description
        
        # create an order for this member : product combination
        if self.product:
            portal = pps.portal()
            member_orders = portal['orders']

            props = {'id'            : self.transaction_reference, 
                     'title'         : self.transaction_reference,
                     'userid'        : memberid,
                     'payment_method': MOOLA,
                     }
            self.order= createContentInContainer(
                member_orders,
                'emas.app.order',
                False,
                **props
            )
            self.order = member_orders._getOb(self.transaction_reference)
            self.order.verification_code = generate_verification_code(self.order)
            self.order.manage_setLocalRoles(self.order.userid, ('Owner',))
                
            relation = create_relation(self.product.getPhysicalPath())
            item_id = self.order.generateUniqueId(type_name='orderitem')
            props = {'id'           : item_id,
                     'title'        : item_id,
                     'related_item' : relation,
                     'quantity'     : 1}
            order_item = createContentInContainer(
                self.order,
                'emas.app.orderitem',
                False,
                **props
            )
            order_item.manage_setLocalRoles(self.order.userid, ('Owner',))

            self.callback_url = \
                '%s/mxitpaymentresponse?productId=%s&order_number=%s&verification_code=%s' %(
                    self.context.absolute_url(),
                    self.product_id,
                    self.order.getId(),
                    self.order.verification_code
            )

        self.cost_settings = registry.forInterface(IEmasServiceCost)
        self.vendor_id = self.cost_settings.MXitVendorId
        self.moola_amount = self.product.amount_of_moola
        self.currency_amount = self.product.price
        url = '%s/%s' %(self.navroot.absolute_url(), self.product.access_path)
        
        # get all active services for this user
        service_intids = practice_service_intids(self.context)
        dao = MemberServicesDataAccess(self.context)
        memberservices = dao.get_memberservices(service_intids, memberid)
        active_services = [m.related_service(self.context) for m in memberservices]

        # check if the currently requested one is in the list
        if self.product in active_services:
            return self.request.response.redirect(url)
        else:
            return self.render()
Exemplo n.º 18
0
    def prepare_field_value(self, new_object, field, value):
        recurse = partial(self.prepare_field_value, new_object, field)

        if isinstance(value, str):
            return recurse(value.decode('utf-8'))

        if isinstance(value, list):
            return map(recurse, value)

        if isinstance(value, tuple):
            return tuple(map(recurse, value))

        relation_fields = filter(IRelation.providedBy,
                                 (field, getattr(field, 'value_type', None)))
        if relation_fields and isinstance(value, unicode):
            target = uuidToObject(value)
            return create_relation('/'.join(target.getPhysicalPath()))

        if IRichText.providedBy(field) \
           and not IRichTextValue.providedBy(value):
            return recurse(field.fromUnicode(value))

        if INamedField.providedBy(field) and value is not None \
           and not isinstance(value, field._type):

            if value == '':
                return None

            if hasattr(value, 'get_size') and value.get_size() == 0:
                return None

            source_is_blobby = IBlobWrapper.providedBy(value)
            target_is_blobby = INamedBlobFileField.providedBy(field) or \
                               INamedBlobImageField.providedBy(field)

            if source_is_blobby and target_is_blobby:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                new_value = field._type(
                    data='',  # empty blob, will be replaced
                    contentType=value.content_type,
                    filename=filename)
                if not hasattr(new_value, '_blob'):
                    raise ValueError(
                        ('Unsupported file value type {!r}'
                         ', missing _blob.').format(
                             new_value.__class__))

                # Simply copy the persistent blob object (with the file system
                # pointer) to the new value so that the file is not copied.
                # We assume that the old object is trashed and can therefore
                # adopt the blob file.
                new_value._blob = value.getBlob()
                return recurse(new_value)

            else:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                data = value.data
                data = getattr(data, 'data', data)  # extract Pdata
                return recurse(field._type(
                    data=data,
                    contentType=value.content_type,
                    filename=filename))

        return value
Exemplo n.º 19
0
    def prepare_field_value(self, new_object, field, value):
        recurse = partial(self.prepare_field_value, new_object, field)

        if isinstance(value, str):
            return recurse(value.decode('utf-8'))

        if isinstance(value, list):
            return map(recurse, value)

        if isinstance(value, tuple):
            return tuple(map(recurse, value))

        relation_fields = filter(IRelationChoice.providedBy,
                                 (field, getattr(field, 'value_type', None)))
        if relation_fields and isinstance(value, unicode):
            target = uuidToObject(value)
            return create_relation('/'.join(target.getPhysicalPath()))

        if IRichText.providedBy(field) \
           and not IRichTextValue.providedBy(value):
            return recurse(field.fromUnicode(value))

        if INamedField.providedBy(field) and value \
           and not isinstance(value, field._type):

            source_is_blobby = IBlobWrapper.providedBy(value)
            target_is_blobby = INamedBlobFileField.providedBy(field) or \
                               INamedBlobImageField.providedBy(field)

            if source_is_blobby and target_is_blobby:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                new_value = field._type(
                    data='',  # empty blob, will be replaced
                    contentType=value.content_type,
                    filename=filename)
                if not hasattr(new_value, '_blob'):
                    raise ValueError(
                        ('Unsupported file value type {!r}'
                         ', missing _blob.').format(
                             new_value.__class__))

                # Simply copy the persistent blob object (with the file system
                # pointer) to the new value so that the file is not copied.
                # We assume that the old object is trashed and can therefore
                # adopt the blob file.
                new_value._blob = value.getBlob()
                return recurse(new_value)

            else:
                filename = value.filename
                if isinstance(filename, str):
                    filename = filename.decode('utf-8')

                data = value.data
                data = getattr(data, 'data', data)  # extract Pdata
                return recurse(field._type(
                    data=data,
                    contentType=value.content_type,
                    filename=filename))

        return value