# 장바구니 합계를 계산해요.
# 할인 쿠폰은 한 번에 하나만 쓸 수 있어요.
def cart_total(items, coupon=None):
    """상품 목록과 쿠폰을 받아 결제할 금액을 돌려줘요."""
    subtotal = 0
    for item in items:
        # 수량이 0 이하인 상품은 건너뛰어요.
        if item["qty"] <= 0:
            continue
        subtotal += item["price"] * item["qty"]

    # 쿠폰이 있으면 정률 할인을 먼저 적용해요.
    if coupon and coupon.get("rate"):
        subtotal = subtotal * (100 - coupon["rate"]) // 100

    # 3만 원 미만이면 배송비 3천 원을 더해요.
    shipping = 3000 if subtotal < 30000 else 0
    return subtotal + shipping
