Example #1
0
def fix_bookings_trading(ctx=None):
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for booking in data.values():
        try:
            booking.attrs['item_number']
        except KeyError:
            obj = get_object_by_uid(portal, booking.attrs['buyable_uid'])
            if obj:
                trading = ITrading(obj)
                item_number = trading.item_number
                gtin = trading.gtin
            else:
                item_number = ''
                gtin = ''
            need_rebuild = True
            booking.attrs['item_number'] = item_number
            logging.info("Added item_number {0} to booking {1}".format(
                item_number, booking.attrs['uid']))
            booking.attrs['gtin'] = gtin
            logging.info("Added gtin {0} to booking {1}".format(
                gtin, booking.attrs['uid']))
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
def fix_bookings_trading(ctx=None):
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for booking in data.values():
        try:
            booking.attrs['item_number']
        except KeyError:
            obj = get_object_by_uid(portal, booking.attrs['buyable_uid'])
            if obj:
                trading = ITrading(obj)
                item_number = trading.item_number
                gtin = trading.gtin
            else:
                item_number = ''
                gtin = ''
            need_rebuild = True
            booking.attrs['item_number'] = item_number
            logging.info(
                u"Added item_number {0} to booking {1}".format(
                    item_number, booking.attrs['uid']
                )
            )
            booking.attrs['gtin'] = gtin
            logging.info(
                u"Added gtin {0} to booking {1}".format(
                    gtin, booking.attrs['uid']
                )
            )
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #3
0
def fix_bookings_vendor_uid(ctx=None):
    """Add vendor_uid attribute to booking records.
    """
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        update = False
        try:
            item.attrs['vendor_uid']
            if not isinstance(item.attrs['vendor_uid'], uuid.UUID):
                update = True
        except KeyError:
            update = True
        if not update:
            continue
        buyable_uid = item.attrs['buyable_uid']
        obj = get_object_by_uid(portal, buyable_uid)
        if not obj:
            shop = acquire_vendor_or_shop_root(portal)
        else:
            shop = acquire_vendor_or_shop_root(obj)
        vendor_uid = uuid.UUID(IUUID(shop))
        item.attrs['vendor_uid'] = vendor_uid
        need_rebuild = True
        logging.info("Added vendor_uid to booking {0}".format(
            item.attrs['uid']))
    if need_rebuild:
        soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #4
0
def create_mail_listing(context, attrs):
    """Create item listing for notification mail.
    """
    soup = get_bookings_soup(context)
    bookings = soup.query((Any('uid', attrs['booking_uids'])))
    lines = []
    for booking in bookings:
        brain = get_catalog_brain(context, booking.attrs['buyable_uid'])
        buyable = brain.getObject()
        title = booking.attrs['title']
        comment = booking.attrs['buyable_comment']
        if comment:
            title = '%s (%s)' % (title, comment)
        line = '{count: 4f} {title}'.format(
            count=booking.attrs['buyable_count'],
            title=title
        )
        lines.append(line)
        if comment:
            lines.append(_indent('({0})'.format(comment)))
        notificationtext = IItemNotificationText(buyable)
        if booking.attrs['state'] == ifaces.STATE_RESERVED\
                and notificationtext.overbook_text:
            lines.append(_indent(notificationtext.overbook_text))
        elif booking.attrs['state'] == ifaces.STATE_NEW\
                and notificationtext.order_text:
            lines.append(_indent(notificationtext.order_text))
    return '\n'.join(lines)
Example #5
0
def fix_bookings_email(ctx=None):
    """Add email attribute to booking records from the corresponding order.
    """
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        update = False
        try:
            item.attrs['email']
        except KeyError:
            update = True
        if not update:
            continue

        order = get_order(portal, item.attrs['order_uid'])
        email = order.attrs.get('personal_data.email', 'n/a')

        item.attrs['email'] = email
        need_rebuild = True
        logging.info("Added email to booking {0}".format(item.attrs['uid']))
    if need_rebuild:
        soup.rebuild()
        logging.info("Rebuilt bookings catalog")
def fix_bookings_email(ctx=None):
    """Add email attribute to booking records from the corresponding order.
    """
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        update = False
        try:
            item.attrs['email']
        except KeyError:
            update = True
        if not update:
            continue

        order = get_order(portal, item.attrs['order_uid'])
        email = order.attrs.get('personal_data.email', 'n/a')

        item.attrs['email'] = email
        need_rebuild = True
        logging.info(
            u"Added email to booking {0}".format(item.attrs['uid'])
        )
    if need_rebuild:
        soup.rebuild()
        logging.info("Rebuilt bookings catalog")
def fix_bookings_vendor_uid(ctx=None):
    """Add vendor_uid attribute to booking records.
    """
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        update = False
        try:
            item.attrs['vendor_uid']
            if not isinstance(item.attrs['vendor_uid'], uuid.UUID):
                update = True
        except KeyError:
            update = True
        if not update:
            continue
        buyable_uid = item.attrs['buyable_uid']
        obj = get_object_by_uid(portal, buyable_uid)
        if not obj:
            shop = acquire_vendor_or_shop_root(portal)
        else:
            shop = acquire_vendor_or_shop_root(obj)
        vendor_uid = uuid.UUID(IUUID(shop))
        item.attrs['vendor_uid'] = vendor_uid
        need_rebuild = True
        logging.info(
            u"Added vendor_uid to booking {0}".format(item.attrs['uid'])
        )
    if need_rebuild:
        soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #8
0
def fix_bookings_state_salaried_tid(ctx=None):
    portal = getSite()
    soup = get_orders_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        order_data = OrderData(portal, order=item)
        try:
            state = item.attrs['state']
            state_exists = True
        except KeyError:
            state = None
            state_exists = False
        try:
            salaried = item.attrs['salaried']
            salaried_exists = True
        except KeyError:
            salaried = None
            salaried_exists = False
        try:
            tid = item.attrs['tid']
            tid_exists = True
        except KeyError:
            tid = 'none'  # tid default in b.p.payment
            tid_exists = False
        for booking in order_data.bookings:
            # add too booking node
            try:
                booking.attrs['state']
            except KeyError:
                booking.attrs['state'] = state
                need_rebuild = True
                logging.info("Added state {0} to booking {1}".format(
                    state, item.attrs['uid']))
            try:
                booking.attrs['salaried']
            except KeyError:
                booking.attrs['salaried'] = salaried
                need_rebuild = True
                logging.info("Added salaried {0} to booking {1}".format(
                    salaried, item.attrs['uid']))
            try:
                booking.attrs['tid']
            except KeyError:
                booking.attrs['tid'] = tid
                need_rebuild = True
                logging.info("Added tid {0} to booking {1}".format(
                    tid, item.attrs['uid']))
        # now, delete from order node
        if state_exists:
            del item.attrs['state']
        if salaried_exists:
            del item.attrs['salaried']
        if tid_exists:
            del item.attrs['tid']
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #9
0
def fix_bookings_shippable(ctx=None):
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for booking in data.values():
        try:
            booking.attrs['shippable']
        except KeyError:
            obj = get_object_by_uid(portal, booking.attrs['buyable_uid'])
            shippable = True
            if obj:
                shippable = IShippingItem(obj).shippable
            booking.attrs['shippable'] = shippable
            need_rebuild = True
            logging.info("Added shippable {0} to booking {1}".format(
                shippable, booking.attrs['uid']))
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #10
0
    def jsondata(self):
        soup = get_bookings_soup(self.context)
        aaData = list()
        size, result = self.query(soup)

        columns = self.columns
        colnames = [_['id'] for _ in columns]

        def record2list(record, bookings_quantity=None):
            result = list()
            for colname in colnames:
                coldef = self.column_def(colname)
                renderer = coldef.get('renderer')

                if coldef['origin'] == 'o':
                    if renderer:
                        value = renderer(colname, record)
                    else:
                        value = self._get_ordervalue(colname, record)
                else:
                    if renderer:
                        value = renderer(colname, record)
                    else:
                        value = record.attrs.get(colname, '')

                result.append(value)
            return result

        for key in result:
            bookings_quantity = 0
            bookings_total_sum = 0
            for record in result[key]:
                bookings_quantity += record.attrs.get('buyable_count') or 0
                bookings_total_sum += self._get_sum(record)
            for record in result[key]:
                record._v_bookings_quantity = bookings_quantity
                record._v_bookings_total_sum = bookings_total_sum
                aaData.append(record2list(record))

        data = {
            "draw": int(self.request.form['draw']),
            "recordsTotal": size,
            "recordsFiltered": size,
            "data": aaData,
        }

        self.request.response.setHeader(
            'Content-Type',
            'application/json; charset=utf-8'
        )
        return json.dumps(data)
    def jsondata(self):
        soup = get_bookings_soup(self.context)
        aaData = list()
        size, result = self.query(soup)

        columns = self.columns
        colnames = [_['id'] for _ in columns]

        def record2list(record, bookings_quantity=None):
            result = list()
            for colname in colnames:
                coldef = self.column_def(colname)
                renderer = coldef.get('renderer')

                if coldef['origin'] == 'o':
                    if renderer:
                        value = renderer(colname, record)
                    else:
                        value = self._get_ordervalue(colname, record)
                else:
                    if renderer:
                        value = renderer(colname, record)
                    else:
                        value = record.attrs.get(colname, '')

                result.append(value)
            return result

        for key in result:
            bookings_quantity = 0
            bookings_total_sum = 0
            for record in result[key]:
                bookings_quantity += record.attrs.get('buyable_count') or 0
                bookings_total_sum += self._get_sum(record)
            for record in result[key]:
                record._v_bookings_quantity = bookings_quantity
                record._v_bookings_total_sum = bookings_total_sum
                aaData.append(record2list(record))

        data = {
            "draw": int(self.request.form['draw']),
            "recordsTotal": size,
            "recordsFiltered": size,
            "data": aaData,
        }

        self.request.response.setHeader(
            'Content-Type',
            'application/json; charset=utf-8'
        )
        return json.dumps(data)
Example #12
0
def create_order_total(context, attrs):
    """Calculate order total price for notification mail.

    XXX: use CartItemCalculator? Problem - lives in bda.plone.shop
    XXX: also consider discount here once implemented
    """
    soup = get_bookings_soup(context)
    bookings = soup.query((Any('uid', attrs['booking_uids'])))
    ret = 0.0
    for booking in bookings:
        count = float(booking.attrs['buyable_count'])
        net = booking.attrs.get('net', 0.0) * count
        ret += net
        ret += net * booking.attrs.get('vat', 0.0) / 100
    return "%.2f" % (ret + float(attrs['shipping']))
Example #13
0
def reset_records(ctx=None):
    ignore_key = lambda x: x.startswith('____')
    portal = getSite()
    soup = get_orders_soup(portal)
    data = soup.storage.data
    for order in data.values():
        reset_odict(order.attrs.storage, ignore_key=ignore_key)
        logging.info("Reset attributes storage on order {0}".format(
            order.attrs['uid'], ))
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    for booking in data.values():
        reset_odict(booking.attrs.storage, ignore_key=ignore_key)
        logging.info("Reset attributes storage on booking {0}".format(
            booking.attrs['uid']))
def fix_bookings_shippable(ctx=None):
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for booking in data.values():
        try:
            booking.attrs['shippable']
        except KeyError:
            obj = get_object_by_uid(portal, booking.attrs['buyable_uid'])
            shippable = True
            if obj:
                shippable = IShippingItem(obj).shippable
            booking.attrs['shippable'] = shippable
            need_rebuild = True
            logging.info(
                u"Added shippable {0} to booking {1}".format(
                    shippable, booking.attrs['uid']
                )
            )
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #15
0
def fix_bookings_state_salaried_tid(ctx=None):
    portal = getSite()
    soup = get_orders_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        order_data = OrderData(portal, order=item)
        state = item.attrs.get('state', None)
        salaried = item.attrs.get('salaried', None)
        tid = item.attrs.get('tid', 'none')  # tid default in b.p.payment
        for booking in order_data.bookings:
            # add too booking node
            if 'state' not in booking.attrs:
                booking.attrs['state'] = state
                need_rebuild = True
                logging.info(
                    "Added state {0} to booking {1}".format(
                        state, item.attrs['uid']
                    )
                )
            if 'salaried' not in booking.attrs:
                booking.attrs['salaried'] = salaried
                need_rebuild = True
                logging.info(
                    "Added salaried {0} to booking {1}".format(
                        salaried, item.attrs['uid']
                    )
                )
            if 'tid' not in booking.attrs:
                booking.attrs['tid'] = tid
                need_rebuild = True
                logging.info(
                    "Added tid {0} to booking {1}".format(
                        tid, item.attrs['uid']
                    )
                )
        # now, delete from order node
        if 'state' in item.attrs:
            del item.attrs['state']
        if 'salaried' in item.attrs:
            del item.attrs['salaried']
        if 'tid' in item.attrs:
            del item.attrs['tid']
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
def fix_discount_attrs(ctx=None):
    portal = getSite()
    # discount attrs on order
    orders_soup = get_orders_soup(portal)
    need_rebuild = False
    data = orders_soup.storage.data
    for item in data.values():
        try:
            item.attrs['cart_discount_net']
        except KeyError:
            need_rebuild = True
            item.attrs['cart_discount_net'] = Decimal(0)
            logging.info(
                u"Added cart_discount_net to order {0}".format(
                    item.attrs['uid']
                )
            )
        try:
            item.attrs['cart_discount_vat']
        except KeyError:
            need_rebuild = True
            item.attrs['cart_discount_vat'] = Decimal(0)
            logging.info(
                u"Added cart_discount_vat to order {0}".format(
                    item.attrs['uid']
                )
            )
    if need_rebuild:
        orders_soup.rebuild()
        logging.info("Rebuilt orders catalog")
    # discount attrs on bookings
    bookings_soup = get_bookings_soup(portal)
    need_rebuild = False
    data = bookings_soup.storage.data
    for item in data.values():
        try:
            item.attrs['discount_net']
        except KeyError:
            need_rebuild = True
            item.attrs['discount_net'] = Decimal(0)
            logging.info(
                u"Added discount_net to booking {0}".format(item.attrs['uid'])
            )
    if need_rebuild:
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #17
0
def reset_records(ctx=None):
    ignore_key = lambda x: x.startswith('____')
    portal = getSite()
    soup = get_orders_soup(portal)
    data = soup.storage.data
    for order in data.values():
        reset_odict(order.attrs.storage, ignore_key=ignore_key)
        logging.info(
            "Reset attributes storage on order {0}".format(order.attrs['uid'],)
        )
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    for booking in data.values():
        reset_odict(booking.attrs.storage, ignore_key=ignore_key)
        logging.info(
            "Reset attributes storage on booking {0}".format(
                booking.attrs['uid']
            )
        )
Example #18
0
def fix_discount_attrs(ctx=None):
    portal = getSite()
    # discount attrs on order
    orders_soup = get_orders_soup(portal)
    need_rebuild = False
    data = orders_soup.storage.data
    for item in data.values():
        try:
            item.attrs['cart_discount_net']
        except KeyError:
            need_rebuild = True
            item.attrs['cart_discount_net'] = Decimal(0)
            logging.info("Added cart_discount_net to order {0}".format(
                item.attrs['uid']))
        try:
            item.attrs['cart_discount_vat']
        except KeyError:
            need_rebuild = True
            item.attrs['cart_discount_vat'] = Decimal(0)
            logging.info("Added cart_discount_vat to order {0}".format(
                item.attrs['uid']))
    if need_rebuild:
        orders_soup.rebuild()
        logging.info("Rebuilt orders catalog")
    # discount attrs on bookings
    bookings_soup = get_bookings_soup(portal)
    need_rebuild = False
    data = bookings_soup.storage.data
    for item in data.values():
        try:
            item.attrs['discount_net']
        except KeyError:
            need_rebuild = True
            item.attrs['discount_net'] = Decimal(0)
            logging.info("Added discount_net to booking {0}".format(
                item.attrs['uid']))
    if need_rebuild:
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #19
0
def fix_bookings_vendor_uid(ctx=None):
    """Add vendor_uid attribute to booking records.
    """
    portal = getSite()
    soup = get_bookings_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        if not 'vendor_uid' in item.attrs\
                or not isinstance(item.attrs['vendor_uid'], uuid.UUID):
            buyable_uid = item.attrs['buyable_uid']
            obj = uuidToObject(buyable_uid)
            shop = acquire_vendor_or_shop_root(obj)
            vendor_uid = uuid.UUID(IUUID(shop))
            item.attrs['vendor_uid'] = vendor_uid
            need_rebuild = True
            logging.info(
                "Added vendor_uid to booking {0}".format(item.attrs['uid'])
            )
    if need_rebuild:
        soup.rebuild()
        logging.info("Rebuilt bookings catalog")
def fix_bookings_state_salaried_tid(ctx=None):
    portal = getSite()
    soup = get_orders_soup(portal)
    data = soup.storage.data
    need_rebuild = False
    for item in data.values():
        order_data = OrderData(portal, order=item)
        try:
            state = item.attrs['state']
            state_exists = True
        except KeyError:
            state = None
            state_exists = False
        try:
            salaried = item.attrs['salaried']
            salaried_exists = True
        except KeyError:
            salaried = None
            salaried_exists = False
        try:
            tid = item.attrs['tid']
            tid_exists = True
        except KeyError:
            tid = 'none'  # tid default in b.p.payment
            tid_exists = False
        for booking in order_data.bookings:
            # add too booking node
            try:
                booking.attrs['state']
            except KeyError:
                booking.attrs['state'] = state
                need_rebuild = True
                logging.info(
                    u"Added state {0} to booking {1}".format(
                        state, item.attrs['uid']
                    )
                )
            try:
                booking.attrs['salaried']
            except KeyError:
                booking.attrs['salaried'] = salaried
                need_rebuild = True
                logging.info(
                    u"Added salaried {0} to booking {1}".format(
                        salaried, item.attrs['uid']
                    )
                )
            try:
                booking.attrs['tid']
            except KeyError:
                booking.attrs['tid'] = tid
                need_rebuild = True
                logging.info(
                    u"Added tid {0} to booking {1}".format(
                        tid, item.attrs['uid']
                    )
                )
        # now, delete from order node
        if state_exists:
            del item.attrs['state']
        if salaried_exists:
            del item.attrs['salaried']
        if tid_exists:
            del item.attrs['tid']
    if need_rebuild:
        bookings_soup = get_bookings_soup(portal)
        bookings_soup.rebuild()
        logging.info("Rebuilt bookings catalog")
Example #21
0
    def get_csv(self):
        context = self.context

        # prepare csv writer
        sio = StringIO()
        ex = csv.writer(sio, dialect='excel-colon', quoting=csv.QUOTE_MINIMAL)
        # exported column keys as first line
        ex.writerow(ORDER_EXPORT_ATTRS +
                    list(COMPUTED_ORDER_EXPORT_ATTRS.keys()) +
                    BOOKING_EXPORT_ATTRS +
                    list(COMPUTED_BOOKING_EXPORT_ATTRS.keys()))

        bookings_soup = get_bookings_soup(context)

        # First, filter by allowed vendor areas
        vendor_uids = get_vendor_uids_for()
        query_b = Any('vendor_uid', vendor_uids)

        # Second, query for the buyable
        query_cat = {}
        query_cat['object_provides'] = IBuyable.__identifier__
        query_cat['path'] = '/'.join(context.getPhysicalPath())
        cat = getToolByName(context, 'portal_catalog')
        res = cat(**query_cat)
        buyable_uids = [IUUID(it.getObject()) for it in res]

        query_b = query_b & Any('buyable_uid', buyable_uids)

        all_orders = {}
        for booking in bookings_soup.query(query_b):
            booking_attrs = []
            # booking export attrs
            for attr_name in BOOKING_EXPORT_ATTRS:
                val = self.export_val(booking, attr_name)
                booking_attrs.append(val)
            # computed booking export attrs
            for attr_name in COMPUTED_BOOKING_EXPORT_ATTRS:
                cb = COMPUTED_BOOKING_EXPORT_ATTRS[attr_name]
                val = cb(context, booking)
                val = cleanup_for_csv(val)
                booking_attrs.append(val)

            # create order_attrs, if it doesn't exist
            order_uid = booking.attrs.get('order_uid')
            if order_uid not in all_orders:
                order = get_order(context, order_uid)
                order_data = OrderData(context,
                                       order=order,
                                       vendor_uids=vendor_uids)
                order_attrs = []
                # order export attrs
                for attr_name in ORDER_EXPORT_ATTRS:
                    val = self.export_val(order, attr_name)
                    order_attrs.append(val)
                # computed order export attrs
                for attr_name in COMPUTED_ORDER_EXPORT_ATTRS:
                    cb = COMPUTED_ORDER_EXPORT_ATTRS[attr_name]
                    val = cb(self.context, order_data)
                    val = cleanup_for_csv(val)
                    order_attrs.append(val)
                all_orders[order_uid] = order_attrs

            ex.writerow(all_orders[order_uid] + booking_attrs)

            # TODO: also set for contextual exports? i'd say no.
            # booking.attrs['exported'] = True
            # bookings_soup.reindex(booking)

        ret = sio.getvalue()
        sio.close()
        return ret
Example #22
0
 def csv(self, request):
     # get orders soup
     orders_soup = get_orders_soup(self.context)
     # get bookings soup
     bookings_soup = get_bookings_soup(self.context)
     # fetch user vendor uids
     vendor_uids = get_vendor_uids_for()
     # base query for time range
     query = Ge('created', self.from_date) & Le('created', self.to_date)
     # filter by given vendor uid or user vendor uids
     vendor_uid = self.vendor
     if vendor_uid:
         vendor_uid = uuid.UUID(vendor_uid)
         # raise if given vendor uid not in user vendor uids
         if not vendor_uid in vendor_uids:
             raise Unauthorized
         query = query & Any('vendor_uids', [vendor_uid])
     else:
         query = query & Any('vendor_uids', vendor_uids)
     # filter by customer if given
     customer = self.customer
     if customer:
         query = query & Eq('creator', customer)
     # prepare csv writer
     sio = StringIO()
     ex = csv.writer(sio, dialect='excel-colon')
     # exported column keys as first line
     ex.writerow(ORDER_EXPORT_ATTRS +
                 COMPUTED_ORDER_EXPORT_ATTRS.keys() +
                 BOOKING_EXPORT_ATTRS +
                 COMPUTED_BOOKING_EXPORT_ATTRS.keys())
     # query orders
     for order in orders_soup.query(query):
         # restrict order bookings for current vendor_uids
         order_data = OrderData(self.context,
                                order=order,
                                vendor_uids=vendor_uids)
         order_attrs = list()
         # order export attrs
         for attr_name in ORDER_EXPORT_ATTRS:
             val = self.export_val(order, attr_name)
             order_attrs.append(val)
         # computed order export attrs
         for attr_name in COMPUTED_ORDER_EXPORT_ATTRS:
             cb = COMPUTED_ORDER_EXPORT_ATTRS[attr_name]
             val = cb(self.context, order_data)
             order_attrs.append(val)
         for booking in order_data.bookings:
             booking_attrs = list()
             # booking export attrs
             for attr_name in BOOKING_EXPORT_ATTRS:
                 val = self.export_val(booking, attr_name)
                 booking_attrs.append(val)
             # computed booking export attrs
             for attr_name in COMPUTED_BOOKING_EXPORT_ATTRS:
                 cb = COMPUTED_BOOKING_EXPORT_ATTRS[attr_name]
                 val = cb(self.context, booking)
                 booking_attrs.append(val)
             ex.writerow(order_attrs + booking_attrs)
             booking.attrs['exported'] = True
             bookings_soup.reindex(booking)
     # create and return response
     s_start = self.from_date.strftime('%G-%m-%d_%H-%M-%S')
     s_end = self.to_date.strftime('%G-%m-%d_%H-%M-%S')
     filename = 'orders-export-%s-%s.csv' % (s_start, s_end)
     self.request.response.setHeader('Content-Type', 'text/csv')
     self.request.response.setHeader('Content-Disposition',
                                     'attachment; filename=%s' % filename)
     return sio.getvalue().decode('utf8')
Example #23
0
 def csv(self, request):
     # get orders soup
     orders_soup = get_orders_soup(self.context)
     # get bookings soup
     bookings_soup = get_bookings_soup(self.context)
     # fetch user vendor uids
     vendor_uids = get_vendor_uids_for()
     # base query for time range
     query = Ge('created', self.from_date) & Le('created', self.to_date)
     # filter by given vendor uid or user vendor uids
     vendor_uid = self.vendor
     if vendor_uid:
         vendor_uid = uuid.UUID(vendor_uid)
         # raise if given vendor uid not in user vendor uids
         if vendor_uid not in vendor_uids:
             raise Unauthorized
         query = query & Any('vendor_uids', [vendor_uid])
     else:
         query = query & Any('vendor_uids', vendor_uids)
     # filter by customer if given
     customer = self.customer
     if customer:
         query = query & Eq('creator', customer)
     # prepare csv writer
     sio = StringIO()
     ex = csv.writer(sio, dialect='excel-colon', quoting=csv.QUOTE_MINIMAL)
     # exported column keys as first line
     ex.writerow(ORDER_EXPORT_ATTRS + COMPUTED_ORDER_EXPORT_ATTRS.keys() +
                 BOOKING_EXPORT_ATTRS +
                 COMPUTED_BOOKING_EXPORT_ATTRS.keys())
     # query orders
     for order in orders_soup.query(query):
         # restrict order bookings for current vendor_uids
         order_data = OrderData(self.context,
                                order=order,
                                vendor_uids=vendor_uids)
         order_attrs = list()
         # order export attrs
         for attr_name in ORDER_EXPORT_ATTRS:
             val = self.export_val(order, attr_name)
             order_attrs.append(val)
         # computed order export attrs
         for attr_name in COMPUTED_ORDER_EXPORT_ATTRS:
             cb = COMPUTED_ORDER_EXPORT_ATTRS[attr_name]
             val = cb(self.context, order_data)
             val = cleanup_for_csv(val)
             order_attrs.append(val)
         for booking in order_data.bookings:
             booking_attrs = list()
             # booking export attrs
             for attr_name in BOOKING_EXPORT_ATTRS:
                 val = self.export_val(booking, attr_name)
                 booking_attrs.append(val)
             # computed booking export attrs
             for attr_name in COMPUTED_BOOKING_EXPORT_ATTRS:
                 cb = COMPUTED_BOOKING_EXPORT_ATTRS[attr_name]
                 val = cb(self.context, booking)
                 val = cleanup_for_csv(val)
                 booking_attrs.append(val)
             ex.writerow(order_attrs + booking_attrs)
             booking.attrs['exported'] = True
             bookings_soup.reindex(booking)
     # create and return response
     s_start = self.from_date.strftime('%G-%m-%d_%H-%M-%S')
     s_end = self.to_date.strftime('%G-%m-%d_%H-%M-%S')
     filename = 'orders-export-%s-%s.csv' % (s_start, s_end)
     self.request.response.setHeader('Content-Type', 'text/csv')
     self.request.response.setHeader('Content-Disposition',
                                     'attachment; filename=%s' % filename)
     ret = sio.getvalue()
     sio.close()
     return ret
Example #24
0
    def get_csv(self):
        context = self.context

        # prepare csv writer
        sio = StringIO()
        ex = csv.writer(sio, dialect='excel-colon', quoting=csv.QUOTE_MINIMAL)
        # exported column keys as first line
        ex.writerow(ORDER_EXPORT_ATTRS + COMPUTED_ORDER_EXPORT_ATTRS.keys() +
                    BOOKING_EXPORT_ATTRS +
                    COMPUTED_BOOKING_EXPORT_ATTRS.keys())

        bookings_soup = get_bookings_soup(context)

        # First, filter by allowed vendor areas
        vendor_uids = get_vendor_uids_for()
        query_b = Any('vendor_uid', vendor_uids)

        # Second, query for the buyable
        query_cat = {}
        query_cat['object_provides'] = IBuyable.__identifier__
        query_cat['path'] = '/'.join(context.getPhysicalPath())
        cat = getToolByName(context, 'portal_catalog')
        res = cat(**query_cat)
        buyable_uids = [IUUID(it.getObject()) for it in res]

        query_b = query_b & Any('buyable_uid', buyable_uids)

        all_orders = {}
        for booking in bookings_soup.query(query_b):
            booking_attrs = []
            # booking export attrs
            for attr_name in BOOKING_EXPORT_ATTRS:
                val = self.export_val(booking, attr_name)
                booking_attrs.append(val)
            # computed booking export attrs
            for attr_name in COMPUTED_BOOKING_EXPORT_ATTRS:
                cb = COMPUTED_BOOKING_EXPORT_ATTRS[attr_name]
                val = cb(context, booking)
                val = cleanup_for_csv(val)
                booking_attrs.append(val)

            # create order_attrs, if it doesn't exist
            order_uid = booking.attrs.get('order_uid')
            if order_uid not in all_orders:
                order = get_order(context, order_uid)
                order_data = OrderData(context,
                                       order=order,
                                       vendor_uids=vendor_uids)
                order_attrs = []
                # order export attrs
                for attr_name in ORDER_EXPORT_ATTRS:
                    val = self.export_val(order, attr_name)
                    order_attrs.append(val)
                # computed order export attrs
                for attr_name in COMPUTED_ORDER_EXPORT_ATTRS:
                    cb = COMPUTED_ORDER_EXPORT_ATTRS[attr_name]
                    val = cb(self.context, order_data)
                    val = cleanup_for_csv(val)
                    order_attrs.append(val)
                all_orders[order_uid] = order_attrs

            ex.writerow(all_orders[order_uid] + booking_attrs)

            # TODO: also set for contextual exports? i'd say no.
            # booking.attrs['exported'] = True
            # bookings_soup.reindex(booking)

        ret = sio.getvalue()
        sio.close()
        return ret