from django.shortcuts import render
import json
from django.conf import settings
from django.shortcuts import render
from sales.models import *
from expenses.models import *
from store.models import *
from masters.models import *
from stock.models import *
from sales.forms import *
from django.db import IntegrityError, transaction

import hashlib
import os
from django.conf import settings
from datetime import datetime
from django.utils import timezone
from django.db.models import Max, F, Q,Sum
import base64
from django.shortcuts import render
from io import BytesIO
from django.conf import settings
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.shortcuts import get_object_or_404
from django.templatetags.static import static
from xhtml2pdf import pisa
from num2words import num2words
from django.contrib.staticfiles import finders
from common.utils import *
from django.views.decorators.csrf import csrf_exempt
from supplier.models import *
from customer.models import *
#```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````



def sales_return(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        branch_id = request.session.get('branch_id')
        is_ho = request.session.get('is_ho')
        encoded_id = request.GET.get('id') or 0
        if user_type == 'stores':
            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            item = selectList(item_table)
            customer = selectList(customer_table, {'branch_id':branch_id},order_by='name')
            supplier = selectList(supplier_table, order_by='name' )
            if encoded_id != 0:
                decoded_id = decode_base64_id(encoded_id) or 0
            else:
                decoded_id = 0
            return render(request, 'sales_return/details.html',{'supplier':supplier,'branch':branch,'item':item,'customer':customer,'decoded_id':decoded_id})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    

def ajax_sales_return_view(request):  
    role_id         = request.session.get('role_id')
    branch_id       = request.session.get('branch_id')
    fyf_name        = request.session.get('fyf')
    financial_year  = calculate_financial_year(fyf_name)
    keyword         = request.POST.get('keyword_search', '').strip()
    search_type     = request.POST.get('search_type')
    from_date       = request.POST.get('from_date')
    to_date         = request.POST.get('to_date')
    store_id        = request.POST.get('store_id')
    sales_id        = request.POST.get('sales_id')

    has_access, error_message = check_user_access(role_id, 'sales', "read")    
    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to view sales orders.'})

    query = Q(status=1, branch_id=branch_id, current_fy=financial_year)
    
    if sales_id:
        query &= Q(id=sales_id)

    if from_date and to_date:
        query &= Q(sr_date__range=[from_date, to_date])
    if store_id:
        query &= Q(store_id=store_id)
    if keyword:
        if search_type == 'name': query &= Q(customer_name__icontains=keyword)
        elif search_type == 'phone': query &= Q(phone__icontains=keyword)
        elif search_type == 'sales_no': query &= Q(inv_no__icontains=keyword)

    # Get main sales records
    data = list(selectList(sales_return_table, query).values())
   
    formatted = []
    for index, item in enumerate(data):
        sales_id = item['id']

        cash_total = return_transaction_table.objects.filter(
            tm_return_id=sales_id, 
            status=1,
            payment_type='cash'
        ).aggregate(
            total_cash=Sum('amount'),
        )

        bank_total = return_transaction_table.objects.filter(
            tm_return_id=sales_id, 
            status=1,
            payment_type='bank'
        ).aggregate(
            total_bank=Sum('amount'),
        )
        finance_total = return_transaction_table.objects.filter(
            tm_return_id=sales_id, 
            status=1,
            payment_type='finance'
        ).aggregate(
            total_finance=Sum('amount'),
        )
        card_total = return_transaction_table.objects.filter(
            tm_return_id=sales_id, 
            status=1,
            payment_type='card'
        ).aggregate(
            total_card=Sum('amount'),
        )



        # Exchange is usually filtered by payment_type or a specific logic
        txn_totals = return_transaction_table.objects.filter(
            tm_return_id=sales_id, 
            status=1
        ).aggregate(            
            total_exchange=Sum('amount', filter=Q(payment_type__iexact='exchange'))
        )

       

        # Set default values to 0.00 if None
        exchange  = txn_totals['total_exchange'] or 0.00

        formatted.append({
            'id': index + 1,
            'action': (
                '<div class="d-flex gap-1 justify-content-center align-items-center">'
                '<button type="button" onclick="edit_data(\'{}\')" class="btn btn-outline-success btn-xs p-1"><i class="fas fa-edit"></i></button>'
                '<button type="button" onclick="delete_data(\'{}\')" class="btn btn-outline-danger btn-xs p-1"><i class="fas fa-trash-alt"></i></button>'
                '</div>'
            ).format(sales_id, sales_id),
            'date'      : format_date_month_year(item['sr_date']) if item['sr_date'] else '-', 
            'inv_no'     : item['sr_no'] if item['sr_no'] else '-', 
            'customer'  :getItemNameById( customer_table ,item['customer_id']) if item['customer_id'] else '-', 
            'quantity'  : item['total_quantity'] if item['total_quantity'] else '0', 
            'amount'    : format_amount(item['total_amount']), 
            'cash'      : format_amount(cash_total['total_cash'] or 0.00), 
            'bank'      : format_amount(bank_total['total_bank'] or 0.00), 
            'finance'      : format_amount(finance_total['total_finance'] or 0.00), 
            'card'      : format_amount(card_total['total_card'] or 0.00), 
            'exchange'  : format_amount(exchange), 
            'balance'   : format_amount(item['balance']), 
            'remarks'   : item['remarks'] if item['remarks'] else '-',    
            'status'    : '<span class="badge text-bg-success">Active</span>' if item['is_active'] else '<span class="badge text-bg-danger">Inactive</span>'
        })

    return JsonResponse({'data': formatted})




def ajax_tx_return_edit(request):
    role_id = request.session.get('role_id')
    branch_id = request.session.get('branch_id')
    fyf_name = request.session.get('fyf')
    financial_year = calculate_financial_year(fyf_name)

    has_access, error_message = check_user_access(role_id, 'sales', "read")
    if not has_access:
        return JsonResponse({
            'message': 'permission',
            'error_message': 'You do not have permission to view the sales details'
        })

    sales_id = request.POST.get('sales_id')

    # ----------------------------  
    # Sales Items
    # ----------------------------
    items_qs = child_sales_return_table.objects.filter(
        tm_return_id=sales_id,
        status=1,
        current_fy=financial_year
    ).values()

    material_ids = (
        child_sales_return_table.objects
        .filter(
            tm_return_id=sales_id,
            status=1,
            current_fy=financial_year
        )
        .values_list('sales_id', flat=True)
        .distinct()
    )

    items = []
    for index, item in enumerate(items_qs):
        items.append({
            'id': index + 1,
            'ean': item['ean_number'] or '-',
            'subcategory_id': item['subcategory_id'] or 0,
            'subcategory_name': getItemNameById(sub_category_table, item['subcategory_id']) if item['subcategory_id'] else '-',

            'brand_id': item['brand_id'] or 0,
            'brand_name': getItemNameById(brand_table, item['brand_id']) if item['brand_id'] else '-',

            'model_id': item['model_id'] or 0,
            'model_name': getItemNameById(model_table, item['model_id']) if item['model_id'] else '-',

            'variant_id': item['variant_id'] or 0,
            'variant_name': getItemNameById(variant_table, item['variant_id']) if item['variant_id'] else '-',


            'color_id': item['color_id'] or 0,
            'color_name': getItemNameById(color_table, item['color_id']) if item['color_id'] else '-',

            'imei_no': item['imei_no'] or '-',

            'rate': item['rate'] or 0.00,
            'quantity': item['quantity'] or 0,
            'amount': item['amount'] or 0.00,

            'source': item['source'] or 0,

            

            'bop_price': item['bop'] or 0.00,
            'mop_price': item['mop'] or 0.00,
            'wsp_price': item['wsp'] or 0.00,
            'fsp_price': item['fsp'] or 0.00,
            'db_price': item['db_price'] or 0.00,

            'tm_id': item['tm_return_id'],
            'sales_id': item['sales_id'],

            'tax_percent': item['tax_percent'] or 0,
            'tax_amount': item['tax_amount'] or 0.00,
            'tax_cgst': item['tax_cgst'] or 0.00,
            'tax_sgst': item['tax_sgst'] or 0.00,

            'discount_amount': item['discount_amount'] or 0.00,
            'discount_percent': item['discount_percent'] or 0,
            
            'id': item['id'],
            'special_id': item['special_id'] or 0,
            'special_amount': item['special_amount'] or 0.00,
            'claim_amount': item['claim_amount'] or 0.00,
            'upgrade_id': item['upgrade_id'] or 0,
            'upgrade_amount': item['upgrade_amount'] or 0.00,
            'collect_amount': item['collect_amount'] or 0.00,
             
        })

    # ----------------------------
    # Sales Transactions (Payments)
    # ----------------------------
    tx_qs = return_transaction_table.objects.filter(
        tm_return_id=sales_id,
        status=1,
        is_active=1
    ).values()

    tx_transaction = []
    for tx in tx_qs:
        tx_transaction.append({
            'payment_type': tx['payment_type'],
            'amount': format_amount(tx['amount']) if tx['amount'] else '0.00',
            'finance_id': tx['finance_id'] or 0,
            'bank_id': tx['bank_id'] or 0,
            'card_id': tx['card_id'] or 0,
            'reference_no': tx['reference_no'] or '',
            'finance_customer': tx['finance_customer'] or '',
            'balance': format_amount(tx['balance']) if tx['balance'] else '0.00',
            'is_collect': tx['is_collect'] or 0,
            'collected_on': format_datetime(tx['collected_on']) or '',
            'collect_amount':tx['collect_amount'] or 0.00,
            'collect_status': tx['collect_status'] or 0,
            'cashback': tx['cashback'] or 0.00,
            'charges': tx['charges'] or 0.00,
            'charge_mode': tx['charge_mode'] or '',
            'charge_bank_id': tx['charge_bank_id'] or 0,
            'charge_status': tx['charge_status'] or '',
            'charge_amount_collect': tx['charge_amount_collect'] or 0.00,
            'charge_collect_on': format_datetime(tx['charge_collect_on']) or '',
            'id': tx['id'],
            'exchange_status': tx['exchange_status'] or 'pending',
            'exchange_claim': tx['exchange_claim'] or 0.00,



        })

    return JsonResponse({
        'items': items,
        'tx_transaction': tx_transaction,
        'pu_ids': list(material_ids)  # ✅ send distinct PU IDs

    })




def sales_return_add(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        branch_id = request.session.get('branch_id')
        fyf_name = request.session.get('fyf')
        is_ho = request.session.get('is_ho')

        financial_year = calculate_financial_year(fyf_name)
        if user_type == 'stores':
            customer = selectList(customer_table, {'branch_id':branch_id},order_by='name')
            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            item = selectList(item_table)
            employee = employee_list(request)     
            if is_ho == 1:
                bank = selectList(bank_table, {'is_default':0}, order_by='name')
            else:
                bank = selectList(bank_table, {'is_default':1}, order_by='name')
            generated_po_no = generate_serial_number(
                    model=sales_return_table,
                    number_field='sr_no',
                    financial_year_field='current_fy',
                    financial_year=financial_year,
                    branch_id=branch_id,
                    prefix=""
                )
            return render(request, 'sales_return/add.html',{'customer':customer,'branch':branch,'item':item,'employee':employee,'generated_po_no':generated_po_no,'bank':bank})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    


#*************** Block 1************
def load_sales_orders(request):
    customer_id = request.GET.get('customer_id')
    tm_id = int(request.GET.get('tm_id') or 0)
    branch_id = request.session.get('branch_id')
    fyf_name = request.session.get('fyf')

    query = Q(status=1, branch_id=branch_id)
    if customer_id:
        query &= Q(customer_id=customer_id)

    valid_pos = []

    returned_sales_qs = child_sales_return_table.objects.filter(
        status=1, is_active=1
    )
    if tm_id:
        returned_sales_qs = returned_sales_qs.exclude(tm_return_id=tm_id)

    returned_sales = returned_sales_qs.values('sales_id').annotate(total_returned=Sum('quantity'))
    returned_map = {r['sales_id']: r['total_returned'] for r in returned_sales}

    sales_qs = sales_order_table.objects.filter(query)
    for po in sales_qs:
        sold_qty = po.total_quantity or 0
        returned_qty = returned_map.get(po.id, 0)
        remaining_qty = sold_qty - returned_qty

        if remaining_qty <= 0:
            continue  # skip fully returned sales

        valid_pos.append({
            'sales_id': po.id,
            'pr_id': 0,  # No PR for customer
            'po_no': po.inv_no,
            'remaining_qty': remaining_qty
        })


    

    return JsonResponse(valid_pos, safe=False)


from django.db import transaction, IntegrityError
from django.db.models import Sum
from django.http import JsonResponse
from django.utils import timezone
import json
from django.db import transaction as db_transaction




def add_sales_return(request):
    if request.method != 'POST':
        return JsonResponse({'message': 'Invalid request'}, status=400)

    try:
        company_id      = request.session.get('company_id')
        branch_id       = request.session.get('branch_id')
        user_id         = request.session.get('user_id')
        role_id         = request.session.get('role_id')
        fyf_name        = request.session.get('fyf')
        financial_year  = calculate_financial_year(fyf_name)
        po_date         = request.POST.get('sales_date')
        customer_id     = int(request.POST.get('customer_id') or 0)
        remarks         = request.POST.get('description')
        total_qty       = float(request.POST.get('total_quantity') or 0)
        sub_total       = float(request.POST.get('sub_total') or 0)
        total_amount    = float(request.POST.get('total_payable') or 0)
        total_paid      = float(request.POST.get('total_paid') or 0)
        balance         = float(request.POST.get('balance') or 0)
        charges         = float(request.POST.get('charges') or 0)
        total_discount  = float(request.POST.get('total_discount') or 0)
        total_tax_cgst  = float(request.POST.get('total_tax_cgst') or 0)
        total_tax_sgst  = float(request.POST.get('total_tax_sgst') or 0)
        employee_id     = request.POST.get('employee_id') or user_id
        now             = timezone.localtime(timezone.now())

        if not check_user_access(role_id, 'sales', "create"):
            return JsonResponse({'message': 'permission', 'error_message': 'Access denied'})
        # -----------------------------
        # Create customer if needed
        # -----------------------------
       
        # Items
        items       = json.loads(request.POST.get('items') or '[]')
        if not items:
            return JsonResponse({'message': 'warning', 'error_message': 'No items added'})

        # Payments
        payments    = json.loads(request.POST.get('payments') or '[]')

        inv_no = generate_serial_number(
            model                 =sales_return_table,
            number_field          ='sr_no',
            financial_year_field  ='current_fy',
            financial_year        = financial_year,
            branch_id             = branch_id,
            prefix                =""
        )

        with db_transaction.atomic():            
            main = sales_return_table.objects.create(
                company_id      =company_id,
                branch_id       =branch_id,
                current_fy      =financial_year,
                sr_no          =inv_no,
                num_series      =generate_num_series(sales_return_table),
                sr_date        =po_date,
                time            = now.time(),
                customer_id     =customer_id,
                total_quantity  =total_qty,
                total_amount    =total_amount,
                sub_total       =sub_total,
                total_paid      =total_paid,
                total_discount  = total_discount,
                charges         = charges,
                balance         =balance,
                remarks         =remarks,
                employee_id     =employee_id,
                created_on      =now,
                updated_on      =now,
                created_by      =user_id,
                updated_by      =user_id,
                status          =1,
                is_active       =1,
                total_cgst      =total_tax_cgst,
                total_sgst      =total_tax_sgst,
            )

            # Sales Items
            for item in items:
                child_sales_return_table.objects.create(
                    company_id      =company_id,
                    current_fy      =financial_year,
                    tm_return_id     =main.id,
                    sales_id        =item['sales_id'],
                    branch_id       =branch_id,
                    customer_id     =customer_id,
                    imei_no         =item['imei'],
                    ean_number      =item['ean'],
                    subcategory_id  =item['subcategory_id'],
                    brand_id        =item['brand_id'],
                    model_id        =item['model_id'],
                    variant_id      =item['variant_id'],
                    color_id        =item['color_id'],
                    quantity        =1,
                    rate            =item['rate'],
                    amount          =item['net_rate'],
                    tax_percent     =item['tax_percent'],
                    tax_amount      =item['tax_amount'],
                    tax_cgst        =item['tax_cgst'],
                    tax_sgst        =item['tax_sgst'],
                    discount_percent=item['discount_percent'],
                    discount_amount=item['discount_amount'],
                    mop             = item['mop_price'],
                    bop             = item['bop_price'],
                    wsp             = item['wsp_price'],
                    fsp             = item['fsp_price'],
                    db_price        = item['db_price'],
                    mrp             = item['rate'],          
                    special_id      = item['special_id'],
                    special_amount  = item['special_amount'],
                    claim_amount    = item['claim_amount'],
                    upgrade_id      = item['upgrade_id'],
                    upgrade_amount  = item['upgrade_amount'],
                    collect_amount  = item['collect_amount'],
                    
                    created_on      =now,
                    updated_on      =now,
                    created_by      =user_id,
                    updated_by      =user_id,
                    status          =1,
                    is_active       =1
                )
            # -----------------------------
            # Payments (MULTI ROW)
            # -----------------------------
            for pay in payments:
                return_transaction_table.objects.create(
                    tm_return_id=main.id,
                    branch_id=branch_id,
                    current_fy=financial_year,
                    date=po_date,
                    time=now.time(),
                    finance_customer=pay.get('customer', ''),
                    payment_type=pay['type'],
                    total_amount=total_amount,
                    amount=float(pay['amount']),
                    finance_id=pay.get('id', 0) if pay['type'] == 'finance' else 0,
                    card_id=pay.get('id', 0) if pay['type'] == 'card' else 0,
                    bank_id=pay.get('id', 0) if pay['type'] == 'bank' else 0,
                    charges=float(pay.get('charges', 0)),
                    reference_no=pay.get('details', ''),
                    cashback=float(pay.get('cashback', 0)),
                    charge_mode=pay.get('mode', ''),
                    charge_bank_id=pay.get('bank_id', 0),
                    balance=balance,
                    created_on=now,
                    updated_on=now,
                    created_by=user_id,
                    updated_by=user_id,
                    status=1,
                    is_active=1
                )

        return JsonResponse({'message': 'success'})

    except IntegrityError as e:
        return JsonResponse({'message': 'exception', 'error': str(e)}, status=200)
    except Exception as e:
        return JsonResponse({'message': 'exception', 'error': f'Unexpected error: {e}'}, status=500)


def get_saled_quantity(po_id, item_id):

    return child_sales_order_table.objects.filter(
        tm_sales_id=po_id,
        item_id=item_id,
        status=1
    ).aggregate(qty=Sum('quantity'))['qty'] or 0


def sales_return_edit(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        branch_id = request.session.get('branch_id')
        fyf_name        = request.session.get('fyf')
        is_ho           = request.session.get('is_ho')

        financial_year = calculate_financial_year(fyf_name)
        if user_type == 'stores':
            encoded_id = request.GET.get('id', None)
            decoded_id = decode_base64_id(encoded_id)
            if decoded_id:
                company = select_row(company_table, {'id': 1})  
                sales_return = select_row(sales_return_table, {'id':decoded_id})
                customer = selectList(customer_table, {'branch_id':branch_id},order_by='name')
                branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
                item = selectList(item_table)
                employee = employee_list(request)
                if is_ho == 1:
                    bank = selectList(bank_table, {'is_default':0}, order_by='name')
                else:
                    bank = selectList(bank_table, {'is_default':1}, order_by='name')
                finance = selectList(finance_table, {'f_type':'finance'},order_by='name')
                card = selectList(finance_table, {'f_type':'card'},order_by='name')
            else:
                return HttpResponse("ID parameter is missing")
            
            return render(request, 'sales_return/edit.html', {'company': company,'sales':sales_return,'id':decoded_id,'customer':customer,
                                    'branch':branch,'item':item,'employee':employee,'bank':bank,'finance':finance,'card':card})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")



def update_sales_return(request):
    if request.method != 'POST':
        return JsonResponse({'message': 'Invalid request'}, status=400)

    try:
        company_id      = request.session.get('company_id')
        branch_id       = request.session.get('branch_id')
        user_id         = request.session.get('user_id')
        role_id         = request.session.get('role_id')
        fyf_name        = request.session.get('fyf')
        financial_year  = calculate_financial_year(fyf_name)
        po_date         = request.POST.get('sales_date')
        customer_id     = int(request.POST.get('customer_id') or 0)
        tm_return_id    = int(request.POST.get('tm_id') or 0)
        remarks         = request.POST.get('description')
        total_qty       = float(request.POST.get('total_quantity') or 0)
        sub_total       = float(request.POST.get('sub_total') or 0)
        total_amount    = float(request.POST.get('total_payable') or 0)
        total_paid      = float(request.POST.get('total_paid') or 0)
        balance         = float(request.POST.get('balance') or 0)
        charges         = float(request.POST.get('charges') or 0)
        total_discount  = float(request.POST.get('total_discount') or 0)
        total_tax_cgst  = float(request.POST.get('total_tax_cgst') or 0)
        total_tax_sgst  = float(request.POST.get('total_tax_sgst') or 0)
        employee_id     = request.POST.get('employee_id') or user_id
        now             = timezone.localtime(timezone.now())

        if not check_user_access(role_id, 'sales', "create"):
            return JsonResponse({'message': 'permission', 'error_message': 'Access denied'})
        # -----------------------------
        # Create customer if needed
        # -----------------------------
        parent = select_row(sales_return_table, {'id': tm_return_id})
        # Items
        items       = json.loads(request.POST.get('items') or '[]')
        if not items:
            return JsonResponse({'message': 'warning', 'error_message': 'No items added'})

        # Payments
        payments    = json.loads(request.POST.get('payments') or '[]')

        
        child_sales_return_table.objects.filter(tm_return_id=parent.id).update(status=0, is_active=0, updated_on=now)
        # Sales Items
        for item in items:
            # Preserve claim and upgrade status from the old record
            old_item_id = item.get('item_id')
            extra_fields = {}
            if old_item_id:
                old_item = child_sales_return_table.objects.filter(id=old_item_id).first()
                if old_item:
                    extra_fields = {
                        'claim_amount': old_item.claim_amount,
                        'upgrade_id': old_item.upgrade_id,
                        'upgrade_amount': old_item.upgrade_amount,
                        'collect_amount': old_item.collect_amount,
                        # Add any other claim/status fields if they exist in this model
                    }

            child_sales_return_table.objects.create(
                company_id      =company_id,
                current_fy      =financial_year,
                tm_return_id     =parent.id,
                sales_id        =item['sales_id'],
                branch_id       =branch_id,
                customer_id     =customer_id,
                imei_no         =item['imei'],
                ean_number      =item['ean'],
                subcategory_id  =item['subcategory_id'],
                brand_id        =item['brand_id'],
                model_id        =item['model_id'],
                variant_id      =item['variant_id'],
                color_id        =item['color_id'],
                quantity        =1,
                rate            =item['rate'],
                amount          =item['net_rate'],
                tax_percent     =item['tax_percent'],
                tax_amount      =item['tax_amount'],
                tax_cgst        =item['tax_cgst'],
                tax_sgst        =item['tax_sgst'],
                discount_percent=item['discount_percent'],
                discount_amount=item['discount_amount'],
                mop             = item['mop_price'],
                bop             = item['bop_price'],
                wsp             = item['wsp_price'],
                fsp             = item['fsp_price'],
                db_price        = item['db_price'],
                mrp             = item['rate'],                    
                created_on      =now,
                updated_on      =now,
                created_by      =user_id,
                updated_by      =user_id,
                special_id      = item['special_id'],
                special_amount  = item['special_amount'],
                status          =1,
                is_active       =1,
                **extra_fields
            )
        # -----------------------------
        # Payments (MULTI ROW)
        # -----------------------------
        return_transaction_table.objects.filter(tm_return_id=parent.id).update(status=0, is_active=0, updated_on=now)
        for pay in payments:
            # Preserve collection status from the old record
            old_tx_id = pay.get('tx_id')
            pay_extra_fields = {}
            if old_tx_id:
                old_pay = return_transaction_table.objects.filter(id=old_tx_id).first()
                if old_pay:
                    pay_extra_fields = {
                        'charge_status': old_pay.charge_status,
                        'charge_amount_collect': old_pay.charge_amount_collect,
                        'charge_collect_on': old_pay.charge_collect_on,
                        'is_collect': old_pay.is_collect,
                        'collect_amount': old_pay.collect_amount,
                        'collect_status': old_pay.collect_status,
                        'collected_on': old_pay.collected_on,
                        'exchange_status': old_pay.exchange_status,
                        'exchange_claim': old_pay.exchange_claim,
                    }

            return_transaction_table.objects.create(
                    tm_return_id=parent.id,
                    branch_id=branch_id,
                    current_fy=financial_year,
                    date=po_date,
                    time=now.time(),
                    finance_customer=pay.get('customer', ''),
                    payment_type=pay['type'],
                    total_amount=total_amount,
                    amount=float(pay['amount']),
                    finance_id=pay.get('id', 0) if pay['type'] == 'finance' else 0,
                    card_id=pay.get('id', 0) if pay['type'] == 'card' else 0,
                    bank_id=pay.get('id', 0) if pay['type'] == 'bank' else 0,
                    charges=float(pay.get('charges', 0)),
                    reference_no=pay.get('details', ''),
                    cashback=float(pay.get('cashback', 0)),
                    charge_mode=pay.get('mode', ''),
                    charge_bank_id=pay.get('bank_id', 0),
                    balance=balance,
                    created_on=now,
                    updated_on=now,
                    created_by=user_id,
                    updated_by=user_id,
                    status=1,
                    is_active=1
                )

        return JsonResponse({'message': 'success'})

    except IntegrityError as e:
        return JsonResponse({'message': 'exception', 'error': str(e)}, status=200)
    except Exception as e:
        return JsonResponse({'message': 'exception', 'error': f'Unexpected error: {e}'}, status=500)


def update_sales_return_summary(po_id):
    try:
        summary = child_sales_return_table.objects.filter(
            tm_return_id=po_id, status=1
        ).aggregate(
            total_quantity=Sum('quantity'),
            total_amount=Sum('amount')
        )

        total_quantity = summary['total_quantity'] or 0
        total_amount = summary['total_amount'] or 0

        sales_return_table.objects.filter(id=po_id).update(
            total_quantity=total_quantity,
            total_amount=total_amount,
            updated_on=timezone.now()
        )
    except Exception as e:
        print(f"Error updating purchase summary: {str(e)}")


def edit_sales_return(request):
    if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST":
        data = child_sales_return_table.objects.filter(id=request.POST.get('id'))    
    return JsonResponse(data.values()[0])



from django.db.models import Sum
from django.http import JsonResponse
from django.utils import timezone

def delete_tx_sales_return(request):
    if request.method != 'POST':
        return JsonResponse({'message': 'Invalid request method'})

    data_id = request.POST.get('id')    
    role_id = request.session.get('role_id')

    # 🔹 Check access
    has_access, error_message = check_user_access(role_id, 'sales_return', "delete")
    if not has_access:
        return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to delete sales return details'})
    
    try:
        child = child_sales_return_table.objects.filter(id=data_id, status=1).first()
        if not child:
            return JsonResponse({'message': 'no such data'})

        tm_sale = sales_return_table.objects.filter(id=child.tm_return_id, status=1).first()
        if not tm_sale:
            return JsonResponse({'message': 'Parent sales return not found'})

        # 🔹 Check transaction permissions
     
        # 🔹 Calculate new totals excluding this child
        totals = child_sales_return_table.objects.filter(
            tm_return_id=tm_sale.id,
            status=1
        ).exclude(id=data_id).aggregate(
            total_qty=Sum('quantity') or 0,
            total_amount=Sum('total_amount') or 0,
            total_loss=Sum('loss') or 0
        )

        # 🔹 Check balance consistency
        total_paid = (tm_sale.cash or 0) + (tm_sale.bank or 0) + (tm_sale.upi_amount or 0)
        new_balance = totals['total_amount'] - total_paid
        if new_balance != tm_sale.balance:
            return JsonResponse({
                'message': 'warning',
                'error_message': 'Balance mismatch! Adjust cash/bank/UPI before deleting this item.'
            })

        # 🔹 Soft delete child
        child.status = 0
        child.is_active = 0
        child.updated_on = timezone.now()
        child.updated_by = request.user.id
        child.save(update_fields=['status', 'is_active', 'updated_on', 'updated_by'])

        # 🔹 Update parent totals
        tm_sale.total_quantity = totals['total_qty'] or 0
        tm_sale.total_amount = totals['total_amount'] or 0
        tm_sale.loss = totals['total_loss'] or 0
        tm_sale.balance = new_balance
        tm_sale.updated_on = timezone.now()
        tm_sale.updated_by = request.user.id
        tm_sale.save(update_fields=['total_quantity', 'total_amount', 'loss', 'balance', 'updated_on', 'updated_by'])

        return JsonResponse({'message': 'yes', 'info': 'Item deleted and parent totals updated successfully'})

    except Exception as e:
        return JsonResponse({'message': 'exception', 'error': str(e)})


def delete_tm_sales_return(request):
    if request.method == 'POST':
        data_id = request.POST.get('id')    
        role_id = request.session.get('role_id')

        has_access, error_message = check_user_access(role_id, 'sales_return', "delete")

       

        if not has_access:
            return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to delete sales return details'})
               
        try:
            updated = sales_return_table.objects.filter(id=data_id).update(status=0)
            updated = child_sales_return_table.objects.filter(id=data_id).update(status=0)
            if updated:
                return JsonResponse({'message': 'yes'})
            else:
                return JsonResponse({'message': 'no such data'})
        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)})

    return JsonResponse({'message': 'Invalid request method'})




from collections import defaultdict




def load_return_items(request):
    branch_id = request.session.get('branch_id')
    po_id = request.GET.get('po_id')  # sales_id
    pr_id = request.GET.get('pr_id')
    po_type = request.GET.get('po_type')

    if not po_id:
        return JsonResponse({"items": [], "summary": {}}, status=400)

    try:
        po_id = int(po_id)
        pr_id = int(pr_id) if pr_id else 0
    except ValueError:
        return JsonResponse({"items": [], "summary": {}}, status=400)

    items_data = []
    item_group = defaultdict(int)

    if po_type == 'customer':
        sales_items = child_sales_order_table.objects.filter(
            tm_sales_id=po_id,
            status=1
        )
        for item in sales_items:
            item_obj = item_table.objects.filter(id=item.item_id).first()
            uom_obj = uom_table.objects.filter(id=item.uom_id).first()

            items_data.append({
                "item_id": item.item_id,
                "item_code": item_obj.sku if item_obj else 'N/A',
                "uom_id": item.uom_id,
                "po_id": po_id,
                "pr_id": 0,  # customer type has no PR
                "batch_no": item.batch_no or 'N/A',
                "item_name": item_obj.name if item_obj else 'N/A',
                "unit_name": uom_obj.name if uom_obj else 'N/A',
                "rate": item.rate,
                "quantity": item.quantity,
                "amount": round(item.quantity * item.rate, 2),
                "remaining_quantity": item.quantity  # For customer, remaining = ordered qty
            })
    else:
        # ✅ Existing logic for store / PR type
        pr_items = child_purchase_return_table.objects.filter(
            tm_return_id=pr_id,  # filter by purchase return id
            status=1,
            is_active=1
        )

        for item in pr_items:
            item_obj = item_table.objects.filter(id=item.item_id).first()
            uom_obj = uom_table.objects.filter(id=item.uom_id).first()

            batch_no = item.batch_no if item.batch_no else 'N/A'
            stock_available = get_available_stock(item.item_id, branch_id)

            items_data.append({
                "item_id": item.item_id,
                "item_code": item_obj.sku if item_obj else 'N/A',
                "uom_id": item.uom_id,
                "po_id": po_id,
                "pr_id": pr_id,
                "batch_no": batch_no,
                "item_name": item_obj.name if item_obj else 'N/A',
                "unit_name": uom_obj.name if uom_obj else 'N/A',
                "rate": item.rate,
                "quantity": item.quantity,
                "amount": item.amount,
                "remaining_quantity": stock_available,
            })

    return JsonResponse({
        "items": items_data,
        "available_stock_summary": item_group
    })


def get_return_item_details(request):
    branch_id = request.session.get('branch_id')
    item_id = request.GET.get('item_id')
    po_id = request.GET.get('po_id')
    pr_id = request.GET.get('pr_id', 0)
    po_type = request.GET.get('po_type')
    edit_id = request.GET.get('edit_id')


    if not item_id or not po_id:
        return JsonResponse({'success': False, 'message': 'Invalid request'}, status=400)

    try:
        item_id = int(item_id)
        po_id = int(po_id)
        pr_id = int(pr_id)
    except ValueError:
        return JsonResponse({'success': False, 'message': 'Invalid IDs'}, status=400)

    # --- Customer PO type: fetch directly from sales table ---
    if po_type == 'customer':
        sales_item = child_sales_order_table.objects.filter(
            tm_sales_id=po_id,
            item_id=item_id,
            status=1
        ).first()

        if not sales_item:
            return JsonResponse({'success': False, 'message': 'No sales record found'}, status=404)

        uom_obj = uom_table.objects.filter(id=sales_item.uom_id).first()
        unit_name = uom_obj.name if uom_obj else 'N/A'

        return JsonResponse({
            'success': True,
            'item': {
                'item_id': sales_item.item_id,
                'uom_id': sales_item.uom_id,
                'unit_name': unit_name,
                'rate': sales_item.rate,
                'mrp': getattr(sales_item, 'mrp', 0),
                'inward_qty': sales_item.quantity,
                'return_qty': 0,
                'quantity': sales_item.quantity,
                'amount': round(sales_item.quantity * sales_item.rate, 2),
                'batch_no': sales_item.batch_no or 'N/A',
                'po_id': po_id,
                'pr_id': 0,
                'po_type': 'customer',
                'purchase_price':sales_item.purchase_price
            }
        })


    inward_qs = child_purchase_return_table.objects.filter(
        tm_return_id=pr_id,
        item_id=item_id,
        status=1,
        is_active=1
    )

    if not inward_qs.exists():
        return JsonResponse({'success': False, 'message': 'No inward record found'}, status=404)

    inward_qty = inward_qs.aggregate(total=Sum('quantity'))['total'] or 0
    inward_item = inward_qs.first()

    # Sales return qty (exclude edit_id if provided)
    return_qs = child_sales_return_table.objects.filter(
        return_id=pr_id,
        status=1,
        is_active=1
    )

    if edit_id and str(edit_id) != "0":  # exclude the current row being edited
        return_qs = return_qs.exclude(id=edit_id)

    return_qty = return_qs.aggregate(total=Sum('quantity'))['total'] or 0
    available_qty = (inward_qty or 0) - (return_qty or 0)

    uom_obj = uom_table.objects.filter(id=inward_item.uom_id).first()
    unit_name = uom_obj.name if uom_obj else 'N/A'

    return JsonResponse({
        'success': True,
        'item': {
            'item_id': inward_item.item_id,
            'uom_id': inward_item.uom_id,
            'unit_name': unit_name,
            'rate': inward_item.rate,
            'mrp': getattr(inward_item, 'mrp', 0),
            'inward_qty': inward_qty,
            'return_qty': return_qty,
            'quantity': available_qty,
            'amount': inward_item.amount,
            'batch_no': inward_item.batch_no,
            'po_id': po_id,
            'pr_id': pr_id,
            'po_type': 'store'
        }
    })



def get_return_item_by_sku(request):
    branch_id = request.session.get('branch_id')
    sku = request.GET.get('sku')
    po_id = request.GET.get('po_id')
    pr_id = request.GET.get('pr_id', 0)
    po_type = request.GET.get('po_type')


    if not sku or not po_id:
        return JsonResponse({'success': False, 'message': 'Invalid request'}, status=400)
    items_data = []
    item_group = defaultdict(int)

    if po_type == 'customer':
        sales_items = child_sales_order_table.objects.filter(
            tm_sales_id=po_id,
            status=1
        ).values_list("item_id", flat=True)

        items = item_table.objects.filter(
            id__in=sales_items,
            sku=sku,
            status=1
        ).values("id", "name", "sku")

        if not items.exists():
            return JsonResponse({'success': False, 'message': 'SKU not found in PO'}, status=404)

        item_list = [{
            'item_id': obj["id"],
            'item_name': obj["name"],
            'sku': obj["sku"],
        } for obj in items]


    else:
            
        inward_items = child_purchase_return_table.objects.filter(
            tm_return_id=po_id,
            branch_id=branch_id,
            status=1
        ).values_list("item_id", flat=True)

        if not inward_items:
            return JsonResponse({'success': False, 'message': 'No items found in PO'}, status=404)

        # 🔹 Step 2: Match with item_table by sku
        items = item_table.objects.filter(
            id__in=inward_items,
            sku=sku,
            status=1
        ).values("id", "name", "sku")

        if not items.exists():
            return JsonResponse({'success': False, 'message': 'SKU not found in PO'}, status=404)

        # 🔹 Step 3: Build response list
        item_list = [{
            'item_id': obj["id"],
            'item_name': obj["name"],
            'sku': obj["sku"],
        } for obj in items]

    return JsonResponse({'success': True, 'items': item_list})



# def return_barcode_details(request):
#     if request.method != 'POST':
#         return JsonResponse({'error': 'Invalid request method'}, status=400)

#     try:
#         data = json.loads(request.body)
#         sku = data.get('sku')  
#         po_id = data.get('po_id')  
#         edit_id = data.get('edit_id')  
#         pr_id = data.get('pr_id')  
#         po_type = data.get('po_type')  
#         print('sku', sku)

#         branch_id = request.session.get('branch_id')
#         fyf_name = request.session.get('fyf')
#         default_year = calculate_financial_year(fyf_name)  # fallback year


#         year, sku_code, batch_no = None, None, None

#         if sku and "/" in sku:
#             parts = sku.split("/")
#             if len(parts) == 3:
#                 # SKU format: year/sku_code/batch_no
#                 year, sku_code, batch_no = parts
#                 year = f"20{year}" if len(year) == 2 else year  # 25 → 2025
#             elif len(parts) == 2:
#                 # SKU format: sku_code/batch_no → assume current FY as year
#                 sku_code, batch_no = parts
#                 year = default_year
#         else:
#             year = default_year


#         print('year',year)
#         print('sku_code',sku_code)
#         print('batch_no',batch_no)
#         print('batchpo_id_no',po_id)

#         if po_type == 'customer':            
#             sales_qs = child_sales_order_table.objects.filter(
#                 tm_sales_id=po_id,
#                 branch_id=branch_id,
#                 batch_no=batch_no,
#                 status=1
#             ).values_list("item_id", flat=True)
             
#             if not inward_qs.exists():
#                 return JsonResponse({'success': False, 'message': 'No items found in PO'}, status=404)
            
#             items = item_table.objects.filter(
#                 id__in=inward_qs,
#                 sku=sku_code,   # ✅ only match scanned item
#                 status=1
#             ).values("id", "name", "sku")

#             if not items.exists():
#                 return JsonResponse({'success': False, 'message': 'SKU not found in PO'}, status=404)

#             # 🔹 Step 3: Build response list
#             item_list = [{
#                 'item_id': obj["id"],
#                 'item_name': obj["name"],
#                 'sku': obj["sku"],
#             } for obj in items]


#         else:
#             inward_qs = child_purchase_return_table.objects.filter(
#                 tm_pr_id=po_id,
#                 branch_id=branch_id,
#                 batch_no=batch_no,
#                 status=1
#             ).values_list("item_id", flat=True)

#             if not inward_qs.exists():
#                 return JsonResponse({'success': False, 'message': 'No items found in PO'}, status=404)

#             items = item_table.objects.filter(
#                 id__in=inward_qs,
#                 sku=sku_code,   # ✅ only match scanned item
#                 status=1
#             ).values("id", "name", "sku")

#             if not items.exists():
#                 return JsonResponse({'success': False, 'message': 'SKU not found in PO'}, status=404)

#             # 🔹 Step 3: Build response list
#             item_list = [{
#                 'item_id': obj["id"],
#                 'item_name': obj["name"],
#                 'sku': obj["sku"],
#             } for obj in items]
        
#         return JsonResponse({'success': True, 'items': item_list})

#     except ValueError as ve:
#         return JsonResponse({'error': str(ve)}, status=400)
#     except Exception as e:
#         return JsonResponse({'error': str(e)}, status=500)


def return_barcode_details(request):
    if request.method != 'POST':
        return JsonResponse({'error': 'Invalid request method'}, status=400)

    try:
        data = json.loads(request.body)
        sku = data.get('sku')
        po_id = data.get('po_id')
        edit_id = data.get('edit_id')  # Sales return ID (when editing)
        pr_id = data.get('pr_id')
        po_type = data.get('po_type')

        branch_id = request.session.get('branch_id')
        fyf_name = request.session.get('fyf')
        default_year = calculate_financial_year(fyf_name)

      
        year, sku_code, batch_no = None, None, None

        # 🔹 Parse SKU format
        if sku and "/" in sku:
            parts = sku.split("/")
            if len(parts) == 3:
                year, sku_code, batch_no = parts
                year = f"20{year}" if len(year) == 2 else year
            elif len(parts) == 2:
                sku_code, batch_no = parts
                year = default_year
        else:
            year = default_year


        # 🔹 Fetch inward items depending on PO type
        if po_type == 'customer':
            inward_qs = child_sales_order_table.objects.filter(
                tm_sales_id=po_id,
                branch_id=branch_id,
                batch_no=batch_no,
                status=1
            ).values_list("item_id", flat=True)
        else:
            inward_qs = child_purchase_return_table.objects.filter(
                tm_return_id=po_id,
                branch_id=branch_id,
                batch_no=batch_no,
                status=1
            ).values_list("item_id", flat=True)


        if not inward_qs.exists():
            return JsonResponse({'success': False, 'message': 'No items found in PO'}, status=404)

        items = item_table.objects.filter(
            id__in=inward_qs,
            sku=sku_code,
            status=1
        )


        # 🔹 Exclude items already returned in edit mode
        if edit_id and str(edit_id) != "0":
            # 🔹 Only exclude items from other sales return entries, not this one
            already_returned = child_sales_return_table.objects.filter(
                ~Q(tm_return_id=edit_id),  # exclude other SRs
                branch_id=branch_id,
                batch_no=batch_no,
                item_id__in=inward_qs,
                status=1
            ).values_list("item_id", flat=True)
            items = items.exclude(id__in=already_returned)



        if not items.exists():
            return JsonResponse({'success': False, 'message': 'SKU not found in PO'}, status=404)

        item_list = [{
            'item_id': obj.id,
            'item_name': obj.name,
            'sku': obj.sku,
        } for obj in items]


        return JsonResponse({'success': True, 'items': item_list})

    except ValueError as ve:
        return JsonResponse({'error': str(ve)}, status=400)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

from django.http import JsonResponse
from django.db.models import Sum

def load_imei_for_sales(request):
    po_id = request.GET.get('po_id')          # sales_id
    branch_id = request.session.get('branch_id')
    edit_id = request.GET.get('edit_id')

    try:
        edit_id = int(edit_id)
    except (TypeError, ValueError):
        edit_id = 0

    if not po_id:
        return JsonResponse([], safe=False)

    # ------------------------------------------------
    # IMEIs sold in this sales order
    # ------------------------------------------------
    sold_imeis = list(
        child_sales_order_table.objects.filter(
            status=1,
            branch_id=branch_id,
            tm_sales_id=po_id
        ).values_list('imei_no', flat=True)
    )

    if not sold_imeis:
        return JsonResponse([], safe=False)

    # ------------------------------------------------
    # Sales Returns (exclude current edit row)
    # ------------------------------------------------
    sales_return_qs = child_sales_return_table.objects.filter(
        status=1,
        branch_id=branch_id,
        sales_id=po_id,
        imei_no__in=sold_imeis
    )

    if edit_id > 0:
        sales_return_qs = sales_return_qs.exclude(
            tm_return_id=edit_id
        )

    returned_map = {
        r['imei_no']: r['total_qty'] or 0
        for r in sales_return_qs.values('imei_no')
        .annotate(total_qty=Sum('quantity'))
    }

    # ------------------------------------------------
    # Compute available IMEIs
    # ------------------------------------------------
    available_imeis = []

    for imei in sold_imeis:
        sold_qty = 1
        returned_qty = returned_map.get(imei, 0)

        available = sold_qty - returned_qty

        if available > 0:
            available_imeis.append(imei)

    # ------------------------------------------------
    # Return for dropdown (Select2 ready)
    # ------------------------------------------------
    data = [{'id': i, 'text': i} for i in available_imeis]

    return JsonResponse(data, safe=False)




def sales_imei_details(request):
    imei_no = request.GET.get('imei_no')
    branch_id = request.session.get('branch_id')

    if not imei_no:
        return JsonResponse({'error': 'IMEI required'}, status=400)

    # Get child sales record
    item = child_sales_order_table.objects.filter(
        imei_no=imei_no,
        branch_id=branch_id,
        status=1
    ).values(
        'tm_sales_id',
        'subcategory_id',
        'brand_id',
        'model_id',
        'variant_id',
        'color_id',
        'rate',
        'amount',
        'tax_percent',    
        'tax_amount',
        'tax_cgst',
        'tax_sgst',
        'discount_percent',    
        'discount_amount',
        'mop',
        'db_price',
        'bop',
        'fsp',
        'wsp',
        'mrp',
        'ean_number',
        'special_id',
        'special_amount',
        'claim_amount',
        'upgrade_id',
        'upgrade_amount',
        'upgrade_collect',
    ).first()

    if not item:
        return JsonResponse({'error': 'Item not found'}, status=404)
    
    sales_id = item.get('tm_sales_id')
    tx_qs = transaction_table.objects.filter(
        tm_sales_id=sales_id,
        status=1,
        is_active=1
    ).values(
        'payment_type', 'amount', 'finance_id', 'bank_id', 'card_id',
        'reference_no', 'finance_customer', 'balance', 'is_collect',
        'collected_on', 'collect_amount', 'collect_status', 'cashback',
        'charges', 'charge_mode', 'charge_bank_id', 'charge_status',
        'charge_amount_collect', 'charge_collect_on'
    )

    tx_transaction = [
        {
            'payment_type': tx['payment_type'],
            'amount': format_amount(tx['amount']) if tx['amount'] else '0.00',
            'finance_id': tx['finance_id'] or 0,
            'bank_id': tx['bank_id'] or 0,
            'card_id': tx['card_id'] or 0,
            'reference_no': tx['reference_no'] or '',
            'finance_customer': tx['finance_customer'] or '',
            'balance': format_amount(tx['balance']) if tx['balance'] else '0.00',
            'is_collect': tx['is_collect'] or 0,
            'collected_on': format_datetime(tx['collected_on']) or '',
            'collect_amount': tx['collect_amount'] or 0.00,
            'collect_status': tx['collect_status'] or 0,
            'cashback': tx['cashback'] or 0.00,
            'charges': tx['charges'] or 0.00,
            'charge_mode': tx['charge_mode'] or '',
            'charge_bank_id': tx['charge_bank_id'] or 0,
            'charge_status': tx['charge_status'] or '',
            'charge_amount_collect': tx['charge_amount_collect'] or 0.00,
            'charge_collect_on': format_datetime(tx['charge_collect_on']) or '',
        }
        for tx in tx_qs
    ]

    def name_for(model, key):
        value = item.get(key)
        if not value:
            return ''
        row = model.objects.filter(id=value).values('name').first()
        return row['name'] if row else ''

    subcategory_name = name_for(sub_category_table, 'subcategory_id')
    brand_name = name_for(brand_table, 'brand_id')
    model_name = name_for(model_table, 'model_id')
    variant_name = name_for(variant_table, 'variant_id')
    color_name = name_for(color_table, 'color_id')
    

    # Prepare response
    response = {
        'subcategory_id': item.get('subcategory_id'),
        'subcategory_name': subcategory_name,
        'brand_id': item.get('brand_id'),
        'brand_name': brand_name,
        'model_id': item.get('model_id'),
        'model_name': model_name,
        'variant_id': item.get('variant_id'),
        'variant_name': variant_name,
        'color_id': item.get('color_id'),
        'color_name': color_name,
        'amount': item.get('amount'),
        'rate': item.get('rate'),
        'mop': item.get('mop'),
        'bop': item.get('bop'),
        'fsp': item.get('fsp'),
        'wsp': item.get('wsp'),
        'mrp': item.get('mrp'),
        'db_price': item.get('db_price'),
        'ean_number': item.get('ean_number'),
        'discount_percent': item.get('discount_percent'),
        'discount_amount': item.get('discount_amount'),
        'tax_percent': item.get('tax_percent'),
        'tax_amount': item.get('tax_amount'),
        'tax_cgst': item.get('tax_cgst'),
        'tax_sgst': item.get('tax_sgst'),
        'special_id': item.get('special_id') or 0,
        'special_amount': item.get('special_amount') or 0.00,
        'claim_amount': item.get('claim_amount') or 0.00,
        'upgrade_id': item.get('upgrade_id') or 0,
        'upgrade_amount': item.get('upgrade_amount') or 0.00,
        'collect_amount': item.get('upgrade_collect') or 0.00,

    }

    return JsonResponse({'response': response, 'tx_transaction': tx_transaction})




def check_sales_return_imei_exists(request):
    imeis = request.POST.getlist('imeis[]') or request.POST.getlist('imeis')
    edit_id_str = request.POST.get('edit_id') # This is now "101,102,103"

    imeis = [i.strip().upper() for i in imeis if i.strip()]
    if not imeis:
        return JsonResponse({"exists": False, "duplicate_imeis": []})

    qs = child_sales_return_table.objects.filter(imei_no__in=imeis, status=1)

    # 🔥 Exclude all IDs belonging to the group being edited
    if edit_id_str and edit_id_str != '0':        
        qs = qs.exclude(tm_return_id=edit_id_str)

    duplicate_imeis = list(qs.values_list('imei_no', flat=True))

    return JsonResponse({
        "exists": bool(duplicate_imeis),
        "duplicate_imeis": duplicate_imeis
    })
