Contents
ecommerce-project is a Django REST backend for a delivery-style store. It has carts, checkout, orders, memberships, vouchers, wallets and delivery staff, split into apps under v1/. It runs on Django 5.1.3 with Django REST framework 3.15.2, PostGIS, Celery and django-constance. It is an application, not a library, and it has no tests and some copy-and-paste, so I will not pretend it is a model codebase.
The part I think is worth writing about is how the cart gets priced. The server computes every number in layers and the client never sends a price. It is also a good example of where that kind of code goes wrong.
The client sends a cart, not a price
The cart app exposes GET /api/v1/cart/billing-info/. It reads two optional query parameters, new_membership_adding and voucher_id, and nothing else. Everything else comes from the customer's Cart rows, each of which is a Variation and a quantity.
@action(detail=False, methods=["GET"], url_path="billing-info")
def billing_info(self, request, *args, **kwargs):
new_membership_adding = request.query_params.get("new_membership_adding", False)
voucher_pk = request.query_params.get("voucher_id", None)
...
if request.user and request.user.is_authenticated:
customer = request.user
if not customer.groups.filter(name=SystemDefaultGroup.CUSTOMER).exists():
raise ValidationError({"customer": "User is not customer."})
final_data = cart_calculation(
customer,
new_membership_adding=new_membership_adding,
voucher_pk=voucher_pk,
)Prices live on Variation: mrp, our_rate, member_rate and exclusive_rate. When a variation is first saved, Variation.save fills an empty member or exclusive rate from our_rate, so the comparisons below always have a number to work with.
Picking one rate per line
item_price_set starts at our_rate and only ever moves down.
item_rate = item.product_variation.our_rate
# exclusive_rate
if (
item.product_variation.product_stock_master
and item.product_variation.product_stock_master.is_exclusive_item
and item.product_variation.exclusive_rate
and item.product_variation.exclusive_rate < item_rate
):
item_rate = item.product_variation.exclusive_rate
# membership rate
if has_exist_membership or new_membership_adding:
if item.product_variation.member_rate < item_rate:
item_rate = item.product_variation.member_rateThe exclusive rate applies only when the stock master is flagged is_exclusive_item. The member rate applies when the customer has an active membership, or is buying one in the same order. Each rule takes the new rate only when it is lower, so a tier can never make a customer pay more than the list price.
Tax comes last. Product.tax is a string field with GST slab choices (0, 5, 12, 14, 18 and 28), and the code adds that percentage on top of the chosen rate.
From lines to a total
cart_calculation sums rate times quantity, then adds delivery, subtracts the discount and adds a membership fee, in that order. The delivery charge is skipped when a promotion marks delivery as free. For a customer's first order, the FIRST_ORDER_DELIVERY_CHARGE flag decides whether to charge at all.
# Added delivery charge
final_total = final_total + final_delivery_charge
# Added discount
final_total = final_total - final_discount
# Added membership fee in this order
if new_membership_adding:
plan = get_one_month_plan()
final_membership_fee = plan.discount_amount
final_total = final_total + final_membership_feeThe result has nine fields, and Checkout has columns with the same nine names. At checkout the totals are stored as a snapshot, and each order line stores the rate it was sold at in FinalDeliveredOrder. Later catalogue edits do not rewrite old orders.
Two traps in the delivery lookup
Delivery tiers are rows in DeliveryCharges with a start, an end and a charge.
def get_delivery_charge(amount):
final_delivery_charge = 0.0
delivery_charges = DeliveryCharges.objects.exclude(is_active=False, is_deleted=True)
for charge in delivery_charges:
if amount in range(
int(charge.amount_starting_range), int(charge.amount_ending_range)
):
final_delivery_charge = charge.delivery_charge
return final_delivery_chargeThe first trap is range(). The amount is a float and includes tax. 150.0 in range(0, 200) is True, but 199.5 in range(0, 200) is False, so a fractional amount can match no tier and the charge falls through to 0.0. The upper bound is also exclusive, and int() truncates the stored bounds. A comparison such as start <= amount < end in the query would remove the float problem and make the boundary a choice you make on purpose.
Where the logic drifted
CheckoutCRUDSerializer.create imports item_price_set and get_delivery_charge, then repeats the rest of cart_calculation inline: the loop, the first-order rule, the discount and the membership fee. The copy adds two things the preview lacks, the delivery tip and the cash-on-delivery limit from MAXIMUM_CASE_DELIVERY. So the number a customer sees from billing-info can differ from the number the checkout stores.
I would make create call cart_calculation and add the tip afterwards. Money is also stored as FloatField throughout the models I read, which I would change to DecimalField.
When this approach fits
A single function that applies rate rules in a fixed order is easy to read from top to bottom, and it suits a small catalogue with a handful of price rules. It stops working when the rules grow. The voucher code in v1/promotion/calculation.py is already a pile of nested conditions. It also stops working when you need exact money or tests, because cart_calculation reads several tables as it goes. I would pass it loaded rows and flags, return plain numbers, and test that function directly.
Found this useful? Share it with your team.