def OrderExport(request): """Export orders as CSV.""" user, _, _ = common.GetUser(request) if request.POST['submit'] == views.EXPORT_CSV: response = http.HttpResponse(mimetype='text/csv') response['Content-Disposition'] = ( 'attachment; filename=%s_orders.csv' % user.email()) _OrderExportInternal(response, request.POST) return response elif request.POST['submit'] == FULFILL_MULTIPLE: order_ids = views.PostedIds(request.POST) order_sheet_id = request.POST.get('order_sheet_id') d = _OrderFulfillInternal(order_ids, order_sheet_id, mode='fulfill') return common.Respond(request, 'order_fulfill', d)
def _OrderExportInternal(writable, post_vars): """Write orders as CSV to a file-like object.""" order_ids = views.PostedIds(post_vars) orders = list(models.Order.get_by_id(order_ids)) orders.sort(key=lambda o: o.site.number) writer = csv.writer(writable) writer.writerow([ 'Site Number', 'Order ID', 'Order modified', 'Street Address', 'City State Zip', 'Order Note', 'Type', 'Item', 'Quantity', 'Measure', 'Subtotal ($)', 'LogisticsStart', 'LogisticsEnd', 'LogisticsInstructions', 'Optional Item Note', ]) order_items_by_order = collections.defaultdict(list) # 30 is the magic filter limit, experimentally derived for i in range(0, len(orders), 30): batch_orders = orders[i:i + 30] logging.info('loading batch of %d orders starting with %d', len(batch_orders), i) q = models.OrderItem.all() q.filter('order IN ', batch_orders) order_items = [oi for oi in q if oi.FloatQuantity()] order_items.sort( key=lambda x: (x.item.order_form_section, x.item.name)) for oi in order_items: o = oi.order order_id = o.key().id() row = [ o.site.number, o.key().id(), o.modified.date().isoformat(), o.site.street_number, o.site.city_state_zip, o.notes, oi.item.VisibleOrderFormSection(), oi.item.VisibleName(), oi.VisibleQuantity(), oi.item.measure, oi.VisibleCost(), o.logistics_start, o.logistics_end, o.logistics_instructions, oi.name, ] order_items_by_order[order_id].append(row) for o in batch_orders: if o.key().id() not in order_items_by_order: row = [ o.site.number, o.key().id(), o.modified.date().isoformat(), o.site.street_number, o.site.city_state_zip, o.notes, '<no items>', '<no items>', '<no items>', '<no items>', '<no items>', o.logistics_start, o.logistics_end, o.logistics_instructions, '<no items>', ] order_items_by_order[o.key().id()].append(row) for o in orders: for row in order_items_by_order[o.key().id()]: row = [unicode(f).encode('ascii', 'ignore') for f in row] writer.writerow(row)
def OrderFulfillConfirm(request, order_sheet_id=None): order_ids = views.PostedIds(request.POST) return _OrderFulfillConfirmInternal(order_ids, order_sheet_id)
def OrderDeleteConfirm(request, order_sheet_id=None): order_ids = views.PostedIds(request.POST) return _OrderConfirmInternal(order_ids, order_sheet_id, state='Deleted')