sub_query = PaymentDetails.objects.filter(order=OuterRef('pk')).order_by('-updated_at')[:1]
payment_summary = """select
jsonb_build_object(
'total_paid_amount',
coalesce(
sum(amount), 0),
'total_due_amount', CASE WHEN (order_order.total_gross -
coalesce(
sum(amount), 0)) > 0.02 then (order_order.total_gross -
coalesce(
sum(amount), 0)) else 0 end,
'is_full_paid',
coalesce(
sum(amount), 0) > 0 and (order_order.total_gross -
coalesce(
sum(amount), 0)) <= 0.02 and order_order.is_payment_completed,
'total_customer_payable_amount', CASE WHEN (
coalesce(
sum(amount), 0) - order_order.total_gross) > 0.02 then
coalesce(
sum(amount), 0) - order_order.total_gross else 0 end
)
from payment_paymentdetails
where payment_paymentdetails.order_id =
order_order.id and payment_paymentdetails.status = %s"""
orders = Order.objects.prefetch_related(
'lines',
'lines__qc',
'lines__variant__product__vendor_user',
'lines__variant__product',
'lines__variant',
'lines__variant__product__vendor_user__vendor_details',
'lines__tickets', 'lines__lines', 'lines__lines__pickup_req'
).select_related('shipping_address').annotate(
payment_updated_at=Subquery(sub_query.values('transaction_date_time'))) \
.annotate(payment_summary=RawSQL(payment_summary, (PaymentStatus.CONFIRMED,))) \
.annotate(payment_method=Subquery(sub_query.values('method'))).order_by('-payment_updated_at').distinct()
if 'status'
in request.GET
or 'id'
in request.GET:
status_list = request.GET.getlist('status')
order_list = request.GET.getlist('id')
if len(status_list) > 0
or len(order_list) > 0:
orders = orders.filter(
Q(status__in=status_list)
| Q(id__in=order_list),
Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED])
)
else:
orders = orders.filter(
Q(status=OrderStatus.UNFULFILLED),
Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED])
)