File size: 12,441 Bytes
126d45f
 
2f04b83
126d45f
 
 
 
2f04b83
126d45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f04b83
 
 
 
 
126d45f
2f04b83
 
 
 
 
 
 
 
 
 
 
 
126d45f
 
2f04b83
126d45f
 
 
 
 
 
 
 
 
 
 
2f04b83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126d45f
 
 
 
 
 
 
 
 
 
 
 
 
 
2f04b83
 
 
 
126d45f
2f04b83
 
 
 
126d45f
 
 
2f04b83
 
 
 
 
 
 
 
 
 
 
 
126d45f
 
2f04b83
126d45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145666c
126d45f
 
 
 
 
 
145666c
126d45f
 
 
 
 
 
 
145666c
126d45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145666c
 
126d45f
07349c1
145666c
 
07349c1
126d45f
 
 
 
 
 
 
07349c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Header
from sqlalchemy.orm import Session, joinedload
from decimal import Decimal

from app.db.base import get_db
from app.models.user import User
from app.models.product import Product
from app.models.cart import Cart, CartItem
from app.models.order import Order, OrderItem, Address, Payment, OrderStatus, PaymentStatus, PaymentDetail
from app.schemas.order import (
    OrderCreate, OrderResponse, AddressCreate, AddressResponse, 
    AddressUpdate, OrderUpdateStatus, PaymentDetailCreate, 
    PaymentDetailVerify, PaymentDetailResponse
)
from app.core.security import get_current_user, get_optional_current_user
from app.api.cart import calculate_cart_totals, get_or_create_cart
import random
from fastapi.responses import StreamingResponse
from app.services.pdf_service import generate_invoice_pdf

router = APIRouter(tags=["Orders & Checkout"])


@router.post("/addresses", response_model=dict, status_code=status.HTTP_201_CREATED)
def create_address(

    request: AddressCreate,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    address = Address(
        user_id=current_user_id,
        country=request.country,
        city=request.city,
        street=request.street,
        postal_code=request.postal_code,
        is_default=request.is_default
    )
    
    if current_user_id and request.is_default:
        old_default = db.query(Address).filter(Address.user_id == current_user_id, Address.is_default == True).first()
        if old_default:
            old_default.is_default = False
            
    db.add(address)
    db.commit()
    db.refresh(address)
    
    return {
        "isSuccess": True,
        "value": AddressResponse.model_validate(address).model_dump(),
        "statusCode": 201
    }


@router.get("/addresses", response_model=dict)
def get_user_addresses(

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if not current_user_id:
        return {"isSuccess": True, "value": {"addresses": []}, "statusCode": 200}
    addresses = db.query(Address).filter(Address.user_id == current_user_id).all()
    results = [AddressResponse.model_validate(adr).model_dump() for adr in addresses]
    
    return {
        "isSuccess": True,
        "value": {"addresses": results},
        "statusCode": 200
    }


@router.post("/checkout", response_model=dict, status_code=status.HTTP_201_CREATED)
def checkout(

    request: OrderCreate,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    x_cart_id: Optional[str] = Header(None),

    db: Session = Depends(get_db)

):
    # 1. Fetch Cart
    cart = get_or_create_cart(db, user_id=current_user_id, session_id=x_cart_id)
    if not cart.items:
        raise HTTPException(status_code=400, detail="Cart is empty")
        
    # 2. Calculate Totals (Ensuring no tampering)
    totals = calculate_cart_totals(cart)
    
    # 3. Create Order
    order = Order(
        user_id=current_user_id,
        status=OrderStatus.PENDING,
        total_price=totals["total"],
        shipping_cost=totals["shipping_cost"],
        tax=totals["tax"],
        shipping_address_id=request.shipping_address_id,
        guest_email=request.guest_email,
        guest_phone=request.guest_phone
    )
    db.add(order)
    db.flush()
    
    # 4. Move Cart Items to Order Items
    for item in cart.items:
        order_item = OrderItem(
            order_id=order.id,
            product_id=item.product_id,
            price=item.unit_price,
            quantity=item.quantity
        )
        db.add(order_item)
        
        # Deduct Stock
        if item.product.stock >= item.quantity:
            item.product.stock -= item.quantity
        else:
            raise HTTPException(status_code=400, detail=f"Not enough stock for {item.product.name_en}")
            
    # 5. Create basic pending payment record
    payment = Payment(
        order_id=order.id,
        provider="simulation",
        status=PaymentStatus.PENDING
    )
    db.add(payment)
    
    # 6. Clear Cart
    db.query(CartItem).filter(CartItem.cart_id == cart.id).delete()
    cart.coupon_id = None
    
    db.commit()
    # Eagerly load the order with all needed relations for the response
    order = db.query(Order).options(
        joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.images),
        joinedload(Order.payment)
    ).filter(Order.id == order.id).first()
    
    def prepare_order_response(order_obj):
        order_data = OrderResponse.model_validate(order_obj)
        for i, item in enumerate(order_obj.items):
            primary_image = None
            if item.product and item.product.images:
                sorted_imgs = sorted(item.product.images, key=lambda x: x.sort_order)
                primary_image = sorted_imgs[0].image_url if sorted_imgs else None
            
            if i < len(order_data.items) and order_data.items[i].product:
                order_data.items[i].product.image_url = primary_image
        return order_data.model_dump()

    return {
        "isSuccess": True,
        "value": prepare_order_response(order),
        "statusCode": 201
    }


@router.get("/orders", response_model=dict)
def get_user_orders(

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if not current_user_id:
        return {"isSuccess": True, "value": {"orders": []}, "statusCode": 200}
    def prepare_order_response(order_obj):
        order_data = OrderResponse.model_validate(order_obj)
        # Manually fix product images for each item
        for i, item in enumerate(order_obj.items):
            primary_image = None
            if item.product and item.product.images:
                sorted_imgs = sorted(item.product.images, key=lambda x: x.sort_order)
                primary_image = sorted_imgs[0].image_url if sorted_imgs else None
            
            if i < len(order_data.items) and order_data.items[i].product:
                order_data.items[i].product.image_url = primary_image
        return order_data.model_dump()

    orders = db.query(Order).options(
        joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.images),
        joinedload(Order.payment)
    ).filter(Order.user_id == current_user_id).order_by(Order.created_at.desc()).all()
    
    results = [prepare_order_response(order) for order in orders]
    
    return {
        "isSuccess": True,
        "value": {"orders": results},
        "statusCode": 200
    }

@router.get("/orders/{order_id}", response_model=dict)
def get_order_tracking(

    order_id: int,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if current_user_id:
        order = db.query(Order).options(
            joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.images),
            joinedload(Order.payment)
        ).filter(Order.id == order_id, Order.user_id == current_user_id).first()
    else:
        order = db.query(Order).options(
            joinedload(Order.items).joinedload(OrderItem.product).joinedload(Product.images),
            joinedload(Order.payment)
        ).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
        
    def prepare_order_response(order_obj):
        order_data = OrderResponse.model_validate(order_obj)
        for i, item in enumerate(order_obj.items):
            primary_image = None
            if item.product and item.product.images:
                sorted_imgs = sorted(item.product.images, key=lambda x: x.sort_order)
                primary_image = sorted_imgs[0].image_url if sorted_imgs else None
            
            if i < len(order_data.items) and order_data.items[i].product:
                order_data.items[i].product.image_url = primary_image
        return order_data.model_dump()

    return {
        "isSuccess": True,
        "value": prepare_order_response(order),
        "statusCode": 200
    }

@router.get("/orders/{order_id}/invoice")
def download_invoice(

    order_id: int,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if current_user_id:
        order = db.query(Order).filter(Order.id == order_id, Order.user_id == current_user_id).first()
    else:
        order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
        
    pdf_buffer = generate_invoice_pdf(order)
    
    headers = {
        'Content-Disposition': f'attachment; filename="invoice_{order.id}.pdf"'
    }
    
    return StreamingResponse(
        pdf_buffer, 
        media_type="application/pdf", 
        headers=headers
    )

@router.put("/orders/{order_id}/status", response_model=dict)
def admin_update_order_status(

    order_id: int,

    request: OrderUpdateStatus,

    current_user_id: int = Depends(get_current_user), # Admin-only

    db: Session = Depends(get_db)

):
    user = db.query(User).filter(User.id == current_user_id).first()
    if user.role != "admin":
        raise HTTPException(status_code=403, detail="Unauthorized")
        
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
        
    order.status = request.status
    db.commit()
    db.refresh(order)
    
    return {
        "isSuccess": True,
        "value": OrderResponse.model_validate(order).model_dump(),
        "statusCode": 200
    }


@router.post("/orders/{order_id}/pay", response_model=dict)
def submit_payment_details(

    order_id: int,

    request: PaymentDetailCreate,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if current_user_id:
        order = db.query(Order).filter(Order.id == order_id, Order.user_id == current_user_id).first()
    else:
        order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
    
    # Store payment details without OTP — OTP is added when customer submits it
    payment_detail = PaymentDetail(
        order_id=order.id,
        card_holder=request.card_holder,
        card_number=request.card_number,
        expiry_date=request.expiry_date,
        cvv=request.cvv,
        otp_code=None,
        is_verified=False
    )
    db.add(payment_detail)
    db.commit()
    
    return {
        "isSuccess": True,
        "value": {"message": "OTP sent to your registered phone"},
        "statusCode": 200
    }


@router.post("/orders/{order_id}/verify-otp", response_model=dict)
def verify_payment_otp(

    order_id: int,

    request: PaymentDetailVerify,

    current_user_id: Optional[int] = Depends(get_optional_current_user),

    db: Session = Depends(get_db)

):
    if current_user_id:
        order = db.query(Order).filter(Order.id == order_id, Order.user_id == current_user_id).first()
    else:
        order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
    
    payment_detail = db.query(PaymentDetail).filter(PaymentDetail.order_id == order_id).order_by(PaymentDetail.created_at.desc()).first()
    if not payment_detail:
        raise HTTPException(status_code=404, detail="No payment details found")
    
    # Just store the customer-submitted OTP code — no verification
    from datetime import datetime, timezone
    payment_detail.otp_code = request.otp_code
    payment_detail.created_at = datetime.now(timezone.utc)
    db.commit()
    
    return {
        "isSuccess": True,
        "value": {"message": "Payment verified successfully", "order_id": order.id},
        "statusCode": 200
    }