diff --git a/app/api/v1/routers/AdminInvoiceRouter.py b/app/api/v1/routers/AdminInvoiceRouter.py index 014f81f..e885723 100644 --- a/app/api/v1/routers/AdminInvoiceRouter.py +++ b/app/api/v1/routers/AdminInvoiceRouter.py @@ -127,13 +127,16 @@ def generate_invoice_for_order( ) # GST calculation matching order details - subtotal = float(order.total_amount) - discount = float(order.discount_amount) - tax_amount = float(order.tax_amount) + tax_amount = float(order.tax_amount or 0.0) + shipping = float(getattr(order, "shipping_cost", 0.0) or 0.0) + discount = float(getattr(order, "discount_amount", 0.0) or 0.0) + total = float(order.final_amount) + total_amount = float(order.total_amount) + is_inclusive_record = abs((total_amount + shipping - discount) - total) < 1.0 and tax_amount > 0 + subtotal = (total_amount - tax_amount) if is_inclusive_record else total_amount cgst = round(tax_amount / 2, 2) sgst = round(tax_amount / 2, 2) igst = 0.0 - total = float(order.final_amount) # Allocate a 16-char GST invoice number # Format: C1P2-26-SEQ diff --git a/app/api/v1/routers/AdminOrderRouter.py b/app/api/v1/routers/AdminOrderRouter.py index ea6211e..71ca90c 100644 --- a/app/api/v1/routers/AdminOrderRouter.py +++ b/app/api/v1/routers/AdminOrderRouter.py @@ -259,13 +259,16 @@ def get_order_invoice_pdf( # Check if invoice already exists invoice = db.query(Invoice).filter(Invoice.order_id == order.order_id).first() if not invoice: - subtotal = float(order.total_amount) - discount = float(order.discount_amount or 0.0) tax_amount = float(order.tax_amount or 0.0) + shipping = float(getattr(order, "shipping_cost", 0.0) or 0.0) + discount = float(order.discount_amount or 0.0) + total = float(order.final_amount) + total_amount = float(order.total_amount) + is_inclusive_record = abs((total_amount + shipping - discount) - total) < 1.0 and tax_amount > 0 + subtotal = (total_amount - tax_amount) if is_inclusive_record else total_amount cgst = round(tax_amount / 2, 2) sgst = round(tax_amount / 2, 2) igst = 0.0 - total = float(order.final_amount) today = datetime.now() fy = today.strftime("%y") diff --git a/app/api/v1/routers/CatalogRouter.py b/app/api/v1/routers/CatalogRouter.py index 1c6c019..3dee18a 100644 --- a/app/api/v1/routers/CatalogRouter.py +++ b/app/api/v1/routers/CatalogRouter.py @@ -1043,6 +1043,10 @@ def get_products( images_list = [{"image_url": first_var.images[0].image_url}] prod_rating, prod_rev_count = ratings_map.get(p.product_id, (5.0, 0)) + mrp_val = price + base_price_val = round(price * Decimal("0.82"), 2) if price is not None else Decimal("0.0") + base_compare_val = round(compare_price * Decimal("0.82"), 2) if compare_price is not None else None + return ProductCardResponse( product_id=p.product_id, category_id=p.category_id, @@ -1050,8 +1054,9 @@ def get_products( name=p.name, thumbnail_url=thumbnail_url, images=images_list, - price=price, - compare_price=compare_price, + price=base_price_val, + compare_price=base_compare_val, + mrp=mrp_val, discount_percent=discount_percent, rating=prod_rating, review_count=prod_rev_count, @@ -1245,6 +1250,25 @@ def get_product_detail_by_slug(slug: str, db: Session = Depends(get_db)): if not variant_images: variant["images"] = product_images_fallback + # Convert catalog MRP prices to pre-tax base prices for storefront PDP & related products + def _apply_storefront_pricing(p_dict: Dict[str, Any]) -> Dict[str, Any]: + if not p_dict: + return p_dict + for v in p_dict.get("variants") or []: + raw_p = v.get("price") + if raw_p is not None: + mrp_f = float(raw_p) + v["mrp"] = mrp_f + v["price"] = round(mrp_f * 0.82, 2) + raw_comp = v.get("compare_price") + if raw_comp is not None: + v["compare_price"] = round(float(raw_comp) * 0.82, 2) + return p_dict + + _apply_storefront_pricing(product_serialized) + for rp in related_serialized: + _apply_storefront_pricing(rp) + response_payload = { "product": product_serialized, "reviews": reviews_serialized, diff --git a/app/api/v1/routers/storefront.py b/app/api/v1/routers/storefront.py index a9d743d..3c00d1c 100644 --- a/app/api/v1/routers/storefront.py +++ b/app/api/v1/routers/storefront.py @@ -83,6 +83,8 @@ def live_search( v_name = f"{p.name} - {label}" if label else p.name v_img = v.images[0].image_url if v.images else (p.images[0].image_url if p.images else None) v_price = float(v.price) if v.price is not None else 0.0 + base_price = round(v_price * 0.82, 2) + base_compare = round(float(v.compare_price) * 0.82, 2) if v.compare_price is not None else None expanded_products.append({ "product_id": p.product_id, "category_id": p.category_id, @@ -91,15 +93,17 @@ def live_search( "variant_sku": v.sku, "variant_name": label or None, "variant_url": f"/products/{p.slug}?variant={v.sku}", - "price": v_price, - "compare_price": float(v.compare_price) if v.compare_price is not None else None, + "price": base_price, + "mrp": v_price, + "compare_price": base_compare, "thumbnail_url": v_img, "images": [{"image_url": v_img}] if v_img else [], "variants": [{ "variant_id": v.variant_id, "product_id": p.product_id, "sku": v.sku, - "price": v_price, + "price": base_price, + "mrp": v_price, "status": "active", }] }) @@ -112,6 +116,8 @@ def live_search( v_img = alt_v.images[0].image_url break price_val = float(first_v.price) if first_v and first_v.price is not None else 0.0 + base_price = round(price_val * 0.82, 2) + base_compare = round(float(first_v.compare_price) * 0.82, 2) if first_v and first_v.compare_price is not None else None expanded_products.append({ "product_id": p.product_id, "category_id": p.category_id, @@ -120,15 +126,17 @@ def live_search( "variant_sku": first_v.sku if first_v else None, "variant_name": None, "variant_url": f"/products/{p.slug}", - "price": price_val, - "compare_price": float(first_v.compare_price) if first_v and first_v.compare_price is not None else None, + "price": base_price, + "mrp": price_val, + "compare_price": base_compare, "thumbnail_url": v_img, "images": [{"image_url": v_img}] if v_img else [], "variants": [{ "variant_id": first_v.variant_id if first_v else p.product_id, "product_id": p.product_id, "sku": first_v.sku if first_v else "", - "price": price_val, + "price": base_price, + "mrp": price_val, "status": "active", }] if first_v else [] }) diff --git a/app/core/invoice_generator.py b/app/core/invoice_generator.py index dce9d8d..143d145 100644 --- a/app/core/invoice_generator.py +++ b/app/core/invoice_generator.py @@ -227,13 +227,41 @@ def generate_invoice_pdf(order, customer, order_items, db=None) -> bytes: Paragraph("Total Price", th_right) ]] + # 4. Totals & Tax Calculation Breakdown + tax_amount = float(order.tax_amount or 0.0) + shipping = float(getattr(order, "shipping_cost", 0.0) or 0.0) + discount = float(getattr(order, "discount_amount", 0.0) or 0.0) + final_amount = float(order.final_amount) + total_amount = float(order.total_amount) + + # Detect if record was stored with older inclusive total_amount + is_inclusive_record = abs((total_amount + shipping - discount) - final_amount) < 1.0 and tax_amount > 0 + + if is_inclusive_record: + taxable_value = total_amount - tax_amount + else: + taxable_value = total_amount + + gst_rate = float(branding.get("gstRate", 18.0)) + half_rate = round(gst_rate / 2.0, 1) + cgst = round(tax_amount / 2, 2) + sgst = round(tax_amount / 2, 2) + igst = 0.0 + for idx, item in enumerate(order_items): + if is_inclusive_record: + u_price = round(float(item.unit_price) * 0.82, 2) + t_price = round(u_price * item.quantity, 2) + else: + u_price = float(item.unit_price) + t_price = float(item.total_price) + table_data.append([ Paragraph(str(idx + 1), td_style), Paragraph(f"{item.sku} - {item.product_name}", td_style), - Paragraph(f"Rs. {float(item.unit_price):.2f}", td_right), + Paragraph(f"Rs. {u_price:,.2f}", td_right), Paragraph(str(item.quantity), td_right), - Paragraph(f"Rs. {float(item.total_price):.2f}", td_right) + Paragraph(f"Rs. {t_price:,.2f}", td_right) ]) items_table = Table(table_data, colWidths=[0.5 * inch, 3.8 * inch, 1.1 * inch, 0.6 * inch, 1.5 * inch]) @@ -248,22 +276,22 @@ def generate_invoice_pdf(order, customer, order_items, db=None) -> bytes: story.append(items_table) story.append(Spacer(1, 15)) - # 4. Totals & Tax Calculation Breakdown - subtotal = float(order.total_amount) - tax_amount = float(order.tax_amount) - gst_rate = float(branding.get("gstRate", 18.0)) - half_rate = round(gst_rate / 2.0, 1) - cgst = round(tax_amount / 2, 2) - sgst = round(tax_amount / 2, 2) - igst = 0.0 - totals_data = [ - [Paragraph("", text_style), Paragraph("Taxable Value:", label_style), Paragraph(f"Rs. {subtotal:.2f}", td_right)], - [Paragraph("", text_style), Paragraph(f"CGST ({half_rate:.1f}%):", label_style), Paragraph(f"Rs. {cgst:.2f}", td_right)], - [Paragraph("", text_style), Paragraph(f"SGST ({half_rate:.1f}%):", label_style), Paragraph(f"Rs. {sgst:.2f}", td_right)], - [Paragraph("", text_style), Paragraph("IGST (0.0%):", label_style), Paragraph(f"Rs. {igst:.2f}", td_right)], - [Paragraph("", text_style), Paragraph("Grand Total:", ParagraphStyle('GrandLabel', parent=label_style, fontSize=11, textColor=colors.HexColor('#1b2559'))), Paragraph(f"Rs. {float(order.final_amount):.2f}", ParagraphStyle('GrandVal', parent=td_right, fontSize=11, fontName='Helvetica-Bold', textColor=colors.HexColor('#1b2559')))] + [Paragraph("", text_style), Paragraph("Taxable Value:", label_style), Paragraph(f"Rs. {taxable_value:,.2f}", td_right)], ] + if discount > 0: + totals_data.append([Paragraph("", text_style), Paragraph("Discount:", label_style), Paragraph(f"-Rs. {discount:,.2f}", td_right)]) + totals_data.extend([ + [Paragraph("", text_style), Paragraph(f"CGST ({half_rate:.1f}%):", label_style), Paragraph(f"Rs. {cgst:,.2f}", td_right)], + [Paragraph("", text_style), Paragraph(f"SGST ({half_rate:.1f}%):", label_style), Paragraph(f"Rs. {sgst:,.2f}", td_right)], + ]) + if igst > 0: + totals_data.append([Paragraph("", text_style), Paragraph(f"IGST ({gst_rate:.1f}%):", label_style), Paragraph(f"Rs. {igst:,.2f}", td_right)]) + if shipping > 0: + totals_data.append([Paragraph("", text_style), Paragraph("Shipping Charges:", label_style), Paragraph(f"Rs. {shipping:,.2f}", td_right)]) + totals_data.append([ + [Paragraph("", text_style), Paragraph("Grand Total:", ParagraphStyle('GrandLabel', parent=label_style, fontSize=11, textColor=colors.HexColor('#1b2559'))), Paragraph(f"Rs. {final_amount:,.2f}", ParagraphStyle('GrandVal', parent=td_right, fontSize=11, fontName='Helvetica-Bold', textColor=colors.HexColor('#1b2559')))] + ]) totals_table = Table(totals_data, colWidths=[4.2 * inch, 1.8 * inch, 1.5 * inch]) totals_table.setStyle(TableStyle([ @@ -368,13 +396,27 @@ def generate_thermal_invoice_pdf(order, customer, order_items) -> bytes: ] # 4. Item List Rows + tax_amount = float(order.tax_amount or 0.0) + shipping = float(getattr(order, "shipping_cost", 0.0) or 0.0) + discount = float(getattr(order, "discount_amount", 0.0) or 0.0) + final_amount = float(order.final_amount) + total_amount = float(order.total_amount) + + is_inclusive_record = abs((total_amount + shipping - discount) - final_amount) < 1.0 and tax_amount > 0 + taxable_value = (total_amount - tax_amount) if is_inclusive_record else total_amount + for item in order_items: # Truncate long names to save receipt slip width short_name = item.product_name[:24] + '..' if len(item.product_name) > 26 else item.product_name + if is_inclusive_record: + item_line_total = round(float(item.unit_price) * 0.82 * item.quantity, 2) + else: + item_line_total = float(item.total_price) + item_header.append([ Paragraph(f"{item.sku}
{short_name}", text_style), Paragraph(str(item.quantity), text_right), - Paragraph(f"Rs. {float(item.total_price):.1f}", text_right) + Paragraph(f"Rs. {item_line_total:,.2f}", text_right) ]) # Table Widths: item=120pt, qty=30pt, total=56pt -> Total 206pt @@ -389,16 +431,23 @@ def generate_thermal_invoice_pdf(order, customer, order_items) -> bytes: story.append(Spacer(1, 8)) # 5. Taxes & Total Breakout - tax_amount = float(order.tax_amount) cgst = round(tax_amount / 2, 2) sgst = round(tax_amount / 2, 2) totals_data = [ - [Paragraph("Taxable Value:", text_style), Paragraph(f"Rs. {float(order.total_amount):.2f}", text_right)], - [Paragraph("CGST (9%):", text_style), Paragraph(f"Rs. {cgst:.2f}", text_right)], - [Paragraph("SGST (9%):", text_style), Paragraph(f"Rs. {sgst:.2f}", text_right)], - [Paragraph("Grand Total:", ParagraphStyle('GrandLabelThermal', parent=text_style, fontName='Helvetica-Bold', fontSize=9)), Paragraph(f"Rs. {float(order.final_amount):.2f}", ParagraphStyle('GrandValThermal', parent=text_right, fontName='Helvetica-Bold', fontSize=9))] + [Paragraph("Taxable Value:", text_style), Paragraph(f"Rs. {taxable_value:,.2f}", text_right)], ] + if discount > 0: + totals_data.append([Paragraph("Discount:", text_style), Paragraph(f"-Rs. {discount:,.2f}", text_right)]) + totals_data.extend([ + [Paragraph("CGST (9%):", text_style), Paragraph(f"Rs. {cgst:,.2f}", text_right)], + [Paragraph("SGST (9%):", text_style), Paragraph(f"Rs. {sgst:,.2f}", text_right)], + ]) + if shipping > 0: + totals_data.append([Paragraph("Shipping:", text_style), Paragraph(f"Rs. {shipping:,.2f}", text_right)]) + totals_data.append([ + [Paragraph("Grand Total:", ParagraphStyle('GrandLabelThermal', parent=text_style, fontName='Helvetica-Bold', fontSize=9)), Paragraph(f"Rs. {final_amount:,.2f}", ParagraphStyle('GrandValThermal', parent=text_right, fontName='Helvetica-Bold', fontSize=9))] + ]) totals_table = Table(totals_data, colWidths=[110, 96]) totals_table.setStyle(TableStyle([ diff --git a/app/schemas/Catalog.py b/app/schemas/Catalog.py index 51031f3..3248e43 100644 --- a/app/schemas/Catalog.py +++ b/app/schemas/Catalog.py @@ -524,6 +524,7 @@ class ProductVariantResponse(BaseModel): barcode: Optional[str] price: Decimal compare_price: Optional[Decimal] + mrp: Optional[Decimal] = None cost_price: Decimal low_stock_threshold: int status: str @@ -672,6 +673,7 @@ class ProductCardResponse(BaseModel): thumbnail_url: Optional[str] = None price: Decimal compare_price: Optional[Decimal] = None + mrp: Optional[Decimal] = None discount_percent: int = 0 rating: float = 5.0 review_count: int = 0 diff --git a/app/services/OrderService.py b/app/services/OrderService.py index 8b96606..f8bda57 100644 --- a/app/services/OrderService.py +++ b/app/services/OrderService.py @@ -246,6 +246,7 @@ class OrderService: validated_items = [] subtotal = 0.0 + total_mrp = 0.0 for item in items: variant_id = item.get("variant_id") @@ -274,19 +275,23 @@ class OrderService: if variant.product: product_name = variant.product.name - unit_price = float(variant.price) - total_price = unit_price * qty - subtotal += total_price + mrp_unit = float(variant.price) + # Pre-tax base price = MRP - 18% GST (82% of MRP) + base_unit_price = round(mrp_unit * 0.82, 2) + base_total_price = round(base_unit_price * qty, 2) + subtotal += base_total_price + total_mrp += round(mrp_unit * qty, 2) validated_items.append({ "variant": variant, "product_name": product_name, "qty": qty, - "unit_price": unit_price, - "total_price": total_price + "unit_price": base_unit_price, + "total_price": base_total_price, + "mrp_unit": mrp_unit }) - shipping_cost = DeliveryService.calculate_shipping_cost(db, subtotal) + shipping_cost = DeliveryService.calculate_shipping_cost(db, total_mrp) # Coupon validation and calculation coupon_obj = None @@ -337,12 +342,8 @@ class OrderService: credits_applied = float(min(wallet.active_balance, max_eligible)) discount = round(coupon_discount + credits_applied, 2) - gross_amount = max(0.0, subtotal - discount) - tax_rate = 18.0 - taxable_amount = round(gross_amount / (1 + tax_rate / 100.0), 2) - tax_amount = round(gross_amount - taxable_amount, 2) - - final_amount = max(0.0, round((subtotal + shipping_cost) - discount)) + total_tax = round(total_mrp - subtotal, 2) + final_amount = max(0.0, round((subtotal + total_tax + shipping_cost) - discount)) method_upper = payment_method.upper() order_id = str(ulid.ULID()) @@ -354,7 +355,7 @@ class OrderService: customer_id=customer.customer_id, total_amount=subtotal, discount_amount=discount, - tax_amount=tax_amount, + tax_amount=total_tax, shipping_cost=shipping_cost, final_amount=final_amount, status="ORDER_CREATED",